max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
7,482
/*  * @ : Copyright (c) 2021 Phytium Information Technology, Inc.  *  * SPDX-License-Identifier: Apache-2.0.  * * @Date: 2021-04-07 09:53:07 * @LastEditTime: 2021-04-07 15:29:20 * @Description:  This files is for list data structure * * @Modify History: * Ver   Who        Date         Changes * ----- ------     --------    -------------------------------------- */ #ifndef FT_LIST_H #define FT_LIST_H #include "ft_types.h" #define container_of(ptr, type, member) \ ((type *)((s8 *)(ptr) - (u32)(&((type *)0)->member))) #endif // ! FT_LIST_H
225
1,844
<reponame>MozartWang/braft<filename>src/braft/closure_helper.h<gh_stars>1000+ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: <EMAIL> (<NAME>) and others // // Contains basic types and utilities used by the rest of the library. #ifndef BRAFT_CLOSURE_HELPER_H #define BRAFT_CLOSURE_HELPER_H #if defined(__osf__) // Tru64 lacks stdint.h, but has inttypes.h which defines a superset of // what stdint.h would define. #include <inttypes.h> #elif !defined(_MSC_VER) #include <stdint.h> #endif #include <braft/raft.h> // braft::Closure namespace braft { // emulates google3/butil/callback.h // Abstract interface for a callback. When calling an RPC, you must provide // a Closure to call when the procedure completes. See the Service interface // in service.h. // // To automatically construct a Closure which calls a particular function or // method with a particular set of parameters, use the NewCallback() function. // Example: // void FooDone(const FooResponse* response) { // ... // } // // void CallFoo() { // ... // // When done, call FooDone() and pass it a pointer to the response. // Closure* callback = NewCallback(&FooDone, response); // // Make the call. // service->Foo(controller, request, response, callback); // } // // Example that calls a method: // class Handler { // public: // ... // // void FooDone(const FooResponse* response) { // ... // } // // void CallFoo() { // ... // // When done, call FooDone() and pass it a pointer to the response. // Closure* callback = NewCallback(this, &Handler::FooDone, response); // // Make the call. // service->Foo(controller, request, response, callback); // } // }; // // Currently NewCallback() supports binding zero, one, or two arguments. // // Callbacks created with NewCallback() automatically delete themselves when // executed. They should be used when a callback is to be called exactly // once (usually the case with RPC callbacks). If a callback may be called // a different number of times (including zero), create it with // NewPermanentCallback() instead. You are then responsible for deleting the // callback (using the "delete" keyword as normal). // // Note that NewCallback() is a bit touchy regarding argument types. Generally, // the values you provide for the parameter bindings must exactly match the // types accepted by the callback function. For example: // void Foo(string s); // NewCallback(&Foo, "foo"); // WON'T WORK: const char* != string // NewCallback(&Foo, string("foo")); // WORKS // Also note that the arguments cannot be references: // void Foo(const string& s); // string my_str; // NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes. // However, correctly-typed pointers will work just fine. // namespace internal { class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure { public: typedef void (*FunctionType)(const butil::Status &status); FunctionClosure0(FunctionType function, bool self_deleting) : function_(function), self_deleting_(self_deleting) {} ~FunctionClosure0(); void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; }; template <typename Class> class MethodClosure0 : public Closure { public: typedef void (Class::*MethodType)(const butil::Status &status); MethodClosure0(Class* object, MethodType method, bool self_deleting) : object_(object), method_(method), self_deleting_(self_deleting) {} ~MethodClosure0() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; }; template <typename Arg1> class FunctionClosure1 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, const butil::Status &status); FunctionClosure1(FunctionType function, bool self_deleting, Arg1 arg1) : function_(function), self_deleting_(self_deleting), arg1_(arg1) {} ~FunctionClosure1() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; }; template <typename Class, typename Arg1> class MethodClosure1 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, const butil::Status &status); MethodClosure1(Class* object, MethodType method, bool self_deleting, Arg1 arg1) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1) {} ~MethodClosure1() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; }; template <typename Arg1, typename Arg2> class FunctionClosure2 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, const butil::Status &status); FunctionClosure2(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2) {} ~FunctionClosure2() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; }; template <typename Class, typename Arg1, typename Arg2> class MethodClosure2 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, const butil::Status &status); MethodClosure2(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2) {} ~MethodClosure2() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; }; template <typename Arg1, typename Arg2, typename Arg3> class FunctionClosure3 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, const butil::Status &status); FunctionClosure3(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3) {} ~FunctionClosure3() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3> class MethodClosure3 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, const butil::Status &status); MethodClosure3(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3) {} ~MethodClosure3() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4> class FunctionClosure4 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, const butil::Status &status); FunctionClosure4(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4) {} ~FunctionClosure4() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4> class MethodClosure4 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, const butil::Status &status); MethodClosure4(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4) {} ~MethodClosure4() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> class FunctionClosure5 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, const butil::Status &status); FunctionClosure5(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4), arg5_(arg5) {} ~FunctionClosure5() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, arg5_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> class MethodClosure5 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, const butil::Status &status); MethodClosure5(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4),arg5_(arg5) {} ~MethodClosure5() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_,arg5_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> class FunctionClosure6 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, const butil::Status &status); FunctionClosure6(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4), arg5_(arg5), arg6_(arg6) {} ~FunctionClosure6() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, arg5_, arg6_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> class MethodClosure6 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, const butil::Status &status); MethodClosure6(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4),arg5_(arg5),arg6_(arg6) {} ~MethodClosure6() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_,arg5_,arg6_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> class FunctionClosure7 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, const butil::Status &status); FunctionClosure7(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4), arg5_(arg5), arg6_(arg6), arg7_(arg7) {} ~FunctionClosure7() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, arg5_, arg6_, arg7_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> class MethodClosure7 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, const butil::Status &status); MethodClosure7(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4),arg5_(arg5),arg6_(arg6),arg7_(arg7) {} ~MethodClosure7() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_,arg5_,arg6_,arg7_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> class FunctionClosure8 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, const butil::Status &status); FunctionClosure8(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4), arg5_(arg5), arg6_(arg6), arg7_(arg7), arg8_(arg8) {} ~FunctionClosure8() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, arg5_, arg6_, arg7_,arg8_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; Arg8 arg8_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> class MethodClosure8 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, const butil::Status &status); MethodClosure8(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4),arg5_(arg5),arg6_(arg6),arg7_(arg7),arg8_(arg8) {} ~MethodClosure8() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_,arg5_,arg6_,arg7_,arg8_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; Arg8 arg8_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> class FunctionClosure9 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, const butil::Status &status); FunctionClosure9(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4), arg5_(arg5), arg6_(arg6), arg7_(arg7), arg8_(arg8), arg9_(arg9) {} ~FunctionClosure9() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, arg5_, arg6_, arg7_,arg8_,arg9_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; Arg8 arg8_; Arg9 arg9_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> class MethodClosure9 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, const butil::Status &status); MethodClosure9(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4),arg5_(arg5),arg6_(arg6),arg7_(arg7),arg8_(arg8),arg9_(arg9) {} ~MethodClosure9() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_,arg5_,arg6_,arg7_,arg8_,arg9_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; Arg8 arg8_; Arg9 arg9_; }; template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> class FunctionClosure10 : public Closure { public: typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10, const butil::Status &status); FunctionClosure10(FunctionType function, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10) : function_(function), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2), arg3_(arg3), arg4_(arg4), arg5_(arg5), arg6_(arg6), arg7_(arg7), arg8_(arg8), arg9_(arg9), arg10_(arg10) {} ~FunctionClosure10() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes function_(arg1_, arg2_, arg3_, arg4_, arg5_, arg6_, arg7_,arg8_,arg9_,arg10_, status()); if (needs_delete) delete this; } private: FunctionType function_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; Arg8 arg8_; Arg9 arg9_; Arg10 arg10_; }; template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> class MethodClosure10 : public Closure { public: typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10, const butil::Status &status); MethodClosure10(Class* object, MethodType method, bool self_deleting, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10) : object_(object), method_(method), self_deleting_(self_deleting), arg1_(arg1), arg2_(arg2),arg3_(arg3),arg4_(arg4),arg5_(arg5),arg6_(arg6),arg7_(arg7),arg8_(arg8),arg9_(arg9),arg10_(arg10) {} ~MethodClosure10() {} void Run() { bool needs_delete = self_deleting_; // read in case callback deletes (object_->*method_)(arg1_, arg2_,arg3_,arg4_,arg5_,arg6_,arg7_,arg8_,arg9_,arg10_, status()); if (needs_delete) delete this; } private: Class* object_; MethodType method_; bool self_deleting_; Arg1 arg1_; Arg2 arg2_; Arg3 arg3_; Arg4 arg4_; Arg5 arg5_; Arg6 arg6_; Arg7 arg7_; Arg8 arg8_; Arg9 arg9_; Arg10 arg10_; }; } // namespace internal // See Closure. inline Closure* NewCallback(void (*function)(const butil::Status&)) { return new internal::FunctionClosure0(function, true); } // See Closure. inline Closure* NewPermanentCallback(void (*function)(const butil::Status&)) { return new internal::FunctionClosure0(function, false); } // See Closure. template <typename Class> inline Closure* NewCallback(Class* object, void (Class::*method)(const butil::Status&)) { return new internal::MethodClosure0<Class>(object, method, true); } // See Closure. template <typename Class> inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(const butil::Status&)) { return new internal::MethodClosure0<Class>(object, method, false); } // See Closure. template <typename Arg1> inline Closure* NewCallback(void (*function)(Arg1, const butil::Status&), Arg1 arg1) { return new internal::FunctionClosure1<Arg1>(function, true, arg1); } // See Closure. template <typename Arg1> inline Closure* NewPermanentCallback(void (*function)(Arg1, const butil::Status&), Arg1 arg1) { return new internal::FunctionClosure1<Arg1>(function, false, arg1); } // See Closure. template <typename Class, typename Arg1> inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, const butil::Status&), Arg1 arg1) { return new internal::MethodClosure1<Class, Arg1>(object, method, true, arg1); } // See Closure. template <typename Class, typename Arg1> inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(Arg1, const butil::Status&), Arg1 arg1) { return new internal::MethodClosure1<Class, Arg1>(object, method, false, arg1); } // See Closure. template <typename Arg1, typename Arg2> inline Closure* NewCallback(void (*function)(Arg1, Arg2, const butil::Status&), Arg1 arg1, Arg2 arg2) { return new internal::FunctionClosure2<Arg1, Arg2>( function, true, arg1, arg2); } // See Closure. template <typename Arg1, typename Arg2> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, const butil::Status&), Arg1 arg1, Arg2 arg2) { return new internal::FunctionClosure2<Arg1, Arg2>( function, false, arg1, arg2); } // See Closure. template <typename Class, typename Arg1, typename Arg2> inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, Arg2, const butil::Status&), Arg1 arg1, Arg2 arg2) { return new internal::MethodClosure2<Class, Arg1, Arg2>( object, method, true, arg1, arg2); } // See Closure. template <typename Class, typename Arg1, typename Arg2> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, const butil::Status&), Arg1 arg1, Arg2 arg2) { return new internal::MethodClosure2<Class, Arg1, Arg2>( object, method, false, arg1, arg2); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3) { return new internal::FunctionClosure3<Arg1, Arg2, Arg3>( function, true, arg1, arg2, arg3); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3) { return new internal::FunctionClosure3<Arg1, Arg2, Arg3>( function, false, arg1, arg2, arg3); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3) { return new internal::MethodClosure3<Class, Arg1, Arg2, Arg3>( object, method, true, arg1, arg2, arg3); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3) { return new internal::MethodClosure3<Class, Arg1, Arg2, Arg3>( object, method, false, arg1, arg2, arg3); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) { return new internal::FunctionClosure4<Arg1, Arg2, Arg3, Arg4>( function, true, arg1, arg2, arg3, arg4); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) { return new internal::FunctionClosure4<Arg1, Arg2, Arg3, Arg4>( function, false, arg1, arg2, arg3, arg4); } // See Closure. template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) { return new internal::MethodClosure4<Class, Arg1, Arg2, Arg3, Arg4>( object, method, true, arg1, arg2, arg3, arg4); } // See Closure. template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) { return new internal::MethodClosure4<Class, Arg1, Arg2, Arg3, Arg4>( object, method, false, arg1, arg2, arg3, arg4); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5) { return new internal::FunctionClosure5<Arg1, Arg2, Arg3, Arg4, Arg5>( function, true, arg1, arg2, arg3, arg4, arg5); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5) { return new internal::FunctionClosure5<Arg1, Arg2, Arg3, Arg4, Arg5>( function, false, arg1, arg2, arg3, arg4, arg5); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5) { return new internal::MethodClosure5<Class, Arg1, Arg2, Arg3, Arg4, Arg5>( object, method, true, arg1, arg2, arg3, arg4, arg5); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5) { return new internal::MethodClosure5<Class, Arg1, Arg2, Arg3, Arg4, Arg5>( object, method, false, arg1, arg2, arg3, arg4, arg5); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6) { return new internal::FunctionClosure6<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( function, true, arg1, arg2, arg3, arg4, arg5, arg6); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6) { return new internal::FunctionClosure6<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( function, false, arg1, arg2, arg3, arg4, arg5, arg6); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6) { return new internal::MethodClosure6<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( object, method, true, arg1, arg2, arg3, arg4, arg5, arg6); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6) { return new internal::MethodClosure6<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>( object, method, false, arg1, arg2, arg3, arg4, arg5, arg6); } // See Closure template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7) { return new internal::FunctionClosure7<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( function, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7) { return new internal::FunctionClosure7<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( function, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7) { return new internal::MethodClosure7<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( object, method, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7) { return new internal::MethodClosure7<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>( object, method, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8) { return new internal::FunctionClosure8<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( function, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8) { return new internal::FunctionClosure8<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( function, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8) { return new internal::MethodClosure8<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( object, method, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8) { return new internal::MethodClosure8<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>( object, method, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9) { return new internal::FunctionClosure9<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( function, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9) { return new internal::FunctionClosure9<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( function, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9) { return new internal::MethodClosure9<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( object, method, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9) { return new internal::MethodClosure9<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>( object, method, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> inline Closure* NewCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10) { return new internal::FunctionClosure10<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10>( function, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } // See Closure. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10) { return new internal::FunctionClosure10<Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10>( function, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> inline Closure* NewCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10) { return new internal::MethodClosure10<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10>( object, method, true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } // See Closure template <typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> inline Closure* NewPermanentCallback( Class* object, void (Class::*method)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, const butil::Status&), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9, Arg10 arg10) { return new internal::MethodClosure10<Class, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10>( object, method, false, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } } // namespace braft #endif // BRAFT_CLOSURE_HELPER_H
16,824
521
/* $Id: USBProxyService.cpp $ */ /** @file * VirtualBox USB Proxy Service (base) class. */ /* * Copyright (C) 2006-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include "USBProxyService.h" #include "HostUSBDeviceImpl.h" #include "HostImpl.h" #include "MachineImpl.h" #include "VirtualBoxImpl.h" #include "AutoCaller.h" #include "Logging.h" #include <VBox/com/array.h> #include <VBox/err.h> #include <iprt/asm.h> #include <iprt/semaphore.h> #include <iprt/thread.h> #include <iprt/mem.h> #include <iprt/string.h> /** Pair of a USB proxy backend and the opaque filter data assigned by the backend. */ typedef std::pair<ComObjPtr<USBProxyBackend> , void *> USBFilterPair; /** List of USB filter pairs. */ typedef std::list<USBFilterPair> USBFilterList; /** * Data for a USB device filter. */ struct USBFilterData { USBFilterData() : llUsbFilters() { } USBFilterList llUsbFilters; }; /** * Initialize data members. */ USBProxyService::USBProxyService(Host *aHost) : mHost(aHost), mDevices(), mBackends() { LogFlowThisFunc(("aHost=%p\n", aHost)); } /** * Stub needed as long as the class isn't virtual */ HRESULT USBProxyService::init(void) { # if defined(RT_OS_DARWIN) ComObjPtr<USBProxyBackendDarwin> UsbProxyBackendHost; # elif defined(RT_OS_LINUX) ComObjPtr<USBProxyBackendLinux> UsbProxyBackendHost; # elif defined(RT_OS_OS2) ComObjPtr<USBProxyBackendOs2> UsbProxyBackendHost; # elif defined(RT_OS_SOLARIS) ComObjPtr<USBProxyBackendSolaris> UsbProxyBackendHost; # elif defined(RT_OS_WINDOWS) ComObjPtr<USBProxyBackendWindows> UsbProxyBackendHost; # elif defined(RT_OS_FREEBSD) ComObjPtr<USBProxyBackendFreeBSD> UsbProxyBackendHost; # else ComObjPtr<USBProxyBackend> UsbProxyBackendHost; # endif UsbProxyBackendHost.createObject(); int vrc = UsbProxyBackendHost->init(this, Utf8Str("host"), Utf8Str(""), false /* fLoadingSettings */); if (RT_FAILURE(vrc)) { mLastError = vrc; } else mBackends.push_back(static_cast<ComObjPtr<USBProxyBackend> >(UsbProxyBackendHost)); return S_OK; } /** * Empty destructor. */ USBProxyService::~USBProxyService() { LogFlowThisFunc(("\n")); while (!mBackends.empty()) mBackends.pop_front(); mDevices.clear(); mBackends.clear(); mHost = NULL; } /** * Query if the service is active and working. * * @returns true if the service is up running. * @returns false if the service isn't running. */ bool USBProxyService::isActive(void) { return mBackends.size() > 0; } /** * Get last error. * Can be used to check why the proxy !isActive() upon construction. * * @returns VBox status code. */ int USBProxyService::getLastError(void) { return mLastError; } /** * We're using the Host object lock. * * This is just a temporary measure until all the USB refactoring is * done, probably... For now it help avoiding deadlocks we don't have * time to fix. * * @returns Lock handle. */ RWLockHandle *USBProxyService::lockHandle() const { return mHost->lockHandle(); } void *USBProxyService::insertFilter(PCUSBFILTER aFilter) { USBFilterData *pFilterData = new USBFilterData(); for (USBProxyBackendList::iterator it = mBackends.begin(); it != mBackends.end(); ++it) { ComObjPtr<USBProxyBackend> pUsbProxyBackend = *it; void *pvId = pUsbProxyBackend->insertFilter(aFilter); pFilterData->llUsbFilters.push_back(USBFilterPair(pUsbProxyBackend, pvId)); } return pFilterData; } void USBProxyService::removeFilter(void *aId) { USBFilterData *pFilterData = (USBFilterData *)aId; for (USBFilterList::iterator it = pFilterData->llUsbFilters.begin(); it != pFilterData->llUsbFilters.end(); ++it) { ComObjPtr<USBProxyBackend> pUsbProxyBackend = it->first; pUsbProxyBackend->removeFilter(it->second); } pFilterData->llUsbFilters.clear(); delete pFilterData; } /** * Gets the collection of USB devices, slave of Host::USBDevices. * * This is an interface for the HostImpl::USBDevices property getter. * * * @param aUSBDevices Where to store the pointer to the collection. * * @returns COM status code. * * @remarks The caller must own the write lock of the host object. */ HRESULT USBProxyService::getDeviceCollection(std::vector<ComPtr<IHostUSBDevice> > &aUSBDevices) { AssertReturn(isWriteLockOnCurrentThread(), E_FAIL); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); aUSBDevices.resize(mDevices.size()); size_t i = 0; for (HostUSBDeviceList::const_iterator it = mDevices.begin(); it != mDevices.end(); ++it, ++i) aUSBDevices[i] = *it; return S_OK; } HRESULT USBProxyService::addUSBDeviceSource(const com::Utf8Str &aBackend, const com::Utf8Str &aId, const com::Utf8Str &aAddress, const std::vector<com::Utf8Str> &aPropertyNames, const std::vector<com::Utf8Str> &aPropertyValues) { AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); HRESULT hrc = createUSBDeviceSource(aBackend, aId, aAddress, aPropertyNames, aPropertyValues, false /* fLoadingSettings */); if (SUCCEEDED(hrc)) { alock.release(); AutoWriteLock vboxLock(mHost->i_parent() COMMA_LOCKVAL_SRC_POS); return mHost->i_parent()->i_saveSettings(); } return hrc; } HRESULT USBProxyService::removeUSBDeviceSource(const com::Utf8Str &aId) { AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); for (USBProxyBackendList::iterator it = mBackends.begin(); it != mBackends.end(); ++it) { ComObjPtr<USBProxyBackend> UsbProxyBackend = *it; if (aId.equals(UsbProxyBackend->i_getId())) { mBackends.erase(it); /* * The proxy backend uninit method will be called when the pointer goes * out of scope. */ alock.release(); AutoWriteLock vboxLock(mHost->i_parent() COMMA_LOCKVAL_SRC_POS); return mHost->i_parent()->i_saveSettings(); } } return setError(VBOX_E_OBJECT_NOT_FOUND, tr("The USB device source \"%s\" could not be found"), aId.c_str()); } /** * Request capture of a specific device. * * This is in an interface for SessionMachine::CaptureUSBDevice(), which is * an internal worker used by Console::AttachUSBDevice() from the VM process. * * When the request is completed, SessionMachine::onUSBDeviceAttach() will * be called for the given machine object. * * * @param aMachine The machine to attach the device to. * @param aId The UUID of the USB device to capture and attach. * @param aCaptureFilename * * @returns COM status code and error info. * * @remarks This method may operate synchronously as well as asynchronously. In the * former case it will temporarily abandon locks because of IPC. */ HRESULT USBProxyService::captureDeviceForVM(SessionMachine *aMachine, IN_GUID aId, const com::Utf8Str &aCaptureFilename) { ComAssertRet(aMachine, E_INVALIDARG); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); /* * Translate the device id into a device object. */ ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId); if (pHostDevice.isNull()) return setError(E_INVALIDARG, tr("The USB device with UUID {%RTuuid} is not currently attached to the host"), Guid(aId).raw()); /* * Try to capture the device */ alock.release(); return pHostDevice->i_requestCaptureForVM(aMachine, true /* aSetError */, aCaptureFilename); } /** * Notification from VM process about USB device detaching progress. * * This is in an interface for SessionMachine::DetachUSBDevice(), which is * an internal worker used by Console::DetachUSBDevice() from the VM process. * * @param aMachine The machine which is sending the notification. * @param aId The UUID of the USB device is concerns. * @param aDone \a false for the pre-action notification (necessary * for advancing the device state to avoid confusing * the guest). * \a true for the post-action notification. The device * will be subjected to all filters except those of * of \a Machine. * * @returns COM status code. * * @remarks When \a aDone is \a true this method may end up doing IPC to other * VMs when running filters. In these cases it will temporarily * abandon its locks. */ HRESULT USBProxyService::detachDeviceFromVM(SessionMachine *aMachine, IN_GUID aId, bool aDone) { LogFlowThisFunc(("aMachine=%p{%s} aId={%RTuuid} aDone=%RTbool\n", aMachine, aMachine->i_getName().c_str(), Guid(aId).raw(), aDone)); // get a list of all running machines while we're outside the lock // (getOpenedMachines requests locks which are incompatible with the lock of the machines list) SessionMachinesList llOpenedMachines; mHost->i_parent()->i_getOpenedMachines(llOpenedMachines); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId); ComAssertRet(!pHostDevice.isNull(), E_FAIL); AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS); /* * Work the state machine. */ LogFlowThisFunc(("id={%RTuuid} state=%s aDone=%RTbool name={%s}\n", pHostDevice->i_getId().raw(), pHostDevice->i_getStateName(), aDone, pHostDevice->i_getName().c_str())); bool fRunFilters = false; HRESULT hrc = pHostDevice->i_onDetachFromVM(aMachine, aDone, &fRunFilters); /* * Run filters if necessary. */ if ( SUCCEEDED(hrc) && fRunFilters) { Assert(aDone && pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->i_getMachine().isNull()); devLock.release(); alock.release(); HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine); ComAssertComRC(hrc2); } return hrc; } /** * Apply filters for the machine to all eligible USB devices. * * This is in an interface for SessionMachine::CaptureUSBDevice(), which * is an internal worker used by Console::AutoCaptureUSBDevices() from the * VM process at VM startup. * * Matching devices will be attached to the VM and may result IPC back * to the VM process via SessionMachine::onUSBDeviceAttach() depending * on whether the device needs to be captured or not. If capture is * required, SessionMachine::onUSBDeviceAttach() will be called * asynchronously by the USB proxy service thread. * * @param aMachine The machine to capture devices for. * * @returns COM status code, perhaps with error info. * * @remarks Temporarily locks this object, the machine object and some USB * device, and the called methods will lock similar objects. */ HRESULT USBProxyService::autoCaptureDevicesForVM(SessionMachine *aMachine) { LogFlowThisFunc(("aMachine=%p{%s}\n", aMachine, aMachine->i_getName().c_str())); /* * Make a copy of the list because we cannot hold the lock protecting it. * (This will not make copies of any HostUSBDevice objects, only reference them.) */ AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); HostUSBDeviceList ListCopy = mDevices; alock.release(); for (HostUSBDeviceList::iterator it = ListCopy.begin(); it != ListCopy.end(); ++it) { ComObjPtr<HostUSBDevice> pHostDevice = *it; AutoReadLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS); if ( pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy || pHostDevice->i_getUnistate() == kHostUSBDeviceState_Unused || pHostDevice->i_getUnistate() == kHostUSBDeviceState_Capturable) { devLock.release(); runMachineFilters(aMachine, pHostDevice); } } return S_OK; } /** * Detach all USB devices currently attached to a VM. * * This is in an interface for SessionMachine::DetachAllUSBDevices(), which * is an internal worker used by Console::powerDown() from the VM process * at VM startup, and SessionMachine::uninit() at VM abend. * * This is, like #detachDeviceFromVM(), normally a two stage journey * where \a aDone indicates where we are. In addition we may be called * to clean up VMs that have abended, in which case there will be no * preparatory call. Filters will be applied to the devices in the final * call with the risk that we have to do some IPC when attaching them * to other VMs. * * @param aMachine The machine to detach devices from. * @param aDone * @param aAbnormal * * @returns COM status code, perhaps with error info. * * @remarks Write locks the host object and may temporarily abandon * its locks to perform IPC. */ HRESULT USBProxyService::detachAllDevicesFromVM(SessionMachine *aMachine, bool aDone, bool aAbnormal) { // get a list of all running machines while we're outside the lock // (getOpenedMachines requests locks which are incompatible with the host object lock) SessionMachinesList llOpenedMachines; mHost->i_parent()->i_getOpenedMachines(llOpenedMachines); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); /* * Make a copy of the device list (not the HostUSBDevice objects, just * the list) since we may end up performing IPC and temporarily have * to abandon locks when applying filters. */ HostUSBDeviceList ListCopy = mDevices; for (HostUSBDeviceList::iterator it = ListCopy.begin(); it != ListCopy.end(); ++it) { ComObjPtr<HostUSBDevice> pHostDevice = *it; AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS); if (pHostDevice->i_getMachine() == aMachine) { /* * Same procedure as in detachUSBDevice(). */ bool fRunFilters = false; HRESULT hrc = pHostDevice->i_onDetachFromVM(aMachine, aDone, &fRunFilters, aAbnormal); if ( SUCCEEDED(hrc) && fRunFilters) { Assert( aDone && pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->i_getMachine().isNull()); devLock.release(); alock.release(); HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine); ComAssertComRC(hrc2); alock.acquire(); } } } return S_OK; } // Internals ///////////////////////////////////////////////////////////////////////////// /** * Loads the given settings and constructs the additional USB device sources. * * @returns COM status code. * @param llUSBDeviceSources The list of additional device sources. */ HRESULT USBProxyService::i_loadSettings(const settings::USBDeviceSourcesList &llUSBDeviceSources) { HRESULT hrc = S_OK; for (settings::USBDeviceSourcesList::const_iterator it = llUSBDeviceSources.begin(); it != llUSBDeviceSources.end() && SUCCEEDED(hrc); ++it) { std::vector<com::Utf8Str> vecPropNames, vecPropValues; const settings::USBDeviceSource &src = *it; hrc = createUSBDeviceSource(src.strBackend, src.strName, src.strAddress, vecPropNames, vecPropValues, true /* fLoadingSettings */); } return hrc; } /** * Saves the additional device sources in the given settings. * * @returns COM status code. * @param llUSBDeviceSources The list of additional device sources. */ HRESULT USBProxyService::i_saveSettings(settings::USBDeviceSourcesList &llUSBDeviceSources) { for (USBProxyBackendList::iterator it = mBackends.begin(); it != mBackends.end(); ++it) { USBProxyBackend *pUsbProxyBackend = *it; /* Host backends are not saved as they are always created during startup. */ if (!pUsbProxyBackend->i_getBackend().equals("host")) { settings::USBDeviceSource src; src.strBackend = pUsbProxyBackend->i_getBackend(); src.strName = pUsbProxyBackend->i_getId(); src.strAddress = pUsbProxyBackend->i_getAddress(); llUSBDeviceSources.push_back(src); } } return S_OK; } /** * Performs the required actions when a device has been added. * * This means things like running filters and subsequent capturing and * VM attaching. This may result in IPC and temporary lock abandonment. * * @param aDevice The device in question. * @param pDev The USB device structure. */ void USBProxyService::i_deviceAdded(ComObjPtr<HostUSBDevice> &aDevice, PUSBDEVICE pDev) { /* * Validate preconditions. */ AssertReturnVoid(!isWriteLockOnCurrentThread()); AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread()); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS); LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n", (HostUSBDevice *)aDevice, aDevice->i_getName().c_str(), aDevice->i_getStateName(), aDevice->i_getId().raw())); /* Add to our list. */ HostUSBDeviceList::iterator it = mDevices.begin(); while (it != mDevices.end()) { ComObjPtr<HostUSBDevice> pHostDevice = *it; /* Assert that the object is still alive. */ AutoCaller devCaller(pHostDevice); AssertComRC(devCaller.rc()); AutoWriteLock curLock(pHostDevice COMMA_LOCKVAL_SRC_POS); if ( pHostDevice->i_getUsbProxyBackend() == aDevice->i_getUsbProxyBackend() && pHostDevice->i_compare(pDev) < 0) break; it++; } mDevices.insert(it, aDevice); /* * Run filters on the device. */ if (aDevice->i_isCapturableOrHeld()) { devLock.release(); alock.release(); SessionMachinesList llOpenedMachines; mHost->i_parent()->i_getOpenedMachines(llOpenedMachines); HRESULT rc = runAllFiltersOnDevice(aDevice, llOpenedMachines, NULL /* aIgnoreMachine */); AssertComRC(rc); } } /** * Remove device notification hook for the USB proxy service. * * @param aDevice The device in question. */ void USBProxyService::i_deviceRemoved(ComObjPtr<HostUSBDevice> &aDevice) { /* * Validate preconditions. */ AssertReturnVoid(!isWriteLockOnCurrentThread()); AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread()); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS); LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n", (HostUSBDevice *)aDevice, aDevice->i_getName().c_str(), aDevice->i_getStateName(), aDevice->i_getId().raw())); mDevices.remove(aDevice); /* * Detach the device from any machine currently using it, * reset all data and uninitialize the device object. */ devLock.release(); alock.release(); aDevice->i_onPhysicalDetached(); } /** * Updates the device state. * * This is responsible for calling HostUSBDevice::updateState(). * * @returns true if there is a state change. * @param aDevice The device in question. * @param aUSBDevice The USB device structure for the last enumeration. * @param fFakeUpdate Flag whether to fake updating state. */ void USBProxyService::i_updateDeviceState(ComObjPtr<HostUSBDevice> &aDevice, PUSBDEVICE aUSBDevice, bool fFakeUpdate) { AssertReturnVoid(aDevice); AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread()); bool fRunFilters = false; SessionMachine *pIgnoreMachine = NULL; bool fDevChanged = false; if (fFakeUpdate) fDevChanged = aDevice->i_updateStateFake(aUSBDevice, &fRunFilters, &pIgnoreMachine); else fDevChanged = aDevice->i_updateState(aUSBDevice, &fRunFilters, &pIgnoreMachine); if (fDevChanged) deviceChanged(aDevice, fRunFilters, pIgnoreMachine); } /** * Handle a device which state changed in some significant way. * * This means things like running filters and subsequent capturing and * VM attaching. This may result in IPC and temporary lock abandonment. * * @param aDevice The device. * @param fRunFilters Flag whether to run filters. * @param aIgnoreMachine Machine to ignore when running filters. */ void USBProxyService::deviceChanged(ComObjPtr<HostUSBDevice> &aDevice, bool fRunFilters, SessionMachine *aIgnoreMachine) { /* * Validate preconditions. */ AssertReturnVoid(!isWriteLockOnCurrentThread()); AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread()); AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS); LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid} aRunFilters=%RTbool aIgnoreMachine=%p\n", (HostUSBDevice *)aDevice, aDevice->i_getName().c_str(), aDevice->i_getStateName(), aDevice->i_getId().raw(), fRunFilters, aIgnoreMachine)); devLock.release(); /* * Run filters if requested to do so. */ if (fRunFilters) { SessionMachinesList llOpenedMachines; mHost->i_parent()->i_getOpenedMachines(llOpenedMachines); HRESULT rc = runAllFiltersOnDevice(aDevice, llOpenedMachines, aIgnoreMachine); AssertComRC(rc); } } /** * Runs all the filters on the specified device. * * All filters mean global and active VM, with the exception of those * belonging to \a aMachine. If a global ignore filter matched or if * none of the filters matched, the device will be released back to * the host. * * The device calling us here will be in the HeldByProxy, Unused, or * Capturable state. The caller is aware that locks held might have * to be abandond because of IPC and that the device might be in * almost any state upon return. * * * @returns COM status code (only parameter & state checks will fail). * @param aDevice The USB device to apply filters to. * @param llOpenedMachines The list of opened machines. * @param aIgnoreMachine The machine to ignore filters from (we've just * detached the device from this machine). * * @note The caller is expected to own no locks. */ HRESULT USBProxyService::runAllFiltersOnDevice(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList &llOpenedMachines, SessionMachine *aIgnoreMachine) { LogFlowThisFunc(("{%s} ignoring=%p\n", aDevice->i_getName().c_str(), aIgnoreMachine)); /* * Verify preconditions. */ AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL); AssertReturn(!aDevice->isWriteLockOnCurrentThread(), E_FAIL); /* * Get the lists we'll iterate. */ Host::USBDeviceFilterList globalFilters; mHost->i_getUSBFilters(&globalFilters); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS); AssertMsgReturn(aDevice->i_isCapturableOrHeld(), ("{%s} %s\n", aDevice->i_getName().c_str(), aDevice->i_getStateName()), E_FAIL); /* * Run global filters filters first. */ bool fHoldIt = false; for (Host::USBDeviceFilterList::const_iterator it = globalFilters.begin(); it != globalFilters.end(); ++it) { AutoWriteLock filterLock(*it COMMA_LOCKVAL_SRC_POS); const HostUSBDeviceFilter::BackupableUSBDeviceFilterData &data = (*it)->i_getData(); if (aDevice->i_isMatch(data)) { USBDeviceFilterAction_T action = USBDeviceFilterAction_Null; (*it)->COMGETTER(Action)(&action); if (action == USBDeviceFilterAction_Ignore) { /* * Release the device to the host and we're done. */ filterLock.release(); devLock.release(); alock.release(); aDevice->i_requestReleaseToHost(); return S_OK; } if (action == USBDeviceFilterAction_Hold) { /* * A device held by the proxy needs to be subjected * to the machine filters. */ fHoldIt = true; break; } AssertMsgFailed(("action=%d\n", action)); } } globalFilters.clear(); /* * Run the per-machine filters. */ for (SessionMachinesList::const_iterator it = llOpenedMachines.begin(); it != llOpenedMachines.end(); ++it) { ComObjPtr<SessionMachine> pMachine = *it; /* Skip the machine the device was just detached from. */ if ( aIgnoreMachine && pMachine == aIgnoreMachine) continue; /* runMachineFilters takes care of checking the machine state. */ devLock.release(); alock.release(); if (runMachineFilters(pMachine, aDevice)) { LogFlowThisFunc(("{%s} attached to %p\n", aDevice->i_getName().c_str(), (void *)pMachine)); return S_OK; } alock.acquire(); devLock.acquire(); } /* * No matching machine, so request hold or release depending * on global filter match. */ devLock.release(); alock.release(); if (fHoldIt) aDevice->i_requestHold(); else aDevice->i_requestReleaseToHost(); return S_OK; } /** * Runs the USB filters of the machine on the device. * * If a match is found we will request capture for VM. This may cause * us to temporary abandon locks while doing IPC. * * @param aMachine Machine whose filters are to be run. * @param aDevice The USB device in question. * @returns @c true if the device has been or is being attached to the VM, @c false otherwise. * * @note Locks several objects temporarily for reading or writing. */ bool USBProxyService::runMachineFilters(SessionMachine *aMachine, ComObjPtr<HostUSBDevice> &aDevice) { LogFlowThisFunc(("{%s} aMachine=%p \n", aDevice->i_getName().c_str(), aMachine)); /* * Validate preconditions. */ AssertReturn(aMachine, false); AssertReturn(!isWriteLockOnCurrentThread(), false); AssertReturn(!aMachine->isWriteLockOnCurrentThread(), false); AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false); /* Let HostUSBDevice::requestCaptureToVM() validate the state. */ /* * Do the job. */ ULONG ulMaskedIfs; if (aMachine->i_hasMatchingUSBFilter(aDevice, &ulMaskedIfs)) { /* try to capture the device */ HRESULT hrc = aDevice->i_requestCaptureForVM(aMachine, false /* aSetError */, Utf8Str(), ulMaskedIfs); return SUCCEEDED(hrc) || hrc == E_UNEXPECTED /* bad device state, give up */; } return false; } /** * Searches the list of devices (mDevices) for the given device. * * * @returns Smart pointer to the device on success, NULL otherwise. * @param aId The UUID of the device we're looking for. */ ComObjPtr<HostUSBDevice> USBProxyService::findDeviceById(IN_GUID aId) { Guid Id(aId); ComObjPtr<HostUSBDevice> Dev; for (HostUSBDeviceList::iterator it = mDevices.begin(); it != mDevices.end(); ++it) if ((*it)->i_getId() == Id) { Dev = (*it); break; } return Dev; } /** * Creates a new USB device source. * * @returns COM status code. * @param aBackend The backend to use. * @param aId The ID of the source. * @param aAddress The backend specific address. * @param aPropertyNames Vector of optional property keys the backend supports. * @param aPropertyValues Vector of optional property values the backend supports. * @param fLoadingSettings Flag whether the USB device source is created while the * settings are loaded or through the Main API. */ HRESULT USBProxyService::createUSBDeviceSource(const com::Utf8Str &aBackend, const com::Utf8Str &aId, const com::Utf8Str &aAddress, const std::vector<com::Utf8Str> &aPropertyNames, const std::vector<com::Utf8Str> &aPropertyValues, bool fLoadingSettings) { HRESULT hrc = S_OK; AssertReturn(isWriteLockOnCurrentThread(), E_FAIL); /** @todo */ NOREF(aPropertyNames); NOREF(aPropertyValues); /* Check whether the ID is used first. */ for (USBProxyBackendList::iterator it = mBackends.begin(); it != mBackends.end(); ++it) { USBProxyBackend *pUsbProxyBackend = *it; if (aId.equals(pUsbProxyBackend->i_getId())) return setError(VBOX_E_OBJECT_IN_USE, tr("The USB device source \"%s\" exists already"), aId.c_str()); } /* Create appropriate proxy backend. */ if (aBackend.equalsIgnoreCase("USBIP")) { ComObjPtr<USBProxyBackendUsbIp> UsbProxyBackend; UsbProxyBackend.createObject(); int vrc = UsbProxyBackend->init(this, aId, aAddress, fLoadingSettings); if (RT_FAILURE(vrc)) hrc = setError(E_FAIL, tr("Creating the USB device source \"%s\" using backend \"%s\" failed with %Rrc"), aId.c_str(), aBackend.c_str(), vrc); else mBackends.push_back(static_cast<ComObjPtr<USBProxyBackend> >(UsbProxyBackend)); } else hrc = setError(VBOX_E_OBJECT_NOT_FOUND, tr("The USB backend \"%s\" is not supported"), aBackend.c_str()); return hrc; } /*static*/ HRESULT USBProxyService::setError(HRESULT aResultCode, const char *aText, ...) { va_list va; va_start(va, aText); HRESULT rc = VirtualBoxBase::setErrorInternal(aResultCode, COM_IIDOF(IHost), "USBProxyService", Utf8Str(aText, va), false /* aWarning*/, true /* aLogIt*/); va_end(va); return rc; } /* vi: set tabstop=4 shiftwidth=4 expandtab: */
13,146
1,350
<reponame>billwert/azure-sdk-for-java<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.servicefabric.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.servicefabric.models.AddOnFeatures; import com.azure.resourcemanager.servicefabric.models.ApplicationTypeVersionsCleanupPolicy; import com.azure.resourcemanager.servicefabric.models.CertificateDescription; import com.azure.resourcemanager.servicefabric.models.ClientCertificateCommonName; import com.azure.resourcemanager.servicefabric.models.ClientCertificateThumbprint; import com.azure.resourcemanager.servicefabric.models.ClusterUpgradeCadence; import com.azure.resourcemanager.servicefabric.models.ClusterUpgradePolicy; import com.azure.resourcemanager.servicefabric.models.NodeTypeDescription; import com.azure.resourcemanager.servicefabric.models.Notification; import com.azure.resourcemanager.servicefabric.models.ReliabilityLevel; import com.azure.resourcemanager.servicefabric.models.ServerCertificateCommonNames; import com.azure.resourcemanager.servicefabric.models.SettingsSectionDescription; import com.azure.resourcemanager.servicefabric.models.SfZonalUpgradeMode; import com.azure.resourcemanager.servicefabric.models.UpgradeMode; import com.azure.resourcemanager.servicefabric.models.VmssZonalUpgradeMode; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; /** Describes the cluster resource properties that can be updated during PATCH operation. */ @Fluent public final class ClusterPropertiesUpdateParameters { @JsonIgnore private final ClientLogger logger = new ClientLogger(ClusterPropertiesUpdateParameters.class); /* * The list of add-on features to enable in the cluster. */ @JsonProperty(value = "addOnFeatures") private List<AddOnFeatures> addOnFeatures; /* * The certificate to use for securing the cluster. The certificate * provided will be used for node to node security within the cluster, SSL * certificate for cluster management endpoint and default admin client. */ @JsonProperty(value = "certificate") private CertificateDescription certificate; /* * Describes a list of server certificates referenced by common name that * are used to secure the cluster. */ @JsonProperty(value = "certificateCommonNames") private ServerCertificateCommonNames certificateCommonNames; /* * The list of client certificates referenced by common name that are * allowed to manage the cluster. This will overwrite the existing list. */ @JsonProperty(value = "clientCertificateCommonNames") private List<ClientCertificateCommonName> clientCertificateCommonNames; /* * The list of client certificates referenced by thumbprint that are * allowed to manage the cluster. This will overwrite the existing list. */ @JsonProperty(value = "clientCertificateThumbprints") private List<ClientCertificateThumbprint> clientCertificateThumbprints; /* * The Service Fabric runtime version of the cluster. This property can * only by set the user when **upgradeMode** is set to 'Manual'. To get * list of available Service Fabric versions for new clusters use * [ClusterVersion API](./ClusterVersion.md). To get the list of available * version for existing clusters use **availableClusterVersions**. */ @JsonProperty(value = "clusterCodeVersion") private String clusterCodeVersion; /* * Indicates if the event store service is enabled. */ @JsonProperty(value = "eventStoreServiceEnabled") private Boolean eventStoreServiceEnabled; /* * The list of custom fabric settings to configure the cluster. This will * overwrite the existing list. */ @JsonProperty(value = "fabricSettings") private List<SettingsSectionDescription> fabricSettings; /* * The list of node types in the cluster. This will overwrite the existing * list. */ @JsonProperty(value = "nodeTypes") private List<NodeTypeDescription> nodeTypes; /* * The reliability level sets the replica set size of system services. * Learn about * [ReliabilityLevel](https://docs.microsoft.com/azure/service-fabric/service-fabric-cluster-capacity). * * - None - Run the System services with a target replica set count of 1. * This should only be used for test clusters. * - Bronze - Run the System services with a target replica set count of 3. * This should only be used for test clusters. * - Silver - Run the System services with a target replica set count of 5. * - Gold - Run the System services with a target replica set count of 7. * - Platinum - Run the System services with a target replica set count of * 9. * */ @JsonProperty(value = "reliabilityLevel") private ReliabilityLevel reliabilityLevel; /* * The server certificate used by reverse proxy. */ @JsonProperty(value = "reverseProxyCertificate") private CertificateDescription reverseProxyCertificate; /* * The policy to use when upgrading the cluster. */ @JsonProperty(value = "upgradeDescription") private ClusterUpgradePolicy upgradeDescription; /* * The policy used to clean up unused versions. */ @JsonProperty(value = "applicationTypeVersionsCleanupPolicy") private ApplicationTypeVersionsCleanupPolicy applicationTypeVersionsCleanupPolicy; /* * The upgrade mode of the cluster when new Service Fabric runtime version * is available. */ @JsonProperty(value = "upgradeMode") private UpgradeMode upgradeMode; /* * This property controls the logical grouping of VMs in upgrade domains * (UDs). This property can't be modified if a node type with multiple * Availability Zones is already present in the cluster. */ @JsonProperty(value = "sfZonalUpgradeMode") private SfZonalUpgradeMode sfZonalUpgradeMode; /* * This property defines the upgrade mode for the virtual machine scale * set, it is mandatory if a node type with multiple Availability Zones is * added. */ @JsonProperty(value = "vmssZonalUpgradeMode") private VmssZonalUpgradeMode vmssZonalUpgradeMode; /* * Indicates if infrastructure service manager is enabled. */ @JsonProperty(value = "infrastructureServiceManager") private Boolean infrastructureServiceManager; /* * Indicates when new cluster runtime version upgrades will be applied * after they are released. By default is Wave0. Only applies when * **upgradeMode** is set to 'Automatic'. */ @JsonProperty(value = "upgradeWave") private ClusterUpgradeCadence upgradeWave; /* * The start timestamp to pause runtime version upgrades on the cluster * (UTC). */ @JsonProperty(value = "upgradePauseStartTimestampUtc") private OffsetDateTime upgradePauseStartTimestampUtc; /* * The end timestamp of pause runtime version upgrades on the cluster * (UTC). */ @JsonProperty(value = "upgradePauseEndTimestampUtc") private OffsetDateTime upgradePauseEndTimestampUtc; /* * Boolean to pause automatic runtime version upgrades to the cluster. */ @JsonProperty(value = "waveUpgradePaused") private Boolean waveUpgradePaused; /* * Indicates a list of notification channels for cluster events. */ @JsonProperty(value = "notifications") private List<Notification> notifications; /** * Get the addOnFeatures property: The list of add-on features to enable in the cluster. * * @return the addOnFeatures value. */ public List<AddOnFeatures> addOnFeatures() { return this.addOnFeatures; } /** * Set the addOnFeatures property: The list of add-on features to enable in the cluster. * * @param addOnFeatures the addOnFeatures value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withAddOnFeatures(List<AddOnFeatures> addOnFeatures) { this.addOnFeatures = addOnFeatures; return this; } /** * Get the certificate property: The certificate to use for securing the cluster. The certificate provided will be * used for node to node security within the cluster, SSL certificate for cluster management endpoint and default * admin client. * * @return the certificate value. */ public CertificateDescription certificate() { return this.certificate; } /** * Set the certificate property: The certificate to use for securing the cluster. The certificate provided will be * used for node to node security within the cluster, SSL certificate for cluster management endpoint and default * admin client. * * @param certificate the certificate value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withCertificate(CertificateDescription certificate) { this.certificate = certificate; return this; } /** * Get the certificateCommonNames property: Describes a list of server certificates referenced by common name that * are used to secure the cluster. * * @return the certificateCommonNames value. */ public ServerCertificateCommonNames certificateCommonNames() { return this.certificateCommonNames; } /** * Set the certificateCommonNames property: Describes a list of server certificates referenced by common name that * are used to secure the cluster. * * @param certificateCommonNames the certificateCommonNames value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withCertificateCommonNames( ServerCertificateCommonNames certificateCommonNames) { this.certificateCommonNames = certificateCommonNames; return this; } /** * Get the clientCertificateCommonNames property: The list of client certificates referenced by common name that are * allowed to manage the cluster. This will overwrite the existing list. * * @return the clientCertificateCommonNames value. */ public List<ClientCertificateCommonName> clientCertificateCommonNames() { return this.clientCertificateCommonNames; } /** * Set the clientCertificateCommonNames property: The list of client certificates referenced by common name that are * allowed to manage the cluster. This will overwrite the existing list. * * @param clientCertificateCommonNames the clientCertificateCommonNames value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withClientCertificateCommonNames( List<ClientCertificateCommonName> clientCertificateCommonNames) { this.clientCertificateCommonNames = clientCertificateCommonNames; return this; } /** * Get the clientCertificateThumbprints property: The list of client certificates referenced by thumbprint that are * allowed to manage the cluster. This will overwrite the existing list. * * @return the clientCertificateThumbprints value. */ public List<ClientCertificateThumbprint> clientCertificateThumbprints() { return this.clientCertificateThumbprints; } /** * Set the clientCertificateThumbprints property: The list of client certificates referenced by thumbprint that are * allowed to manage the cluster. This will overwrite the existing list. * * @param clientCertificateThumbprints the clientCertificateThumbprints value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withClientCertificateThumbprints( List<ClientCertificateThumbprint> clientCertificateThumbprints) { this.clientCertificateThumbprints = clientCertificateThumbprints; return this; } /** * Get the clusterCodeVersion property: The Service Fabric runtime version of the cluster. This property can only by * set the user when **upgradeMode** is set to 'Manual'. To get list of available Service Fabric versions for new * clusters use [ClusterVersion API](./ClusterVersion.md). To get the list of available version for existing * clusters use **availableClusterVersions**. * * @return the clusterCodeVersion value. */ public String clusterCodeVersion() { return this.clusterCodeVersion; } /** * Set the clusterCodeVersion property: The Service Fabric runtime version of the cluster. This property can only by * set the user when **upgradeMode** is set to 'Manual'. To get list of available Service Fabric versions for new * clusters use [ClusterVersion API](./ClusterVersion.md). To get the list of available version for existing * clusters use **availableClusterVersions**. * * @param clusterCodeVersion the clusterCodeVersion value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withClusterCodeVersion(String clusterCodeVersion) { this.clusterCodeVersion = clusterCodeVersion; return this; } /** * Get the eventStoreServiceEnabled property: Indicates if the event store service is enabled. * * @return the eventStoreServiceEnabled value. */ public Boolean eventStoreServiceEnabled() { return this.eventStoreServiceEnabled; } /** * Set the eventStoreServiceEnabled property: Indicates if the event store service is enabled. * * @param eventStoreServiceEnabled the eventStoreServiceEnabled value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withEventStoreServiceEnabled(Boolean eventStoreServiceEnabled) { this.eventStoreServiceEnabled = eventStoreServiceEnabled; return this; } /** * Get the fabricSettings property: The list of custom fabric settings to configure the cluster. This will overwrite * the existing list. * * @return the fabricSettings value. */ public List<SettingsSectionDescription> fabricSettings() { return this.fabricSettings; } /** * Set the fabricSettings property: The list of custom fabric settings to configure the cluster. This will overwrite * the existing list. * * @param fabricSettings the fabricSettings value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withFabricSettings(List<SettingsSectionDescription> fabricSettings) { this.fabricSettings = fabricSettings; return this; } /** * Get the nodeTypes property: The list of node types in the cluster. This will overwrite the existing list. * * @return the nodeTypes value. */ public List<NodeTypeDescription> nodeTypes() { return this.nodeTypes; } /** * Set the nodeTypes property: The list of node types in the cluster. This will overwrite the existing list. * * @param nodeTypes the nodeTypes value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withNodeTypes(List<NodeTypeDescription> nodeTypes) { this.nodeTypes = nodeTypes; return this; } /** * Get the reliabilityLevel property: The reliability level sets the replica set size of system services. Learn * about [ReliabilityLevel](https://docs.microsoft.com/azure/service-fabric/service-fabric-cluster-capacity). * * <p>- None - Run the System services with a target replica set count of 1. This should only be used for test * clusters. - Bronze - Run the System services with a target replica set count of 3. This should only be used for * test clusters. - Silver - Run the System services with a target replica set count of 5. - Gold - Run the System * services with a target replica set count of 7. - Platinum - Run the System services with a target replica set * count of 9. * * @return the reliabilityLevel value. */ public ReliabilityLevel reliabilityLevel() { return this.reliabilityLevel; } /** * Set the reliabilityLevel property: The reliability level sets the replica set size of system services. Learn * about [ReliabilityLevel](https://docs.microsoft.com/azure/service-fabric/service-fabric-cluster-capacity). * * <p>- None - Run the System services with a target replica set count of 1. This should only be used for test * clusters. - Bronze - Run the System services with a target replica set count of 3. This should only be used for * test clusters. - Silver - Run the System services with a target replica set count of 5. - Gold - Run the System * services with a target replica set count of 7. - Platinum - Run the System services with a target replica set * count of 9. * * @param reliabilityLevel the reliabilityLevel value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withReliabilityLevel(ReliabilityLevel reliabilityLevel) { this.reliabilityLevel = reliabilityLevel; return this; } /** * Get the reverseProxyCertificate property: The server certificate used by reverse proxy. * * @return the reverseProxyCertificate value. */ public CertificateDescription reverseProxyCertificate() { return this.reverseProxyCertificate; } /** * Set the reverseProxyCertificate property: The server certificate used by reverse proxy. * * @param reverseProxyCertificate the reverseProxyCertificate value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withReverseProxyCertificate( CertificateDescription reverseProxyCertificate) { this.reverseProxyCertificate = reverseProxyCertificate; return this; } /** * Get the upgradeDescription property: The policy to use when upgrading the cluster. * * @return the upgradeDescription value. */ public ClusterUpgradePolicy upgradeDescription() { return this.upgradeDescription; } /** * Set the upgradeDescription property: The policy to use when upgrading the cluster. * * @param upgradeDescription the upgradeDescription value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withUpgradeDescription(ClusterUpgradePolicy upgradeDescription) { this.upgradeDescription = upgradeDescription; return this; } /** * Get the applicationTypeVersionsCleanupPolicy property: The policy used to clean up unused versions. * * @return the applicationTypeVersionsCleanupPolicy value. */ public ApplicationTypeVersionsCleanupPolicy applicationTypeVersionsCleanupPolicy() { return this.applicationTypeVersionsCleanupPolicy; } /** * Set the applicationTypeVersionsCleanupPolicy property: The policy used to clean up unused versions. * * @param applicationTypeVersionsCleanupPolicy the applicationTypeVersionsCleanupPolicy value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withApplicationTypeVersionsCleanupPolicy( ApplicationTypeVersionsCleanupPolicy applicationTypeVersionsCleanupPolicy) { this.applicationTypeVersionsCleanupPolicy = applicationTypeVersionsCleanupPolicy; return this; } /** * Get the upgradeMode property: The upgrade mode of the cluster when new Service Fabric runtime version is * available. * * @return the upgradeMode value. */ public UpgradeMode upgradeMode() { return this.upgradeMode; } /** * Set the upgradeMode property: The upgrade mode of the cluster when new Service Fabric runtime version is * available. * * @param upgradeMode the upgradeMode value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withUpgradeMode(UpgradeMode upgradeMode) { this.upgradeMode = upgradeMode; return this; } /** * Get the sfZonalUpgradeMode property: This property controls the logical grouping of VMs in upgrade domains (UDs). * This property can't be modified if a node type with multiple Availability Zones is already present in the * cluster. * * @return the sfZonalUpgradeMode value. */ public SfZonalUpgradeMode sfZonalUpgradeMode() { return this.sfZonalUpgradeMode; } /** * Set the sfZonalUpgradeMode property: This property controls the logical grouping of VMs in upgrade domains (UDs). * This property can't be modified if a node type with multiple Availability Zones is already present in the * cluster. * * @param sfZonalUpgradeMode the sfZonalUpgradeMode value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withSfZonalUpgradeMode(SfZonalUpgradeMode sfZonalUpgradeMode) { this.sfZonalUpgradeMode = sfZonalUpgradeMode; return this; } /** * Get the vmssZonalUpgradeMode property: This property defines the upgrade mode for the virtual machine scale set, * it is mandatory if a node type with multiple Availability Zones is added. * * @return the vmssZonalUpgradeMode value. */ public VmssZonalUpgradeMode vmssZonalUpgradeMode() { return this.vmssZonalUpgradeMode; } /** * Set the vmssZonalUpgradeMode property: This property defines the upgrade mode for the virtual machine scale set, * it is mandatory if a node type with multiple Availability Zones is added. * * @param vmssZonalUpgradeMode the vmssZonalUpgradeMode value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withVmssZonalUpgradeMode(VmssZonalUpgradeMode vmssZonalUpgradeMode) { this.vmssZonalUpgradeMode = vmssZonalUpgradeMode; return this; } /** * Get the infrastructureServiceManager property: Indicates if infrastructure service manager is enabled. * * @return the infrastructureServiceManager value. */ public Boolean infrastructureServiceManager() { return this.infrastructureServiceManager; } /** * Set the infrastructureServiceManager property: Indicates if infrastructure service manager is enabled. * * @param infrastructureServiceManager the infrastructureServiceManager value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withInfrastructureServiceManager(Boolean infrastructureServiceManager) { this.infrastructureServiceManager = infrastructureServiceManager; return this; } /** * Get the upgradeWave property: Indicates when new cluster runtime version upgrades will be applied after they are * released. By default is Wave0. Only applies when **upgradeMode** is set to 'Automatic'. * * @return the upgradeWave value. */ public ClusterUpgradeCadence upgradeWave() { return this.upgradeWave; } /** * Set the upgradeWave property: Indicates when new cluster runtime version upgrades will be applied after they are * released. By default is Wave0. Only applies when **upgradeMode** is set to 'Automatic'. * * @param upgradeWave the upgradeWave value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withUpgradeWave(ClusterUpgradeCadence upgradeWave) { this.upgradeWave = upgradeWave; return this; } /** * Get the upgradePauseStartTimestampUtc property: The start timestamp to pause runtime version upgrades on the * cluster (UTC). * * @return the upgradePauseStartTimestampUtc value. */ public OffsetDateTime upgradePauseStartTimestampUtc() { return this.upgradePauseStartTimestampUtc; } /** * Set the upgradePauseStartTimestampUtc property: The start timestamp to pause runtime version upgrades on the * cluster (UTC). * * @param upgradePauseStartTimestampUtc the upgradePauseStartTimestampUtc value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withUpgradePauseStartTimestampUtc( OffsetDateTime upgradePauseStartTimestampUtc) { this.upgradePauseStartTimestampUtc = upgradePauseStartTimestampUtc; return this; } /** * Get the upgradePauseEndTimestampUtc property: The end timestamp of pause runtime version upgrades on the cluster * (UTC). * * @return the upgradePauseEndTimestampUtc value. */ public OffsetDateTime upgradePauseEndTimestampUtc() { return this.upgradePauseEndTimestampUtc; } /** * Set the upgradePauseEndTimestampUtc property: The end timestamp of pause runtime version upgrades on the cluster * (UTC). * * @param upgradePauseEndTimestampUtc the upgradePauseEndTimestampUtc value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withUpgradePauseEndTimestampUtc( OffsetDateTime upgradePauseEndTimestampUtc) { this.upgradePauseEndTimestampUtc = upgradePauseEndTimestampUtc; return this; } /** * Get the waveUpgradePaused property: Boolean to pause automatic runtime version upgrades to the cluster. * * @return the waveUpgradePaused value. */ public Boolean waveUpgradePaused() { return this.waveUpgradePaused; } /** * Set the waveUpgradePaused property: Boolean to pause automatic runtime version upgrades to the cluster. * * @param waveUpgradePaused the waveUpgradePaused value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withWaveUpgradePaused(Boolean waveUpgradePaused) { this.waveUpgradePaused = waveUpgradePaused; return this; } /** * Get the notifications property: Indicates a list of notification channels for cluster events. * * @return the notifications value. */ public List<Notification> notifications() { return this.notifications; } /** * Set the notifications property: Indicates a list of notification channels for cluster events. * * @param notifications the notifications value to set. * @return the ClusterPropertiesUpdateParameters object itself. */ public ClusterPropertiesUpdateParameters withNotifications(List<Notification> notifications) { this.notifications = notifications; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (certificate() != null) { certificate().validate(); } if (certificateCommonNames() != null) { certificateCommonNames().validate(); } if (clientCertificateCommonNames() != null) { clientCertificateCommonNames().forEach(e -> e.validate()); } if (clientCertificateThumbprints() != null) { clientCertificateThumbprints().forEach(e -> e.validate()); } if (fabricSettings() != null) { fabricSettings().forEach(e -> e.validate()); } if (nodeTypes() != null) { nodeTypes().forEach(e -> e.validate()); } if (reverseProxyCertificate() != null) { reverseProxyCertificate().validate(); } if (upgradeDescription() != null) { upgradeDescription().validate(); } if (applicationTypeVersionsCleanupPolicy() != null) { applicationTypeVersionsCleanupPolicy().validate(); } if (notifications() != null) { notifications().forEach(e -> e.validate()); } } }
9,102
880
/** * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.qos.logback.classic.util; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertSame; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.junit.Test; import ch.qos.logback.core.testUtil.RandomUtil; public class LogbackMDCAdapterTest { final static String A_SUFFIX = "A_SUFFIX"; final static String B_SUFFIX = "B_SUFFIX"; int diff = RandomUtil.getPositiveInt(); private final LogbackMDCAdapter mdcAdapter = new LogbackMDCAdapter(); /** * Test that CopyOnInheritThreadLocal does not barf when the * MDC hashmap is null * * @throws InterruptedException */ @Test public void LOGBACK_442() throws InterruptedException { Map<String, String> parentHM = getMapFromMDCAdapter(mdcAdapter); assertNull(parentHM); ChildThreadForMDCAdapter childThread = new ChildThreadForMDCAdapter(mdcAdapter); childThread.start(); childThread.join(); assertTrue(childThread.successul); assertNull(childThread.childHM); } @Test public void removeForNullKeyTest() { mdcAdapter.remove(null); } @Test public void removeInexistentKey() { mdcAdapter.remove("abcdlw0"); } @Test public void sequenceWithGet() { mdcAdapter.put("k0", "v0"); Map<String, String> map0 = mdcAdapter.copyOnThreadLocal.get(); mdcAdapter.get("k0"); mdcAdapter.put("k1", "v1"); // no map copy required // verify that map0 is the same instance and that value was updated assertSame(map0, mdcAdapter.copyOnThreadLocal.get()); } @Test public void sequenceWithGetPropertyMap() { mdcAdapter.put("k0", "v0"); Map<String, String> map0 = mdcAdapter.getPropertyMap(); // point 0 mdcAdapter.put("k0", "v1"); // new map should be created // verify that map0 is that in point 0 assertEquals("v0", map0.get("k0")); } @Test public void sequenceWithCopyContextMap() { mdcAdapter.put("k0", "v0"); Map<String, String> map0 = mdcAdapter.copyOnThreadLocal.get(); mdcAdapter.getCopyOfContextMap(); mdcAdapter.put("k1", "v1"); // no map copy required // verify that map0 is the same instance and that value was updated assertSame(map0, mdcAdapter.copyOnThreadLocal.get()); } // ================================================= /** * Test that LogbackMDCAdapter does not copy its hashmap when a child * thread inherits it. * * @throws InterruptedException */ @Test public void noCopyOnInheritenceTest() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); String firstKey = "x" + diff; String secondKey = "o" + diff; mdcAdapter.put(firstKey, firstKey + A_SUFFIX); ChildThread childThread = new ChildThread(mdcAdapter, firstKey, secondKey, countDownLatch); childThread.start(); countDownLatch.await(); mdcAdapter.put(firstKey, firstKey + B_SUFFIX); childThread.join(); assertNull(mdcAdapter.get(secondKey)); assertTrue(childThread.successful); Map<String, String> parentHM = getMapFromMDCAdapter(mdcAdapter); assertTrue(parentHM != childThread.childHM); HashMap<String, String> parentHMWitness = new HashMap<String, String>(); parentHMWitness.put(firstKey, firstKey + B_SUFFIX); assertEquals(parentHMWitness, parentHM); HashMap<String, String> childHMWitness = new HashMap<String, String>(); childHMWitness.put(secondKey, secondKey + A_SUFFIX); assertEquals(childHMWitness, childThread.childHM); } // see also http://jira.qos.ch/browse/LBCLASSIC-253 @Test public void clearOnChildThreadShouldNotAffectParent() throws InterruptedException { String firstKey = "x" + diff; String secondKey = "o" + diff; mdcAdapter.put(firstKey, firstKey + A_SUFFIX); assertEquals(firstKey + A_SUFFIX, mdcAdapter.get(firstKey)); Thread clearer = new ChildThread(mdcAdapter, firstKey, secondKey) { @Override public void run() { mdcAdapter.clear(); assertNull(mdcAdapter.get(firstKey)); } }; clearer.start(); clearer.join(); assertEquals(firstKey + A_SUFFIX, mdcAdapter.get(firstKey)); } // see http://jira.qos.ch/browse/LBCLASSIC-289 // this test used to fail without synchronization code in LogbackMDCAdapter @Test public void nearSimultaneousPutsShouldNotCauseConcurrentModificationException() throws InterruptedException { // For the weirdest reason, modifications to mdcAdapter must be done // before the definition anonymous ChildThread class below. Otherwise, the // map in the child thread, the one contained in mdcAdapter.copyOnInheritThreadLocal, // is null. How strange is that? // let the map have lots of elements so that copying it takes time for (int i = 0; i < 2048; i++) { mdcAdapter.put("k" + i, "v" + i); } ChildThread childThread = new ChildThread(mdcAdapter, null, null) { @Override public void run() { for (int i = 0; i < 16; i++) { mdcAdapter.put("ck" + i, "cv" + i); Thread.yield(); } successful = true; } }; childThread.start(); Thread.sleep(1); for (int i = 0; i < 16; i++) { mdcAdapter.put("K" + i, "V" + i); } childThread.join(); assertTrue(childThread.successful); } Map<String, String> getMapFromMDCAdapter(LogbackMDCAdapter lma) { ThreadLocal<Map<String, String>> copyOnThreadLocal = lma.copyOnThreadLocal; return copyOnThreadLocal.get(); } // ========================== various thread classes class ChildThreadForMDCAdapter extends Thread { LogbackMDCAdapter logbackMDCAdapter; boolean successul; Map<String, String> childHM; ChildThreadForMDCAdapter(LogbackMDCAdapter logbackMDCAdapter) { this.logbackMDCAdapter = logbackMDCAdapter; } @Override public void run() { childHM = getMapFromMDCAdapter(logbackMDCAdapter); logbackMDCAdapter.get(""); successul = true; } } class ChildThread extends Thread { LogbackMDCAdapter logbackMDCAdapter; String firstKey; String secondKey; boolean successful; Map<String, String> childHM; CountDownLatch countDownLatch; ChildThread(LogbackMDCAdapter logbackMDCAdapter) { this(logbackMDCAdapter, null, null); } ChildThread(LogbackMDCAdapter logbackMDCAdapter, String firstKey, String secondKey) { this(logbackMDCAdapter, firstKey, secondKey, null); } ChildThread(LogbackMDCAdapter logbackMDCAdapter, String firstKey, String secondKey, CountDownLatch countDownLatch) { super("chil"); this.logbackMDCAdapter = logbackMDCAdapter; this.firstKey = firstKey; this.secondKey = secondKey; this.countDownLatch = countDownLatch; } @Override public void run() { logbackMDCAdapter.put(secondKey, secondKey + A_SUFFIX); assertNull(logbackMDCAdapter.get(firstKey)); if (countDownLatch != null) countDownLatch.countDown(); assertNotNull(logbackMDCAdapter.get(secondKey)); assertEquals(secondKey + A_SUFFIX, logbackMDCAdapter.get(secondKey)); successful = true; childHM = getMapFromMDCAdapter(logbackMDCAdapter); } } }
2,839
462
## # Copyright (c) 2009-2017 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## """ Generic ADAPI database access object. """ __all__ = [ "AbstractADBAPIDatabase", ] import threading try: from txdav.base.datastore.subpostgres import postgres except ImportError: postgres = None from twisted.enterprise.adbapi import ConnectionPool from twisted.internet.defer import inlineCallbacks, returnValue from twisted.python.threadpool import ThreadPool from twext.python.log import Logger from twistedcaldav.config import ConfigurationError log = Logger() class ConnectionCloseThread(threading.Thread): """ An L{Thread} that closes its DB connection when it has finished running. """ def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): if target is not None: self._realTarget = target target = self.targetWithConnectionClose super(ConnectionCloseThread, self).__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, verbose=verbose) def targetWithConnectionClose(self, *args, **kwargs): self._realTarget(*args, **kwargs) if hasattr(self, "_db_close"): self._db_close() class ConnectionClosingThreadPool(ThreadPool): """ A L{ThreadPool} that closes connections for each worker thread when stopped. """ threadFactory = ConnectionCloseThread def stop(self): for tid, conn in self.pool.connections.items(): for thread in self.threads: if thread.ident == tid: thread._db_close = lambda: self.pool.disconnect(conn) ThreadPool.stop(self) class AbstractADBAPIDatabase(object): """ A generic SQL database. """ def __init__(self, dbID, dbapiName, dbapiArgs, persistent, **kwargs): """ @param persistent: C{True} if the data in the DB must be perserved during upgrades, C{False} if the DB data can be re-created from an external source. @type persistent: bool """ self.dbID = dbID self.dbapiName = dbapiName self.dbapiArgs = dbapiArgs self.dbapikwargs = kwargs self.persistent = persistent self.initialized = False def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.pool) @inlineCallbacks def open(self): """ Access the underlying database. @return: a db2 connection object for this index's underlying data store. """ if not self.initialized: self.pool = ConnectionPool(self.dbapiName, *self.dbapiArgs, **self.dbapikwargs) # sqlite3 is not thread safe which means we have to close the sqlite3 connections in the same thread that # opened them. We need a special thread pool class that has a thread worker function that does a close # when a thread is closed. if self.dbapiName == "sqlite3": self.pool.threadpool.stop() self.pool.threadpool = ConnectionClosingThreadPool(1, 1) self.pool.threadpool.start() self.pool.threadpool.pool = self.pool # # Set up the schema # # Create CALDAV table if needed try: test = (yield self._test_schema_table()) if test: version = (yield self._db_value_for_sql("select VALUE from CALDAV where KEY = 'SCHEMA_VERSION'")) dbtype = (yield self._db_value_for_sql("select VALUE from CALDAV where KEY = 'TYPE'")) if (version != self._db_version()) or (dbtype != self._db_type()): if dbtype != self._db_type(): log.error( "Database {db} has different type ({t1} vs. {t2})", db=self.dbID, t1=dbtype, t2=self._db_type() ) # Delete this index and start over yield self._db_remove() yield self._db_init() elif version != self._db_version(): log.error( "Database {db} has different schema (v.{v1} vs. v.{v2})", db=self.dbID, v1=version, v2=self._db_version() ) # Upgrade the DB yield self._db_upgrade(version) else: yield self._db_init() self.initialized = True except: # Clean up upon error so we don't end up leaking threads self.pool.close() self.pool = None raise def close(self): if self.initialized: try: self.pool.close() except Exception, e: log.error("Error whilst closing connection pool: {ex}", ex=e) self.pool = None self.initialized = False @inlineCallbacks def clean(self): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: yield self._db_empty_data_tables() except Exception, e: log.error("Error in database clean: {ex}", ex=e) self.close() else: break @inlineCallbacks def execute(self, sql, *query_params): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: yield self._db_execute(sql, *query_params) except Exception, e: log.error("Error in database execute: {ex}", ex=e) self.close() else: break @inlineCallbacks def executescript(self, script): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: yield self._db_execute_script(script) except Exception, e: log.error("Error in database executescript: {ex}", ex=e) self.close() else: break @inlineCallbacks def query(self, sql, *query_params): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: result = (yield self._db_all_values_for_sql(sql, *query_params)) except Exception, e: log.error("Error in database query: {ex}", ex=e) self.close() else: break returnValue(result) @inlineCallbacks def queryList(self, sql, *query_params): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: result = (yield self._db_values_for_sql(sql, *query_params)) except Exception, e: log.error("Error in database queryList: {ex}", ex=e) self.close() else: break returnValue(result) @inlineCallbacks def queryOne(self, sql, *query_params): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: result = (yield self._db_value_for_sql(sql, *query_params)) except Exception, e: log.error("Error in database queryOne: {ex}", ex=e) self.close() else: break returnValue(result) def _db_version(self): """ @return: the schema version assigned to this DB. """ raise NotImplementedError def _db_type(self): """ @return: the collection type assigned to this DB. """ raise NotImplementedError def _test_schema_table(self): return self._test_table("CALDAV") @inlineCallbacks def _db_init(self): """ Initialise the underlying database tables. """ log.info("Initializing database {db}", db=self.dbID) # TODO we need an exclusive lock of some kind here to prevent a race condition # in which multiple processes try to create the tables. yield self._db_init_schema_table() yield self._db_init_data_tables() yield self._db_recreate() @inlineCallbacks def _db_init_schema_table(self): """ Initialise the underlying database tables. @param db_filename: the file name of the index database. @param q: a database cursor to use. """ # # CALDAV table keeps track of our schema version and type # yield self._create_table("CALDAV", ( ("KEY", "text unique"), ("VALUE", "text unique"), ), True) yield self._db_execute( """ insert or ignore into CALDAV (KEY, VALUE) values ('SCHEMA_VERSION', :1) """, (self._db_version(),) ) yield self._db_execute( """ insert or ignore into CALDAV (KEY, VALUE) values ('TYPE', :1) """, (self._db_type(),) ) def _db_init_data_tables(self): """ Initialise the underlying database tables. """ raise NotImplementedError def _db_empty_data_tables(self): """ Delete the database tables. """ # Implementations can override this to re-create data pass def _db_recreate(self): """ Recreate the database tables. """ # Implementations can override this to re-create data pass @inlineCallbacks def _db_upgrade(self, old_version): """ Upgrade the database tables. """ if self.persistent: yield self._db_upgrade_data_tables(old_version) yield self._db_upgrade_schema() else: # Non-persistent DB's by default can be removed and re-created. However, for simple # DB upgrades they SHOULD override this method and handle those for better performance. yield self._db_remove() yield self._db_init() def _db_upgrade_data_tables(self, old_version): """ Upgrade the data from an older version of the DB. """ # Persistent DB's MUST override this method and do a proper upgrade. Their data # cannot be thrown away. raise NotImplementedError("Persistent databases MUST support an upgrade method.") @inlineCallbacks def _db_upgrade_schema(self): """ Upgrade the stored schema version to the current one. """ yield self._db_execute("insert or replace into CALDAV (KEY, VALUE) values ('SCHEMA_VERSION', :1)", (self._db_version(),)) @inlineCallbacks def _db_remove(self): """ Remove all database information (all the tables) """ yield self._db_remove_data_tables() yield self._db_remove_schema() def _db_remove_data_tables(self): """ Remove all the data from an older version of the DB. """ raise NotImplementedError("Each database must remove its own tables.") @inlineCallbacks def _db_remove_schema(self): """ Remove the stored schema version table. """ yield self._db_execute("drop table if exists CALDAV") @inlineCallbacks def _db_all_values_for_sql(self, sql, *query_params): """ Execute an SQL query and obtain the resulting values. @param sql: the SQL query to execute. @param query_params: parameters to C{sql}. @return: an interable of values in the first column of each row resulting from executing C{sql} with C{query_params}. @raise AssertionError: if the query yields multiple columns. """ sql = self._prepare_statement(sql) results = (yield self.pool.runQuery(sql, *query_params)) returnValue(tuple(results)) @inlineCallbacks def _db_values_for_sql(self, sql, *query_params): """ Execute an SQL query and obtain the resulting values. @param sql: the SQL query to execute. @param query_params: parameters to C{sql}. @return: an interable of values in the first column of each row resulting from executing C{sql} with C{query_params}. @raise AssertionError: if the query yields multiple columns. """ sql = self._prepare_statement(sql) results = (yield self.pool.runQuery(sql, *query_params)) returnValue(tuple([row[0] for row in results])) @inlineCallbacks def _db_value_for_sql(self, sql, *query_params): """ Execute an SQL query and obtain a single value. @param sql: the SQL query to execute. @param query_params: parameters to C{sql}. @return: the value resulting from the executing C{sql} with C{query_params}. @raise AssertionError: if the query yields multiple rows or columns. """ value = None for row in (yield self._db_values_for_sql(sql, *query_params)): assert value is None, "Multiple values in DB for %s %s" % (sql, query_params) value = row returnValue(value) def _db_execute(self, sql, *query_params): """ Execute an SQL operation that returns None. @param sql: the SQL query to execute. @param query_params: parameters to C{sql}. @return: an iterable of tuples for each row resulting from executing C{sql} with C{query_params}. """ sql = self._prepare_statement(sql) return self.pool.runOperation(sql, *query_params) """ Since different databases support different types of columns and modifiers on those we need to have an "abstract" way of specifying columns in our code and then map the abstract specifiers to the underlying DB's allowed types. Types we can use are: integer text text(n) date serial The " unique" modifier can be appended to any of those. """ def _map_column_types(self, type): raise NotImplementedError def _create_table(self, name, columns, ifnotexists=False): raise NotImplementedError def _test_table(self, name): raise NotImplementedError def _create_index(self, name, ontable, columns, ifnotexists=False): raise NotImplementedError def _prepare_statement(self, sql): raise NotImplementedError class ADBAPISqliteMixin(object): @classmethod def _map_column_types(self, coltype): result = "" splits = coltype.split() if splits[0] == "integer": result = "integer" elif splits[0] == "text": result = "text" elif splits[0].startswith("text("): result = splits[0] elif splits[0] == "date": result = "date" elif splits[0] == "serial": result = "integer primary key autoincrement" if len(splits) > 1 and splits[1] == "unique": result += " unique" return result @inlineCallbacks def _create_table(self, name, columns, ifnotexists=False): colDefs = ["%s %s" % (colname, self._map_column_types(coltype)) for colname, coltype in columns] statement = "create table %s%s (%s)" % ( "if not exists " if ifnotexists else "", name, ", ".join(colDefs), ) yield self._db_execute(statement) @inlineCallbacks def _test_table(self, name): result = (yield self._db_value_for_sql(""" select (1) from SQLITE_MASTER where TYPE = 'table' and NAME = '%s' """ % (name,))) returnValue(result) @inlineCallbacks def _create_index(self, name, ontable, columns, ifnotexists=False): statement = "create index %s%s on %s (%s)" % ( "if not exists " if ifnotexists else "", name, ontable, ", ".join(columns), ) yield self._db_execute(statement) def _prepare_statement(self, sql): # We are going to use the sqlite syntax of :1, :2 etc for our # internal statements so we do not need to remap those return sql if postgres: class ADBAPIPostgreSQLMixin(object): @classmethod def _map_column_types(self, coltype): result = "" splits = coltype.split() if splits[0] == "integer": result = "integer" elif splits[0] == "text": result = "text" elif splits[0].startswith("text("): result = "char" + splits[0][4:] elif splits[0] == "date": result = "date" elif splits[0] == "serial": result = "serial" if len(splits) > 1 and splits[1] == "unique": result += " unique" return result @inlineCallbacks def _create_table(self, name, columns, ifnotexists=False): colDefs = ["%s %s" % (colname, self._map_column_types(coltype)) for colname, coltype in columns] statement = "create table %s (%s)" % ( name, ", ".join(colDefs), ) try: yield self._db_execute(statement) except postgres.DatabaseError: if not ifnotexists: raise result = (yield self._test_table(name)) if not result: raise @inlineCallbacks def _test_table(self, name): result = (yield self._db_value_for_sql(""" select * from pg_tables where tablename = '%s' """ % (name.lower(),))) returnValue(result) @inlineCallbacks def _create_index(self, name, ontable, columns, ifnotexists=False): statement = "create index %s on %s (%s)" % ( name, ontable, ", ".join(columns), ) try: yield self._db_execute(statement) except postgres.DatabaseError: if not ifnotexists: raise result = (yield self._test_table(name)) if not result: raise @inlineCallbacks def _db_init_schema_table(self): """ Initialise the underlying database tables. @param db_filename: the file name of the index database. @param q: a database cursor to use. """ # # CALDAV table keeps track of our schema version and type # try: yield self._create_table("CALDAV", ( ("KEY", "text unique"), ("VALUE", "text unique"), ), True) yield self._db_execute( """ insert into CALDAV (KEY, VALUE) values ('SCHEMA_VERSION', :1) """, (self._db_version(),) ) yield self._db_execute( """ insert into CALDAV (KEY, VALUE) values ('TYPE', :1) """, (self._db_type(),) ) except postgres.DatabaseError: pass def _prepare_statement(self, sql): # Convert :1, :2 etc format into %s ctr = 1 while sql.find(":%d" % (ctr,)) != -1: sql = sql.replace(":%d" % (ctr,), "%s") ctr += 1 return sql else: class ADBAPIPostgreSQLMixin(object): def __init__(self): raise ConfigurationError("PostgreSQL module not available.")
9,812
410
<reponame>GyPapi/RHash<gh_stars>100-1000 /* tth.c - calculate TTH (Tiger Tree Hash) function. * * Copyright (c) 2007, <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #include "byte_order.h" #include "tth.h" /** * Initialize context before calculaing hash. * * @param ctx context to initialize */ void rhash_tth_init(tth_ctx* ctx) { rhash_tiger_init(&ctx->tiger); ctx->tiger.message[ ctx->tiger.length++ ] = 0x00; ctx->block_count = 0; } /** * The core transformation. * * @param ctx algorithm state */ static void rhash_tth_process_block(tth_ctx* ctx) { uint64_t it; unsigned pos = 0; unsigned char msg[24]; for (it = 1; it & ctx->block_count; it <<= 1) { rhash_tiger_final(&ctx->tiger, msg); rhash_tiger_init(&ctx->tiger); ctx->tiger.message[ctx->tiger.length++] = 0x01; rhash_tiger_update(&ctx->tiger, (unsigned char*)(ctx->stack + pos), 24); /* note: we can cut this step, if the previous rhash_tiger_final saves directly to ctx->tiger.message+25; */ rhash_tiger_update(&ctx->tiger, msg, 24); pos += 3; } rhash_tiger_final(&ctx->tiger, (unsigned char*)(ctx->stack + pos)); ctx->block_count++; } /** * Calculate message hash. * Can be called repeatedly with chunks of the message to be hashed. * * @param ctx the algorithm context containing current hashing state * @param msg message chunk * @param size length of the message chunk */ void rhash_tth_update(tth_ctx* ctx, const unsigned char* msg, size_t size) { size_t rest = 1025 - (size_t)ctx->tiger.length; for (;;) { if (size < rest) rest = size; rhash_tiger_update(&ctx->tiger, msg, rest); msg += rest; size -= rest; if (ctx->tiger.length < 1025) { return; } /* process block hash */ rhash_tth_process_block(ctx); /* init block hash */ rhash_tiger_init(&ctx->tiger); ctx->tiger.message[ ctx->tiger.length++ ] = 0x00; rest = 1024; } } /** * Store calculated hash into the given array. * * @param ctx the algorithm context containing current hashing state * @param result calculated hash in binary form */ void rhash_tth_final(tth_ctx* ctx, unsigned char result[24]) { uint64_t it = 1; unsigned pos = 0; unsigned char msg[24]; const unsigned char* last_message; /* process the bytes left in the context buffer */ if (ctx->tiger.length > 1 || ctx->block_count == 0) { rhash_tth_process_block(ctx); } for (; it < ctx->block_count && (it & ctx->block_count) == 0; it <<= 1) pos += 3; last_message = (unsigned char*)(ctx->stack + pos); for (it <<= 1; it <= ctx->block_count; it <<= 1) { /* merge TTH sums in the tree */ pos += 3; if (it & ctx->block_count) { rhash_tiger_init(&ctx->tiger); ctx->tiger.message[ ctx->tiger.length++ ] = 0x01; rhash_tiger_update(&ctx->tiger, (unsigned char*)(ctx->stack + pos), 24); rhash_tiger_update(&ctx->tiger, last_message, 24); rhash_tiger_final(&ctx->tiger, msg); last_message = msg; } } /* save result hash */ memcpy(ctx->tiger.hash, last_message, tiger_hash_length); if (result) memcpy(result, last_message, tiger_hash_length); }
1,383
777
<gh_stars>100-1000 #!/usr/bin/env python # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Script to download LLVM gold plugin from google storage.""" import find_depot_tools import json import os import shutil import subprocess import sys import zipfile SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CHROME_SRC = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir)) DEPOT_PATH = find_depot_tools.add_depot_tools_to_path() GSUTIL_PATH = os.path.join(DEPOT_PATH, 'gsutil.py') LLVM_BUILD_PATH = os.path.join(CHROME_SRC, 'third_party', 'llvm-build', 'Release+Asserts') CLANG_UPDATE_PY = os.path.join(CHROME_SRC, 'tools', 'clang', 'scripts', 'update.py') CLANG_REVISION = os.popen(CLANG_UPDATE_PY + ' --print-revision').read().rstrip() CLANG_BUCKET = 'gs://chromium-browser-clang/Linux_x64' def main(): targz_name = 'llvmgold-%s.tgz' % CLANG_REVISION remote_path = '%s/%s' % (CLANG_BUCKET, targz_name) os.chdir(LLVM_BUILD_PATH) subprocess.check_call(['python', GSUTIL_PATH, 'cp', remote_path, targz_name]) subprocess.check_call(['tar', 'xzf', targz_name]) os.remove(targz_name) return 0 if __name__ == '__main__': sys.exit(main())
591
690
<filename>artemis-core/artemis/src/main/java/com/artemis/ComponentTypeFactory.java<gh_stars>100-1000 package com.artemis; import java.lang.reflect.Modifier; import java.util.IdentityHashMap; import com.artemis.utils.Bag; import com.artemis.utils.reflect.ClassReflection; import com.artemis.utils.reflect.Constructor; import com.artemis.utils.reflect.ReflectionException; /** * Tracks all component types in a single world. * @see ComponentType */ public class ComponentTypeFactory { /** * Contains all generated component types, newly generated component types * will be stored here. */ private final IdentityHashMap<Class<? extends Component>, ComponentType> componentTypes = new IdentityHashMap<Class<? extends Component>, ComponentType>(); private final Bag<ComponentTypeListener> listeners = new Bag<ComponentTypeListener>(); /** Index of this component type in componentTypes. */ final Bag<ComponentType> types = new Bag(ComponentType.class); int initialMapperCapacity; private final ComponentManager cm; public ComponentTypeFactory(ComponentManager cm, int entityContainerSize) { this.cm = cm; initialMapperCapacity = entityContainerSize; } /** * Gets the component type for the given component class. * <p> * If no component type exists yet, a new one will be created and stored * for later retrieval. * </p> * * @param c * the component's class to get the type for * * @return the component's {@link ComponentType} */ public ComponentType getTypeFor(Class<? extends Component> c) { ComponentType type = componentTypes.get(c); if (type == null) type = createComponentType(c); return type; } private ComponentType createComponentType(Class<? extends Component> c) { try { Constructor ctor = ClassReflection.getConstructor(c); if ((ctor.getModifiers() & Modifier.PUBLIC) == 0) throw new InvalidComponentException(c, "missing public constructor"); } catch (ReflectionException e) { throw new InvalidComponentException(c, "missing public constructor", e); } ComponentType type = new ComponentType(c, types.size()); componentTypes.put(c, type); types.add(type); cm.registerComponentType(type, initialMapperCapacity); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onCreated(type); } return type; } /** * Gets component type by index. * <p> * @param index maps to {@link ComponentType} * @return the component's {@link ComponentType} */ public ComponentType getTypeFor(int index) { return types.get(index); } /** * Get the index of the component type of given component class. * * @param c * the component class to get the type index for * * @return the component type's index */ public int getIndexFor(Class<? extends Component> c) { return getTypeFor(c).getIndex(); } public void register(ComponentTypeListener listener) { listeners.add(listener); listener.initialize(types); } public interface ComponentTypeListener { void initialize(Bag<ComponentType> registered); void onCreated(ComponentType type); } }
953
1,030
{ "rtId": { "type": "String", "metadata": { "description": "Resource Id of the route table. Example:/subscriptions/yourSubscription/resourceGroups/yourResourceGroup/providers/Microsoft.Network/routeTables/aTable", "displayName": "Route Table Id" } } }
112
1,444
package mage.cards.s; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.common.MetalcraftCondition; import mage.abilities.decorator.ConditionalAsThoughEffect; import mage.abilities.decorator.ConditionalContinuousEffect; import mage.abilities.effects.Effect; import mage.abilities.effects.common.combat.CanAttackAsThoughItDidntHaveDefenderSourceEffect; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.hint.common.MetalcraftHint; import mage.abilities.keyword.DefenderAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import java.util.UUID; /** * @author <EMAIL> */ public final class SpireSerpent extends CardImpl { private static final String abilityText1 = "As long as you control three or more artifacts, {this} gets +2/+2"; public SpireSerpent(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{U}"); this.subtype.add(SubType.SERPENT); this.color.setBlue(true); this.power = new MageInt(3); this.toughness = new MageInt(5); // Defender this.addAbility(DefenderAbility.getInstance()); // Metalcraft — As long as you control three or more artifacts, Spire Serpent gets +2/+2 and can attack as though it didn’t have defender. ConditionalContinuousEffect effect1 = new ConditionalContinuousEffect(new BoostSourceEffect(2, 2, Duration.WhileOnBattlefield), MetalcraftCondition.instance, abilityText1); Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect1); Effect effect = new ConditionalAsThoughEffect(new CanAttackAsThoughItDidntHaveDefenderSourceEffect(Duration.WhileOnBattlefield), MetalcraftCondition.instance); effect.setText("and can attack as though it didn't have defender"); ability.addEffect(effect); ability.setAbilityWord(AbilityWord.METALCRAFT); ability.addHint(MetalcraftHint.instance); this.addAbility(ability); } private SpireSerpent(final SpireSerpent card) { super(card); } @Override public SpireSerpent copy() { return new SpireSerpent(this); } }
777
8,747
<reponame>DCNick3/esp-idf void app_main(void) { }
26
32,544
package com.baeldung.jdbcmetadata; import org.apache.log4j.Logger; import java.sql.SQLException; public class JdbcMetadataApplication { private static final Logger LOG = Logger.getLogger(JdbcMetadataApplication.class); public static void main(String[] args) { DatabaseConfig databaseConfig = new DatabaseConfig(); databaseConfig.init(); try { MetadataExtractor metadataExtractor = new MetadataExtractor(databaseConfig.getConnection()); metadataExtractor.extractTableInfo(); metadataExtractor.extractSystemTables(); metadataExtractor.extractViews(); String tableName = "CUSTOMER"; metadataExtractor.extractColumnInfo(tableName); metadataExtractor.extractPrimaryKeys(tableName); metadataExtractor.extractForeignKeys("CUST_ADDRESS"); metadataExtractor.extractDatabaseInfo(); metadataExtractor.extractUserName(); metadataExtractor.extractSupportedFeatures(); } catch (SQLException e) { LOG.error("Error while executing SQL statements", e); } } }
449
743
<reponame>althink/hermes package pl.allegro.tech.hermes.client; public interface MessageDeliveryListener { void onSend(HermesResponse response, long latency); void onFailure(HermesResponse message, int attemptCount); void onFailedRetry(HermesResponse message, int attemptCount); void onSuccessfulRetry(HermesResponse message, int attemptCount); void onMaxRetriesExceeded(HermesResponse message, int attemptCount); }
131
742
<reponame>TotalCaesar659/OpenTESArena<gh_stars>100-1000 #include <algorithm> #include "SDL.h" #include "GameWorldPanel.h" #include "LoadSavePanel.h" #include "MainMenuPanel.h" #include "OptionsPanel.h" #include "PauseMenuPanel.h" #include "PauseMenuUiController.h" #include "../Game/Game.h" #include "../Math/Constants.h" void PauseMenuUiController::onNewGameButtonSelected(Game &game) { game.setGameState(nullptr); game.setPanel<MainMenuPanel>(); const MusicLibrary &musicLibrary = game.getMusicLibrary(); const MusicDefinition *musicDef = musicLibrary.getRandomMusicDefinition( MusicDefinition::Type::MainMenu, game.getRandom()); if (musicDef == nullptr) { DebugLogWarning("Missing main menu music."); } AudioManager &audioManager = game.getAudioManager(); audioManager.setMusic(musicDef); } void PauseMenuUiController::onLoadButtonSelected(Game &game) { game.setPanel<LoadSavePanel>(LoadSavePanel::Type::Load); } void PauseMenuUiController::onSaveButtonSelected(Game &game) { // @todo // SaveGamePanel... //auto optionsPanel = std::make_unique<OptionsPanel>(game); //game.setPanel(std::move(optionsPanel)); } void PauseMenuUiController::onExitButtonSelected(Game &game) { SDL_Event evt; evt.quit.type = SDL_QUIT; evt.quit.timestamp = 0; SDL_PushEvent(&evt); } void PauseMenuUiController::onResumeButtonSelected(Game &game) { game.setPanel<GameWorldPanel>(); } void PauseMenuUiController::onOptionsButtonSelected(Game &game) { game.setPanel<OptionsPanel>(); } void PauseMenuUiController::onSoundUpButtonSelected(Game &game, PauseMenuPanel &panel) { auto &options = game.getOptions(); options.setAudio_SoundVolume(std::min(options.getAudio_SoundVolume() + 0.050, 1.0)); auto &audioManager = game.getAudioManager(); audioManager.setSoundVolume(options.getAudio_SoundVolume()); panel.updateSoundText(options.getAudio_SoundVolume()); } void PauseMenuUiController::onSoundDownButtonSelected(Game &game, PauseMenuPanel &panel) { auto &options = game.getOptions(); const double newVolume = [&options]() { const double volume = std::max(options.getAudio_SoundVolume() - 0.050, 0.0); // Clamp very small values to zero to avoid precision issues with tiny numbers. return volume < Constants::Epsilon ? 0.0 : volume; }(); options.setAudio_SoundVolume(newVolume); auto &audioManager = game.getAudioManager(); audioManager.setSoundVolume(options.getAudio_SoundVolume()); panel.updateSoundText(options.getAudio_SoundVolume()); } void PauseMenuUiController::onMusicUpButtonSelected(Game &game, PauseMenuPanel &panel) { auto &options = game.getOptions(); options.setAudio_MusicVolume(std::min(options.getAudio_MusicVolume() + 0.050, 1.0)); auto &audioManager = game.getAudioManager(); audioManager.setMusicVolume(options.getAudio_MusicVolume()); panel.updateMusicText(options.getAudio_MusicVolume()); } void PauseMenuUiController::onMusicDownButtonSelected(Game &game, PauseMenuPanel &panel) { auto &options = game.getOptions(); const double newVolume = [&options]() { const double volume = std::max(options.getAudio_MusicVolume() - 0.050, 0.0); // Clamp very small values to zero to avoid precision issues with tiny numbers. return volume < Constants::Epsilon ? 0.0 : volume; }(); options.setAudio_MusicVolume(newVolume); auto &audioManager = game.getAudioManager(); audioManager.setMusicVolume(options.getAudio_MusicVolume()); panel.updateMusicText(options.getAudio_MusicVolume()); }
1,143
348
{"nom":"Doubs","circ":"5ème circonscription","dpt":"Doubs","inscrits":1952,"abs":974,"votants":978,"blancs":11,"nuls":10,"exp":957,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":382},{"nuance":"LR","nom":"Mme <NAME>","voix":275},{"nuance":"FN","nom":"<NAME>","voix":109},{"nuance":"FI","nom":"Mme <NAME>","voix":102},{"nuance":"ECO","nom":"M. <NAME>","voix":40},{"nuance":"COM","nom":"Mme <NAME>","voix":15},{"nuance":"ECO","nom":"M. <NAME>","voix":13},{"nuance":"EXG","nom":"Mme <NAME>","voix":9},{"nuance":"DIV","nom":"M. <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":4}]}
239
777
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/media/video_capture_manager.h" #include <algorithm> #include <set> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/task_runner_util.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "content/browser/media/capture/desktop_capture_device_uma_types.h" #include "content/browser/media/capture/web_contents_video_capture_device.h" #include "content/browser/media/media_internals.h" #include "content/browser/renderer_host/media/video_capture_controller.h" #include "content/browser/renderer_host/media/video_capture_controller_event_handler.h" #include "content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.h" #include "content/browser/renderer_host/media/video_frame_receiver_on_io_thread.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/common/media_stream_request.h" #include "media/base/bind_to_current_loop.h" #include "media/base/media_switches.h" #include "media/capture/video/video_capture_buffer_pool_impl.h" #include "media/capture/video/video_capture_buffer_tracker_factory_impl.h" #include "media/capture/video/video_capture_device.h" #include "media/capture/video/video_capture_device_client.h" #include "media/capture/video/video_capture_device_factory.h" #if defined(ENABLE_SCREEN_CAPTURE) #if BUILDFLAG(ENABLE_WEBRTC) && !defined(OS_ANDROID) #include "content/browser/media/capture/desktop_capture_device.h" #endif #if defined(USE_AURA) #include "content/browser/media/capture/desktop_capture_device_aura.h" #endif #if defined(OS_ANDROID) #include "content/browser/media/capture/screen_capture_device_android.h" #endif #endif // defined(ENABLE_SCREEN_CAPTURE) namespace { class VideoFrameConsumerFeedbackObserverOnTaskRunner : public media::VideoFrameConsumerFeedbackObserver { public: VideoFrameConsumerFeedbackObserverOnTaskRunner( media::VideoFrameConsumerFeedbackObserver* observer, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : observer_(observer), task_runner_(std::move(task_runner)) {} void OnUtilizationReport(int frame_feedback_id, double utilization) override { task_runner_->PostTask( FROM_HERE, base::Bind( &media::VideoFrameConsumerFeedbackObserver::OnUtilizationReport, base::Unretained(observer_), frame_feedback_id, utilization)); } private: media::VideoFrameConsumerFeedbackObserver* const observer_; const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; // Compares two VideoCaptureFormat by checking smallest frame_size area, then // by _largest_ frame_rate. Used to order a VideoCaptureFormats vector so that // the first entry for a given resolution has the largest frame rate, as needed // by the ConsolidateCaptureFormats() method. bool IsCaptureFormatSmaller(const media::VideoCaptureFormat& format1, const media::VideoCaptureFormat& format2) { DCHECK(format1.frame_size.GetCheckedArea().IsValid()); DCHECK(format2.frame_size.GetCheckedArea().IsValid()); if (format1.frame_size.GetCheckedArea().ValueOrDefault(0) == format2.frame_size.GetCheckedArea().ValueOrDefault(0)) { return format1.frame_rate > format2.frame_rate; } return format1.frame_size.GetCheckedArea().ValueOrDefault(0) < format2.frame_size.GetCheckedArea().ValueOrDefault(0); } bool IsCaptureFormatSizeEqual(const media::VideoCaptureFormat& format1, const media::VideoCaptureFormat& format2) { DCHECK(format1.frame_size.GetCheckedArea().IsValid()); DCHECK(format2.frame_size.GetCheckedArea().IsValid()); return format1.frame_size.GetCheckedArea().ValueOrDefault(0) == format2.frame_size.GetCheckedArea().ValueOrDefault(0); } // This function receives a list of capture formats, removes duplicated // resolutions while keeping the highest frame rate for each, and forcing I420 // pixel format. void ConsolidateCaptureFormats(media::VideoCaptureFormats* formats) { if (formats->empty()) return; std::sort(formats->begin(), formats->end(), IsCaptureFormatSmaller); // Due to the ordering imposed, the largest frame_rate is kept while removing // duplicated resolutions. media::VideoCaptureFormats::iterator last = std::unique(formats->begin(), formats->end(), IsCaptureFormatSizeEqual); formats->erase(last, formats->end()); // Mark all formats as I420, since this is what the renderer side will get // anyhow: the actual pixel format is decided at the device level. // Don't do this for Y16 format as it is handled separatelly. for (auto& format : *formats) { if (format.pixel_format != media::PIXEL_FORMAT_Y16) format.pixel_format = media::PIXEL_FORMAT_I420; } } // The maximum number of video frame buffers in-flight at any one time. This // value should be based on the logical capacity of the capture pipeline, and // not on hardware performance. For example, tab capture requires more buffers // than webcam capture because the pipeline is longer (it includes read-backs // pending in the GPU pipeline). const int kMaxNumberOfBuffers = 3; // TODO(miu): The value for tab capture should be determined programmatically. // http://crbug.com/460318 const int kMaxNumberOfBuffersForTabCapture = 10; // Used for logging capture events. // Elements in this enum should not be deleted or rearranged; the only // permitted operation is to add new elements before NUM_VIDEO_CAPTURE_EVENT. enum VideoCaptureEvent { VIDEO_CAPTURE_START_CAPTURE = 0, VIDEO_CAPTURE_STOP_CAPTURE_OK = 1, VIDEO_CAPTURE_STOP_CAPTURE_DUE_TO_ERROR = 2, VIDEO_CAPTURE_STOP_CAPTURE_OK_NO_FRAMES_PRODUCED_BY_DEVICE = 3, VIDEO_CAPTURE_STOP_CAPTURE_OK_NO_FRAMES_PRODUCED_BY_DESKTOP_OR_TAB = 4, NUM_VIDEO_CAPTURE_EVENT }; void LogVideoCaptureEvent(VideoCaptureEvent event) { UMA_HISTOGRAM_ENUMERATION("Media.VideoCaptureManager.Event", event, NUM_VIDEO_CAPTURE_EVENT); } // Counter used for identifying a DeviceRequest to start a capture device. static int g_device_start_id = 0; const media::VideoCaptureSessionId kFakeSessionId = -1; std::unique_ptr<media::VideoCaptureJpegDecoder> CreateGpuJpegDecoder( const media::VideoCaptureJpegDecoder::DecodeDoneCB& decode_done_cb) { return base::MakeUnique<content::VideoCaptureGpuJpegDecoder>(decode_done_cb); } } // namespace namespace content { // Instances of this struct go through several different phases during their // lifetime. // Phase 1: When first created (in GetOrCreateDeviceEntry()), this consists of // only the |video_capture_controller|. Clients can already connect to the // controller, but there is no |buffer_pool| or |video_capture_device| present. // Phase 2: When a request to "start" the entry comes in (via // HandleQueuedStartRequest()), |buffer_pool| is created and creation of // |video_capture_device| is scheduled to run asynchronously on the Device // Thread. // Phase 3: As soon as the creation of the VideoCaptureDevice is complete, this // newly created VideoCaptureDevice instance is connected to the // VideoCaptureController via SetConsumerFeedbackObserver(). Furthermore, the // |buffer_pool| is connected to the |video_capture_controller| as a // FrameBufferPool via SetFrameBufferPool(). // Phase 4: This phase can only be reached on Android. When the application goes // to the background, the |video_capture_device| is asynchronously stopped and // released on the Device Thread. The existing |buffer_pool| is kept alive, and // all clients of |video_capture_controller| stay connected. When the // application is resumed, we transition to Phase 2, except that the existing // |buffer_pool| get reused instead of creating a new one. struct VideoCaptureManager::DeviceEntry { public: DeviceEntry(MediaStreamType stream_type, const std::string& id, const media::VideoCaptureParams& params); ~DeviceEntry(); std::unique_ptr<media::VideoCaptureDevice::Client> CreateDeviceClient(); std::unique_ptr<media::FrameBufferPool> CreateFrameBufferPool(); const int serial_id; const MediaStreamType stream_type; const std::string id; const media::VideoCaptureParams parameters; VideoCaptureController video_capture_controller; scoped_refptr<media::VideoCaptureBufferPool> buffer_pool; std::unique_ptr<media::VideoCaptureDevice> video_capture_device; }; // Bundles a media::VideoCaptureDeviceDescriptor with corresponding supported // video formats. struct VideoCaptureManager::DeviceInfo { DeviceInfo(); DeviceInfo(media::VideoCaptureDeviceDescriptor descriptor); DeviceInfo(const DeviceInfo& other); ~DeviceInfo(); DeviceInfo& operator=(const DeviceInfo& other); media::VideoCaptureDeviceDescriptor descriptor; media::VideoCaptureFormats supported_formats; }; class BufferPoolFrameBufferPool : public media::FrameBufferPool { public: explicit BufferPoolFrameBufferPool( scoped_refptr<media::VideoCaptureBufferPool> buffer_pool) : buffer_pool_(std::move(buffer_pool)) {} void SetBufferHold(int buffer_id) override { buffer_pool_->HoldForConsumers(buffer_id, 1); } void ReleaseBufferHold(int buffer_id) override { buffer_pool_->RelinquishConsumerHold(buffer_id, 1); } private: scoped_refptr<media::VideoCaptureBufferPool> buffer_pool_; }; // Class used for queuing request for starting a device. class VideoCaptureManager::CaptureDeviceStartRequest { public: CaptureDeviceStartRequest(int serial_id, media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params); int serial_id() const { return serial_id_; } media::VideoCaptureSessionId session_id() const { return session_id_; } media::VideoCaptureParams params() const { return params_; } // Set to true if the device should be stopped before it has successfully // been started. bool abort_start() const { return abort_start_; } void set_abort_start() { abort_start_ = true; } private: const int serial_id_; const media::VideoCaptureSessionId session_id_; const media::VideoCaptureParams params_; // Set to true if the device should be stopped before it has successfully // been started. bool abort_start_; }; VideoCaptureManager::DeviceEntry::DeviceEntry( MediaStreamType stream_type, const std::string& id, const media::VideoCaptureParams& params) : serial_id(g_device_start_id++), stream_type(stream_type), id(id), parameters(params) {} VideoCaptureManager::DeviceEntry::~DeviceEntry() { DCHECK_CURRENTLY_ON(BrowserThread::IO); // DCHECK that this DeviceEntry does not still own a // media::VideoCaptureDevice. media::VideoCaptureDevice must be deleted on // the device thread. DCHECK(video_capture_device == nullptr); } std::unique_ptr<media::VideoCaptureDevice::Client> VideoCaptureManager::DeviceEntry::CreateDeviceClient() { DCHECK_CURRENTLY_ON(BrowserThread::IO); const int max_buffers = stream_type == MEDIA_TAB_VIDEO_CAPTURE ? kMaxNumberOfBuffersForTabCapture : kMaxNumberOfBuffers; if (!buffer_pool) { buffer_pool = new media::VideoCaptureBufferPoolImpl( base::MakeUnique<media::VideoCaptureBufferTrackerFactoryImpl>(), max_buffers); } return base::MakeUnique<media::VideoCaptureDeviceClient>( base::MakeUnique<VideoFrameReceiverOnIOThread>( video_capture_controller.GetWeakPtrForIOThread()), buffer_pool, base::Bind( &CreateGpuJpegDecoder, base::Bind(&media::VideoFrameReceiver::OnIncomingCapturedVideoFrame, video_capture_controller.GetWeakPtrForIOThread()))); } std::unique_ptr<media::FrameBufferPool> VideoCaptureManager::DeviceEntry::CreateFrameBufferPool() { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(buffer_pool); return base::MakeUnique<BufferPoolFrameBufferPool>(buffer_pool); } VideoCaptureManager::DeviceInfo::DeviceInfo() = default; VideoCaptureManager::DeviceInfo::DeviceInfo( media::VideoCaptureDeviceDescriptor descriptor) : descriptor(descriptor) {} VideoCaptureManager::DeviceInfo::DeviceInfo( const VideoCaptureManager::DeviceInfo& other) = default; VideoCaptureManager::DeviceInfo::~DeviceInfo() = default; VideoCaptureManager::DeviceInfo& VideoCaptureManager::DeviceInfo::operator=( const VideoCaptureManager::DeviceInfo& other) = default; VideoCaptureManager::CaptureDeviceStartRequest::CaptureDeviceStartRequest( int serial_id, media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params) : serial_id_(serial_id), session_id_(session_id), params_(params), abort_start_(false) { } VideoCaptureManager::VideoCaptureManager( std::unique_ptr<media::VideoCaptureDeviceFactory> factory) : listener_(nullptr), new_capture_session_id_(1), video_capture_device_factory_(std::move(factory)) {} VideoCaptureManager::~VideoCaptureManager() { DCHECK(devices_.empty()); DCHECK(device_start_queue_.empty()); } void VideoCaptureManager::Register( MediaStreamProviderListener* listener, const scoped_refptr<base::SingleThreadTaskRunner>& device_task_runner) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!listener_); DCHECK(!device_task_runner_.get()); listener_ = listener; device_task_runner_ = device_task_runner; #if defined(OS_ANDROID) application_state_has_running_activities_ = true; app_status_listener_.reset(new base::android::ApplicationStatusListener( base::Bind(&VideoCaptureManager::OnApplicationStateChange, base::Unretained(this)))); #endif } void VideoCaptureManager::Unregister() { DCHECK(listener_); listener_ = nullptr; } void VideoCaptureManager::EnumerateDevices( const EnumerationCallback& client_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "VideoCaptureManager::EnumerateDevices"; // Bind a callback to ConsolidateDevicesInfoOnDeviceThread() with an argument // for another callback to OnDevicesInfoEnumerated() to be run in the current // loop, i.e. IO loop. Pass a timer for UMA histogram collection. base::Callback<void(std::unique_ptr<VideoCaptureDeviceDescriptors>)> devices_enumerated_callback = base::Bind( &VideoCaptureManager::ConsolidateDevicesInfoOnDeviceThread, this, media::BindToCurrentLoop(base::Bind( &VideoCaptureManager::OnDevicesInfoEnumerated, this, base::Owned(new base::ElapsedTimer()), client_callback)), devices_info_cache_); // OK to use base::Unretained() since we own the VCDFactory and |this| is // bound in |devices_enumerated_callback|. device_task_runner_->PostTask( FROM_HERE, base::Bind(&media::VideoCaptureDeviceFactory::EnumerateDeviceDescriptors, base::Unretained(video_capture_device_factory_.get()), devices_enumerated_callback)); } int VideoCaptureManager::Open(const StreamDeviceInfo& device_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(listener_); // Generate a new id for the session being opened. const media::VideoCaptureSessionId capture_session_id = new_capture_session_id_++; DCHECK(sessions_.find(capture_session_id) == sessions_.end()); DVLOG(1) << "VideoCaptureManager::Open, id " << capture_session_id; // We just save the stream info for processing later. sessions_[capture_session_id] = device_info.device; // Notify our listener asynchronously; this ensures that we return // |capture_session_id| to the caller of this function before using that same // id in a listener event. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&VideoCaptureManager::OnOpened, this, device_info.device.type, capture_session_id)); return capture_session_id; } void VideoCaptureManager::Close(int capture_session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(listener_); DVLOG(1) << "VideoCaptureManager::Close, id " << capture_session_id; SessionMap::iterator session_it = sessions_.find(capture_session_id); if (session_it == sessions_.end()) { NOTREACHED(); return; } DeviceEntry* const existing_device = GetDeviceEntryByTypeAndId(session_it->second.type, session_it->second.id); if (existing_device) { // Remove any client that is still using the session. This is safe to call // even if there are no clients using the session. existing_device->video_capture_controller.StopSession(capture_session_id); // StopSession() may have removed the last client, so we might need to // close the device. DestroyDeviceEntryIfNoClients(existing_device); } // Notify listeners asynchronously, and forget the session. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&VideoCaptureManager::OnClosed, this, session_it->second.type, capture_session_id)); sessions_.erase(session_it); } void VideoCaptureManager::QueueStartDevice( media::VideoCaptureSessionId session_id, DeviceEntry* entry, const media::VideoCaptureParams& params) { DCHECK_CURRENTLY_ON(BrowserThread::IO); device_start_queue_.push_back( CaptureDeviceStartRequest(entry->serial_id, session_id, params)); if (device_start_queue_.size() == 1) HandleQueuedStartRequest(); } void VideoCaptureManager::DoStopDevice(DeviceEntry* entry) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // TODO(mcasas): use a helper function https://crbug.com/624854. DCHECK( std::find_if(devices_.begin(), devices_.end(), [entry](const std::unique_ptr<DeviceEntry>& device_entry) { return device_entry.get() == entry; }) != devices_.end()); // Find the matching start request. for (DeviceStartQueue::reverse_iterator request = device_start_queue_.rbegin(); request != device_start_queue_.rend(); ++request) { if (request->serial_id() == entry->serial_id) { request->set_abort_start(); DVLOG(3) << "DoStopDevice, aborting start request for device " << entry->id << " serial_id = " << entry->serial_id; return; } } DVLOG(3) << "DoStopDevice. Send stop request for device = " << entry->id << " serial_id = " << entry->serial_id << "."; entry->video_capture_controller.OnLog( base::StringPrintf("Stopping device: id: %s", entry->id.c_str())); entry->video_capture_controller.SetConsumerFeedbackObserver(nullptr); entry->video_capture_controller.SetFrameBufferPool(nullptr); // |entry->video_capture_device| can be null if creating the device has // failed. if (entry->video_capture_device) { device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureManager::DoStopDeviceOnDeviceThread, this, base::Passed(&entry->video_capture_device))); } } void VideoCaptureManager::HandleQueuedStartRequest() { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Remove all start requests that have been aborted. while (device_start_queue_.begin() != device_start_queue_.end() && device_start_queue_.begin()->abort_start()) { device_start_queue_.pop_front(); } DeviceStartQueue::iterator request = device_start_queue_.begin(); if (request == device_start_queue_.end()) return; const int serial_id = request->serial_id(); DeviceEntry* const entry = GetDeviceEntryBySerialId(serial_id); DCHECK(entry); DVLOG(3) << "HandleQueuedStartRequest, Post start to device thread, device = " << entry->id << " start id = " << entry->serial_id; std::unique_ptr<media::VideoCaptureDevice::Client> device_client = entry->CreateDeviceClient(); std::unique_ptr<media::FrameBufferPool> frame_buffer_pool = entry->CreateFrameBufferPool(); base::Callback<std::unique_ptr<VideoCaptureDevice>(void)> start_capture_function; switch (entry->stream_type) { case MEDIA_DEVICE_VIDEO_CAPTURE: { // We look up the device id from the renderer in our local enumeration // since the renderer does not have all the information that might be // held in the browser-side VideoCaptureDevice::Name structure. const DeviceInfo* found = GetDeviceInfoById(entry->id); if (found) { entry->video_capture_controller.OnLog( base::StringPrintf("Starting device: id: %s, name: %s, api: %s", found->descriptor.device_id.c_str(), found->descriptor.GetNameAndModel().c_str(), found->descriptor.GetCaptureApiTypeString())); start_capture_function = base::Bind(&VideoCaptureManager::DoStartDeviceCaptureOnDeviceThread, this, found->descriptor, request->params(), base::Passed(std::move(device_client))); } else { // Errors from DoStartDeviceCaptureOnDeviceThread go via // VideoCaptureDeviceClient::OnError, which needs some thread // dancing to get errors processed on the IO thread. But since // we're on that thread, we call VideoCaptureController // methods directly. const std::string log_message = base::StringPrintf( "Error on %s:%d: device %s unknown. Maybe recently disconnected?", __FILE__, __LINE__, entry->id.c_str()); DLOG(ERROR) << log_message; entry->video_capture_controller.OnLog(log_message); entry->video_capture_controller.OnError(); // Drop the failed start request. device_start_queue_.pop_front(); return; } break; } case MEDIA_TAB_VIDEO_CAPTURE: start_capture_function = base::Bind( &VideoCaptureManager::DoStartTabCaptureOnDeviceThread, this, entry->id, request->params(), base::Passed(std::move(device_client))); break; case MEDIA_DESKTOP_VIDEO_CAPTURE: start_capture_function = base::Bind( &VideoCaptureManager::DoStartDesktopCaptureOnDeviceThread, this, entry->id, request->params(), base::Passed(std::move(device_client))); break; default: { NOTIMPLEMENTED(); return; } } base::PostTaskAndReplyWithResult( device_task_runner_.get(), FROM_HERE, start_capture_function, base::Bind(&VideoCaptureManager::OnDeviceStarted, this, request->serial_id(), base::Passed(&frame_buffer_pool))); } void VideoCaptureManager::OnDeviceStarted( int serial_id, std::unique_ptr<media::FrameBufferPool> frame_buffer_pool, std::unique_ptr<VideoCaptureDevice> device) { DVLOG(3) << __func__; DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(serial_id, device_start_queue_.begin()->serial_id()); // |device| can be null if creation failed in // DoStartDeviceCaptureOnDeviceThread. if (device_start_queue_.front().abort_start()) { // The device is no longer wanted. Stop the device again. DVLOG(3) << "OnDeviceStarted but start request have been aborted."; media::VideoCaptureDevice* device_ptr = device.get(); base::Closure closure = base::Bind(&VideoCaptureManager::DoStopDeviceOnDeviceThread, this, base::Passed(&device)); if (device_ptr && !device_task_runner_->PostTask(FROM_HERE, closure)) { // PostTask failed. The device must be stopped anyway. device_ptr->StopAndDeAllocate(); } } else { DeviceEntry* const entry = GetDeviceEntryBySerialId(serial_id); DCHECK(entry); DCHECK(!entry->video_capture_device); if (device) { entry->video_capture_controller.SetFrameBufferPool( std::move(frame_buffer_pool)); // Passing raw pointer |device.get()| to the controller is safe, // because we transfer ownership of it to |entry|. We are calling // SetConsumerFeedbackObserver(nullptr) before releasing // |entry->video_capture_device_| on the |device_task_runner_|. entry->video_capture_controller.SetConsumerFeedbackObserver( base::MakeUnique<VideoFrameConsumerFeedbackObserverOnTaskRunner>( device.get(), device_task_runner_)); } entry->video_capture_device = std::move(device); if (entry->stream_type == MEDIA_DESKTOP_VIDEO_CAPTURE) { const media::VideoCaptureSessionId session_id = device_start_queue_.front().session_id(); DCHECK(session_id != kFakeSessionId); MaybePostDesktopCaptureWindowId(session_id); } auto it = photo_request_queue_.begin(); while (it != photo_request_queue_.end()) { auto request = it++; DeviceEntry* maybe_entry = GetDeviceEntryBySessionId(request->first); if (maybe_entry && maybe_entry->video_capture_device) { request->second.Run(maybe_entry->video_capture_device.get()); photo_request_queue_.erase(request); } } } device_start_queue_.pop_front(); HandleQueuedStartRequest(); } std::unique_ptr<media::VideoCaptureDevice> VideoCaptureManager::DoStartDeviceCaptureOnDeviceThread( const VideoCaptureDeviceDescriptor& descriptor, const media::VideoCaptureParams& params, std::unique_ptr<VideoCaptureDevice::Client> device_client) { SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime"); DCHECK(IsOnDeviceThread()); std::unique_ptr<VideoCaptureDevice> video_capture_device; video_capture_device = video_capture_device_factory_->CreateDevice(descriptor); if (!video_capture_device) { device_client->OnError(FROM_HERE, "Could not create capture device"); return nullptr; } video_capture_device->AllocateAndStart(params, std::move(device_client)); return video_capture_device; } std::unique_ptr<media::VideoCaptureDevice> VideoCaptureManager::DoStartTabCaptureOnDeviceThread( const std::string& id, const media::VideoCaptureParams& params, std::unique_ptr<VideoCaptureDevice::Client> device_client) { SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime"); DCHECK(IsOnDeviceThread()); std::unique_ptr<VideoCaptureDevice> video_capture_device; #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) video_capture_device = WebContentsVideoCaptureDevice::Create(id); #endif if (!video_capture_device) { device_client->OnError(FROM_HERE, "Could not create capture device"); return nullptr; } video_capture_device->AllocateAndStart(params, std::move(device_client)); return video_capture_device; } std::unique_ptr<media::VideoCaptureDevice> VideoCaptureManager::DoStartDesktopCaptureOnDeviceThread( const std::string& id, const media::VideoCaptureParams& params, std::unique_ptr<VideoCaptureDevice::Client> device_client) { SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime"); DCHECK(IsOnDeviceThread()); std::unique_ptr<VideoCaptureDevice> video_capture_device; #if defined(ENABLE_SCREEN_CAPTURE) DesktopMediaID desktop_id = DesktopMediaID::Parse(id); if (desktop_id.is_null()) { device_client->OnError(FROM_HERE, "Desktop media ID is null"); return nullptr; } if (desktop_id.type == DesktopMediaID::TYPE_WEB_CONTENTS) { #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) video_capture_device = WebContentsVideoCaptureDevice::Create(id); IncrementDesktopCaptureCounter(TAB_VIDEO_CAPTURER_CREATED); if (desktop_id.audio_share) { IncrementDesktopCaptureCounter(TAB_VIDEO_CAPTURER_CREATED_WITH_AUDIO); } else { IncrementDesktopCaptureCounter(TAB_VIDEO_CAPTURER_CREATED_WITHOUT_AUDIO); } #endif } else { #if defined(OS_ANDROID) video_capture_device = base::MakeUnique<ScreenCaptureDeviceAndroid>(); #else #if defined(USE_AURA) video_capture_device = DesktopCaptureDeviceAura::Create(desktop_id); #endif // defined(USE_AURA) #if BUILDFLAG(ENABLE_WEBRTC) if (!video_capture_device) video_capture_device = DesktopCaptureDevice::Create(desktop_id); #endif // BUILDFLAG(ENABLE_WEBRTC) #endif // defined (OS_ANDROID) } #endif // defined(ENABLE_SCREEN_CAPTURE) if (!video_capture_device) { device_client->OnError(FROM_HERE, "Could not create capture device"); return nullptr; } video_capture_device->AllocateAndStart(params, std::move(device_client)); return video_capture_device; } void VideoCaptureManager::StartCaptureForClient( media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params, VideoCaptureControllerID client_id, VideoCaptureControllerEventHandler* client_handler, const DoneCB& done_cb) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << __func__ << ", session_id = " << session_id << ", request: " << media::VideoCaptureFormat::ToString(params.requested_format); DeviceEntry* entry = GetOrCreateDeviceEntry(session_id, params); if (!entry) { done_cb.Run(base::WeakPtr<VideoCaptureController>()); return; } LogVideoCaptureEvent(VIDEO_CAPTURE_START_CAPTURE); // First client starts the device. if (!entry->video_capture_controller.HasActiveClient() && !entry->video_capture_controller.HasPausedClient()) { DVLOG(1) << "VideoCaptureManager starting device (type = " << entry->stream_type << ", id = " << entry->id << ")"; QueueStartDevice(session_id, entry, params); } // Run the callback first, as AddClient() may trigger OnFrameInfo(). done_cb.Run(entry->video_capture_controller.GetWeakPtrForIOThread()); entry->video_capture_controller.AddClient(client_id, client_handler, session_id, params); } void VideoCaptureManager::StopCaptureForClient( VideoCaptureController* controller, VideoCaptureControllerID client_id, VideoCaptureControllerEventHandler* client_handler, bool aborted_due_to_error) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(controller); DCHECK(client_handler); DeviceEntry* entry = GetDeviceEntryByController(controller); if (!entry) { NOTREACHED(); return; } if (!aborted_due_to_error) { if (controller->has_received_frames()) { LogVideoCaptureEvent(VIDEO_CAPTURE_STOP_CAPTURE_OK); } else if (entry->stream_type == MEDIA_DEVICE_VIDEO_CAPTURE) { LogVideoCaptureEvent( VIDEO_CAPTURE_STOP_CAPTURE_OK_NO_FRAMES_PRODUCED_BY_DEVICE); } else { LogVideoCaptureEvent( VIDEO_CAPTURE_STOP_CAPTURE_OK_NO_FRAMES_PRODUCED_BY_DESKTOP_OR_TAB); } } else { LogVideoCaptureEvent(VIDEO_CAPTURE_STOP_CAPTURE_DUE_TO_ERROR); for (auto it : sessions_) { if (it.second.type == entry->stream_type && it.second.id == entry->id) { listener_->Aborted(it.second.type, it.first); // Aborted() call might synchronously destroy |entry|, recheck. entry = GetDeviceEntryByController(controller); if (!entry) return; break; } } } // Detach client from controller. const media::VideoCaptureSessionId session_id = controller->RemoveClient(client_id, client_handler); DVLOG(1) << __func__ << ", session_id = " << session_id; // If controller has no more clients, delete controller and device. DestroyDeviceEntryIfNoClients(entry); } void VideoCaptureManager::PauseCaptureForClient( VideoCaptureController* controller, VideoCaptureControllerID client_id, VideoCaptureControllerEventHandler* client_handler) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(controller); DCHECK(client_handler); DeviceEntry* entry = GetDeviceEntryByController(controller); if (!entry) NOTREACHED() << "Got Null entry while pausing capture"; const bool had_active_client = controller->HasActiveClient(); controller->PauseClient(client_id, client_handler); if (!had_active_client || controller->HasActiveClient()) return; if (media::VideoCaptureDevice* device = entry->video_capture_device.get()) { device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureDevice::MaybeSuspend, // Unretained is safe to use here because |device| would be // null if it was scheduled for shutdown and destruction, and // because this task is guaranteed to run before the task // that destroys the |device|. base::Unretained(device))); } } void VideoCaptureManager::ResumeCaptureForClient( media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params, VideoCaptureController* controller, VideoCaptureControllerID client_id, VideoCaptureControllerEventHandler* client_handler) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(controller); DCHECK(client_handler); DeviceEntry* entry = GetDeviceEntryByController(controller); if (!entry) NOTREACHED() << "Got Null entry while resuming capture"; const bool had_active_client = controller->HasActiveClient(); controller->ResumeClient(client_id, client_handler); if (had_active_client || !controller->HasActiveClient()) return; if (media::VideoCaptureDevice* device = entry->video_capture_device.get()) { device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureDevice::Resume, // Unretained is safe to use here because |device| would be // null if it was scheduled for shutdown and destruction, and // because this task is guaranteed to run before the task // that destroys the |device|. base::Unretained(device))); } } void VideoCaptureManager::RequestRefreshFrameForClient( VideoCaptureController* controller) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (DeviceEntry* entry = GetDeviceEntryByController(controller)) { if (media::VideoCaptureDevice* device = entry->video_capture_device.get()) { device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureDevice::RequestRefreshFrame, // Unretained is safe to use here because |device| would be // null if it was scheduled for shutdown and destruction, // and because this task is guaranteed to run before the // task that destroys the |device|. base::Unretained(device))); } } } bool VideoCaptureManager::GetDeviceSupportedFormats( media::VideoCaptureSessionId capture_session_id, media::VideoCaptureFormats* supported_formats) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(supported_formats->empty()); SessionMap::iterator it = sessions_.find(capture_session_id); if (it == sessions_.end()) return false; DVLOG(1) << "GetDeviceSupportedFormats for device: " << it->second.name; // Return all available formats of the device, regardless its started state. DeviceInfo* existing_device = GetDeviceInfoById(it->second.id); if (existing_device) *supported_formats = existing_device->supported_formats; return true; } bool VideoCaptureManager::GetDeviceFormatsInUse( media::VideoCaptureSessionId capture_session_id, media::VideoCaptureFormats* formats_in_use) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(formats_in_use->empty()); SessionMap::iterator it = sessions_.find(capture_session_id); if (it == sessions_.end()) return false; DVLOG(1) << "GetDeviceFormatsInUse for device: " << it->second.name; // Return the currently in-use format(s) of the device, if it's started. DeviceEntry* device_in_use = GetDeviceEntryByTypeAndId(it->second.type, it->second.id); if (device_in_use) { // Currently only one format-in-use is supported at the VCC level. formats_in_use->push_back( device_in_use->video_capture_controller.GetVideoCaptureFormat()); } return true; } void VideoCaptureManager::SetDesktopCaptureWindowId( media::VideoCaptureSessionId session_id, gfx::NativeViewId window_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); VLOG(2) << "SetDesktopCaptureWindowId called for session " << session_id; notification_window_ids_[session_id] = window_id; MaybePostDesktopCaptureWindowId(session_id); } void VideoCaptureManager::MaybePostDesktopCaptureWindowId( media::VideoCaptureSessionId session_id) { SessionMap::iterator session_it = sessions_.find(session_id); if (session_it == sessions_.end()) return; DeviceEntry* const existing_device = GetDeviceEntryByTypeAndId(session_it->second.type, session_it->second.id); if (!existing_device) { DVLOG(2) << "Failed to find an existing screen capture device."; return; } if (!existing_device->video_capture_device) { DVLOG(2) << "Screen capture device not yet started."; return; } DCHECK_EQ(MEDIA_DESKTOP_VIDEO_CAPTURE, existing_device->stream_type); DesktopMediaID id = DesktopMediaID::Parse(existing_device->id); if (id.is_null()) return; auto window_id_it = notification_window_ids_.find(session_id); if (window_id_it == notification_window_ids_.end()) { DVLOG(2) << "Notification window id not set for screen capture."; return; } // Post |existing_device->video_capture_device| to the VideoCaptureDevice to // the device_task_runner_. This is safe since the device is destroyed on the // device_task_runner_. device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureManager::SetDesktopCaptureWindowIdOnDeviceThread, this, existing_device->video_capture_device.get(), window_id_it->second)); notification_window_ids_.erase(window_id_it); } void VideoCaptureManager::GetPhotoCapabilities( int session_id, VideoCaptureDevice::GetPhotoCapabilitiesCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const DeviceEntry* entry = GetDeviceEntryBySessionId(session_id); if (!entry) return; VideoCaptureDevice* device = entry->video_capture_device.get(); if (device) { VideoCaptureManager::DoGetPhotoCapabilities(std::move(callback), device); return; } // |entry| is known but |device| is nullptr, queue up a request for later. photo_request_queue_.emplace_back( session_id, base::Bind(&VideoCaptureManager::DoGetPhotoCapabilities, this, base::Passed(&callback))); } void VideoCaptureManager::SetPhotoOptions( int session_id, media::mojom::PhotoSettingsPtr settings, VideoCaptureDevice::SetPhotoOptionsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const DeviceEntry* entry = GetDeviceEntryBySessionId(session_id); if (!entry) return; VideoCaptureDevice* device = entry->video_capture_device.get(); if (device) { VideoCaptureManager::DoSetPhotoOptions(std::move(callback), std::move(settings), device); return; } // |entry| is known but |device| is nullptr, queue up a request for later. photo_request_queue_.emplace_back( session_id, base::Bind(&VideoCaptureManager::DoSetPhotoOptions, this, base::Passed(&callback), base::Passed(&settings))); } void VideoCaptureManager::TakePhoto( int session_id, VideoCaptureDevice::TakePhotoCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const DeviceEntry* entry = GetDeviceEntryBySessionId(session_id); if (!entry) return; VideoCaptureDevice* device = entry->video_capture_device.get(); if (device) { VideoCaptureManager::DoTakePhoto(std::move(callback), device); return; } // |entry| is known but |device| is nullptr, queue up a request for later. photo_request_queue_.emplace_back( session_id, base::Bind(&VideoCaptureManager::DoTakePhoto, this, base::Passed(&callback))); } void VideoCaptureManager::DoStopDeviceOnDeviceThread( std::unique_ptr<VideoCaptureDevice> device) { SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StopDeviceTime"); DCHECK(IsOnDeviceThread()); device->StopAndDeAllocate(); DVLOG(3) << "DoStopDeviceOnDeviceThread"; } void VideoCaptureManager::OnOpened( MediaStreamType stream_type, media::VideoCaptureSessionId capture_session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!listener_) { // Listener has been removed. return; } listener_->Opened(stream_type, capture_session_id); } void VideoCaptureManager::OnClosed( MediaStreamType stream_type, media::VideoCaptureSessionId capture_session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!listener_) { // Listener has been removed. return; } listener_->Closed(stream_type, capture_session_id); } void VideoCaptureManager::OnDevicesInfoEnumerated( base::ElapsedTimer* timer, const EnumerationCallback& client_callback, const VideoCaptureManager::DeviceInfos& new_devices_info_cache) { DCHECK_CURRENTLY_ON(BrowserThread::IO); UMA_HISTOGRAM_TIMES( "Media.VideoCaptureManager.GetAvailableDevicesInfoOnDeviceThreadTime", timer->Elapsed()); devices_info_cache_ = new_devices_info_cache; // Walk the |devices_info_cache_| and produce a // media::VideoCaptureDeviceDescriptors for return purposes. media::VideoCaptureDeviceDescriptors devices; std::vector<std::tuple<media::VideoCaptureDeviceDescriptor, media::VideoCaptureFormats>> descriptors_and_formats; for (const auto& it : devices_info_cache_) { devices.emplace_back(it.descriptor); descriptors_and_formats.emplace_back(it.descriptor, it.supported_formats); MediaInternals::GetInstance()->UpdateVideoCaptureDeviceCapabilities( descriptors_and_formats); } client_callback.Run(devices); } bool VideoCaptureManager::IsOnDeviceThread() const { return device_task_runner_->BelongsToCurrentThread(); } void VideoCaptureManager::ConsolidateDevicesInfoOnDeviceThread( base::Callback<void(const VideoCaptureManager::DeviceInfos&)> on_devices_enumerated_callback, const VideoCaptureManager::DeviceInfos& old_device_info_cache, std::unique_ptr<VideoCaptureDeviceDescriptors> descriptors_snapshot) { DCHECK(IsOnDeviceThread()); // Construct |new_devices_info_cache| with the cached devices that are still // present in the system, and remove their names from |names_snapshot|, so we // keep there the truly new devices. VideoCaptureManager::DeviceInfos new_devices_info_cache; for (const auto& device_info : old_device_info_cache) { for (VideoCaptureDeviceDescriptors::iterator it = descriptors_snapshot->begin(); it != descriptors_snapshot->end(); ++it) { if (device_info.descriptor.device_id == it->device_id) { new_devices_info_cache.push_back(device_info); descriptors_snapshot->erase(it); break; } } } // Get the device info for the new devices in |names_snapshot|. for (const auto& it : *descriptors_snapshot) { DeviceInfo device_info(it); video_capture_device_factory_->GetSupportedFormats( it, &device_info.supported_formats); ConsolidateCaptureFormats(&device_info.supported_formats); new_devices_info_cache.push_back(device_info); } on_devices_enumerated_callback.Run(new_devices_info_cache); } void VideoCaptureManager::DestroyDeviceEntryIfNoClients(DeviceEntry* entry) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Removal of the last client stops the device. if (!entry->video_capture_controller.HasActiveClient() && !entry->video_capture_controller.HasPausedClient()) { DVLOG(1) << "VideoCaptureManager stopping device (type = " << entry->stream_type << ", id = " << entry->id << ")"; // The DeviceEntry is removed from |devices_| immediately. The controller is // deleted immediately, and the device is freed asynchronously. After this // point, subsequent requests to open this same device ID will create a new // DeviceEntry, VideoCaptureController, and VideoCaptureDevice. DoStopDevice(entry); // TODO(mcasas): use a helper function https://crbug.com/624854. DeviceEntries::iterator device_it = std::find_if(devices_.begin(), devices_.end(), [entry](const std::unique_ptr<DeviceEntry>& device_entry) { return device_entry.get() == entry; }); devices_.erase(device_it); } } VideoCaptureManager::DeviceEntry* VideoCaptureManager::GetDeviceEntryBySessionId(int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); SessionMap::const_iterator session_it = sessions_.find(session_id); if (session_it == sessions_.end()) return nullptr; return GetDeviceEntryByTypeAndId(session_it->second.type, session_it->second.id); } VideoCaptureManager::DeviceEntry* VideoCaptureManager::GetDeviceEntryByTypeAndId( MediaStreamType type, const std::string& device_id) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const std::unique_ptr<DeviceEntry>& device : devices_) { if (type == device->stream_type && device_id == device->id) return device.get(); } return nullptr; } VideoCaptureManager::DeviceEntry* VideoCaptureManager::GetDeviceEntryByController( const VideoCaptureController* controller) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Look up |controller| in |devices_|. for (const std::unique_ptr<DeviceEntry>& device : devices_) { if (&device->video_capture_controller == controller) return device.get(); } return nullptr; } VideoCaptureManager::DeviceEntry* VideoCaptureManager::GetDeviceEntryBySerialId( int serial_id) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const std::unique_ptr<DeviceEntry>& device : devices_) { if (device->serial_id == serial_id) return device.get(); } return nullptr; } VideoCaptureManager::DeviceInfo* VideoCaptureManager::GetDeviceInfoById( const std::string& id) { for (auto& it : devices_info_cache_) { if (it.descriptor.device_id == id) return &it; } return nullptr; } VideoCaptureManager::DeviceEntry* VideoCaptureManager::GetOrCreateDeviceEntry( media::VideoCaptureSessionId capture_session_id, const media::VideoCaptureParams& params) { DCHECK_CURRENTLY_ON(BrowserThread::IO); SessionMap::iterator session_it = sessions_.find(capture_session_id); if (session_it == sessions_.end()) return nullptr; const MediaStreamDevice& device_info = session_it->second; // Check if another session has already opened this device. If so, just // use that opened device. DeviceEntry* const existing_device = GetDeviceEntryByTypeAndId(device_info.type, device_info.id); if (existing_device) { DCHECK_EQ(device_info.type, existing_device->stream_type); return existing_device; } devices_.emplace_back( new DeviceEntry(device_info.type, device_info.id, params)); return devices_.back().get(); } void VideoCaptureManager::SetDesktopCaptureWindowIdOnDeviceThread( media::VideoCaptureDevice* device, gfx::NativeViewId window_id) { DCHECK(IsOnDeviceThread()); #if defined(ENABLE_SCREEN_CAPTURE) && BUILDFLAG(ENABLE_WEBRTC) && !defined(OS_ANDROID) DesktopCaptureDevice* desktop_device = static_cast<DesktopCaptureDevice*>(device); desktop_device->SetNotificationWindowId(window_id); VLOG(2) << "Screen capture notification window passed on device thread."; #endif } void VideoCaptureManager::DoGetPhotoCapabilities( VideoCaptureDevice::GetPhotoCapabilitiesCallback callback, VideoCaptureDevice* device) { // Unretained() is safe to use here because |device| would be null if it // was scheduled for shutdown and destruction, and because this task is // guaranteed to run before the task that destroys the |device|. device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureDevice::GetPhotoCapabilities, base::Unretained(device), base::Passed(&callback))); } void VideoCaptureManager::DoSetPhotoOptions( VideoCaptureDevice::SetPhotoOptionsCallback callback, media::mojom::PhotoSettingsPtr settings, VideoCaptureDevice* device) { // Unretained() is safe to use here because |device| would be null if it // was scheduled for shutdown and destruction, and because this task is // guaranteed to run before the task that destroys the |device|. device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureDevice::SetPhotoOptions, base::Unretained(device), base::Passed(&settings), base::Passed(&callback))); } void VideoCaptureManager::DoTakePhoto( VideoCaptureDevice::TakePhotoCallback callback, VideoCaptureDevice* device) { // Unretained() is safe to use here because |device| would be null if it // was scheduled for shutdown and destruction, and because this task is // guaranteed to run before the task that destroys the |device|. device_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoCaptureDevice::TakePhoto, base::Unretained(device), base::Passed(&callback))); } #if defined(OS_ANDROID) void VideoCaptureManager::OnApplicationStateChange( base::android::ApplicationState state) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Only release/resume devices when the Application state changes from // RUNNING->STOPPED->RUNNING. if (state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES && !application_state_has_running_activities_) { ResumeDevices(); application_state_has_running_activities_ = true; } else if (state == base::android::APPLICATION_STATE_HAS_STOPPED_ACTIVITIES) { ReleaseDevices(); application_state_has_running_activities_ = false; } } void VideoCaptureManager::ReleaseDevices() { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (auto& entry : devices_) { // Do not stop Content Video Capture devices, e.g. Tab or Screen capture. if (entry->stream_type != MEDIA_DEVICE_VIDEO_CAPTURE) continue; DoStopDevice(entry.get()); } } void VideoCaptureManager::ResumeDevices() { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (auto& entry : devices_) { // Do not resume Content Video Capture devices, e.g. Tab or Screen capture. // Do not try to restart already running devices. if (entry->stream_type != MEDIA_DEVICE_VIDEO_CAPTURE || entry->video_capture_device) continue; // Check if the device is already in the start queue. bool device_in_queue = false; for (auto& request : device_start_queue_) { if (request.serial_id() == entry->serial_id) { device_in_queue = true; break; } } if (!device_in_queue) { // Session ID is only valid for Screen capture. So we can fake it to // resume video capture devices here. QueueStartDevice(kFakeSessionId, entry.get(), entry->parameters); } } } #endif // defined(OS_ANDROID) } // namespace content
18,039
930
# Copyright 2016 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from django.apps import apps from django.contrib.staticfiles.finders import AppDirectoriesFinder class HorizonStaticFinder(AppDirectoriesFinder): """Static files finder that also looks into the directory of each panel.""" def __init__(self, app_names=None, *args, **kwargs): super().__init__(*args, **kwargs) app_configs = apps.get_app_configs() for app_config in app_configs: if 'openstack_dashboard' in app_config.path: for panel in os.listdir(app_config.path): panel_path = os.path.join(app_config.path, panel) if os.path.isdir(panel_path) and panel != self.source_dir: # Look for the static folder static_path = os.path.join(panel_path, self.source_dir) if os.path.isdir(static_path): panel_name = app_config.name + panel app_storage = self.storage_class(static_path) self.storages[panel_name] = app_storage
669
8,360
# coding:utf-8 # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from paddlehub.utils.log import logger class InputExample(object): ''' Input data structure of BERT/ERNIE, can satisfy single sequence task like text classification, sequence lableing; Sequence pair task like dialog task. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For single sequence tasks, only this sequence must be specified. text_b: (Optional) string. The untokenized text of the second sequence. Only must be specified for sequence pair tasks. label: (Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples. ''' def __init__(self, guid, text_a, text_b=None, label=None): self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label def __str__(self): if self.text_b is None: return 'text={}\tlabel={}'.format(self.text_a, self.label) else: return 'text_a={}\ttext_b={},label={}'.format(self.text_a, self.text_b, self.label) class BaseDataset(object): def __init__(self, base_path, train_file=None, dev_file=None, test_file=None, predict_file=None, label_file=None, label_list=None, train_file_with_header=False, dev_file_with_header=False, test_file_with_header=False, predict_file_with_header=False): if not (train_file or dev_file or test_file): raise ValueError('At least one file should be assigned') self.base_path = base_path self.train_file = train_file self.dev_file = dev_file self.test_file = test_file self.predict_file = predict_file self.label_file = label_file self.label_list = label_list self.train_examples = [] self.dev_examples = [] self.test_examples = [] self.predict_examples = [] self.if_file_with_header = { 'train': train_file_with_header, 'dev': dev_file_with_header, 'test': test_file_with_header, 'predict': predict_file_with_header } if train_file: self._load_train_examples() if dev_file: self._load_dev_examples() if test_file: self._load_test_examples() if predict_file: self._load_predict_examples() if self.label_file: if not self.label_list: self.label_list = self._load_label_data() else: logger.warning('As label_list has been assigned, label_file is noneffective') if self.label_list: self.label_index = dict(zip(self.label_list, range(len(self.label_list)))) def get_train_examples(self): return self.train_examples def get_dev_examples(self): return self.dev_examples def get_test_examples(self): return self.test_examples def get_val_examples(self): return self.get_dev_examples() def get_predict_examples(self): return self.predict_examples def get_examples(self, phase): if phase == 'train': return self.get_train_examples() elif phase == 'dev': return self.get_dev_examples() elif phase == 'test': return self.get_test_examples() elif phase == 'val': return self.get_val_examples() elif phase == 'predict': return self.get_predict_examples() else: raise ValueError('Invalid phase: %s' % phase) def get_labels(self): return self.label_list @property def num_labels(self): return len(self.label_list) # To be compatible with ImageClassificationDataset def label_dict(self): return {index: key for index, key in enumerate(self.label_list)} def _load_train_examples(self): self.train_path = os.path.join(self.base_path, self.train_file) self.train_examples = self._read_file(self.train_path, phase='train') def _load_dev_examples(self): self.dev_path = os.path.join(self.base_path, self.dev_file) self.dev_examples = self._read_file(self.dev_path, phase='dev') def _load_test_examples(self): self.test_path = os.path.join(self.base_path, self.test_file) self.test_examples = self._read_file(self.test_path, phase='test') def _load_predict_examples(self): self.predict_path = os.path.join(self.base_path, self.predict_file) self.predict_examples = self._read_file(self.predict_path, phase='predict') def _read_file(self, path, phase=None): raise NotImplementedError def _load_label_data(self): with open(os.path.join(self.base_path, self.label_file), 'r', encoding='utf8') as file: return file.read().strip().split('\n') def __str__(self): return 'Dataset: %s with %i train examples, %i dev examples and %i test examples' % ( self.__class__.__name__, len(self.train_examples), len(self.dev_examples), len(self.test_examples))
2,586
381
<filename>push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/APNSClientProducer.java package org.jboss.aerogear.unifiedpush.message.jms; import javax.ejb.Stateless; import org.jboss.aerogear.unifiedpush.api.APNSVariant; @Stateless public class APNSClientProducer extends AbstractJMSMessageProducer { private static final String APNS_CLIENT = "APNSClient"; public void changeAPNClient(final APNSVariant iOSVariant) { super.sendTransacted(APNS_CLIENT, iOSVariant, true); } }
191
346
{ "name": "calendario", "version": "2.0.0", "homepage": "http://tympanus.net/codrops/2012/11/27/calendario-a-flexible-calendar-plugin/", }
66
975
<filename>shieldCore/src/main/java/com/dianping/agentsdk/pagecontainer/OnTopViewLayoutChangeListener.java package com.dianping.agentsdk.pagecontainer; import android.view.View; import android.view.ViewGroup; /** * Created by zhi.he on 2018/3/23. */ public interface OnTopViewLayoutChangeListener { void onLayoutLocationChangeListener(View view, int preTopViewPosition, int preTopViewStatus, ViewGroup.MarginLayoutParams lp); }
135
2,151
{ "name": "identity_unittests", "display_name": "<NAME>", "interface_provider_specs": { "service_manager:connector": { "provides": { "service_manager:service_factory": [ "service_manager.mojom.ServiceFactory" ] }, "requires": { "identity": [ "identity_manager" ] } } } }
166
707
<filename>wpilibc/src/main/native/cpp/simulation/PWMSim.cpp // Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "frc/simulation/PWMSim.h" #include <memory> #include <utility> #include <hal/simulation/PWMData.h> #include "frc/PWM.h" using namespace frc; using namespace frc::sim; PWMSim::PWMSim(const PWM& pwm) : m_index{pwm.GetChannel()} {} PWMSim::PWMSim(int channel) : m_index{channel} {} std::unique_ptr<CallbackStore> PWMSim::RegisterInitializedCallback( NotifyCallback callback, bool initialNotify) { auto store = std::make_unique<CallbackStore>( m_index, -1, callback, &HALSIM_CancelPWMInitializedCallback); store->SetUid(HALSIM_RegisterPWMInitializedCallback( m_index, &CallbackStoreThunk, store.get(), initialNotify)); return store; } bool PWMSim::GetInitialized() const { return HALSIM_GetPWMInitialized(m_index); } void PWMSim::SetInitialized(bool initialized) { HALSIM_SetPWMInitialized(m_index, initialized); } std::unique_ptr<CallbackStore> PWMSim::RegisterRawValueCallback( NotifyCallback callback, bool initialNotify) { auto store = std::make_unique<CallbackStore>( m_index, -1, callback, &HALSIM_CancelPWMRawValueCallback); store->SetUid(HALSIM_RegisterPWMRawValueCallback(m_index, &CallbackStoreThunk, store.get(), initialNotify)); return store; } int PWMSim::GetRawValue() const { return HALSIM_GetPWMRawValue(m_index); } void PWMSim::SetRawValue(int rawValue) { HALSIM_SetPWMRawValue(m_index, rawValue); } std::unique_ptr<CallbackStore> PWMSim::RegisterSpeedCallback( NotifyCallback callback, bool initialNotify) { auto store = std::make_unique<CallbackStore>(m_index, -1, callback, &HALSIM_CancelPWMSpeedCallback); store->SetUid(HALSIM_RegisterPWMSpeedCallback(m_index, &CallbackStoreThunk, store.get(), initialNotify)); return store; } double PWMSim::GetSpeed() const { return HALSIM_GetPWMSpeed(m_index); } void PWMSim::SetSpeed(double speed) { HALSIM_SetPWMSpeed(m_index, speed); } std::unique_ptr<CallbackStore> PWMSim::RegisterPositionCallback( NotifyCallback callback, bool initialNotify) { auto store = std::make_unique<CallbackStore>( m_index, -1, callback, &HALSIM_CancelPWMPositionCallback); store->SetUid(HALSIM_RegisterPWMPositionCallback(m_index, &CallbackStoreThunk, store.get(), initialNotify)); return store; } double PWMSim::GetPosition() const { return HALSIM_GetPWMPosition(m_index); } void PWMSim::SetPosition(double position) { HALSIM_SetPWMPosition(m_index, position); } std::unique_ptr<CallbackStore> PWMSim::RegisterPeriodScaleCallback( NotifyCallback callback, bool initialNotify) { auto store = std::make_unique<CallbackStore>( m_index, -1, callback, &HALSIM_CancelPWMPeriodScaleCallback); store->SetUid(HALSIM_RegisterPWMPeriodScaleCallback( m_index, &CallbackStoreThunk, store.get(), initialNotify)); return store; } int PWMSim::GetPeriodScale() const { return HALSIM_GetPWMPeriodScale(m_index); } void PWMSim::SetPeriodScale(int periodScale) { HALSIM_SetPWMPeriodScale(m_index, periodScale); } std::unique_ptr<CallbackStore> PWMSim::RegisterZeroLatchCallback( NotifyCallback callback, bool initialNotify) { auto store = std::make_unique<CallbackStore>( m_index, -1, callback, &HALSIM_CancelPWMZeroLatchCallback); store->SetUid(HALSIM_RegisterPWMZeroLatchCallback( m_index, &CallbackStoreThunk, store.get(), initialNotify)); return store; } bool PWMSim::GetZeroLatch() const { return HALSIM_GetPWMZeroLatch(m_index); } void PWMSim::SetZeroLatch(bool zeroLatch) { HALSIM_SetPWMZeroLatch(m_index, zeroLatch); } void PWMSim::ResetData() { HALSIM_ResetPWMData(m_index); }
1,582
14,668
<reponame>zealoussnow/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_CLIPBOARD_VIEWS_CLIPBOARD_HISTORY_TEXT_ITEM_VIEW_H_ #define ASH_CLIPBOARD_VIEWS_CLIPBOARD_HISTORY_TEXT_ITEM_VIEW_H_ #include "ash/clipboard/views/clipboard_history_item_view.h" namespace views { class MenuItemView; } // namespace views namespace ash { // The menu item showing the plain text. class ClipboardHistoryTextItemView : public ClipboardHistoryItemView { public: ClipboardHistoryTextItemView( const ClipboardHistoryItem* clipboard_history_item, views::MenuItemView* container); ClipboardHistoryTextItemView(const ClipboardHistoryTextItemView& rhs) = delete; ClipboardHistoryItemView& operator=(const ClipboardHistoryTextItemView& rhs) = delete; ~ClipboardHistoryTextItemView() override; protected: const std::u16string& text() const { return text_; } // ClipboardHistoryItemView: std::unique_ptr<ContentsView> CreateContentsView() override; private: class TextContentsView; // ClipboardHistoryItemView: std::u16string GetAccessibleName() const override; const char* GetClassName() const override; // Text to show. const std::u16string text_; }; } // namespace ash #endif // ASH_CLIPBOARD_VIEWS_CLIPBOARD_HISTORY_TEXT_ITEM_VIEW_H_
463
2,728
# /* ************************************************************************** # * * # * (C) Copyright <NAME> 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* Revised by <NAME> (2020) */ # # /* See http://www.boost.org for most recent version. */ # # if BOOST_PP_LOCAL_C(513) BOOST_PP_LOCAL_MACRO(513) # endif # if BOOST_PP_LOCAL_C(514) BOOST_PP_LOCAL_MACRO(514) # endif # if BOOST_PP_LOCAL_C(515) BOOST_PP_LOCAL_MACRO(515) # endif # if BOOST_PP_LOCAL_C(516) BOOST_PP_LOCAL_MACRO(516) # endif # if BOOST_PP_LOCAL_C(517) BOOST_PP_LOCAL_MACRO(517) # endif # if BOOST_PP_LOCAL_C(518) BOOST_PP_LOCAL_MACRO(518) # endif # if BOOST_PP_LOCAL_C(519) BOOST_PP_LOCAL_MACRO(519) # endif # if BOOST_PP_LOCAL_C(520) BOOST_PP_LOCAL_MACRO(520) # endif # if BOOST_PP_LOCAL_C(521) BOOST_PP_LOCAL_MACRO(521) # endif # if BOOST_PP_LOCAL_C(522) BOOST_PP_LOCAL_MACRO(522) # endif # if BOOST_PP_LOCAL_C(523) BOOST_PP_LOCAL_MACRO(523) # endif # if BOOST_PP_LOCAL_C(524) BOOST_PP_LOCAL_MACRO(524) # endif # if BOOST_PP_LOCAL_C(525) BOOST_PP_LOCAL_MACRO(525) # endif # if BOOST_PP_LOCAL_C(526) BOOST_PP_LOCAL_MACRO(526) # endif # if BOOST_PP_LOCAL_C(527) BOOST_PP_LOCAL_MACRO(527) # endif # if BOOST_PP_LOCAL_C(528) BOOST_PP_LOCAL_MACRO(528) # endif # if BOOST_PP_LOCAL_C(529) BOOST_PP_LOCAL_MACRO(529) # endif # if BOOST_PP_LOCAL_C(530) BOOST_PP_LOCAL_MACRO(530) # endif # if BOOST_PP_LOCAL_C(531) BOOST_PP_LOCAL_MACRO(531) # endif # if BOOST_PP_LOCAL_C(532) BOOST_PP_LOCAL_MACRO(532) # endif # if BOOST_PP_LOCAL_C(533) BOOST_PP_LOCAL_MACRO(533) # endif # if BOOST_PP_LOCAL_C(534) BOOST_PP_LOCAL_MACRO(534) # endif # if BOOST_PP_LOCAL_C(535) BOOST_PP_LOCAL_MACRO(535) # endif # if BOOST_PP_LOCAL_C(536) BOOST_PP_LOCAL_MACRO(536) # endif # if BOOST_PP_LOCAL_C(537) BOOST_PP_LOCAL_MACRO(537) # endif # if BOOST_PP_LOCAL_C(538) BOOST_PP_LOCAL_MACRO(538) # endif # if BOOST_PP_LOCAL_C(539) BOOST_PP_LOCAL_MACRO(539) # endif # if BOOST_PP_LOCAL_C(540) BOOST_PP_LOCAL_MACRO(540) # endif # if BOOST_PP_LOCAL_C(541) BOOST_PP_LOCAL_MACRO(541) # endif # if BOOST_PP_LOCAL_C(542) BOOST_PP_LOCAL_MACRO(542) # endif # if BOOST_PP_LOCAL_C(543) BOOST_PP_LOCAL_MACRO(543) # endif # if BOOST_PP_LOCAL_C(544) BOOST_PP_LOCAL_MACRO(544) # endif # if BOOST_PP_LOCAL_C(545) BOOST_PP_LOCAL_MACRO(545) # endif # if BOOST_PP_LOCAL_C(546) BOOST_PP_LOCAL_MACRO(546) # endif # if BOOST_PP_LOCAL_C(547) BOOST_PP_LOCAL_MACRO(547) # endif # if BOOST_PP_LOCAL_C(548) BOOST_PP_LOCAL_MACRO(548) # endif # if BOOST_PP_LOCAL_C(549) BOOST_PP_LOCAL_MACRO(549) # endif # if BOOST_PP_LOCAL_C(550) BOOST_PP_LOCAL_MACRO(550) # endif # if BOOST_PP_LOCAL_C(551) BOOST_PP_LOCAL_MACRO(551) # endif # if BOOST_PP_LOCAL_C(552) BOOST_PP_LOCAL_MACRO(552) # endif # if BOOST_PP_LOCAL_C(553) BOOST_PP_LOCAL_MACRO(553) # endif # if BOOST_PP_LOCAL_C(554) BOOST_PP_LOCAL_MACRO(554) # endif # if BOOST_PP_LOCAL_C(555) BOOST_PP_LOCAL_MACRO(555) # endif # if BOOST_PP_LOCAL_C(556) BOOST_PP_LOCAL_MACRO(556) # endif # if BOOST_PP_LOCAL_C(557) BOOST_PP_LOCAL_MACRO(557) # endif # if BOOST_PP_LOCAL_C(558) BOOST_PP_LOCAL_MACRO(558) # endif # if BOOST_PP_LOCAL_C(559) BOOST_PP_LOCAL_MACRO(559) # endif # if BOOST_PP_LOCAL_C(560) BOOST_PP_LOCAL_MACRO(560) # endif # if BOOST_PP_LOCAL_C(561) BOOST_PP_LOCAL_MACRO(561) # endif # if BOOST_PP_LOCAL_C(562) BOOST_PP_LOCAL_MACRO(562) # endif # if BOOST_PP_LOCAL_C(563) BOOST_PP_LOCAL_MACRO(563) # endif # if BOOST_PP_LOCAL_C(564) BOOST_PP_LOCAL_MACRO(564) # endif # if BOOST_PP_LOCAL_C(565) BOOST_PP_LOCAL_MACRO(565) # endif # if BOOST_PP_LOCAL_C(566) BOOST_PP_LOCAL_MACRO(566) # endif # if BOOST_PP_LOCAL_C(567) BOOST_PP_LOCAL_MACRO(567) # endif # if BOOST_PP_LOCAL_C(568) BOOST_PP_LOCAL_MACRO(568) # endif # if BOOST_PP_LOCAL_C(569) BOOST_PP_LOCAL_MACRO(569) # endif # if BOOST_PP_LOCAL_C(570) BOOST_PP_LOCAL_MACRO(570) # endif # if BOOST_PP_LOCAL_C(571) BOOST_PP_LOCAL_MACRO(571) # endif # if BOOST_PP_LOCAL_C(572) BOOST_PP_LOCAL_MACRO(572) # endif # if BOOST_PP_LOCAL_C(573) BOOST_PP_LOCAL_MACRO(573) # endif # if BOOST_PP_LOCAL_C(574) BOOST_PP_LOCAL_MACRO(574) # endif # if BOOST_PP_LOCAL_C(575) BOOST_PP_LOCAL_MACRO(575) # endif # if BOOST_PP_LOCAL_C(576) BOOST_PP_LOCAL_MACRO(576) # endif # if BOOST_PP_LOCAL_C(577) BOOST_PP_LOCAL_MACRO(577) # endif # if BOOST_PP_LOCAL_C(578) BOOST_PP_LOCAL_MACRO(578) # endif # if BOOST_PP_LOCAL_C(579) BOOST_PP_LOCAL_MACRO(579) # endif # if BOOST_PP_LOCAL_C(580) BOOST_PP_LOCAL_MACRO(580) # endif # if BOOST_PP_LOCAL_C(581) BOOST_PP_LOCAL_MACRO(581) # endif # if BOOST_PP_LOCAL_C(582) BOOST_PP_LOCAL_MACRO(582) # endif # if BOOST_PP_LOCAL_C(583) BOOST_PP_LOCAL_MACRO(583) # endif # if BOOST_PP_LOCAL_C(584) BOOST_PP_LOCAL_MACRO(584) # endif # if BOOST_PP_LOCAL_C(585) BOOST_PP_LOCAL_MACRO(585) # endif # if BOOST_PP_LOCAL_C(586) BOOST_PP_LOCAL_MACRO(586) # endif # if BOOST_PP_LOCAL_C(587) BOOST_PP_LOCAL_MACRO(587) # endif # if BOOST_PP_LOCAL_C(588) BOOST_PP_LOCAL_MACRO(588) # endif # if BOOST_PP_LOCAL_C(589) BOOST_PP_LOCAL_MACRO(589) # endif # if BOOST_PP_LOCAL_C(590) BOOST_PP_LOCAL_MACRO(590) # endif # if BOOST_PP_LOCAL_C(591) BOOST_PP_LOCAL_MACRO(591) # endif # if BOOST_PP_LOCAL_C(592) BOOST_PP_LOCAL_MACRO(592) # endif # if BOOST_PP_LOCAL_C(593) BOOST_PP_LOCAL_MACRO(593) # endif # if BOOST_PP_LOCAL_C(594) BOOST_PP_LOCAL_MACRO(594) # endif # if BOOST_PP_LOCAL_C(595) BOOST_PP_LOCAL_MACRO(595) # endif # if BOOST_PP_LOCAL_C(596) BOOST_PP_LOCAL_MACRO(596) # endif # if BOOST_PP_LOCAL_C(597) BOOST_PP_LOCAL_MACRO(597) # endif # if BOOST_PP_LOCAL_C(598) BOOST_PP_LOCAL_MACRO(598) # endif # if BOOST_PP_LOCAL_C(599) BOOST_PP_LOCAL_MACRO(599) # endif # if BOOST_PP_LOCAL_C(600) BOOST_PP_LOCAL_MACRO(600) # endif # if BOOST_PP_LOCAL_C(601) BOOST_PP_LOCAL_MACRO(601) # endif # if BOOST_PP_LOCAL_C(602) BOOST_PP_LOCAL_MACRO(602) # endif # if BOOST_PP_LOCAL_C(603) BOOST_PP_LOCAL_MACRO(603) # endif # if BOOST_PP_LOCAL_C(604) BOOST_PP_LOCAL_MACRO(604) # endif # if BOOST_PP_LOCAL_C(605) BOOST_PP_LOCAL_MACRO(605) # endif # if BOOST_PP_LOCAL_C(606) BOOST_PP_LOCAL_MACRO(606) # endif # if BOOST_PP_LOCAL_C(607) BOOST_PP_LOCAL_MACRO(607) # endif # if BOOST_PP_LOCAL_C(608) BOOST_PP_LOCAL_MACRO(608) # endif # if BOOST_PP_LOCAL_C(609) BOOST_PP_LOCAL_MACRO(609) # endif # if BOOST_PP_LOCAL_C(610) BOOST_PP_LOCAL_MACRO(610) # endif # if BOOST_PP_LOCAL_C(611) BOOST_PP_LOCAL_MACRO(611) # endif # if BOOST_PP_LOCAL_C(612) BOOST_PP_LOCAL_MACRO(612) # endif # if BOOST_PP_LOCAL_C(613) BOOST_PP_LOCAL_MACRO(613) # endif # if BOOST_PP_LOCAL_C(614) BOOST_PP_LOCAL_MACRO(614) # endif # if BOOST_PP_LOCAL_C(615) BOOST_PP_LOCAL_MACRO(615) # endif # if BOOST_PP_LOCAL_C(616) BOOST_PP_LOCAL_MACRO(616) # endif # if BOOST_PP_LOCAL_C(617) BOOST_PP_LOCAL_MACRO(617) # endif # if BOOST_PP_LOCAL_C(618) BOOST_PP_LOCAL_MACRO(618) # endif # if BOOST_PP_LOCAL_C(619) BOOST_PP_LOCAL_MACRO(619) # endif # if BOOST_PP_LOCAL_C(620) BOOST_PP_LOCAL_MACRO(620) # endif # if BOOST_PP_LOCAL_C(621) BOOST_PP_LOCAL_MACRO(621) # endif # if BOOST_PP_LOCAL_C(622) BOOST_PP_LOCAL_MACRO(622) # endif # if BOOST_PP_LOCAL_C(623) BOOST_PP_LOCAL_MACRO(623) # endif # if BOOST_PP_LOCAL_C(624) BOOST_PP_LOCAL_MACRO(624) # endif # if BOOST_PP_LOCAL_C(625) BOOST_PP_LOCAL_MACRO(625) # endif # if BOOST_PP_LOCAL_C(626) BOOST_PP_LOCAL_MACRO(626) # endif # if BOOST_PP_LOCAL_C(627) BOOST_PP_LOCAL_MACRO(627) # endif # if BOOST_PP_LOCAL_C(628) BOOST_PP_LOCAL_MACRO(628) # endif # if BOOST_PP_LOCAL_C(629) BOOST_PP_LOCAL_MACRO(629) # endif # if BOOST_PP_LOCAL_C(630) BOOST_PP_LOCAL_MACRO(630) # endif # if BOOST_PP_LOCAL_C(631) BOOST_PP_LOCAL_MACRO(631) # endif # if BOOST_PP_LOCAL_C(632) BOOST_PP_LOCAL_MACRO(632) # endif # if BOOST_PP_LOCAL_C(633) BOOST_PP_LOCAL_MACRO(633) # endif # if BOOST_PP_LOCAL_C(634) BOOST_PP_LOCAL_MACRO(634) # endif # if BOOST_PP_LOCAL_C(635) BOOST_PP_LOCAL_MACRO(635) # endif # if BOOST_PP_LOCAL_C(636) BOOST_PP_LOCAL_MACRO(636) # endif # if BOOST_PP_LOCAL_C(637) BOOST_PP_LOCAL_MACRO(637) # endif # if BOOST_PP_LOCAL_C(638) BOOST_PP_LOCAL_MACRO(638) # endif # if BOOST_PP_LOCAL_C(639) BOOST_PP_LOCAL_MACRO(639) # endif # if BOOST_PP_LOCAL_C(640) BOOST_PP_LOCAL_MACRO(640) # endif # if BOOST_PP_LOCAL_C(641) BOOST_PP_LOCAL_MACRO(641) # endif # if BOOST_PP_LOCAL_C(642) BOOST_PP_LOCAL_MACRO(642) # endif # if BOOST_PP_LOCAL_C(643) BOOST_PP_LOCAL_MACRO(643) # endif # if BOOST_PP_LOCAL_C(644) BOOST_PP_LOCAL_MACRO(644) # endif # if BOOST_PP_LOCAL_C(645) BOOST_PP_LOCAL_MACRO(645) # endif # if BOOST_PP_LOCAL_C(646) BOOST_PP_LOCAL_MACRO(646) # endif # if BOOST_PP_LOCAL_C(647) BOOST_PP_LOCAL_MACRO(647) # endif # if BOOST_PP_LOCAL_C(648) BOOST_PP_LOCAL_MACRO(648) # endif # if BOOST_PP_LOCAL_C(649) BOOST_PP_LOCAL_MACRO(649) # endif # if BOOST_PP_LOCAL_C(650) BOOST_PP_LOCAL_MACRO(650) # endif # if BOOST_PP_LOCAL_C(651) BOOST_PP_LOCAL_MACRO(651) # endif # if BOOST_PP_LOCAL_C(652) BOOST_PP_LOCAL_MACRO(652) # endif # if BOOST_PP_LOCAL_C(653) BOOST_PP_LOCAL_MACRO(653) # endif # if BOOST_PP_LOCAL_C(654) BOOST_PP_LOCAL_MACRO(654) # endif # if BOOST_PP_LOCAL_C(655) BOOST_PP_LOCAL_MACRO(655) # endif # if BOOST_PP_LOCAL_C(656) BOOST_PP_LOCAL_MACRO(656) # endif # if BOOST_PP_LOCAL_C(657) BOOST_PP_LOCAL_MACRO(657) # endif # if BOOST_PP_LOCAL_C(658) BOOST_PP_LOCAL_MACRO(658) # endif # if BOOST_PP_LOCAL_C(659) BOOST_PP_LOCAL_MACRO(659) # endif # if BOOST_PP_LOCAL_C(660) BOOST_PP_LOCAL_MACRO(660) # endif # if BOOST_PP_LOCAL_C(661) BOOST_PP_LOCAL_MACRO(661) # endif # if BOOST_PP_LOCAL_C(662) BOOST_PP_LOCAL_MACRO(662) # endif # if BOOST_PP_LOCAL_C(663) BOOST_PP_LOCAL_MACRO(663) # endif # if BOOST_PP_LOCAL_C(664) BOOST_PP_LOCAL_MACRO(664) # endif # if BOOST_PP_LOCAL_C(665) BOOST_PP_LOCAL_MACRO(665) # endif # if BOOST_PP_LOCAL_C(666) BOOST_PP_LOCAL_MACRO(666) # endif # if BOOST_PP_LOCAL_C(667) BOOST_PP_LOCAL_MACRO(667) # endif # if BOOST_PP_LOCAL_C(668) BOOST_PP_LOCAL_MACRO(668) # endif # if BOOST_PP_LOCAL_C(669) BOOST_PP_LOCAL_MACRO(669) # endif # if BOOST_PP_LOCAL_C(670) BOOST_PP_LOCAL_MACRO(670) # endif # if BOOST_PP_LOCAL_C(671) BOOST_PP_LOCAL_MACRO(671) # endif # if BOOST_PP_LOCAL_C(672) BOOST_PP_LOCAL_MACRO(672) # endif # if BOOST_PP_LOCAL_C(673) BOOST_PP_LOCAL_MACRO(673) # endif # if BOOST_PP_LOCAL_C(674) BOOST_PP_LOCAL_MACRO(674) # endif # if BOOST_PP_LOCAL_C(675) BOOST_PP_LOCAL_MACRO(675) # endif # if BOOST_PP_LOCAL_C(676) BOOST_PP_LOCAL_MACRO(676) # endif # if BOOST_PP_LOCAL_C(677) BOOST_PP_LOCAL_MACRO(677) # endif # if BOOST_PP_LOCAL_C(678) BOOST_PP_LOCAL_MACRO(678) # endif # if BOOST_PP_LOCAL_C(679) BOOST_PP_LOCAL_MACRO(679) # endif # if BOOST_PP_LOCAL_C(680) BOOST_PP_LOCAL_MACRO(680) # endif # if BOOST_PP_LOCAL_C(681) BOOST_PP_LOCAL_MACRO(681) # endif # if BOOST_PP_LOCAL_C(682) BOOST_PP_LOCAL_MACRO(682) # endif # if BOOST_PP_LOCAL_C(683) BOOST_PP_LOCAL_MACRO(683) # endif # if BOOST_PP_LOCAL_C(684) BOOST_PP_LOCAL_MACRO(684) # endif # if BOOST_PP_LOCAL_C(685) BOOST_PP_LOCAL_MACRO(685) # endif # if BOOST_PP_LOCAL_C(686) BOOST_PP_LOCAL_MACRO(686) # endif # if BOOST_PP_LOCAL_C(687) BOOST_PP_LOCAL_MACRO(687) # endif # if BOOST_PP_LOCAL_C(688) BOOST_PP_LOCAL_MACRO(688) # endif # if BOOST_PP_LOCAL_C(689) BOOST_PP_LOCAL_MACRO(689) # endif # if BOOST_PP_LOCAL_C(690) BOOST_PP_LOCAL_MACRO(690) # endif # if BOOST_PP_LOCAL_C(691) BOOST_PP_LOCAL_MACRO(691) # endif # if BOOST_PP_LOCAL_C(692) BOOST_PP_LOCAL_MACRO(692) # endif # if BOOST_PP_LOCAL_C(693) BOOST_PP_LOCAL_MACRO(693) # endif # if BOOST_PP_LOCAL_C(694) BOOST_PP_LOCAL_MACRO(694) # endif # if BOOST_PP_LOCAL_C(695) BOOST_PP_LOCAL_MACRO(695) # endif # if BOOST_PP_LOCAL_C(696) BOOST_PP_LOCAL_MACRO(696) # endif # if BOOST_PP_LOCAL_C(697) BOOST_PP_LOCAL_MACRO(697) # endif # if BOOST_PP_LOCAL_C(698) BOOST_PP_LOCAL_MACRO(698) # endif # if BOOST_PP_LOCAL_C(699) BOOST_PP_LOCAL_MACRO(699) # endif # if BOOST_PP_LOCAL_C(700) BOOST_PP_LOCAL_MACRO(700) # endif # if BOOST_PP_LOCAL_C(701) BOOST_PP_LOCAL_MACRO(701) # endif # if BOOST_PP_LOCAL_C(702) BOOST_PP_LOCAL_MACRO(702) # endif # if BOOST_PP_LOCAL_C(703) BOOST_PP_LOCAL_MACRO(703) # endif # if BOOST_PP_LOCAL_C(704) BOOST_PP_LOCAL_MACRO(704) # endif # if BOOST_PP_LOCAL_C(705) BOOST_PP_LOCAL_MACRO(705) # endif # if BOOST_PP_LOCAL_C(706) BOOST_PP_LOCAL_MACRO(706) # endif # if BOOST_PP_LOCAL_C(707) BOOST_PP_LOCAL_MACRO(707) # endif # if BOOST_PP_LOCAL_C(708) BOOST_PP_LOCAL_MACRO(708) # endif # if BOOST_PP_LOCAL_C(709) BOOST_PP_LOCAL_MACRO(709) # endif # if BOOST_PP_LOCAL_C(710) BOOST_PP_LOCAL_MACRO(710) # endif # if BOOST_PP_LOCAL_C(711) BOOST_PP_LOCAL_MACRO(711) # endif # if BOOST_PP_LOCAL_C(712) BOOST_PP_LOCAL_MACRO(712) # endif # if BOOST_PP_LOCAL_C(713) BOOST_PP_LOCAL_MACRO(713) # endif # if BOOST_PP_LOCAL_C(714) BOOST_PP_LOCAL_MACRO(714) # endif # if BOOST_PP_LOCAL_C(715) BOOST_PP_LOCAL_MACRO(715) # endif # if BOOST_PP_LOCAL_C(716) BOOST_PP_LOCAL_MACRO(716) # endif # if BOOST_PP_LOCAL_C(717) BOOST_PP_LOCAL_MACRO(717) # endif # if BOOST_PP_LOCAL_C(718) BOOST_PP_LOCAL_MACRO(718) # endif # if BOOST_PP_LOCAL_C(719) BOOST_PP_LOCAL_MACRO(719) # endif # if BOOST_PP_LOCAL_C(720) BOOST_PP_LOCAL_MACRO(720) # endif # if BOOST_PP_LOCAL_C(721) BOOST_PP_LOCAL_MACRO(721) # endif # if BOOST_PP_LOCAL_C(722) BOOST_PP_LOCAL_MACRO(722) # endif # if BOOST_PP_LOCAL_C(723) BOOST_PP_LOCAL_MACRO(723) # endif # if BOOST_PP_LOCAL_C(724) BOOST_PP_LOCAL_MACRO(724) # endif # if BOOST_PP_LOCAL_C(725) BOOST_PP_LOCAL_MACRO(725) # endif # if BOOST_PP_LOCAL_C(726) BOOST_PP_LOCAL_MACRO(726) # endif # if BOOST_PP_LOCAL_C(727) BOOST_PP_LOCAL_MACRO(727) # endif # if BOOST_PP_LOCAL_C(728) BOOST_PP_LOCAL_MACRO(728) # endif # if BOOST_PP_LOCAL_C(729) BOOST_PP_LOCAL_MACRO(729) # endif # if BOOST_PP_LOCAL_C(730) BOOST_PP_LOCAL_MACRO(730) # endif # if BOOST_PP_LOCAL_C(731) BOOST_PP_LOCAL_MACRO(731) # endif # if BOOST_PP_LOCAL_C(732) BOOST_PP_LOCAL_MACRO(732) # endif # if BOOST_PP_LOCAL_C(733) BOOST_PP_LOCAL_MACRO(733) # endif # if BOOST_PP_LOCAL_C(734) BOOST_PP_LOCAL_MACRO(734) # endif # if BOOST_PP_LOCAL_C(735) BOOST_PP_LOCAL_MACRO(735) # endif # if BOOST_PP_LOCAL_C(736) BOOST_PP_LOCAL_MACRO(736) # endif # if BOOST_PP_LOCAL_C(737) BOOST_PP_LOCAL_MACRO(737) # endif # if BOOST_PP_LOCAL_C(738) BOOST_PP_LOCAL_MACRO(738) # endif # if BOOST_PP_LOCAL_C(739) BOOST_PP_LOCAL_MACRO(739) # endif # if BOOST_PP_LOCAL_C(740) BOOST_PP_LOCAL_MACRO(740) # endif # if BOOST_PP_LOCAL_C(741) BOOST_PP_LOCAL_MACRO(741) # endif # if BOOST_PP_LOCAL_C(742) BOOST_PP_LOCAL_MACRO(742) # endif # if BOOST_PP_LOCAL_C(743) BOOST_PP_LOCAL_MACRO(743) # endif # if BOOST_PP_LOCAL_C(744) BOOST_PP_LOCAL_MACRO(744) # endif # if BOOST_PP_LOCAL_C(745) BOOST_PP_LOCAL_MACRO(745) # endif # if BOOST_PP_LOCAL_C(746) BOOST_PP_LOCAL_MACRO(746) # endif # if BOOST_PP_LOCAL_C(747) BOOST_PP_LOCAL_MACRO(747) # endif # if BOOST_PP_LOCAL_C(748) BOOST_PP_LOCAL_MACRO(748) # endif # if BOOST_PP_LOCAL_C(749) BOOST_PP_LOCAL_MACRO(749) # endif # if BOOST_PP_LOCAL_C(750) BOOST_PP_LOCAL_MACRO(750) # endif # if BOOST_PP_LOCAL_C(751) BOOST_PP_LOCAL_MACRO(751) # endif # if BOOST_PP_LOCAL_C(752) BOOST_PP_LOCAL_MACRO(752) # endif # if BOOST_PP_LOCAL_C(753) BOOST_PP_LOCAL_MACRO(753) # endif # if BOOST_PP_LOCAL_C(754) BOOST_PP_LOCAL_MACRO(754) # endif # if BOOST_PP_LOCAL_C(755) BOOST_PP_LOCAL_MACRO(755) # endif # if BOOST_PP_LOCAL_C(756) BOOST_PP_LOCAL_MACRO(756) # endif # if BOOST_PP_LOCAL_C(757) BOOST_PP_LOCAL_MACRO(757) # endif # if BOOST_PP_LOCAL_C(758) BOOST_PP_LOCAL_MACRO(758) # endif # if BOOST_PP_LOCAL_C(759) BOOST_PP_LOCAL_MACRO(759) # endif # if BOOST_PP_LOCAL_C(760) BOOST_PP_LOCAL_MACRO(760) # endif # if BOOST_PP_LOCAL_C(761) BOOST_PP_LOCAL_MACRO(761) # endif # if BOOST_PP_LOCAL_C(762) BOOST_PP_LOCAL_MACRO(762) # endif # if BOOST_PP_LOCAL_C(763) BOOST_PP_LOCAL_MACRO(763) # endif # if BOOST_PP_LOCAL_C(764) BOOST_PP_LOCAL_MACRO(764) # endif # if BOOST_PP_LOCAL_C(765) BOOST_PP_LOCAL_MACRO(765) # endif # if BOOST_PP_LOCAL_C(766) BOOST_PP_LOCAL_MACRO(766) # endif # if BOOST_PP_LOCAL_C(767) BOOST_PP_LOCAL_MACRO(767) # endif # if BOOST_PP_LOCAL_C(768) BOOST_PP_LOCAL_MACRO(768) # endif # if BOOST_PP_LOCAL_C(769) BOOST_PP_LOCAL_MACRO(769) # endif # if BOOST_PP_LOCAL_C(770) BOOST_PP_LOCAL_MACRO(770) # endif # if BOOST_PP_LOCAL_C(771) BOOST_PP_LOCAL_MACRO(771) # endif # if BOOST_PP_LOCAL_C(772) BOOST_PP_LOCAL_MACRO(772) # endif # if BOOST_PP_LOCAL_C(773) BOOST_PP_LOCAL_MACRO(773) # endif # if BOOST_PP_LOCAL_C(774) BOOST_PP_LOCAL_MACRO(774) # endif # if BOOST_PP_LOCAL_C(775) BOOST_PP_LOCAL_MACRO(775) # endif # if BOOST_PP_LOCAL_C(776) BOOST_PP_LOCAL_MACRO(776) # endif # if BOOST_PP_LOCAL_C(777) BOOST_PP_LOCAL_MACRO(777) # endif # if BOOST_PP_LOCAL_C(778) BOOST_PP_LOCAL_MACRO(778) # endif # if BOOST_PP_LOCAL_C(779) BOOST_PP_LOCAL_MACRO(779) # endif # if BOOST_PP_LOCAL_C(780) BOOST_PP_LOCAL_MACRO(780) # endif # if BOOST_PP_LOCAL_C(781) BOOST_PP_LOCAL_MACRO(781) # endif # if BOOST_PP_LOCAL_C(782) BOOST_PP_LOCAL_MACRO(782) # endif # if BOOST_PP_LOCAL_C(783) BOOST_PP_LOCAL_MACRO(783) # endif # if BOOST_PP_LOCAL_C(784) BOOST_PP_LOCAL_MACRO(784) # endif # if BOOST_PP_LOCAL_C(785) BOOST_PP_LOCAL_MACRO(785) # endif # if BOOST_PP_LOCAL_C(786) BOOST_PP_LOCAL_MACRO(786) # endif # if BOOST_PP_LOCAL_C(787) BOOST_PP_LOCAL_MACRO(787) # endif # if BOOST_PP_LOCAL_C(788) BOOST_PP_LOCAL_MACRO(788) # endif # if BOOST_PP_LOCAL_C(789) BOOST_PP_LOCAL_MACRO(789) # endif # if BOOST_PP_LOCAL_C(790) BOOST_PP_LOCAL_MACRO(790) # endif # if BOOST_PP_LOCAL_C(791) BOOST_PP_LOCAL_MACRO(791) # endif # if BOOST_PP_LOCAL_C(792) BOOST_PP_LOCAL_MACRO(792) # endif # if BOOST_PP_LOCAL_C(793) BOOST_PP_LOCAL_MACRO(793) # endif # if BOOST_PP_LOCAL_C(794) BOOST_PP_LOCAL_MACRO(794) # endif # if BOOST_PP_LOCAL_C(795) BOOST_PP_LOCAL_MACRO(795) # endif # if BOOST_PP_LOCAL_C(796) BOOST_PP_LOCAL_MACRO(796) # endif # if BOOST_PP_LOCAL_C(797) BOOST_PP_LOCAL_MACRO(797) # endif # if BOOST_PP_LOCAL_C(798) BOOST_PP_LOCAL_MACRO(798) # endif # if BOOST_PP_LOCAL_C(799) BOOST_PP_LOCAL_MACRO(799) # endif # if BOOST_PP_LOCAL_C(800) BOOST_PP_LOCAL_MACRO(800) # endif # if BOOST_PP_LOCAL_C(801) BOOST_PP_LOCAL_MACRO(801) # endif # if BOOST_PP_LOCAL_C(802) BOOST_PP_LOCAL_MACRO(802) # endif # if BOOST_PP_LOCAL_C(803) BOOST_PP_LOCAL_MACRO(803) # endif # if BOOST_PP_LOCAL_C(804) BOOST_PP_LOCAL_MACRO(804) # endif # if BOOST_PP_LOCAL_C(805) BOOST_PP_LOCAL_MACRO(805) # endif # if BOOST_PP_LOCAL_C(806) BOOST_PP_LOCAL_MACRO(806) # endif # if BOOST_PP_LOCAL_C(807) BOOST_PP_LOCAL_MACRO(807) # endif # if BOOST_PP_LOCAL_C(808) BOOST_PP_LOCAL_MACRO(808) # endif # if BOOST_PP_LOCAL_C(809) BOOST_PP_LOCAL_MACRO(809) # endif # if BOOST_PP_LOCAL_C(810) BOOST_PP_LOCAL_MACRO(810) # endif # if BOOST_PP_LOCAL_C(811) BOOST_PP_LOCAL_MACRO(811) # endif # if BOOST_PP_LOCAL_C(812) BOOST_PP_LOCAL_MACRO(812) # endif # if BOOST_PP_LOCAL_C(813) BOOST_PP_LOCAL_MACRO(813) # endif # if BOOST_PP_LOCAL_C(814) BOOST_PP_LOCAL_MACRO(814) # endif # if BOOST_PP_LOCAL_C(815) BOOST_PP_LOCAL_MACRO(815) # endif # if BOOST_PP_LOCAL_C(816) BOOST_PP_LOCAL_MACRO(816) # endif # if BOOST_PP_LOCAL_C(817) BOOST_PP_LOCAL_MACRO(817) # endif # if BOOST_PP_LOCAL_C(818) BOOST_PP_LOCAL_MACRO(818) # endif # if BOOST_PP_LOCAL_C(819) BOOST_PP_LOCAL_MACRO(819) # endif # if BOOST_PP_LOCAL_C(820) BOOST_PP_LOCAL_MACRO(820) # endif # if BOOST_PP_LOCAL_C(821) BOOST_PP_LOCAL_MACRO(821) # endif # if BOOST_PP_LOCAL_C(822) BOOST_PP_LOCAL_MACRO(822) # endif # if BOOST_PP_LOCAL_C(823) BOOST_PP_LOCAL_MACRO(823) # endif # if BOOST_PP_LOCAL_C(824) BOOST_PP_LOCAL_MACRO(824) # endif # if BOOST_PP_LOCAL_C(825) BOOST_PP_LOCAL_MACRO(825) # endif # if BOOST_PP_LOCAL_C(826) BOOST_PP_LOCAL_MACRO(826) # endif # if BOOST_PP_LOCAL_C(827) BOOST_PP_LOCAL_MACRO(827) # endif # if BOOST_PP_LOCAL_C(828) BOOST_PP_LOCAL_MACRO(828) # endif # if BOOST_PP_LOCAL_C(829) BOOST_PP_LOCAL_MACRO(829) # endif # if BOOST_PP_LOCAL_C(830) BOOST_PP_LOCAL_MACRO(830) # endif # if BOOST_PP_LOCAL_C(831) BOOST_PP_LOCAL_MACRO(831) # endif # if BOOST_PP_LOCAL_C(832) BOOST_PP_LOCAL_MACRO(832) # endif # if BOOST_PP_LOCAL_C(833) BOOST_PP_LOCAL_MACRO(833) # endif # if BOOST_PP_LOCAL_C(834) BOOST_PP_LOCAL_MACRO(834) # endif # if BOOST_PP_LOCAL_C(835) BOOST_PP_LOCAL_MACRO(835) # endif # if BOOST_PP_LOCAL_C(836) BOOST_PP_LOCAL_MACRO(836) # endif # if BOOST_PP_LOCAL_C(837) BOOST_PP_LOCAL_MACRO(837) # endif # if BOOST_PP_LOCAL_C(838) BOOST_PP_LOCAL_MACRO(838) # endif # if BOOST_PP_LOCAL_C(839) BOOST_PP_LOCAL_MACRO(839) # endif # if BOOST_PP_LOCAL_C(840) BOOST_PP_LOCAL_MACRO(840) # endif # if BOOST_PP_LOCAL_C(841) BOOST_PP_LOCAL_MACRO(841) # endif # if BOOST_PP_LOCAL_C(842) BOOST_PP_LOCAL_MACRO(842) # endif # if BOOST_PP_LOCAL_C(843) BOOST_PP_LOCAL_MACRO(843) # endif # if BOOST_PP_LOCAL_C(844) BOOST_PP_LOCAL_MACRO(844) # endif # if BOOST_PP_LOCAL_C(845) BOOST_PP_LOCAL_MACRO(845) # endif # if BOOST_PP_LOCAL_C(846) BOOST_PP_LOCAL_MACRO(846) # endif # if BOOST_PP_LOCAL_C(847) BOOST_PP_LOCAL_MACRO(847) # endif # if BOOST_PP_LOCAL_C(848) BOOST_PP_LOCAL_MACRO(848) # endif # if BOOST_PP_LOCAL_C(849) BOOST_PP_LOCAL_MACRO(849) # endif # if BOOST_PP_LOCAL_C(850) BOOST_PP_LOCAL_MACRO(850) # endif # if BOOST_PP_LOCAL_C(851) BOOST_PP_LOCAL_MACRO(851) # endif # if BOOST_PP_LOCAL_C(852) BOOST_PP_LOCAL_MACRO(852) # endif # if BOOST_PP_LOCAL_C(853) BOOST_PP_LOCAL_MACRO(853) # endif # if BOOST_PP_LOCAL_C(854) BOOST_PP_LOCAL_MACRO(854) # endif # if BOOST_PP_LOCAL_C(855) BOOST_PP_LOCAL_MACRO(855) # endif # if BOOST_PP_LOCAL_C(856) BOOST_PP_LOCAL_MACRO(856) # endif # if BOOST_PP_LOCAL_C(857) BOOST_PP_LOCAL_MACRO(857) # endif # if BOOST_PP_LOCAL_C(858) BOOST_PP_LOCAL_MACRO(858) # endif # if BOOST_PP_LOCAL_C(859) BOOST_PP_LOCAL_MACRO(859) # endif # if BOOST_PP_LOCAL_C(860) BOOST_PP_LOCAL_MACRO(860) # endif # if BOOST_PP_LOCAL_C(861) BOOST_PP_LOCAL_MACRO(861) # endif # if BOOST_PP_LOCAL_C(862) BOOST_PP_LOCAL_MACRO(862) # endif # if BOOST_PP_LOCAL_C(863) BOOST_PP_LOCAL_MACRO(863) # endif # if BOOST_PP_LOCAL_C(864) BOOST_PP_LOCAL_MACRO(864) # endif # if BOOST_PP_LOCAL_C(865) BOOST_PP_LOCAL_MACRO(865) # endif # if BOOST_PP_LOCAL_C(866) BOOST_PP_LOCAL_MACRO(866) # endif # if BOOST_PP_LOCAL_C(867) BOOST_PP_LOCAL_MACRO(867) # endif # if BOOST_PP_LOCAL_C(868) BOOST_PP_LOCAL_MACRO(868) # endif # if BOOST_PP_LOCAL_C(869) BOOST_PP_LOCAL_MACRO(869) # endif # if BOOST_PP_LOCAL_C(870) BOOST_PP_LOCAL_MACRO(870) # endif # if BOOST_PP_LOCAL_C(871) BOOST_PP_LOCAL_MACRO(871) # endif # if BOOST_PP_LOCAL_C(872) BOOST_PP_LOCAL_MACRO(872) # endif # if BOOST_PP_LOCAL_C(873) BOOST_PP_LOCAL_MACRO(873) # endif # if BOOST_PP_LOCAL_C(874) BOOST_PP_LOCAL_MACRO(874) # endif # if BOOST_PP_LOCAL_C(875) BOOST_PP_LOCAL_MACRO(875) # endif # if BOOST_PP_LOCAL_C(876) BOOST_PP_LOCAL_MACRO(876) # endif # if BOOST_PP_LOCAL_C(877) BOOST_PP_LOCAL_MACRO(877) # endif # if BOOST_PP_LOCAL_C(878) BOOST_PP_LOCAL_MACRO(878) # endif # if BOOST_PP_LOCAL_C(879) BOOST_PP_LOCAL_MACRO(879) # endif # if BOOST_PP_LOCAL_C(880) BOOST_PP_LOCAL_MACRO(880) # endif # if BOOST_PP_LOCAL_C(881) BOOST_PP_LOCAL_MACRO(881) # endif # if BOOST_PP_LOCAL_C(882) BOOST_PP_LOCAL_MACRO(882) # endif # if BOOST_PP_LOCAL_C(883) BOOST_PP_LOCAL_MACRO(883) # endif # if BOOST_PP_LOCAL_C(884) BOOST_PP_LOCAL_MACRO(884) # endif # if BOOST_PP_LOCAL_C(885) BOOST_PP_LOCAL_MACRO(885) # endif # if BOOST_PP_LOCAL_C(886) BOOST_PP_LOCAL_MACRO(886) # endif # if BOOST_PP_LOCAL_C(887) BOOST_PP_LOCAL_MACRO(887) # endif # if BOOST_PP_LOCAL_C(888) BOOST_PP_LOCAL_MACRO(888) # endif # if BOOST_PP_LOCAL_C(889) BOOST_PP_LOCAL_MACRO(889) # endif # if BOOST_PP_LOCAL_C(890) BOOST_PP_LOCAL_MACRO(890) # endif # if BOOST_PP_LOCAL_C(891) BOOST_PP_LOCAL_MACRO(891) # endif # if BOOST_PP_LOCAL_C(892) BOOST_PP_LOCAL_MACRO(892) # endif # if BOOST_PP_LOCAL_C(893) BOOST_PP_LOCAL_MACRO(893) # endif # if BOOST_PP_LOCAL_C(894) BOOST_PP_LOCAL_MACRO(894) # endif # if BOOST_PP_LOCAL_C(895) BOOST_PP_LOCAL_MACRO(895) # endif # if BOOST_PP_LOCAL_C(896) BOOST_PP_LOCAL_MACRO(896) # endif # if BOOST_PP_LOCAL_C(897) BOOST_PP_LOCAL_MACRO(897) # endif # if BOOST_PP_LOCAL_C(898) BOOST_PP_LOCAL_MACRO(898) # endif # if BOOST_PP_LOCAL_C(899) BOOST_PP_LOCAL_MACRO(899) # endif # if BOOST_PP_LOCAL_C(900) BOOST_PP_LOCAL_MACRO(900) # endif # if BOOST_PP_LOCAL_C(901) BOOST_PP_LOCAL_MACRO(901) # endif # if BOOST_PP_LOCAL_C(902) BOOST_PP_LOCAL_MACRO(902) # endif # if BOOST_PP_LOCAL_C(903) BOOST_PP_LOCAL_MACRO(903) # endif # if BOOST_PP_LOCAL_C(904) BOOST_PP_LOCAL_MACRO(904) # endif # if BOOST_PP_LOCAL_C(905) BOOST_PP_LOCAL_MACRO(905) # endif # if BOOST_PP_LOCAL_C(906) BOOST_PP_LOCAL_MACRO(906) # endif # if BOOST_PP_LOCAL_C(907) BOOST_PP_LOCAL_MACRO(907) # endif # if BOOST_PP_LOCAL_C(908) BOOST_PP_LOCAL_MACRO(908) # endif # if BOOST_PP_LOCAL_C(909) BOOST_PP_LOCAL_MACRO(909) # endif # if BOOST_PP_LOCAL_C(910) BOOST_PP_LOCAL_MACRO(910) # endif # if BOOST_PP_LOCAL_C(911) BOOST_PP_LOCAL_MACRO(911) # endif # if BOOST_PP_LOCAL_C(912) BOOST_PP_LOCAL_MACRO(912) # endif # if BOOST_PP_LOCAL_C(913) BOOST_PP_LOCAL_MACRO(913) # endif # if BOOST_PP_LOCAL_C(914) BOOST_PP_LOCAL_MACRO(914) # endif # if BOOST_PP_LOCAL_C(915) BOOST_PP_LOCAL_MACRO(915) # endif # if BOOST_PP_LOCAL_C(916) BOOST_PP_LOCAL_MACRO(916) # endif # if BOOST_PP_LOCAL_C(917) BOOST_PP_LOCAL_MACRO(917) # endif # if BOOST_PP_LOCAL_C(918) BOOST_PP_LOCAL_MACRO(918) # endif # if BOOST_PP_LOCAL_C(919) BOOST_PP_LOCAL_MACRO(919) # endif # if BOOST_PP_LOCAL_C(920) BOOST_PP_LOCAL_MACRO(920) # endif # if BOOST_PP_LOCAL_C(921) BOOST_PP_LOCAL_MACRO(921) # endif # if BOOST_PP_LOCAL_C(922) BOOST_PP_LOCAL_MACRO(922) # endif # if BOOST_PP_LOCAL_C(923) BOOST_PP_LOCAL_MACRO(923) # endif # if BOOST_PP_LOCAL_C(924) BOOST_PP_LOCAL_MACRO(924) # endif # if BOOST_PP_LOCAL_C(925) BOOST_PP_LOCAL_MACRO(925) # endif # if BOOST_PP_LOCAL_C(926) BOOST_PP_LOCAL_MACRO(926) # endif # if BOOST_PP_LOCAL_C(927) BOOST_PP_LOCAL_MACRO(927) # endif # if BOOST_PP_LOCAL_C(928) BOOST_PP_LOCAL_MACRO(928) # endif # if BOOST_PP_LOCAL_C(929) BOOST_PP_LOCAL_MACRO(929) # endif # if BOOST_PP_LOCAL_C(930) BOOST_PP_LOCAL_MACRO(930) # endif # if BOOST_PP_LOCAL_C(931) BOOST_PP_LOCAL_MACRO(931) # endif # if BOOST_PP_LOCAL_C(932) BOOST_PP_LOCAL_MACRO(932) # endif # if BOOST_PP_LOCAL_C(933) BOOST_PP_LOCAL_MACRO(933) # endif # if BOOST_PP_LOCAL_C(934) BOOST_PP_LOCAL_MACRO(934) # endif # if BOOST_PP_LOCAL_C(935) BOOST_PP_LOCAL_MACRO(935) # endif # if BOOST_PP_LOCAL_C(936) BOOST_PP_LOCAL_MACRO(936) # endif # if BOOST_PP_LOCAL_C(937) BOOST_PP_LOCAL_MACRO(937) # endif # if BOOST_PP_LOCAL_C(938) BOOST_PP_LOCAL_MACRO(938) # endif # if BOOST_PP_LOCAL_C(939) BOOST_PP_LOCAL_MACRO(939) # endif # if BOOST_PP_LOCAL_C(940) BOOST_PP_LOCAL_MACRO(940) # endif # if BOOST_PP_LOCAL_C(941) BOOST_PP_LOCAL_MACRO(941) # endif # if BOOST_PP_LOCAL_C(942) BOOST_PP_LOCAL_MACRO(942) # endif # if BOOST_PP_LOCAL_C(943) BOOST_PP_LOCAL_MACRO(943) # endif # if BOOST_PP_LOCAL_C(944) BOOST_PP_LOCAL_MACRO(944) # endif # if BOOST_PP_LOCAL_C(945) BOOST_PP_LOCAL_MACRO(945) # endif # if BOOST_PP_LOCAL_C(946) BOOST_PP_LOCAL_MACRO(946) # endif # if BOOST_PP_LOCAL_C(947) BOOST_PP_LOCAL_MACRO(947) # endif # if BOOST_PP_LOCAL_C(948) BOOST_PP_LOCAL_MACRO(948) # endif # if BOOST_PP_LOCAL_C(949) BOOST_PP_LOCAL_MACRO(949) # endif # if BOOST_PP_LOCAL_C(950) BOOST_PP_LOCAL_MACRO(950) # endif # if BOOST_PP_LOCAL_C(951) BOOST_PP_LOCAL_MACRO(951) # endif # if BOOST_PP_LOCAL_C(952) BOOST_PP_LOCAL_MACRO(952) # endif # if BOOST_PP_LOCAL_C(953) BOOST_PP_LOCAL_MACRO(953) # endif # if BOOST_PP_LOCAL_C(954) BOOST_PP_LOCAL_MACRO(954) # endif # if BOOST_PP_LOCAL_C(955) BOOST_PP_LOCAL_MACRO(955) # endif # if BOOST_PP_LOCAL_C(956) BOOST_PP_LOCAL_MACRO(956) # endif # if BOOST_PP_LOCAL_C(957) BOOST_PP_LOCAL_MACRO(957) # endif # if BOOST_PP_LOCAL_C(958) BOOST_PP_LOCAL_MACRO(958) # endif # if BOOST_PP_LOCAL_C(959) BOOST_PP_LOCAL_MACRO(959) # endif # if BOOST_PP_LOCAL_C(960) BOOST_PP_LOCAL_MACRO(960) # endif # if BOOST_PP_LOCAL_C(961) BOOST_PP_LOCAL_MACRO(961) # endif # if BOOST_PP_LOCAL_C(962) BOOST_PP_LOCAL_MACRO(962) # endif # if BOOST_PP_LOCAL_C(963) BOOST_PP_LOCAL_MACRO(963) # endif # if BOOST_PP_LOCAL_C(964) BOOST_PP_LOCAL_MACRO(964) # endif # if BOOST_PP_LOCAL_C(965) BOOST_PP_LOCAL_MACRO(965) # endif # if BOOST_PP_LOCAL_C(966) BOOST_PP_LOCAL_MACRO(966) # endif # if BOOST_PP_LOCAL_C(967) BOOST_PP_LOCAL_MACRO(967) # endif # if BOOST_PP_LOCAL_C(968) BOOST_PP_LOCAL_MACRO(968) # endif # if BOOST_PP_LOCAL_C(969) BOOST_PP_LOCAL_MACRO(969) # endif # if BOOST_PP_LOCAL_C(970) BOOST_PP_LOCAL_MACRO(970) # endif # if BOOST_PP_LOCAL_C(971) BOOST_PP_LOCAL_MACRO(971) # endif # if BOOST_PP_LOCAL_C(972) BOOST_PP_LOCAL_MACRO(972) # endif # if BOOST_PP_LOCAL_C(973) BOOST_PP_LOCAL_MACRO(973) # endif # if BOOST_PP_LOCAL_C(974) BOOST_PP_LOCAL_MACRO(974) # endif # if BOOST_PP_LOCAL_C(975) BOOST_PP_LOCAL_MACRO(975) # endif # if BOOST_PP_LOCAL_C(976) BOOST_PP_LOCAL_MACRO(976) # endif # if BOOST_PP_LOCAL_C(977) BOOST_PP_LOCAL_MACRO(977) # endif # if BOOST_PP_LOCAL_C(978) BOOST_PP_LOCAL_MACRO(978) # endif # if BOOST_PP_LOCAL_C(979) BOOST_PP_LOCAL_MACRO(979) # endif # if BOOST_PP_LOCAL_C(980) BOOST_PP_LOCAL_MACRO(980) # endif # if BOOST_PP_LOCAL_C(981) BOOST_PP_LOCAL_MACRO(981) # endif # if BOOST_PP_LOCAL_C(982) BOOST_PP_LOCAL_MACRO(982) # endif # if BOOST_PP_LOCAL_C(983) BOOST_PP_LOCAL_MACRO(983) # endif # if BOOST_PP_LOCAL_C(984) BOOST_PP_LOCAL_MACRO(984) # endif # if BOOST_PP_LOCAL_C(985) BOOST_PP_LOCAL_MACRO(985) # endif # if BOOST_PP_LOCAL_C(986) BOOST_PP_LOCAL_MACRO(986) # endif # if BOOST_PP_LOCAL_C(987) BOOST_PP_LOCAL_MACRO(987) # endif # if BOOST_PP_LOCAL_C(988) BOOST_PP_LOCAL_MACRO(988) # endif # if BOOST_PP_LOCAL_C(989) BOOST_PP_LOCAL_MACRO(989) # endif # if BOOST_PP_LOCAL_C(990) BOOST_PP_LOCAL_MACRO(990) # endif # if BOOST_PP_LOCAL_C(991) BOOST_PP_LOCAL_MACRO(991) # endif # if BOOST_PP_LOCAL_C(992) BOOST_PP_LOCAL_MACRO(992) # endif # if BOOST_PP_LOCAL_C(993) BOOST_PP_LOCAL_MACRO(993) # endif # if BOOST_PP_LOCAL_C(994) BOOST_PP_LOCAL_MACRO(994) # endif # if BOOST_PP_LOCAL_C(995) BOOST_PP_LOCAL_MACRO(995) # endif # if BOOST_PP_LOCAL_C(996) BOOST_PP_LOCAL_MACRO(996) # endif # if BOOST_PP_LOCAL_C(997) BOOST_PP_LOCAL_MACRO(997) # endif # if BOOST_PP_LOCAL_C(998) BOOST_PP_LOCAL_MACRO(998) # endif # if BOOST_PP_LOCAL_C(999) BOOST_PP_LOCAL_MACRO(999) # endif # if BOOST_PP_LOCAL_C(1000) BOOST_PP_LOCAL_MACRO(1000) # endif # if BOOST_PP_LOCAL_C(1001) BOOST_PP_LOCAL_MACRO(1001) # endif # if BOOST_PP_LOCAL_C(1002) BOOST_PP_LOCAL_MACRO(1002) # endif # if BOOST_PP_LOCAL_C(1003) BOOST_PP_LOCAL_MACRO(1003) # endif # if BOOST_PP_LOCAL_C(1004) BOOST_PP_LOCAL_MACRO(1004) # endif # if BOOST_PP_LOCAL_C(1005) BOOST_PP_LOCAL_MACRO(1005) # endif # if BOOST_PP_LOCAL_C(1006) BOOST_PP_LOCAL_MACRO(1006) # endif # if BOOST_PP_LOCAL_C(1007) BOOST_PP_LOCAL_MACRO(1007) # endif # if BOOST_PP_LOCAL_C(1008) BOOST_PP_LOCAL_MACRO(1008) # endif # if BOOST_PP_LOCAL_C(1009) BOOST_PP_LOCAL_MACRO(1009) # endif # if BOOST_PP_LOCAL_C(1010) BOOST_PP_LOCAL_MACRO(1010) # endif # if BOOST_PP_LOCAL_C(1011) BOOST_PP_LOCAL_MACRO(1011) # endif # if BOOST_PP_LOCAL_C(1012) BOOST_PP_LOCAL_MACRO(1012) # endif # if BOOST_PP_LOCAL_C(1013) BOOST_PP_LOCAL_MACRO(1013) # endif # if BOOST_PP_LOCAL_C(1014) BOOST_PP_LOCAL_MACRO(1014) # endif # if BOOST_PP_LOCAL_C(1015) BOOST_PP_LOCAL_MACRO(1015) # endif # if BOOST_PP_LOCAL_C(1016) BOOST_PP_LOCAL_MACRO(1016) # endif # if BOOST_PP_LOCAL_C(1017) BOOST_PP_LOCAL_MACRO(1017) # endif # if BOOST_PP_LOCAL_C(1018) BOOST_PP_LOCAL_MACRO(1018) # endif # if BOOST_PP_LOCAL_C(1019) BOOST_PP_LOCAL_MACRO(1019) # endif # if BOOST_PP_LOCAL_C(1020) BOOST_PP_LOCAL_MACRO(1020) # endif # if BOOST_PP_LOCAL_C(1021) BOOST_PP_LOCAL_MACRO(1021) # endif # if BOOST_PP_LOCAL_C(1022) BOOST_PP_LOCAL_MACRO(1022) # endif # if BOOST_PP_LOCAL_C(1023) BOOST_PP_LOCAL_MACRO(1023) # endif # if BOOST_PP_LOCAL_C(1024) BOOST_PP_LOCAL_MACRO(1024) # endif
24,759
335
<gh_stars>100-1000 { "word": "Commercial", "definitions": [ "Concerned with or engaged in commerce.", "Making or intended to make a profit.", "Having profit rather than artistic or other value as a primary aim.", "(of television or radio) funded by the revenue from broadcast advertisements.", "(of chemicals) supplied in bulk and not of the highest purity." ], "parts-of-speech": "Adjective" }
152
1,016
<filename>metadata/metadata-modeshape/src/main/java/com/thinkbiganalytics/metadata/modeshape/datasource/JcrDatasourceProvider.java package com.thinkbiganalytics.metadata.modeshape.datasource; /*- * #%L * thinkbig-metadata-modeshape * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.metadata.api.MetadataException; import com.thinkbiganalytics.metadata.api.datasource.Datasource; import com.thinkbiganalytics.metadata.api.datasource.DatasourceCriteria; import com.thinkbiganalytics.metadata.api.datasource.DatasourceDetails; import com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider; import com.thinkbiganalytics.metadata.api.datasource.DerivedDatasource; import com.thinkbiganalytics.metadata.api.datasource.UserDatasource; import com.thinkbiganalytics.metadata.core.AbstractMetadataCriteria; import com.thinkbiganalytics.metadata.modeshape.BaseJcrProvider; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.modeshape.MetadataRepositoryException; import com.thinkbiganalytics.metadata.modeshape.common.EntityUtil; import com.thinkbiganalytics.metadata.modeshape.common.JcrEntity; import com.thinkbiganalytics.metadata.modeshape.common.JcrObject; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedEntityActionsProvider; import com.thinkbiganalytics.metadata.modeshape.support.JcrObjectTypeResolver; import com.thinkbiganalytics.metadata.modeshape.support.JcrQueryUtil; import com.thinkbiganalytics.metadata.modeshape.support.JcrTool; import com.thinkbiganalytics.metadata.modeshape.support.JcrUtil; import com.thinkbiganalytics.security.AccessController; import com.thinkbiganalytics.security.UsernamePrincipal; import com.thinkbiganalytics.security.action.AllowedActions; import com.thinkbiganalytics.security.role.SecurityRole; import com.thinkbiganalytics.security.role.SecurityRoleProvider; import org.apache.commons.lang3.reflect.FieldUtils; import org.joda.time.DateTime; import org.modeshape.common.text.Jsr283Encoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.lang.reflect.Field; import java.security.Principal; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.inject.Inject; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; /** */ public class JcrDatasourceProvider extends BaseJcrProvider<Datasource, Datasource.ID> implements DatasourceProvider { private static final Logger log = LoggerFactory.getLogger(JcrDatasourceProvider.class); private static final Map<Class<? extends Datasource>, Class<? extends JcrDatasource>> DOMAIN_TYPES_MAP; private static final Map<String, Class<? extends JcrDatasource>> NODE_TYPES_MAP; public static final JcrObjectTypeResolver<? extends JcrDatasource> TYPE_RESOLVER = new JcrObjectTypeResolver<JcrDatasource>() { @Override public Class<? extends JcrDatasource> resolve(Node node) { try { if (NODE_TYPES_MAP.containsKey(node.getPrimaryNodeType().getName())) { return NODE_TYPES_MAP.get(node.getPrimaryNodeType().getName()); } else { return JcrDatasource.class; } } catch (RepositoryException e) { throw new MetadataRepositoryException("Failed to determine type of node: " + node, e); } } }; static { Map<Class<? extends Datasource>, Class<? extends JcrDatasource>> map = new HashMap<>(); map.put(DerivedDatasource.class, JcrDerivedDatasource.class); map.put(UserDatasource.class, JcrUserDatasource.class); DOMAIN_TYPES_MAP = map; } static { Map<String, Class<? extends JcrDatasource>> map = new HashMap<>(); map.put(JcrDerivedDatasource.NODE_TYPE, JcrDerivedDatasource.class); map.put(JcrUserDatasource.NODE_TYPE, JcrUserDatasource.class); NODE_TYPES_MAP = map; } @Inject private JcrAllowedEntityActionsProvider actionsProvider; @Override protected String getEntityQueryStartingPath() { return EntityUtil.pathForDataSource(); } @Inject private SecurityRoleProvider roleProvider; @Inject private AccessController accessController; public static Class<? extends JcrEntity<?>> resolveJcrEntityClass(String jcrNodeType) { if (NODE_TYPES_MAP.containsKey(jcrNodeType)) { return NODE_TYPES_MAP.get(jcrNodeType); } else { return JcrDatasource.class; } } public static Class<? extends JcrEntity<?>> resolveJcrEntityClass(Node node) { try { return resolveJcrEntityClass(node.getPrimaryNodeType().getName()); } catch (RepositoryException e) { throw new MetadataRepositoryException("Failed to determine type of node: " + node, e); } } /** * Finds the derived ds by Type and System Name */ public DerivedDatasource findDerivedDatasource(String datasourceType, String systemName) { String query = "SELECT * from " + EntityUtil.asQueryProperty(JcrDerivedDatasource.NODE_TYPE) + " as e " + "WHERE e." + EntityUtil.asQueryProperty(JcrDerivedDatasource.TYPE_NAME) + " = $datasourceType " + "AND e." + EntityUtil.asQueryProperty(JcrDatasource.SYSTEM_NAME) + " = $identityString"; Map<String, String> bindParams = new HashMap<>(); bindParams.put("datasourceType", datasourceType); bindParams.put("identityString", systemName); return JcrQueryUtil.findFirst(getSession(), query, bindParams, JcrDerivedDatasource.class); } private JcrDerivedDatasource findDerivedDatasourceByNodeName(String nodeName) throws RepositoryException { Node parentNode = getSession().getNode(EntityUtil.pathForDerivedDatasource()); try { Node child = parentNode.getNode(nodeName); if (child != null) { JcrDerivedDatasource jcrDerivedDatasource = new JcrDerivedDatasource(child); return jcrDerivedDatasource; } } catch (PathNotFoundException e) { //this is ok if we cant find it we will try to create it. } return null; } /** * gets or creates the Derived datasource */ public DerivedDatasource ensureDerivedDatasource(String datasourceType, String identityString, String title, String desc, Map<String, Object> properties) { //ensure the identity String is not null if (identityString == null) { identityString = ""; } if (datasourceType == null) { datasourceType = "Datasource"; } DerivedDatasource derivedDatasource = findDerivedDatasource(datasourceType, identityString); if (derivedDatasource == null) { try { if (!getSession().getRootNode().hasNode("metadata/datasources/derived")) { if (!getSession().getRootNode().hasNode("metadata/datasources")) { getSession().getRootNode().addNode("metadata", "datasources"); } getSession().getRootNode().getNode("metadata/datasources").addNode("derived"); } Node parentNode = getSession().getNode(EntityUtil.pathForDerivedDatasource()); String nodeName = datasourceType + "-" + identityString; if (Jsr283Encoder.containsEncodeableCharacters(identityString)) { nodeName = new Jsr283Encoder().encode(nodeName); } JcrDerivedDatasource jcrDerivedDatasource = null; try { jcrDerivedDatasource = findDerivedDatasourceByNodeName(nodeName); } catch (RepositoryException e) { log.warn("An exception occurred trying to find the DerivedDatasource by node name {}. {} ", nodeName, e.getMessage()); } derivedDatasource = jcrDerivedDatasource; if (jcrDerivedDatasource == null) { Node derivedDatasourceNode = JcrUtil.createNode(parentNode, nodeName, JcrDerivedDatasource.NODE_TYPE); jcrDerivedDatasource = new JcrDerivedDatasource(derivedDatasourceNode); jcrDerivedDatasource.setSystemName(identityString); jcrDerivedDatasource.setDatasourceType(datasourceType); jcrDerivedDatasource.setTitle(title); jcrDerivedDatasource.setDescription(desc); derivedDatasource = jcrDerivedDatasource; } } catch (RepositoryException e) { log.error("Failed to create Derived Datasource for DatasourceType: {}, IdentityString: {}, Error: {}", datasourceType, identityString, e.getMessage(), e); } } if (derivedDatasource != null) { // ((JcrDerivedDatasource)derivedDatasource).mergeProperties() if (properties != null) { derivedDatasource.setProperties(properties); } derivedDatasource.setTitle(title); } return derivedDatasource; } @Override public Class<? extends Datasource> getEntityClass() { return JcrDatasource.class; } @Override public Class<? extends JcrEntity<?>> getJcrEntityClass() { return JcrDatasource.class; } @Override public Class<? extends JcrEntity<?>> getJcrEntityClass(String jcrNodeType) { return resolveJcrEntityClass(jcrNodeType); } @Override public String getNodeType(Class<? extends JcrObject> jcrEntityType) { try { Field folderField = FieldUtils.getField(jcrEntityType, "NODE_TYPE", true); String jcrType = (String) folderField.get(null); return jcrType; } catch (IllegalArgumentException | IllegalAccessException e) { // Shouldn't really happen. throw new MetadataException("Unable to determine JCR node the for entity class: " + jcrEntityType, e); } } @Override public DatasourceCriteria datasetCriteria() { return new Criteria(); } @Override @SuppressWarnings("unchecked") public <D extends Datasource> D ensureDatasource(String name, String descr, Class<D> type) { JcrDatasource datasource = createImpl(name, descr, type); datasource.setDescription(descr); return (D) datasource; } @Override protected String getFindAllFilter() { return "ISDESCENDANTNODE('" + EntityUtil.pathForDataSource() + "')"; } @Override public Datasource getDatasource(Datasource.ID id) { return findById(id); } @Override public List<Datasource> getDatasources() { return findAll(); } @Override public List<Datasource> getDatasources(DatasourceCriteria criteria) { return findAll().stream().filter((Criteria) criteria).collect(Collectors.toList()); } @Override public Datasource.ID resolve(Serializable id) { return resolveId(id); } @Override public void removeDatasource(Datasource.ID id) { Datasource ds = getDatasource(id); if (ds != null) { try { ((JcrDatasource) ds).getNode().remove(); } catch (RepositoryException e) { throw new MetadataRepositoryException("Unable to remove Datasource: " + id); } } } @Override public DerivedDatasource ensureGenericDatasource(String name, String descr) { DerivedDatasource genericDatasource = ensureDatasource(name, descr, DerivedDatasource.class); return genericDatasource; } @Override public <D extends DatasourceDetails> Optional<D> ensureDatasourceDetails(@Nonnull final Datasource.ID id, @Nonnull final Class<D> type) { try { // Ensure the data source exists final Optional<JcrUserDatasource> parent = Optional.ofNullable(getDatasource(id)) .filter(JcrUserDatasource.class::isInstance) .map(JcrUserDatasource.class::cast); if (!parent.isPresent()) { return Optional.empty(); } // Create the details final Class<? extends JcrDatasourceDetails> implType = JcrUserDatasource.resolveDetailsClass(type); final boolean isNew = !hasEntityNode(parent.get().getPath(), JcrUserDatasource.DETAILS); final String nodeType = getNodeType(implType); final Node node = JcrUtil.getOrCreateNode(parent.get().getNode(), JcrUserDatasource.DETAILS, nodeType); @SuppressWarnings("unchecked") final D details = (D) JcrUtil.createJcrObject(node, implType); // Re-assign permissions to data source if (isNew) { final UsernamePrincipal owner = parent .map(JcrUserDatasource::getOwner) .map(Principal::getName) .map(UsernamePrincipal::new) .orElse(JcrMetadataAccess.getActiveUser()); if (accessController.isEntityAccessControlled()) { final List<SecurityRole> roles = roleProvider.getEntityRoles(SecurityRole.DATASOURCE); actionsProvider.getAvailableActions(AllowedActions.DATASOURCE) .ifPresent(actions -> parent.get().enableAccessControl((JcrAllowedActions) actions, owner, roles)); } else { actionsProvider.getAvailableActions(AllowedActions.DATASOURCE) .ifPresent(actions -> parent.get().disableAccessControl(owner)); } } return Optional.of(details); } catch (final IllegalArgumentException e) { throw new MetadataException("Unable to create datasource details: " + type, e); } } public Datasource.ID resolveId(Serializable fid) { return new JcrDatasource.DatasourceId(fid); } private <J extends JcrDatasource> J createImpl(String name, String descr, Class<? extends Datasource> type) { try { JcrTool tool = new JcrTool(); Class<J> implType = deriveImplType(type); Field folderField = FieldUtils.getField(implType, "PATH_NAME", true); String subfolderName = (String) folderField.get(null); String dsPath = EntityUtil.pathForDataSource(); Node dsNode = getSession().getNode(dsPath); Node subfolderNode = tool.findOrCreateChild(dsNode, subfolderName, "nt:folder"); Map<String, Object> props = new HashMap<>(); props.put(JcrDatasource.SYSTEM_NAME, name); String encodedName = org.modeshape.jcr.value.Path.DEFAULT_ENCODER.encode(name); final boolean isNew = !hasEntityNode(subfolderNode.getPath(), encodedName); @SuppressWarnings("unchecked") J datasource = (J) findOrCreateEntity(subfolderNode.getPath(), encodedName, implType, props); if (isNew && JcrUserDatasource.class.isAssignableFrom(type)) { if (this.accessController.isEntityAccessControlled()) { final List<SecurityRole> roles = roleProvider.getEntityRoles(SecurityRole.DATASOURCE); actionsProvider.getAvailableActions(AllowedActions.DATASOURCE) .ifPresent(actions -> ((JcrUserDatasource) datasource).enableAccessControl((JcrAllowedActions) actions, JcrMetadataAccess.getActiveUser(), roles)); } else { actionsProvider.getAvailableActions(AllowedActions.DATASOURCE) .ifPresent(actions -> ((JcrUserDatasource) datasource).disableAccessControl(JcrMetadataAccess.getActiveUser())); } } datasource.setTitle(name); datasource.setDescription(descr); return datasource; } catch (IllegalArgumentException | IllegalAccessException | RepositoryException e) { throw new MetadataException("Unable to create datasource: " + type, e); } } @SuppressWarnings("unchecked") private <J extends JcrDatasource> Class<J> deriveImplType(Class<? extends Datasource> domainType) { Class<? extends JcrDatasource> implType = DOMAIN_TYPES_MAP.get(domainType); if (implType != null) { return (Class<J>) implType; } else { throw new MetadataException("No datasource implementation found for type: " + domainType); } } // TODO Replace this implementation with a query restricting version. This is just a // workaround that filters on the results set. private static class Criteria extends AbstractMetadataCriteria<DatasourceCriteria> implements DatasourceCriteria, Predicate<Datasource>, Comparator<Datasource> { private String name; private DateTime createdOn; private DateTime createdAfter; private DateTime createdBefore; private Class<? extends Datasource> type; @Override public boolean test(Datasource input) { if (this.type != null && !this.type.isAssignableFrom(input.getClass())) { return false; } if (this.name != null && !name.equals(input.getName())) { return false; } if (this.createdOn != null && !this.createdOn.equals(input.getCreatedTime())) { return false; } if (this.createdAfter != null && !this.createdAfter.isBefore(input.getCreatedTime())) { return false; } if (this.createdBefore != null && !this.createdBefore.isBefore(input.getCreatedTime())) { return false; } return true; } @Override public int compare(Datasource o1, Datasource o2) { return o2.getCreatedTime().compareTo(o1.getCreatedTime()); } @Override public DatasourceCriteria name(String name) { this.name = name; return this; } @Override public DatasourceCriteria createdOn(DateTime time) { this.createdOn = time; return this; } @Override public DatasourceCriteria createdAfter(DateTime time) { this.createdAfter = time; return this; } @Override public DatasourceCriteria createdBefore(DateTime time) { this.createdBefore = time; return this; } @Override public DatasourceCriteria type(Class<? extends Datasource> type) { this.type = type; return this; } } }
8,275
7,986
<reponame>stackriot-labs/gitsome # -*- coding: utf-8 -*- """Main entry points of the xonsh history.""" import argparse import builtins import datetime import functools import json import os import sys from xonsh.history.base import History from xonsh.history.dummy import DummyHistory from xonsh.history.json import JsonHistory from xonsh.history.sqlite import SqliteHistory import xonsh.diff_history as xdh import xonsh.lazyasd as xla import xonsh.tools as xt HISTORY_BACKENDS = {"dummy": DummyHistory, "json": JsonHistory, "sqlite": SqliteHistory} def construct_history(**kwargs): """Construct the history backend object.""" env = builtins.__xonsh__.env backend = env.get("XONSH_HISTORY_BACKEND") if isinstance(backend, str) and backend in HISTORY_BACKENDS: kls_history = HISTORY_BACKENDS[backend] elif xt.is_class(backend): kls_history = backend elif isinstance(backend, History): return backend else: print( "Unknown history backend: {}. Using JSON version".format(backend), file=sys.stderr, ) kls_history = JsonHistory return kls_history(**kwargs) def _xh_session_parser(hist=None, newest_first=False, **kwargs): """Returns history items of current session.""" if hist is None: hist = builtins.__xonsh__.history return hist.items() def _xh_all_parser(hist=None, newest_first=False, **kwargs): """Returns all history items.""" if hist is None: hist = builtins.__xonsh__.history return hist.all_items(newest_first=newest_first) def _xh_find_histfile_var(file_list, default=None): """Return the path of the history file from the value of the envvar HISTFILE. """ for f in file_list: f = xt.expanduser_abs_path(f) if not os.path.isfile(f): continue with open(f, "r") as rc_file: for line in rc_file: if line.startswith("HISTFILE="): hist_file = line.split("=", 1)[1].strip("'\"\n") hist_file = xt.expanduser_abs_path(hist_file) if os.path.isfile(hist_file): return hist_file else: if default: default = xt.expanduser_abs_path(default) if os.path.isfile(default): return default def _xh_bash_hist_parser(location=None, **kwargs): """Yield commands from bash history file""" if location is None: location = _xh_find_histfile_var( [os.path.join("~", ".bashrc"), os.path.join("~", ".bash_profile")], os.path.join("~", ".bash_history"), ) if location: with open(location, "r", errors="backslashreplace") as bash_hist: for ind, line in enumerate(bash_hist): yield {"inp": line.rstrip(), "ts": 0.0, "ind": ind} else: print("No bash history file", file=sys.stderr) def _xh_zsh_hist_parser(location=None, **kwargs): """Yield commands from zsh history file""" if location is None: location = _xh_find_histfile_var( [os.path.join("~", ".zshrc"), os.path.join("~", ".zprofile")], os.path.join("~", ".zsh_history"), ) if location: with open(location, "r", errors="backslashreplace") as zsh_hist: for ind, line in enumerate(zsh_hist): if line.startswith(":"): try: start_time, command = line.split(";", 1) except ValueError: # Invalid history entry continue try: start_time = float(start_time.split(":")[1]) except ValueError: start_time = 0.0 yield {"inp": command.rstrip(), "ts": start_time, "ind": ind} else: yield {"inp": line.rstrip(), "ts": 0.0, "ind": ind} else: print("No zsh history file found", file=sys.stderr) def _xh_filter_ts(commands, start_time, end_time): """Yield only the commands between start and end time.""" for cmd in commands: if start_time <= cmd["ts"] < end_time: yield cmd def _xh_get_history( session="session", *, slices=None, datetime_format=None, start_time=None, end_time=None, location=None ): """Get the requested portion of shell history. Parameters ---------- session: {'session', 'all', 'xonsh', 'bash', 'zsh'} The history session to get. slices : list of slice-like objects, optional Get only portions of history. start_time, end_time: float, optional Filter commands by timestamp. location: string, optional The history file location (bash or zsh) Returns ------- generator A filtered list of commands """ cmds = [] for i, item in enumerate(_XH_HISTORY_SESSIONS[session](location=location)): item["ind"] = i cmds.append(item) if slices: # transform/check all slices slices = [xt.ensure_slice(s) for s in slices] cmds = xt.get_portions(cmds, slices) if start_time or end_time: if start_time is None: start_time = 0.0 else: start_time = xt.ensure_timestamp(start_time, datetime_format) if end_time is None: end_time = float("inf") else: end_time = xt.ensure_timestamp(end_time, datetime_format) cmds = _xh_filter_ts(cmds, start_time, end_time) return cmds def _xh_show_history(hist, ns, stdout=None, stderr=None): """Show the requested portion of shell history. Accepts same parameters with `_xh_get_history`. """ try: commands = _xh_get_history( ns.session, slices=ns.slices, start_time=ns.start_time, end_time=ns.end_time, datetime_format=ns.datetime_format, ) except Exception as err: print("history: error: {}".format(err), file=stderr) return if ns.reverse: commands = reversed(list(commands)) end = "\0" if ns.null_byte else "\n" if ns.numerate and ns.timestamp: for c in commands: dt = datetime.datetime.fromtimestamp(c["ts"]) print( "{}:({}) {}".format(c["ind"], xt.format_datetime(dt), c["inp"]), file=stdout, end=end, ) elif ns.numerate: for c in commands: print("{}: {}".format(c["ind"], c["inp"]), file=stdout, end=end) elif ns.timestamp: for c in commands: dt = datetime.datetime.fromtimestamp(c["ts"]) print( "({}) {}".format(xt.format_datetime(dt), c["inp"]), file=stdout, end=end ) else: for c in commands: print(c["inp"], file=stdout, end=end) @xla.lazyobject def _XH_HISTORY_SESSIONS(): return { "session": _xh_session_parser, "xonsh": _xh_all_parser, "all": _xh_all_parser, "zsh": _xh_zsh_hist_parser, "bash": _xh_bash_hist_parser, } _XH_MAIN_ACTIONS = {"show", "id", "file", "info", "diff", "gc"} @functools.lru_cache() def _xh_create_parser(): """Create a parser for the "history" command.""" p = argparse.ArgumentParser( prog="history", description="try 'history <command> --help' " "for more info" ) subp = p.add_subparsers(title="commands", dest="action") # session action show = subp.add_parser( "show", prefix_chars="-+", help="display history of a session, default command" ) show.add_argument( "-r", dest="reverse", default=False, action="store_true", help="reverses the direction", ) show.add_argument( "-n", dest="numerate", default=False, action="store_true", help="numerate each command", ) show.add_argument( "-t", dest="timestamp", default=False, action="store_true", help="show command timestamps", ) show.add_argument( "-T", dest="end_time", default=None, help="show only commands before timestamp" ) show.add_argument( "+T", dest="start_time", default=None, help="show only commands after timestamp" ) show.add_argument( "-f", dest="datetime_format", default=None, help="the datetime format to be used for" "filtering and printing", ) show.add_argument( "-0", dest="null_byte", default=False, action="store_true", help="separate commands by the null character for piping " "history to external filters", ) show.add_argument( "session", nargs="?", choices=_XH_HISTORY_SESSIONS.keys(), default="session", metavar="session", help="{} (default: current session, all is an alias for xonsh)" "".format(", ".join(map(repr, _XH_HISTORY_SESSIONS.keys()))), ) show.add_argument( "slices", nargs="*", default=None, metavar="slice", help="integer or slice notation", ) # 'id' subcommand subp.add_parser("id", help="display the current session id") # 'file' subcommand subp.add_parser("file", help="display the current history filename") # 'info' subcommand info = subp.add_parser( "info", help=("display information about the " "current history") ) info.add_argument( "--json", dest="json", default=False, action="store_true", help="print in JSON format", ) # gc gcp = subp.add_parser("gc", help="launches a new history garbage collector") gcp.add_argument( "--size", nargs=2, dest="size", default=None, help=( "next two arguments represent the history size and " 'units; e.g. "--size 8128 commands"' ), ) bgcp = gcp.add_mutually_exclusive_group() bgcp.add_argument( "--blocking", dest="blocking", default=True, action="store_true", help=("ensures that the gc blocks the main thread, " "default True"), ) bgcp.add_argument( "--non-blocking", dest="blocking", action="store_false", help="makes the gc non-blocking, and thus return sooner", ) hist = builtins.__xonsh__.history if isinstance(hist, JsonHistory): # add actions belong only to JsonHistory diff = subp.add_parser("diff", help="diff two xonsh history files") xdh.dh_create_parser(p=diff) import xonsh.replay as xrp replay = subp.add_parser("replay", help="replay a xonsh history file") xrp.replay_create_parser(p=replay) _XH_MAIN_ACTIONS.add("replay") return p def _xh_parse_args(args): """Prepare and parse arguments for the history command. Add default action for ``history`` and default session for ``history show``. """ parser = _xh_create_parser() if not args: args = ["show", "session"] elif args[0] not in _XH_MAIN_ACTIONS and args[0] not in ("-h", "--help"): args = ["show", "session"] + args if args[0] == "show": if not any(a in _XH_HISTORY_SESSIONS for a in args): args.insert(1, "session") ns, slices = parser.parse_known_args(args) if slices: if not ns.slices: ns.slices = slices else: ns.slices.extend(slices) else: ns = parser.parse_args(args) return ns def history_main( args=None, stdin=None, stdout=None, stderr=None, spec=None, stack=None ): """This is the history command entry point.""" hist = builtins.__xonsh__.history ns = _xh_parse_args(args) if not ns or not ns.action: return if ns.action == "show": _xh_show_history(hist, ns, stdout=stdout, stderr=stderr) elif ns.action == "info": data = hist.info() if ns.json: s = json.dumps(data) print(s, file=stdout) else: lines = ["{0}: {1}".format(k, v) for k, v in data.items()] print("\n".join(lines), file=stdout) elif ns.action == "id": if not hist.sessionid: return print(str(hist.sessionid), file=stdout) elif ns.action == "file": if not hist.filename: return print(str(hist.filename), file=stdout) elif ns.action == "gc": hist.run_gc(size=ns.size, blocking=ns.blocking) elif ns.action == "diff": if isinstance(hist, JsonHistory): xdh.dh_main_action(ns) elif ns.action == "replay": if isinstance(hist, JsonHistory): import xonsh.replay as xrp xrp.replay_main_action(hist, ns, stdout=stdout, stderr=stderr) else: print("Unknown history action {}".format(ns.action), file=sys.stderr)
6,113
934
{ "theme_name": "IDA-Dark by UNIS", "author": "UNIS", "version": "v1.0", "preview_image": "preview.png", "clr_file": "myColors.clr", "qss_file": "stylesheet.qss" }
95
1,006
<reponame>eenurkka/incubator-nuttx /**************************************************************************** * include/nuttx/ioexpander/tca64xx.h * * Copyright (C) 2016 <NAME>. All rights reserved. * Author: <NAME> <<EMAIL>> * * This header file derives, in part, from the Project Ara TCA64xx driver * which has this copyright: * * Copyright (c) 2014-2015 Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_IOEXPANDER_TCA64XX_H #define __INCLUDE_NUTTX_IOEXPANDER_TCA64XX_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> /**************************************************************************** * Public Types ****************************************************************************/ /* Identifies supported TCA64xx parts (as well as the number of supported * parts). */ enum tca64xx_part_e { TCA6408_PART = 0, TCA6416_PART, TCA6424_PART, TCA64_NPARTS }; #ifdef CONFIG_TCA64XX_INT_ENABLE /* This is the type of the TCA64xx interrupt handler */ typedef CODE void (*tca64_handler_t)(FAR void *arg); #endif /* A reference to a structure of this type must be passed to the TCA64xx * driver when the driver is instantiated. This structure provides * information about the configuration of the TCA64xx and provides some * board-specific hooks. * * Memory for this structure is provided by the caller. It is not copied by * the driver and is presumed to persist while the driver is active. The * memory must be writeable because, under certain circumstances, the driver * may modify the frequency. */ struct tca64_config_s { /* Device characterization */ uint8_t address; /* 7-bit I2C address (only bits 0-6 used) */ uint8_t part; /* See enum tca64xx_part_e */ uint32_t frequency; /* I2C or SPI frequency */ #ifdef CONFIG_TCA64XX_INT_ENABLE /* IRQ/GPIO access callbacks. These operations all hidden behind * callbacks to isolate the TCA64xx driver from differences in GPIO * interrupt handling by varying boards and MCUs. * * attach - Attach the TCA64xx interrupt handler to the GPIO interrupt * enable - Enable or disable the GPIO interrupt */ CODE int (*attach)(FAR struct tca64_config_s *state, tca64_handler_t handler, FAR void *arg); CODE void (*enable)(FAR struct tca64_config_s *state, bool enable); #endif }; /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: tca64_initialize * * Description: * Instantiate and configure the TCA64xx device driver to use the provided * I2C device instance. * * Input Parameters: * i2c - An I2C driver instance * minor - The device i2c address * config - Persistent board configuration data * * Returned Value: * an ioexpander_dev_s instance on success, NULL on failure. * ****************************************************************************/ struct i2c_master_s; FAR struct ioexpander_dev_s *tca64_initialize(FAR struct i2c_master_s *i2c, FAR struct tca64_config_s *config); #endif /* __INCLUDE_NUTTX_IOEXPANDER_TCA64XX_H */
1,440
402
/* * Copyright 2000-2021 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.flow.internal.nodefeature; import java.util.ArrayDeque; import java.util.Deque; import java.util.Optional; import java.util.function.Consumer; import com.vaadin.flow.internal.StateNode; import com.vaadin.flow.internal.change.NodeChange; import com.vaadin.flow.shared.util.UniqueSerializable; /** * Server-side feature defining whether a node is inert, and if it should ignore * inheriting inert state from parent. By default, a node is not inert, and it * will inherit the inert state from the parent. If the node lacks the inert * feature, then it will be just inheriting the state from parent. * <p> * The inert status is only updated when the changes are written to the client * side because the inert state changes are applied for upcoming requests from * the client side. Thus when an RPC call (like any DOM event) causes a node to * become inert, the inert state does not block any pending executions until * changes are written to the client side. * <p> * Implementation notes: The inert state changes are collected like with client * side changes (markAsDirty), but nothing is actually sent to the client side. * This is just to make sure the changes are applied when needed, when writing * changes to client side, instead of applying them immediately. By default the * elements only have the inert data feature but as "not initialized" state * which means that the node is not inert unless parent is inert, and thus it * does not ignore parent inert by default. The inert data feature is * initialized when the node will be made explicitly inert or to explicitly * ignore parent inert data. */ public class InertData extends ServerSideFeature { // Null is ignored by Map.computeIfAbsent -> using a marker value instead private static final UniqueSerializable NULL_MARKER = new UniqueSerializable() { // empty }; private boolean ignoreParentInert; private boolean inertSelf; /* * This value stores the latest inert status that the node had before the * latest response was sent to the client side. Otherwise any RPC handler * code that changes the inert state for a node in a request could cause * unwanted RPC handler executions to occur. */ private Boolean cachedInert; /** * Creates a new feature for the given node. * * @param node * the node which supports the feature */ public InertData(StateNode node) { super(node); } /** * Sets whether or not the node should ignore parent's inert state or not. * By default the parent state is inherited {@code false}. * * @param ignoreParentInert * {@code true} for ignoring {@code false} for not */ public void setIgnoreParentInert(boolean ignoreParentInert) { if (this.ignoreParentInert != ignoreParentInert) { this.ignoreParentInert = ignoreParentInert; markAsDirty(); } } /** * Sets whether the node itself is inert. By default the node is not inert, * unless parent is inert and inhering parent inert is not blocked. * * @param inertSelf * {@code} true for setting the node explicitly inert, * {@code false} for not */ public void setInertSelf(boolean inertSelf) { if (this.inertSelf != inertSelf) { this.inertSelf = inertSelf; markAsDirty(); } } /** * Gets whether the node itself has been set to be inert (regardless of its * ancestors' inert setting). * * @return whether this node has been set inert */ public boolean isInertSelf() { return inertSelf; } /** * Gets whether the inertness setting of ancestor nodes should be ignored. * * @return whether this node should ignore its ancestors' inert setting */ public boolean isIgnoreParentInert() { return ignoreParentInert; } @Override public void generateChangesFromEmpty() { updateInertAndCascadeToChildren(null); } @Override public void collectChanges(Consumer<NodeChange> collector) { updateInertAndCascadeToChildren(null); } private void markAsDirty() { /* * Even though not sending any changes to client, making sure the inert * status is updated for the node before writing the response by using * the same mechanism as collecting changes to the client. */ getNode().markAsDirty(); getNode().getChangeTracker(this, () -> NULL_MARKER); } /** * Returns whether this node is explicitly inert and if not, then checks * parents for the same. The returned value has been updated when the most * recent changes have been written to the client side. * * @return {@code true} for inert, {@code false} for not */ public boolean isInert() { if (cachedInert == null) { final StateNode parent = getNode().getParent(); return parent != null && parent.isInert(); } else { return cachedInert; } } private void updateInertAndCascadeToChildren(Boolean resolvedParentInert) { boolean newInert = resolveInert(resolvedParentInert); if (cachedInert != null && cachedInert == newInert) { return; } // cascade update to all children unless those are ignoring parent // value or have same value and thus don't need updating. // (all explicitly updated nodes are visited separately) Deque<StateNode> stack = new ArrayDeque<>(); getNode().forEachChild(stack::add); while (!stack.isEmpty()) { StateNode node = stack.pop(); if (node.hasFeature(InertData.class)) { final Optional<InertData> featureIfInitialized = node .getFeatureIfInitialized(InertData.class); if (featureIfInitialized.isPresent()) { featureIfInitialized.get() .updateInertAndCascadeToChildren(newInert); } else { node.forEachChild(stack::push); } } else { node.forEachChild(stack::push); } } cachedInert = newInert; } private boolean resolveInert(Boolean resolvedParentInert) { StateNode parent = getNode().getParent(); if (inertSelf || ignoreParentInert || parent == null) { return inertSelf; } if (resolvedParentInert != null) { return resolvedParentInert; } do { final Optional<InertData> optionalInertData = parent .getFeatureIfInitialized(InertData.class); if (optionalInertData.isPresent()) { // Most state nodes will not have inert data so using recursion // is safe. Need to use resolveInert() as the execution order of // change collection is random return optionalInertData.get().resolveInert(null); } else { parent = parent.getParent(); } } while (parent != null); return false; } /* * Not overriding allowChanges() since that is tied to isInactive() in state * node, which is always inherited from parent (this is maybe inherited). */ }
2,903
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Scye","circ":"1ère circonscription","dpt":"Haute-Saône","inscrits":104,"abs":25,"votants":79,"blancs":2,"nuls":14,"exp":63,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":38},{"nuance":"FN","nom":"Mme <NAME>","voix":25}]}
114
872
<reponame>krishna13052001/LeetCode #!/usr/bin/python3 """ Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". Example 3: Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c". Example 4: Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b". Note: 1 <= S.length <= 200 1 <= T.length <= 200 S and T only contain lowercase letters and '#' characters. Follow up: Can you solve it in O(N) time and O(1) space? """ class Solution: def backspaceCompare(self, S: str, T: str) -> bool: """ stk use a stk to build the string Another approach: Iterate the string reversely. When encountering "#", count, and skip the chars based on skip count. """ return self.make_stk(S) == self.make_stk(T) def make_stk(self, S): stk = [] for s in S: if s == "#": if stk: stk.pop() else: stk.append(s) return stk
571
488
public class Synch { public synchronized void s() { // This call to notify() isn't supposed to cause a // java.lang.IllegalMonitorStateException. notify (); } public static void main (String[] args) { (new Synch()).s(); System.out.println ("Ok"); } }
119
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/guest_os/guest_os_registry_service.h" #include <utility> #include "ash/constants/ash_features.h" #include "ash/public/cpp/app_list/app_list_config.h" #include "base/bind.h" #include "base/feature_list.h" #include "base/files/file_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/time/clock.h" #include "base/time/default_clock.h" #include "base/time/time.h" #include "chrome/browser/apps/app_service/app_icon/app_icon_factory.h" #include "chrome/browser/apps/app_service/app_icon/dip_px_util.h" #include "chrome/browser/ash/borealis/borealis_features.h" #include "chrome/browser/ash/borealis/borealis_service.h" #include "chrome/browser/ash/crostini/crostini_features.h" #include "chrome/browser/ash/crostini/crostini_manager.h" #include "chrome/browser/ash/crostini/crostini_shelf_utils.h" #include "chrome/browser/ash/guest_os/guest_os_pref_names.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_features.h" #include "chrome/browser/ash/plugin_vm/plugin_vm_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/icon_transcoder/svg_icon_transcoder.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/app_list_syncable_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" #include "chrome/grit/app_icon_resources.h" #include "chrome/grit/generated_resources.h" #include "chromeos/dbus/vm_applications/apps.pb.h" #include "components/crx_file/id_util.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/services/app_service/public/cpp/icon_types.h" #include "extensions/browser/api/file_handlers/mime_util.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/image/image_skia_operations.h" using vm_tools::apps::App; namespace guest_os { namespace { // This prefix is used when generating the crostini app list id. constexpr char kCrostiniAppIdPrefix[] = "crostini:"; constexpr char kCrostiniIconFolder[] = "crostini.icons"; constexpr char kCrostiniAppsInstalledHistogram[] = "Crostini.AppsInstalledAtLogin"; constexpr char kPluginVmAppsInstalledHistogram[] = "PluginVm.AppsInstalledAtLogin"; constexpr char kBorealisAppsInstalledHistogram[] = "Borealis.AppsInstalledAtLogin"; base::Value ProtoToDictionary(const App::LocaleString& locale_string) { base::Value result(base::Value::Type::DICTIONARY); for (const App::LocaleString::Entry& entry : locale_string.values()) { const std::string& locale = entry.locale(); std::string locale_with_dashes(locale); std::replace(locale_with_dashes.begin(), locale_with_dashes.end(), '_', '-'); if (!locale.empty() && !l10n_util::IsValidLocaleSyntax(locale_with_dashes)) { continue; } result.SetKey(locale, base::Value(entry.value())); } return result; } std::set<std::string> ListToStringSet(const base::Value* list, bool to_lower_ascii = false) { std::set<std::string> result; if (!list) { return result; } for (const base::Value& value : list->GetList()) { result.insert(to_lower_ascii ? base::ToLowerASCII(value.GetString()) : value.GetString()); } return result; } base::Value ProtoToList( const google::protobuf::RepeatedPtrField<std::string>& strings) { base::Value result(base::Value::Type::LIST); for (const std::string& string : strings) { result.Append(string); } return result; } base::Value LocaleStringsProtoToDictionary( const App::LocaleStrings& repeated_locale_string) { base::Value result(base::Value::Type::DICTIONARY); for (const auto& strings_with_locale : repeated_locale_string.values()) { const std::string& locale = strings_with_locale.locale(); std::string locale_with_dashes(locale); std::replace(locale_with_dashes.begin(), locale_with_dashes.end(), '_', '-'); if (!locale.empty() && !l10n_util::IsValidLocaleSyntax(locale_with_dashes)) { continue; } result.SetKey(locale, ProtoToList(strings_with_locale.value())); } return result; } // Populate |pref_registration| based on the given App proto. // |name| should be |app.name()| in Dictionary form. void PopulatePrefRegistrationFromApp(base::Value& pref_registration, GuestOsRegistryService::VmType vm_type, const std::string& vm_name, const std::string& container_name, const vm_tools::apps::App& app, base::Value name) { pref_registration.SetKey(guest_os::prefs::kAppDesktopFileIdKey, base::Value(app.desktop_file_id())); pref_registration.SetIntKey(guest_os::prefs::kAppVmTypeKey, static_cast<int>(vm_type)); pref_registration.SetKey(guest_os::prefs::kAppVmNameKey, base::Value(vm_name)); pref_registration.SetKey(guest_os::prefs::kAppContainerNameKey, base::Value(container_name)); pref_registration.SetKey(guest_os::prefs::kAppNameKey, std::move(name)); pref_registration.SetKey(guest_os::prefs::kAppCommentKey, ProtoToDictionary(app.comment())); pref_registration.SetKey(guest_os::prefs::kAppExecKey, base::Value(app.exec())); pref_registration.SetKey(guest_os::prefs::kAppExecutableFileNameKey, base::Value(app.executable_file_name())); pref_registration.SetKey(guest_os::prefs::kAppExtensionsKey, ProtoToList(app.extensions())); pref_registration.SetKey(guest_os::prefs::kAppMimeTypesKey, ProtoToList(app.mime_types())); pref_registration.SetKey(guest_os::prefs::kAppKeywordsKey, LocaleStringsProtoToDictionary(app.keywords())); pref_registration.SetKey(guest_os::prefs::kAppNoDisplayKey, base::Value(app.no_display())); pref_registration.SetKey(guest_os::prefs::kAppStartupWMClassKey, base::Value(app.startup_wm_class())); pref_registration.SetKey(guest_os::prefs::kAppStartupNotifyKey, base::Value(app.startup_notify())); pref_registration.SetKey(guest_os::prefs::kAppPackageIdKey, base::Value(app.package_id())); } bool EqualsExcludingTimestamps(const base::Value& left, const base::Value& right) { auto left_items = left.DictItems(); auto right_items = right.DictItems(); auto left_iter = left_items.begin(); auto right_iter = right_items.begin(); while (left_iter != left_items.end() && right_iter != right_items.end()) { if (left_iter->first == guest_os::prefs::kAppInstallTimeKey || left_iter->first == guest_os::prefs::kAppLastLaunchTimeKey) { ++left_iter; continue; } if (right_iter->first == guest_os::prefs::kAppInstallTimeKey || right_iter->first == guest_os::prefs::kAppLastLaunchTimeKey) { ++right_iter; continue; } if (*left_iter != *right_iter) return false; ++left_iter; ++right_iter; } return left_iter == left_items.end() && right_iter == right_items.end(); } void InstallIconFromFileThread(const base::FilePath& icon_path, const std::string& content) { DCHECK(!content.empty()); base::CreateDirectory(icon_path.DirName()); int wrote = base::WriteFile(icon_path, content.c_str(), content.size()); if (wrote != static_cast<int>(content.size())) { VLOG(2) << "Failed to write Crostini icon file: " << icon_path.MaybeAsASCII(); if (!base::DeleteFile(icon_path)) { VLOG(2) << "Couldn't delete broken icon file" << icon_path.MaybeAsASCII(); } } } void DeleteIconFolderFromFileThread(const base::FilePath& path) { DCHECK(path.DirName().BaseName().MaybeAsASCII() == kCrostiniIconFolder && (!base::PathExists(path) || base::DirectoryExists(path))); const bool deleted = base::DeletePathRecursively(path); DCHECK(deleted); } template <typename List> static std::string Join(const List& list); static std::string ToString(bool b) { return b ? "true" : "false"; } static std::string ToString(int i) { return base::NumberToString(i); } static std::string ToString(const std::string& string) { return '"' + string + '"'; } static std::string ToString( const google::protobuf::RepeatedPtrField<std::string>& list) { return Join(list); } static std::string ToString( const vm_tools::apps::App_LocaleString_Entry& entry) { return "{locale: " + ToString(entry.locale()) + ", value: " + ToString(entry.value()) + "}"; } static std::string ToString( const vm_tools::apps::App_LocaleStrings_StringsWithLocale& strings_with_locale) { return "{locale: " + ToString(strings_with_locale.locale()) + ", value: " + ToString(strings_with_locale.value()) + "}"; } static std::string ToString(const vm_tools::apps::App_LocaleString& string) { return Join(string.values()); } static std::string ToString(const vm_tools::apps::App_LocaleStrings& strings) { return Join(strings.values()); } static std::string ToString(const vm_tools::apps::App& app) { return "{desktop_file_id: " + ToString(app.desktop_file_id()) + ", name: " + ToString(app.name()) + ", comment: " + ToString(app.comment()) + ", mime_types: " + ToString(app.mime_types()) + ", no_display: " + ToString(app.no_display()) + ", startup_wm_class: " + ToString(app.startup_wm_class()) + ", startup_notify: " + ToString(app.startup_notify()) + ", keywords: " + ToString(app.keywords()) + ", exec: " + ToString(app.exec()) + ", executable_file_name: " + ToString(app.executable_file_name()) + ", package_id: " + ToString(app.package_id()) + ", extensions: " + ToString(app.extensions()) + "}"; } static std::string ToString(const vm_tools::apps::ApplicationList& list) { return "{apps: " + Join(list.apps()) + ", vm_type: " + ToString(list.vm_type()) + ", vm_name: " + ToString(list.vm_name()) + ", container_name: " + ToString(list.container_name()) + ", owner_id: " + ToString(list.owner_id()) + "}"; } template <typename List> static std::string Join(const List& list) { std::string joined = "["; const char* seperator = ""; for (const auto& list_item : list) { joined += seperator + ToString(list_item); seperator = ", "; } joined += "]"; return joined; } void SetLocaleString(App::LocaleString* locale_string, const std::string& locale, const std::string& value) { DCHECK(!locale.empty()); App::LocaleString::Entry* entry = locale_string->add_values(); // Add both specified locale, and empty default. for (auto& l : {locale, std::string()}) { entry->set_locale(l); entry->set_value(value); } } void SetLocaleStrings(App::LocaleStrings* locale_strings, const std::string& locale, std::vector<std::string> values) { DCHECK(!locale.empty()); App::LocaleStrings::StringsWithLocale* strings = locale_strings->add_values(); // Add both specified locale, and empty default. for (auto& l : {locale, std::string()}) { strings->set_locale(l); for (auto& v : values) { strings->add_value(v); } } } // Creates a Terminal registration using partial values from prefs such as // last_launch_time. GuestOsRegistryService::Registration GetTerminalRegistration( const base::Value* pref) { std::string locale = l10n_util::NormalizeLocale(g_browser_process->GetApplicationLocale()); vm_tools::apps::App app; SetLocaleString(app.mutable_name(), locale, l10n_util::GetStringUTF8(IDS_CROSTINI_TERMINAL_APP_NAME)); app.add_mime_types( extensions::app_file_handler_util::kMimeTypeInodeDirectory); SetLocaleStrings( app.mutable_keywords(), locale, {"linux", "terminal", "crostini", l10n_util::GetStringUTF8(IDS_CROSTINI_TERMINAL_APP_SEARCH_TERMS)}); base::Value pref_registration = pref ? pref->Clone() : base::Value(base::Value::Type::DICTIONARY); PopulatePrefRegistrationFromApp( pref_registration, GuestOsRegistryService::VmType::ApplicationList_VmType_TERMINA, crostini::kCrostiniDefaultVmName, crostini::kCrostiniDefaultContainerName, app, ProtoToDictionary(app.name())); return GuestOsRegistryService::Registration( crostini::kCrostiniTerminalSystemAppId, std::move(pref_registration)); } } // namespace GuestOsRegistryService::Registration::Registration(std::string app_id, base::Value pref) : app_id_(std::move(app_id)), pref_(std::move(pref)) {} GuestOsRegistryService::Registration::~Registration() = default; std::string GuestOsRegistryService::Registration::DesktopFileId() const { return GetString(guest_os::prefs::kAppDesktopFileIdKey); } GuestOsRegistryService::VmType GuestOsRegistryService::Registration::VmType() const { if (!pref_.is_dict()) { return GuestOsRegistryService::VmType::ApplicationList_VmType_TERMINA; } // The VmType field is new, existing Apps that do not include it must be // TERMINA (0) Apps, as Plugin VM apps are not yet in production. return static_cast<GuestOsRegistryService::VmType>( pref_.FindIntKey(guest_os::prefs::kAppVmTypeKey).value_or(0)); } std::string GuestOsRegistryService::Registration::VmName() const { return GetString(guest_os::prefs::kAppVmNameKey); } std::string GuestOsRegistryService::Registration::ContainerName() const { return GetString(guest_os::prefs::kAppContainerNameKey); } std::string GuestOsRegistryService::Registration::Name() const { if (VmType() == VmType::ApplicationList_VmType_PLUGIN_VM) { return l10n_util::GetStringFUTF8( IDS_PLUGIN_VM_APP_NAME_WINDOWS_SUFFIX, base::UTF8ToUTF16(GetLocalizedString(guest_os::prefs::kAppNameKey))); } return GetLocalizedString(guest_os::prefs::kAppNameKey); } std::string GuestOsRegistryService::Registration::Comment() const { return GetLocalizedString(guest_os::prefs::kAppCommentKey); } std::string GuestOsRegistryService::Registration::Exec() const { return GetString(guest_os::prefs::kAppExecKey); } std::string GuestOsRegistryService::Registration::ExecutableFileName() const { return GetString(guest_os::prefs::kAppExecutableFileNameKey); } std::set<std::string> GuestOsRegistryService::Registration::Extensions() const { if (!pref_.is_dict()) { return {}; } // Convert to lowercase ASCII to allow case-insensitive match. return ListToStringSet(pref_.FindKeyOfType(guest_os::prefs::kAppExtensionsKey, base::Value::Type::LIST), /*to_lower_ascii=*/true); } std::set<std::string> GuestOsRegistryService::Registration::MimeTypes() const { if (!pref_.is_dict()) { return {}; } // Convert to lowercase ASCII to allow case-insensitive match. return ListToStringSet(pref_.FindKeyOfType(guest_os::prefs::kAppMimeTypesKey, base::Value::Type::LIST), /*to_lower_ascii=*/true); } std::set<std::string> GuestOsRegistryService::Registration::Keywords() const { return GetLocalizedList(guest_os::prefs::kAppKeywordsKey); } bool GuestOsRegistryService::Registration::NoDisplay() const { return GetBool(guest_os::prefs::kAppNoDisplayKey); } std::string GuestOsRegistryService::Registration::PackageId() const { return GetString(guest_os::prefs::kAppPackageIdKey); } bool GuestOsRegistryService::Registration::CanUninstall() const { if (!pref_.is_dict()) { return false; } // We can uninstall if and only if there is a package that owns the // application. If no package owns the application, we don't know how to // uninstall the app. // // We don't check other things that might prevent us from uninstalling the // app. In particular, we don't check if there are other packages which // depend on the owning package. This should be rare for packages that have // desktop files, and it's better to show an error message (which the user can // then Google to learn more) than to just not have an uninstall option at // all. const base::Value* package_id = pref_.FindKeyOfType( guest_os::prefs::kAppPackageIdKey, base::Value::Type::STRING); if (package_id) { return !package_id->GetString().empty(); } return false; } base::Time GuestOsRegistryService::Registration::InstallTime() const { return GetTime(guest_os::prefs::kAppInstallTimeKey); } base::Time GuestOsRegistryService::Registration::LastLaunchTime() const { return GetTime(guest_os::prefs::kAppLastLaunchTimeKey); } bool GuestOsRegistryService::Registration::IsScaled() const { return GetBool(guest_os::prefs::kAppScaledKey); } std::string GuestOsRegistryService::Registration::GetString( base::StringPiece key) const { if (!pref_.is_dict()) { return std::string(); } const base::Value* value = pref_.FindKeyOfType(key, base::Value::Type::STRING); if (!value) { return std::string(); } return value->GetString(); } bool GuestOsRegistryService::Registration::GetBool( base::StringPiece key) const { if (!pref_.is_dict()) { return false; } const base::Value* value = pref_.FindKeyOfType(key, base::Value::Type::BOOLEAN); if (!value) { return false; } return value->GetBool(); } // This is the companion to GuestOsRegistryService::SetCurrentTime(). base::Time GuestOsRegistryService::Registration::GetTime( base::StringPiece key) const { if (!pref_.is_dict()) { return base::Time(); } const base::Value* value = pref_.FindKeyOfType(key, base::Value::Type::STRING); int64_t time; if (!value || !base::StringToInt64(value->GetString(), &time)) { return base::Time(); } return base::Time::FromDeltaSinceWindowsEpoch(base::Microseconds(time)); } // We store in prefs all the localized values for given fields (formatted with // undescores, e.g. 'fr' or 'en_US'), but users of the registry don't need to // deal with this. std::string GuestOsRegistryService::Registration::GetLocalizedString( base::StringPiece key) const { if (!pref_.is_dict()) { return std::string(); } const base::Value* dict = pref_.FindKeyOfType(key, base::Value::Type::DICTIONARY); if (!dict) { return std::string(); } std::string current_locale = l10n_util::NormalizeLocale(g_browser_process->GetApplicationLocale()); std::vector<std::string> locales; l10n_util::GetParentLocales(current_locale, &locales); // We use an empty locale as fallback. locales.push_back(std::string()); for (const std::string& locale : locales) { const base::Value* value = dict->FindKeyOfType(locale, base::Value::Type::STRING); if (value) { return value->GetString(); } } return std::string(); } std::set<std::string> GuestOsRegistryService::Registration::GetLocalizedList( base::StringPiece key) const { if (!pref_.is_dict()) { return {}; } const base::Value* dict = pref_.FindKeyOfType(key, base::Value::Type::DICTIONARY); if (!dict) { return {}; } std::string current_locale = l10n_util::NormalizeLocale(g_browser_process->GetApplicationLocale()); std::vector<std::string> locales; l10n_util::GetParentLocales(current_locale, &locales); // We use an empty locale as fallback. locales.push_back(std::string()); for (const std::string& locale : locales) { const base::Value* value = dict->FindKeyOfType(locale, base::Value::Type::LIST); if (value) { return ListToStringSet(value); } } return {}; } GuestOsRegistryService::GuestOsRegistryService(Profile* profile) : profile_(profile), prefs_(profile->GetPrefs()), base_icon_path_(profile->GetPath().AppendASCII(kCrostiniIconFolder)), clock_(base::DefaultClock::GetInstance()), svg_icon_transcoder_(std::make_unique<apps::SvgIconTranscoder>(profile)) { RecordStartupMetrics(); } GuestOsRegistryService::~GuestOsRegistryService() = default; base::WeakPtr<GuestOsRegistryService> GuestOsRegistryService::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } std::map<std::string, GuestOsRegistryService::Registration> GuestOsRegistryService::GetAllRegisteredApps() const { const base::Value* apps = prefs_->GetDictionary(guest_os::prefs::kGuestOsRegistry); std::map<std::string, GuestOsRegistryService::Registration> result; // Register Terminal by merging optional prefs with app values. if (!base::FeatureList::IsEnabled(chromeos::features::kTerminalSSH)) { result.emplace(crostini::kCrostiniTerminalSystemAppId, GetTerminalRegistration(apps->FindKeyOfType( crostini::kCrostiniTerminalSystemAppId, base::Value::Type::DICTIONARY))); } for (const auto item : apps->DictItems()) { if (item.first != crostini::kCrostiniTerminalSystemAppId) { result.emplace(item.first, Registration(item.first, item.second.Clone())); } } return result; } std::map<std::string, GuestOsRegistryService::Registration> GuestOsRegistryService::GetEnabledApps() const { bool crostini_enabled = crostini::CrostiniFeatures::Get()->IsEnabled(profile_); bool plugin_vm_enabled = plugin_vm::PluginVmFeatures::Get()->IsEnabled(profile_); bool borealis_enabled = borealis::BorealisService::GetForProfile(profile_) ->Features() .IsEnabled(); if (!crostini_enabled && !plugin_vm_enabled && !borealis_enabled) { return {}; } auto apps = GetAllRegisteredApps(); for (auto it = apps.cbegin(); it != apps.cend();) { bool enabled = false; switch (it->second.VmType()) { case VmType::ApplicationList_VmType_TERMINA: enabled = crostini_enabled; break; case VmType::ApplicationList_VmType_PLUGIN_VM: enabled = plugin_vm_enabled; break; case VmType::ApplicationList_VmType_BOREALIS: enabled = borealis_enabled; break; default: LOG(ERROR) << "Unsupported VmType: " << static_cast<int>(it->second.VmType()); } if (enabled) { ++it; } else { it = apps.erase(it); } } return apps; } std::map<std::string, GuestOsRegistryService::Registration> GuestOsRegistryService::GetRegisteredApps(VmType vm_type) const { auto apps = GetAllRegisteredApps(); for (auto it = apps.cbegin(); it != apps.cend();) { if (it->second.VmType() == vm_type) { ++it; } else { it = apps.erase(it); } } return apps; } absl::optional<GuestOsRegistryService::Registration> GuestOsRegistryService::GetRegistration(const std::string& app_id) const { const base::Value* apps = prefs_->GetDictionary(guest_os::prefs::kGuestOsRegistry); if (app_id == crostini::kCrostiniTerminalSystemAppId) { return GetTerminalRegistration(apps->FindKeyOfType( crostini::kCrostiniTerminalSystemAppId, base::Value::Type::DICTIONARY)); } const base::Value* pref_registration = apps->FindKeyOfType(app_id, base::Value::Type::DICTIONARY); if (!pref_registration) { return absl::nullopt; } return absl::make_optional<Registration>(app_id, pref_registration->Clone()); } void GuestOsRegistryService::RecordStartupMetrics() { const base::Value* apps = prefs_->GetDictionary(guest_os::prefs::kGuestOsRegistry); base::flat_map<int, int> num_apps; for (const auto item : apps->DictItems()) { if (item.first == crostini::kCrostiniTerminalSystemAppId) { continue; } absl::optional<bool> no_display = item.second.FindBoolKey(guest_os::prefs::kAppNoDisplayKey); if (no_display && no_display.value()) { continue; } int vm_type = item.second.FindIntKey(guest_os::prefs::kAppVmTypeKey).value_or(0); num_apps[vm_type]++; } if (crostini::CrostiniFeatures::Get()->IsEnabled(profile_)) { UMA_HISTOGRAM_COUNTS_1000(kCrostiniAppsInstalledHistogram, num_apps[VmType::ApplicationList_VmType_TERMINA]); } if (plugin_vm::PluginVmFeatures::Get()->IsEnabled(profile_)) { UMA_HISTOGRAM_COUNTS_1000( kPluginVmAppsInstalledHistogram, num_apps[VmType::ApplicationList_VmType_PLUGIN_VM]); } if (borealis::BorealisService::GetForProfile(profile_) ->Features() .IsEnabled()) { UMA_HISTOGRAM_COUNTS_1000( kBorealisAppsInstalledHistogram, num_apps[VmType::ApplicationList_VmType_BOREALIS]); } } base::FilePath GuestOsRegistryService::GetAppPath( const std::string& app_id) const { return base_icon_path_.AppendASCII(app_id); } base::FilePath GuestOsRegistryService::GetIconPath( const std::string& app_id, ui::ResourceScaleFactor scale_factor) const { const base::FilePath app_path = GetAppPath(app_id); switch (scale_factor) { case ui::k100Percent: return app_path.AppendASCII("icon_100p.png"); case ui::k200Percent: return app_path.AppendASCII("icon_200p.png"); case ui::k300Percent: return app_path.AppendASCII("icon_300p.png"); case ui::kScaleFactorNone: return app_path.AppendASCII("icon.svg"); default: NOTREACHED(); return base::FilePath(); } } void GuestOsRegistryService::LoadIcon(const std::string& app_id, const apps::IconKey& icon_key, apps::IconType icon_type, int32_t size_hint_in_dip, bool allow_placeholder_icon, int fallback_icon_resource_id, apps::LoadIconCallback callback) { // Add container-badging to all crostini apps except the terminal, which is // shared between containers. This is part of the multi-container UI, so is // guarded by a flag. if (app_id != crostini::kCrostiniTerminalSystemAppId && crostini::CrostiniFeatures::Get()->IsMultiContainerAllowed(profile_)) { auto reg = GetRegistration(app_id); if (reg && reg->VmType() == VmType::ApplicationList_VmType_TERMINA) { callback = base::BindOnce( &GuestOsRegistryService::ApplyContainerBadge, weak_ptr_factory_.GetWeakPtr(), crostini::GetContainerBadgeColor( profile_, crostini::ContainerId(reg->VmName(), reg->ContainerName())), std::move(callback)); } } if (icon_key.resource_id != apps::mojom::IconKey::kInvalidResourceId) { // The icon is a resource built into the Chrome OS binary. constexpr bool is_placeholder_icon = false; apps::LoadIconFromResource( icon_type, size_hint_in_dip, icon_key.resource_id, is_placeholder_icon, static_cast<apps::IconEffects>(icon_key.icon_effects), std::move(callback)); return; } // There are paths where nothing higher up the call stack will resize so // we need to ensure that returned icons are always resized to be // size_hint_in_dip big. crbug/1170455 is an example. apps::IconEffects icon_effects = static_cast<apps::IconEffects>( icon_key.icon_effects | apps::IconEffects::kResizeAndPad); auto scale_factor = apps_util::GetPrimaryDisplayUIScaleFactor(); auto load_icon_from_vm_fallback = base::BindOnce( &GuestOsRegistryService::LoadIconFromVM, weak_ptr_factory_.GetWeakPtr(), app_id, icon_type, size_hint_in_dip, scale_factor, icon_effects, fallback_icon_resource_id); auto transcode_svg_fallback = base::BindOnce( &GuestOsRegistryService::TranscodeIconFromSvg, weak_ptr_factory_.GetWeakPtr(), GetIconPath(app_id, ui::kScaleFactorNone), GetIconPath(app_id, scale_factor), icon_type, size_hint_in_dip, icon_effects, std::move(load_icon_from_vm_fallback)); // Try loading the icon from an on-disk cache. If that fails, try to transcode // the app's svg icon, and if that fails, fall back // to LoadIconFromVM. apps::LoadIconFromFileWithFallback( icon_type, size_hint_in_dip, GetIconPath(app_id, scale_factor), icon_effects, std::move(callback), std::move(transcode_svg_fallback)); } void GuestOsRegistryService::ApplyContainerBadge( SkColor badge_color, apps::LoadIconCallback callback, apps::IconValuePtr icon) { gfx::ImageSkia badge_mask = *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_ICON_BADGE_MASK); if (badge_mask.size() != icon->uncompressed.size()) { badge_mask = gfx::ImageSkiaOperations::CreateResizedImage( badge_mask, skia::ImageOperations::RESIZE_BEST, icon->uncompressed.size()); } badge_mask = gfx::ImageSkiaOperations::CreateColorMask(badge_mask, badge_color); icon->uncompressed = gfx::ImageSkiaOperations::CreateSuperimposedImage( icon->uncompressed, badge_mask); std::move(callback).Run(std::move(icon)); } void GuestOsRegistryService::TranscodeIconFromSvg( base::FilePath svg_path, base::FilePath png_path, apps::IconType icon_type, int32_t size_hint_in_dip, apps::IconEffects icon_effects, base::OnceCallback<void(apps::LoadIconCallback)> fallback, apps::LoadIconCallback callback) { svg_icon_transcoder_->Transcode( std::move(svg_path), std::move(png_path), gfx::Size(128, 128), base::BindOnce( [](apps::IconType icon_type, int32_t size_hint_in_dip, apps::IconEffects icon_effects, apps::LoadIconCallback callback, base::OnceCallback<void(apps::LoadIconCallback)> fallback, std::string icon_content) { if (!icon_content.empty()) { apps::LoadIconFromCompressedData( icon_type, size_hint_in_dip, icon_effects, std::move(icon_content), std::move(callback)); return; } if (fallback) { std::move(fallback).Run(std::move(callback)); } }, icon_type, size_hint_in_dip, icon_effects, std::move(callback), std::move(fallback))); } void GuestOsRegistryService::LoadIconFromVM( const std::string& app_id, apps::IconType icon_type, int32_t size_hint_in_dip, ui::ResourceScaleFactor scale_factor, apps::IconEffects icon_effects, int fallback_icon_resource_id, apps::LoadIconCallback callback) { RequestIcon(app_id, scale_factor, base::BindOnce(&GuestOsRegistryService::OnLoadIconFromVM, weak_ptr_factory_.GetWeakPtr(), app_id, icon_type, size_hint_in_dip, icon_effects, fallback_icon_resource_id, std::move(callback))); } void GuestOsRegistryService::OnLoadIconFromVM( const std::string& app_id, apps::IconType icon_type, int32_t size_hint_in_dip, apps::IconEffects icon_effects, int fallback_icon_resource_id, apps::LoadIconCallback callback, std::string compressed_icon_data) { if (compressed_icon_data.empty()) { if (fallback_icon_resource_id != apps::mojom::IconKey::kInvalidResourceId) { // We load the fallback icon, but we tell AppsService that this is not // a placeholder to avoid endless repeat calls since we don't expect to // find a better icon than this any time soon. apps::LoadIconFromResource( icon_type, size_hint_in_dip, fallback_icon_resource_id, /*is_placeholder_icon=*/false, icon_effects, std::move(callback)); } else { std::move(callback).Run(std::make_unique<apps::IconValue>()); } } else { apps::LoadIconFromCompressedData(icon_type, size_hint_in_dip, icon_effects, compressed_icon_data, std::move(callback)); } } void GuestOsRegistryService::RequestIcon( const std::string& app_id, ui::ResourceScaleFactor scale_factor, base::OnceCallback<void(std::string)> callback) { if (!GetRegistration(app_id)) { // App isn't registered (e.g. a GUI app launched from within Crostini // that doesn't have a .desktop file). Can't get an icon for that case so // return an empty icon. std::move(callback).Run({}); return; } // Coalesce calls to the container. auto& callbacks = active_icon_requests_[{app_id, scale_factor}]; callbacks.emplace_back(std::move(callback)); if (callbacks.size() > 1) { return; } RequestContainerAppIcon(app_id, scale_factor); } void GuestOsRegistryService::ClearApplicationList( VmType vm_type, const std::string& vm_name, const std::string& container_name) { std::vector<std::string> removed_apps; // The DictionaryPrefUpdate should be destructed before calling the observer. { DictionaryPrefUpdate update(prefs_, guest_os::prefs::kGuestOsRegistry); base::DictionaryValue* apps = update.Get(); for (const auto item : apps->DictItems()) { if (item.first == crostini::kCrostiniTerminalSystemAppId) { continue; } Registration registration(item.first, item.second.Clone()); if (vm_type != registration.VmType()) { continue; } if (vm_name != registration.VmName()) { continue; } if (!container_name.empty() && container_name != registration.ContainerName()) { continue; } removed_apps.push_back(item.first); } for (const std::string& removed_app : removed_apps) { RemoveAppData(removed_app); apps->RemoveKey(removed_app); } } if (removed_apps.empty()) { return; } std::vector<std::string> updated_apps; std::vector<std::string> inserted_apps; for (Observer& obs : observers_) { obs.OnRegistryUpdated(this, vm_type, updated_apps, removed_apps, inserted_apps); } } void GuestOsRegistryService::UpdateApplicationList( const vm_tools::apps::ApplicationList& app_list) { VLOG(1) << "Received ApplicationList : " << ToString(app_list); if (app_list.vm_name().empty()) { LOG(WARNING) << "Received app list with missing VM name"; return; } if (app_list.container_name().empty()) { LOG(WARNING) << "Received app list with missing container name"; return; } // We need to compute the diff between the new list of apps and the old list // of apps (with matching vm/container names). We keep a set of the new app // ids so that we can compute these and update the Dictionary directly. std::set<std::string> new_app_ids; std::vector<std::string> updated_apps; std::vector<std::string> removed_apps; std::vector<std::string> inserted_apps; // The DictionaryPrefUpdate should be destructed before calling the observer. { DictionaryPrefUpdate update(prefs_, guest_os::prefs::kGuestOsRegistry); base::DictionaryValue* apps = update.Get(); for (const App& app : app_list.apps()) { if (app.desktop_file_id().empty()) { LOG(WARNING) << "Received app with missing desktop file id"; continue; } base::Value name = ProtoToDictionary(app.name()); if (name.FindKey(base::StringPiece()) == nullptr) { LOG(WARNING) << "Received app '" << app.desktop_file_id() << "' with missing unlocalized name"; continue; } std::string app_id = GenerateAppId( app.desktop_file_id(), app_list.vm_name(), app_list.container_name()); new_app_ids.insert(app_id); base::Value pref_registration(base::Value::Type::DICTIONARY); PopulatePrefRegistrationFromApp( pref_registration, app_list.vm_type(), app_list.vm_name(), app_list.container_name(), app, std::move(name)); base::Value* old_app = apps->FindKey(app_id); if (old_app && EqualsExcludingTimestamps(pref_registration, *old_app)) { continue; } base::Value* old_install_time = nullptr; base::Value* old_last_launch_time = nullptr; if (old_app) { updated_apps.push_back(app_id); old_install_time = old_app->FindKey(guest_os::prefs::kAppInstallTimeKey); old_last_launch_time = old_app->FindKey(guest_os::prefs::kAppLastLaunchTimeKey); } else { inserted_apps.push_back(app_id); } if (old_install_time) { pref_registration.SetKey(guest_os::prefs::kAppInstallTimeKey, old_install_time->Clone()); } else { SetCurrentTime(&pref_registration, guest_os::prefs::kAppInstallTimeKey); } if (old_last_launch_time) { pref_registration.SetKey(guest_os::prefs::kAppLastLaunchTimeKey, old_last_launch_time->Clone()); } apps->SetKey(app_id, std::move(pref_registration)); } for (const auto item : apps->DictItems()) { if (item.first == crostini::kCrostiniTerminalSystemAppId) { continue; } if (item.second.FindKey(guest_os::prefs::kAppVmNameKey)->GetString() == app_list.vm_name() && item.second.FindKey(guest_os::prefs::kAppContainerNameKey) ->GetString() == app_list.container_name() && new_app_ids.find(item.first) == new_app_ids.end()) { removed_apps.push_back(item.first); } } for (const std::string& removed_app : removed_apps) { RemoveAppData(removed_app); apps->RemoveKey(removed_app); } } // When we receive notification of the application list then the container // *should* be online and we can retry all of our icon requests that failed // due to the container being offline. for (auto retry_iter = retry_icon_requests_.begin(); retry_iter != retry_icon_requests_.end(); ++retry_iter) { for (ui::ResourceScaleFactor scale_factor : ui::GetSupportedResourceScaleFactors()) { if (retry_iter->second & (1 << scale_factor)) { RequestContainerAppIcon(retry_iter->first, scale_factor); } } } retry_icon_requests_.clear(); if (updated_apps.empty() && removed_apps.empty() && inserted_apps.empty()) { return; } for (Observer& obs : observers_) { obs.OnRegistryUpdated(this, app_list.vm_type(), updated_apps, removed_apps, inserted_apps); } } void GuestOsRegistryService::ContainerBadgeColorChanged( const crostini::ContainerId& container_id) { std::vector<std::string> updated_apps; for (const auto& it : GetAllRegisteredApps()) { if (it.second.VmName() == container_id.vm_name && it.second.ContainerName() == container_id.container_name) { updated_apps.push_back(it.first); } } std::vector<std::string> removed_apps; std::vector<std::string> inserted_apps; for (Observer& obs : observers_) { obs.OnRegistryUpdated(this, VmType::ApplicationList_VmType_TERMINA, updated_apps, removed_apps, inserted_apps); } } void GuestOsRegistryService::RemoveAppData(const std::string& app_id) { // Remove any pending requests we have for this icon. retry_icon_requests_.erase(app_id); // Remove local data on filesystem for the icons. base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&DeleteIconFolderFromFileThread, GetAppPath(app_id))); } void GuestOsRegistryService::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void GuestOsRegistryService::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void GuestOsRegistryService::AppLaunched(const std::string& app_id) { DictionaryPrefUpdate update(prefs_, guest_os::prefs::kGuestOsRegistry); base::DictionaryValue* apps = update.Get(); base::Value* app = apps->FindKey(app_id); if (!app) { DCHECK_EQ(app_id, crostini::kCrostiniTerminalSystemAppId); base::Value pref(base::Value::Type::DICTIONARY); SetCurrentTime(&pref, guest_os::prefs::kAppLastLaunchTimeKey); apps->SetKey(app_id, std::move(pref)); return; } SetCurrentTime(app, guest_os::prefs::kAppLastLaunchTimeKey); } void GuestOsRegistryService::SetCurrentTime(base::Value* dictionary, const char* key) const { DCHECK(dictionary); int64_t time = clock_->Now().ToDeltaSinceWindowsEpoch().InMicroseconds(); dictionary->SetKey(key, base::Value(base::NumberToString(time))); } void GuestOsRegistryService::SetAppScaled(const std::string& app_id, bool scaled) { DCHECK_NE(app_id, crostini::kCrostiniTerminalSystemAppId); DictionaryPrefUpdate update(prefs_, guest_os::prefs::kGuestOsRegistry); base::DictionaryValue* apps = update.Get(); base::Value* app = apps->FindKey(app_id); if (!app) { LOG(ERROR) << "Tried to set display scaled property on the app with this app_id " << app_id << " that doesn't exist in the registry."; return; } app->SetKey(guest_os::prefs::kAppScaledKey, base::Value(scaled)); } // static std::string GuestOsRegistryService::GenerateAppId( const std::string& desktop_file_id, const std::string& vm_name, const std::string& container_name) { // These can collide in theory because the user could choose VM and container // names which contain slashes, but this will only result in apps missing from // the launcher. return crx_file::id_util::GenerateId(kCrostiniAppIdPrefix + vm_name + "/" + container_name + "/" + desktop_file_id); } void GuestOsRegistryService::RequestContainerAppIcon( const std::string& app_id, ui::ResourceScaleFactor scale_factor) { // Ignore requests for app_id that isn't registered. absl::optional<GuestOsRegistryService::Registration> registration = GetRegistration(app_id); DCHECK(registration); if (!registration) { LOG(ERROR) << "Request to load icon for non-registered app: " << app_id; return; } VLOG(1) << "Request to load icon for app: " << app_id; // Now make the call to request the actual icon. std::vector<std::string> desktop_file_ids{registration->DesktopFileId()}; // We can only send integer scale factors to Crostini, so if we have a // non-integral scale factor we need round the scale factor. We do not expect // Crostini to give us back exactly what we ask for and we deal with that in // the CrostiniAppIcon class and may rescale the result in there to match our // needs. uint32_t icon_scale = 1; switch (scale_factor) { case ui::k200Percent: icon_scale = 2; break; case ui::k300Percent: icon_scale = 3; break; default: break; } crostini::CrostiniManager::GetForProfile(profile_)->GetContainerAppIcons( crostini::ContainerId(registration->VmName(), registration->ContainerName()), desktop_file_ids, ash::SharedAppListConfig::instance().default_grid_icon_dimension(), icon_scale, base::BindOnce(&GuestOsRegistryService::OnContainerAppIcon, weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor)); } void GuestOsRegistryService::InvokeActiveIconCallbacks( std::string app_id, ui::ResourceScaleFactor scale_factor, std::string icon_content) { // Invoke all active icon request callbacks with the icon. auto key = std::pair<std::string, ui::ResourceScaleFactor>(app_id, scale_factor); auto& callbacks = active_icon_requests_[key]; VLOG(1) << "Invoking icon callbacks for app: " << app_id << ", num callbacks: " << callbacks.size(); for (auto& callback : callbacks) { std::move(callback).Run(icon_content); } active_icon_requests_.erase(key); } void GuestOsRegistryService::OnSvgIconTranscoded( std::string app_id, ui::ResourceScaleFactor scale_factor, std::string svg_icon_content, std::string png_icon_content) { if (png_icon_content.empty()) { VLOG(1) << "Failed to transcode svg icon for " << app_id; } // Write svg to disk, then invoke active callbacks with png content. base::ThreadPool::PostTaskAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&InstallIconFromFileThread, GetIconPath(app_id, ui::kScaleFactorNone), std::move(svg_icon_content)), base::BindOnce(&GuestOsRegistryService::InvokeActiveIconCallbacks, weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor, std::move(png_icon_content))); } void GuestOsRegistryService::OnContainerAppIcon( const std::string& app_id, ui::ResourceScaleFactor scale_factor, bool success, const std::vector<crostini::Icon>& icons) { std::string icon_content; if (!success) { VLOG(1) << "Failed to load icon for app: " << app_id; // Add this to the list of retryable icon requests so we redo this when // we get feedback from the container that it's available. retry_icon_requests_[app_id] |= (1 << scale_factor); InvokeActiveIconCallbacks(app_id, scale_factor, std::string()); return; } if (icons.empty()) { VLOG(1) << "No icon in container for app: " << app_id; InvokeActiveIconCallbacks(app_id, scale_factor, std::string()); return; } // Install the icon that we received, and invoke active callbacks. const base::FilePath icon_path = GetIconPath(app_id, scale_factor); bool is_svg = icons[0].format == vm_tools::cicerone::DesktopIcon::SVG; VLOG(1) << "Found icon in container for app: " << app_id << " path: " << icon_path << " format: " << (is_svg ? "svg" : "png") << " bytes: " << icons[0].content.size(); if (is_svg) { svg_icon_transcoder_->Transcode( icons[0].content, std::move(icon_path), gfx::Size(128, 128), base::BindOnce(&GuestOsRegistryService::OnSvgIconTranscoded, weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor, icons[0].content)); return; } base::ThreadPool::PostTaskAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&InstallIconFromFileThread, std::move(icon_path), icons[0].content), base::BindOnce(&GuestOsRegistryService::InvokeActiveIconCallbacks, weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor, icons[0].content)); } } // namespace guest_os
18,900
320
from guizero import App, PushButton, Text def get_folder(): folder_returned = app.select_folder() folder_name.value = folder_returned app = App() PushButton(app, command=get_folder, text="Get folder") folder_name = Text(app) app.display()
86
1,251
<reponame>palerdot/BlingFire /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #include "blingfire-compile_src_pch.h" #include "FAConfig.h" #include "FAMealyNfa2Dfa.h" #include "FARSNfaA.h" #include "FAMealyNfaA.h" #include "FAUtils.h" namespace BlingFire { FAMealyNfa2Dfa::_TEqGraph:: _TEqGraph (const int * pV, const int Count, const FANfa2EqPairs * pE) : m_pV (pV), m_Count (Count), m_pE (pE) {} const int FAMealyNfa2Dfa::_TEqGraph:: GetVertices (const int ** ppV) const { DebugLogAssert (0 < m_Count && m_pV); DebugLogAssert (ppV); *ppV = m_pV; return m_Count; } const int FAMealyNfa2Dfa::_TEqGraph:: GetArcCount () const { DebugLogAssert (m_pE); const int Count = m_pE->GetPairCount (); return Count; } void FAMealyNfa2Dfa::_TEqGraph:: GetArc (const int Num, int * pFrom, int * pTo) const { DebugLogAssert (m_pE); DebugLogAssert (pFrom && pTo); m_pE->GetPair (Num, pFrom, pTo); } FAMealyNfa2Dfa::FAMealyNfa2Dfa (FAAllocatorA * pAlloc) : m_pInNfa (NULL), m_pInOws (NULL), m_pFsm1Ows (NULL), m_pFsm1Dfa (NULL), m_pFsm2Ows (NULL), m_pFsm2Dfa (NULL), m_eq_pairs (pAlloc), m_q2c (pAlloc), m_split_states (pAlloc), m_rev (pAlloc), m_rev_nfa (pAlloc), m_calc_fsm1 (pAlloc), m_calc_fsm2 (pAlloc), m_UseBiMachine (false) { m_tmp.SetAllocator (pAlloc); m_tmp.Create (); m_rev.SetOutNfa (&m_rev_nfa); m_calc_fsm1.SetInNfa (&m_rev_nfa); m_calc_fsm2.SetInNfa (&m_rev_nfa); } void FAMealyNfa2Dfa::Clear () { m_tmp.Clear (); m_tmp.Create (); m_eq_pairs.Clear (); m_q2c.Clear (); m_split_states.Clear (); m_rev.Clear (); m_rev_nfa.Clear (); m_calc_fsm1.Clear (); m_calc_fsm2.Clear (); } void FAMealyNfa2Dfa::SetOutFsm1 (FARSDfaA * pFsm1Dfa, FAMealyDfaA * pFsm1Ows) { m_pFsm1Ows = pFsm1Ows; m_pFsm1Dfa = pFsm1Dfa; } void FAMealyNfa2Dfa::SetOutFsm2 (FARSDfaA * pFsm2Dfa, FAMealyDfaA * pFsm2Ows) { m_pFsm2Ows = pFsm2Ows; m_pFsm2Dfa = pFsm2Dfa; } void FAMealyNfa2Dfa::SetUseBiMachine (const bool UseBiMachine) { m_UseBiMachine = UseBiMachine; } void FAMealyNfa2Dfa:: SetInNfa (const FARSNfaA * pInNfa, const FAMealyNfaA * pInOws) { m_pInNfa = pInNfa; m_pInOws = pInOws; m_eq_pairs.SetNfa (m_pInNfa); m_rev.SetInNfa (m_pInNfa); m_calc_fsm2.SetSigma (pInOws); } void FAMealyNfa2Dfa::CreateDfa_triv () { DebugLogAssert (m_pInNfa && m_pInOws); DebugLogAssert (m_pFsm1Dfa && m_pFsm1Ows); const int * pStates; int Count; const int MaxState = m_pInNfa->GetMaxState (); m_pFsm1Dfa->SetMaxState (MaxState); const int MaxIw = m_pInNfa->GetMaxIw (); m_pFsm1Dfa->SetMaxIw (MaxIw); // make the output automaton ready m_pFsm1Dfa->Create (); // set up initial states Count = m_pInNfa->GetInitials (&pStates); DebugLogAssert (1 == Count && pStates); m_pFsm1Dfa->SetInitial (*pStates); // set up final states Count = m_pInNfa->GetFinals (&pStates); DebugLogAssert (0 < Count && pStates); m_pFsm1Dfa->SetFinals (pStates, Count); // make iteration thru the states of input automaton for (int State = 0; State <= MaxState; ++State) { // get input weights const int * pIws; const int IwsCount = m_pInNfa->GetIWs (State, &pIws); // make iteration thru the input weights for (int iw_idx = 0; iw_idx < IwsCount; ++iw_idx) { DebugLogAssert (pIws); const int Iw = pIws [iw_idx]; // copy the destination states Count = m_pInNfa->GetDest (State, Iw, &pStates); DebugLogAssert (-1 == Count || 1 == Count); if (-1 != Count) { DebugLogAssert (pStates); const int Dst = *pStates; m_pFsm1Dfa->SetTransition (State, Iw, Dst); const int Ow = m_pInOws->GetOw (State, Iw, Dst); if (-1 != Ow) { m_pFsm1Ows->SetOw (State, Iw, Ow); } } } // of for (int iw_idx = 0; ... } // of for (int State = 0; ... m_pFsm1Dfa->Prepare (); } void FAMealyNfa2Dfa::CalcEqPairs () { m_eq_pairs.Process (); // this should always be true unless FAIsDfa () has failed DebugLogAssert (0 < m_eq_pairs.GetPairCount ()); } void FAMealyNfa2Dfa::ColorGraph () { const int MaxState = m_pInNfa->GetMaxState (); m_tmp.resize (MaxState + 1); for (int k = 0; k <= MaxState; ++k) { m_tmp [k] = k; } // we won't need g longer than m_q2c.Process () works _TEqGraph g (m_tmp.begin (), m_tmp.size (), &m_eq_pairs); m_q2c.SetGraph (&g); m_q2c.Process (); const int * pS2C; const int Size = m_q2c.GetColorMap (&pS2C); m_calc_fsm1.SetColorMap (pS2C, Size); } void FAMealyNfa2Dfa::CalcRevNfa () { m_rev.Process (); } void FAMealyNfa2Dfa::SplitStates () { const int * pS2C; const int Size = m_q2c.GetColorMap (&pS2C); m_split_states.SetNfa (&m_rev_nfa); m_split_states.SetS2C (pS2C, Size); m_split_states.Process (); const int * pS2C_new; const int Size_new = m_split_states.GetS2C (&pS2C_new); DebugLogAssert (Size_new == Size); m_calc_fsm1.SetColorMap (pS2C_new, Size_new); } void FAMealyNfa2Dfa::SetMaxClasses () { const int MaxState = m_rev_nfa.GetMaxState (); m_tmp.resize (MaxState + 1); for (int State = 0; State <= MaxState; ++State) { m_tmp [State] = State; } m_calc_fsm1.SetColorMap (m_tmp.begin (), m_tmp.size ()); } void FAMealyNfa2Dfa::CalcFsm1 () { m_calc_fsm1.Process (); } void FAMealyNfa2Dfa::CalcFsm2 () { DebugLogAssert (m_pFsm2Dfa && m_pFsm2Ows); const FARSDfaA * pDfa1 = m_calc_fsm1.GetDfa (); DebugLogAssert (pDfa1); const FAMealyDfaA * pOws1 = m_calc_fsm1.GetSigma (); DebugLogAssert (pOws1); m_calc_fsm2.SetMealy1 (pDfa1, pOws1); m_calc_fsm2.Process (); const FARSNfaA * pNfa2 = m_calc_fsm2.GetOutNfa (); const FAMealyNfaA * pOws2 = m_calc_fsm2.GetSigma (); if (FAIsDfa (pNfa2)) { FACopyNfa2Dfa (m_pFsm2Dfa, pNfa2); const int * pIws; const int IwsCount = m_pFsm2Dfa->GetIWs (&pIws); const int MaxState = m_pFsm2Dfa->GetMaxState (); for (int i = 0; i <= MaxState; ++i) { for (int j = 0; j < IwsCount; ++j) { const int Iw = pIws [j]; const int Dst = m_pFsm2Dfa->GetDest (i, Iw); if (-1 != Dst) { const int Ow = pOws2->GetOw (i, Iw, Dst); if (-1 != Ow) { m_pFsm2Ows->SetOw (i, Iw, Ow); } } } // of for (int j = 0; j < IwsCount; ... } // of for (int i = 0; i <= MaxState; ... } } void FAMealyNfa2Dfa::RmArcs1 () { DebugLogAssert (m_pFsm1Dfa && m_pFsm1Ows); DebugLogAssert (m_pFsm2Dfa); const FARSDfaA * pDfa1 = m_calc_fsm1.GetDfa (); DebugLogAssert (pDfa1); const FAMealyDfaA * pOws1 = m_calc_fsm1.GetSigma (); DebugLogAssert (pOws1); const FARSNfaA * pNfa2 = m_calc_fsm2.GetOutNfa (); m_tmp.resize (0); FAGetAlphabet (pNfa2, & m_tmp); const int * pIws2 = m_tmp.begin (); const int Iws2 = m_tmp.size (); DebugLogAssert (0 < Iws2 && pIws2); DebugLogAssert (FAIsSortUniqed (pIws2, Iws2)); const int * pIws1; const int Iws1 = pDfa1->GetIWs (&pIws1); DebugLogAssert (0 < Iws1 && pIws1); DebugLogAssert (FAIsSortUniqed (pIws1, Iws1)); const int MaxState = pDfa1->GetMaxState (); m_pFsm1Dfa->SetMaxState (MaxState); const int MaxIw = pDfa1->GetMaxIw (); m_pFsm1Dfa->SetMaxIw (MaxIw); m_pFsm1Dfa->Create (); const int Initial = pDfa1->GetInitial (); m_pFsm1Dfa->SetInitial (Initial); const int * pFinals; const int Finals = pDfa1->GetFinals (&pFinals); DebugLogAssert (0 < Finals && pFinals); m_pFsm1Dfa->SetFinals (pFinals, Finals); for (int State = 0; State <= MaxState; ++State) { for (int i = 0; i < Iws1; ++i) { const int Iw1 = pIws1 [i]; const int Dst = pDfa1->GetDest (State, Iw1); if (-1 == Dst) continue; const int Ow = pOws1->GetOw (State, Iw1); DebugLogAssert (-1 != Ow); if (-1 != FAFind_log (pIws2, Iws2, Ow)) { m_pFsm1Dfa->SetTransition (State, Iw1, Dst); m_pFsm1Ows->SetOw (State, Iw1, Ow); } } // of for (int i = 0; ... } // of for (int State = 0; ... m_pFsm1Dfa->Prepare (); } const bool FAMealyNfa2Dfa::IsNonDet () const { const FARSNfaA * pNfa2 = m_calc_fsm2.GetOutNfa (); return !FAIsDfa (pNfa2); } const FARSNfaA * FAMealyNfa2Dfa::GetNfa2 () const { const FARSNfaA * pNfa2 = m_calc_fsm2.GetOutNfa (); return pNfa2; } const FAMealyNfaA * FAMealyNfa2Dfa::GetSigma2 () const { const FAMealyNfaA * pOws2 = m_calc_fsm2.GetSigma (); return pOws2; } void FAMealyNfa2Dfa::Process () { DebugLogAssert (m_pInNfa && m_pInOws); // see whether no decomposition is needed if (FAIsDfa (m_pInNfa)) { CreateDfa_triv (); } else { if (!m_UseBiMachine) { CalcEqPairs (); ColorGraph (); CalcRevNfa (); SplitStates (); } else { CalcRevNfa (); SetMaxClasses (); } CalcFsm1 (); CalcFsm2 (); RmArcs1 (); } } }
5,514
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices */ // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXStruct_kFm5bA__ #define __XXStruct_kFm5bA__ 1 typedef struct { unsigned long _field1; id *_field2; unsigned long *_field3; unsigned long _field4[5]; } XXStruct_kFm5bA; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __GEOTileKey__ #define __GEOTileKey__ 1 typedef struct _GEOTileKey { unsigned z : 6; unsigned x : 26; unsigned y : 26; unsigned type : 6; unsigned pixelSize : 8; unsigned textScale : 8; unsigned provider : 8; unsigned expires : 1; unsigned reserved1 : 7; unsigned char reserved2[4]; } GEOTileKey; #endif typedef struct _ExpEntry { GEOTileKey _field1; double _field2; struct ExpEntry *_field3; struct ExpEntry *_field4; } ExpEntry; // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __dispatch_queue_s__ #define __dispatch_queue_s__ 1 typedef struct dispatch_queue_s dispatch_queue_s; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __sqlite3__ #define __sqlite3__ 1 typedef struct sqlite3 sqlite3; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __sqlite3_stmt__ #define __sqlite3_stmt__ 1 typedef struct sqlite3_stmt sqlite3_stmt; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXStruct_19EQxD__ #define __XXStruct_19EQxD__ 1 typedef struct { long long *list; unsigned count; unsigned size; } XXStruct_19EQxD; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXStruct_K5nmsA__ #define __XXStruct_K5nmsA__ 1 // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXStruct_K5nmsA__ #define __XXStruct_K5nmsA__ 1 typedef struct { int _field1; int _field2; } XXStruct_K5nmsA; #endif #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXStruct_zYrK5D__ #define __XXStruct_zYrK5D__ 1 typedef struct { double latitude; double longitude; } XXStruct_zYrK5D; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __xpc_connection_s__ #define __xpc_connection_s__ 1 typedef struct _xpc_connection_s xpc_connection_s; #endif typedef struct { XXStruct_zYrK5D _field1; double _field2; double _field3; } XXStruct_SnKRpD;
931
619
<filename>tools/mull-cxx-frontend/src/MullClangPlugin.cpp #include "ASTInstrumentation.h" #include "ASTMutationsSearchVisitor.h" #include "ASTNodeFactory.h" #include "MullASTMutator.h" #include "MutationMap.h" #include <clang/AST/AST.h> #include <clang/AST/ASTConsumer.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/FrontendPluginRegistry.h> #include <clang/Sema/Sema.h> #include <clang/Sema/SemaConsumer.h> #include <llvm/Support/raw_ostream.h> using namespace clang; using namespace llvm; namespace mull { namespace cxx { class MullASTConsumer : public ASTConsumer { CompilerInstance &instance; std::unique_ptr<MullASTMutator> astMutator; MutationMap mutationMap; public: MullASTConsumer(CompilerInstance &instance, const MutationMap mutationMap) : instance(instance), astMutator(nullptr), mutationMap(mutationMap) {} void Initialize(ASTContext &Context) override { ASTConsumer::Initialize(Context); } /// This function can be considered a main() function of the /// mull-cxx-frontend plugin. This method is called multiple times by /// clang::ParseAST() for each declaration when it's finished being parsed. /// For each found function declaration below, a two-pass approach is used: /// 1) First all mutation points are found in the function declaration by the /// recursive AST visitor class ASTMutationsSearchVisitor. /// 2) For each mutation point, the mutations are performed on the Clang AST /// level. The mutation is performed by the higher-level MullASTMutator class /// which class to the lower-level ClangASTMutator class. bool HandleTopLevelDecl(DeclGroupRef DG) override { /// Could be a better place to create this. But at Initialize(), getSema() /// hits an internal assert because it is not initialized yet at that time. if (!astMutator) { astMutator = std::make_unique<MullASTMutator>(instance.getASTContext(), instance.getSema()); astMutator->instrumentTranslationUnit(); } for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { if ((*I)->getKind() != Decl::Function) { continue; } FunctionDecl *f = static_cast<FunctionDecl *>(*I); if (f->getDeclName().getAsString() == "main") { continue; } clang::SourceLocation functionLocation = f->getLocation(); if (instance.getSourceManager().isInSystemHeader(functionLocation)) { continue; } std::string sourceFilePath = instance.getSourceManager().getFilename(functionLocation).str(); if (sourceFilePath.find("include/gtest") != std::string::npos) { continue; } ASTMutationsSearchVisitor visitor(instance.getASTContext(), mutationMap); errs() << "HandleTopLevelDecl: Looking at function: " << f->getDeclName() << "\n"; visitor.TraverseFunctionDecl(f); for (auto &foundMutation : visitor.getAstMutations()) { foundMutation->performMutation(*astMutator); } } return true; } // This method is the last to be called when all declarations have already // been called on with HandleTopLevelDecl(). At this point, it is possible to // visualize the final mutated AST tree. void HandleTranslationUnit(ASTContext &context) override { // The following is useful for debugging mutations: // context.getTranslationUnitDecl()->print(llvm::errs(), 2); // context.getTranslationUnitDecl()->dump(); // exit(1); } }; class MullAction : public PluginASTAction { MutationMap mutationMap; protected: std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) override { return std::make_unique<MullASTConsumer>(CI, mutationMap); } bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &args) override { clang::ASTContext &astContext = CI.getASTContext(); for (const auto &arg : args) { std::string delimiter = "="; std::vector<std::string> components; size_t last = 0; size_t next = 0; while ((next = arg.find(delimiter, last)) != std::string::npos) { components.push_back(arg.substr(last, next - last)); last = next + 1; } components.push_back(arg.substr(last)); if (components[0] != "mutators") { clang::DiagnosticsEngine &diag = astContext.getDiagnostics(); unsigned diagId = diag.getCustomDiagID(clang::DiagnosticsEngine::Error, "Only 'mutator=' argument is supported."); astContext.getDiagnostics().Report(diagId); } assert(components.size() == 2); mutationMap.addMutation(components.at(1)); } mutationMap.setDefaultMutationsIfNotSpecified(); return true; } PluginASTAction::ActionType getActionType() override { /// Note: AddBeforeMainAction is the only option when mutations have effect. return AddBeforeMainAction; } }; } // namespace cxx } // namespace mull static FrontendPluginRegistry::Add<mull::cxx::MullAction> X("mull-cxx-frontend", "Mull: Prepare mutations");
1,831
303
<gh_stars>100-1000 // // SRMockWaitBlockOperation.h // SignalR.Client.ObjC // // Created by <NAME> on 3/15/16. // Copyright © 2016 DyKnow LLC. All rights reserved. // #import <Foundation/Foundation.h> @interface SRMockWaitBlockOperation : NSObject @property (readwrite, nonatomic, copy) void (^afterWait)(); @property (readwrite, nonatomic, assign) double waitTime; @property (readwrite, nonatomic, strong) id mock; - (instancetype)initWithWaitTime:(int)expectedWait; - (void)stopMocking; @end
174
337
<filename>python/setup.py #!/usr/bin/env python """ pyton_setup.py file for SWIG ultimateAlprSdk You must run this file from 'binaries/os/arch' (e.g. 'binaries/windows/x86_64') folder. """ from distutils.core import setup, Extension from distutils import sysconfig from Cython.Distutils import build_ext from sys import platform import os # Shared library name print("Your platform: %s" % platform) LIBNAME = 'ultimate_alpr-sdk' if platform.startswith('win'): LIBNAME = 'ultimateALPR-SDK' # Do not add suffix (e.g. 'cp36-win_amd64') class NoSuffixBuilder(build_ext): def get_ext_filename(self, ext_name): filename = super().get_ext_filename(ext_name) suffix = sysconfig.get_config_var('EXT_SUFFIX') ext = os.path.splitext(filename)[1] return filename.replace(suffix, "") + ext ultimateAlprSdk_module = Extension('_ultimateAlprSdk', sources=[os.path.abspath('../../../python/ultimateALPR-SDK-API-PUBLIC-SWIG_python.cxx')], include_dirs=['../../../c++'], language='c++11', library_dirs=['.'], libraries=[LIBNAME] ) setup (name = 'ultimateAlprSdk', version = '3.0.0', author = "<NAME>", description = """ultimateAlprSdk for python""", ext_modules = [ultimateAlprSdk_module], py_modules = ["ultimateAlprSdk"], cmdclass={"build_ext": NoSuffixBuilder}, )
687
397
<gh_stars>100-1000 // // UITextField+Chat.h // sample-push-notifications // // Created by Injoit on 18.11.2020. // Copyright © 2020 QuickBlox. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UITextField (Chat) - (void)setPadding:(CGFloat)padding isLeft:(Boolean)isLeft; - (void)addShadow:(UIColor *)color cornerRadius:(CGFloat)cornerRadius; @end NS_ASSUME_NONNULL_END
170
777
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SymbolsIterator_h #define SymbolsIterator_h #include "platform/fonts/FontFallbackPriority.h" #include "platform/fonts/FontOrientation.h" #include "platform/fonts/ScriptRunIterator.h" #include "platform/fonts/UTF16TextIterator.h" #include "wtf/Allocator.h" #include "wtf/Noncopyable.h" #include <memory> namespace blink { class PLATFORM_EXPORT SymbolsIterator { USING_FAST_MALLOC(SymbolsIterator); WTF_MAKE_NONCOPYABLE(SymbolsIterator); public: SymbolsIterator(const UChar* buffer, unsigned bufferSize); bool consume(unsigned* symbolsLimit, FontFallbackPriority*); private: FontFallbackPriority fontFallbackPriorityForCharacter(UChar32); std::unique_ptr<UTF16TextIterator> m_utf16Iterator; unsigned m_bufferSize; UChar32 m_nextChar; bool m_atEnd; FontFallbackPriority m_currentFontFallbackPriority; FontFallbackPriority m_previousFontFallbackPriority; }; } // namespace blink #endif
362
1,537
<filename>pynq/lib/_pynq/common/aarch64/xparameters.h #ifndef XPARAMETERS_H /* prevent circular inclusions */ #define XPARAMETERS_H /* by using protection macros */ /* Definition for CPU ID */ #define XPAR_CPU_ID 0U /* Definitions for peripheral PSU_CORTEXA53_0 */ #define XPAR_PSU_CORTEXA53_0_CPU_CLK_FREQ_HZ 1199988000 #define XPAR_PSU_CORTEXA53_0_TIMESTAMP_CLK_FREQ 99999000 /******************************************************************/ /* Canonical definitions for peripheral PSU_CORTEXA53_0 */ #define XPAR_CPU_CORTEXA53_0_CPU_CLK_FREQ_HZ 1199988000 #define XPAR_CPU_CORTEXA53_0_TIMESTAMP_CLK_FREQ 99999000 /******************************************************************/ /* Definition for PSS REF CLK FREQUENCY */ #define XPAR_PSU_PSS_REF_CLK_FREQ_HZ 33333000U #include "xparameters_ps.h" #define XPS_BOARD_ZCU104 /* Number of Fabric Resets */ #define XPAR_NUM_FABRIC_RESETS 1 #define STDIN_BASEADDRESS 0xFF000000 #define STDOUT_BASEADDRESS 0xFF000000 /******************************************************************/ /* Platform specific definitions */ #define PLATFORM_ZYNQMP /* Definitions for sleep timer configuration */ #define XSLEEP_TIMER_IS_DEFAULT_TIMER /******************************************************************/ /* Definitions for driver AVBUF */ #define XPAR_XAVBUF_NUM_INSTANCES 1 /* Definitions for peripheral PSU_DP */ #define XPAR_PSU_DP_DEVICE_ID 0 #define XPAR_PSU_DP_BASEADDR 0xFD4A0000 #define XPAR_PSU_DP_HIGHADDR 0xFD4AFFFF /******************************************************************/ /* Canonical definitions for peripheral PSU_DP */ #define XPAR_XAVBUF_0_DEVICE_ID XPAR_PSU_DP_DEVICE_ID #define XPAR_XAVBUF_0_BASEADDR 0xFD4A0000 #define XPAR_XAVBUF_0_HIGHADDR 0xFD4AFFFF /******************************************************************/ /* Definitions for driver AXIPMON */ #define XPAR_XAXIPMON_NUM_INSTANCES 4U /* Definitions for peripheral PSU_APM_0 */ #define XPAR_PSU_APM_0_DEVICE_ID 0U #define XPAR_PSU_APM_0_BASEADDR 0xFD0B0000U #define XPAR_PSU_APM_0_HIGHADDR 0xFD0BFFFFU #define XPAR_PSU_APM_0_GLOBAL_COUNT_WIDTH 32U #define XPAR_PSU_APM_0_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_PSU_APM_0_ENABLE_EVENT_COUNT 1U #define XPAR_PSU_APM_0_NUM_MONITOR_SLOTS 6U #define XPAR_PSU_APM_0_NUM_OF_COUNTERS 10U #define XPAR_PSU_APM_0_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_PSU_APM_0_ENABLE_EVENT_LOG 0U #define XPAR_PSU_APM_0_FIFO_AXIS_DEPTH 32U #define XPAR_PSU_APM_0_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_PSU_APM_0_FIFO_AXIS_TID_WIDTH 1U #define XPAR_PSU_APM_0_METRIC_COUNT_SCALE 1U #define XPAR_PSU_APM_0_ENABLE_ADVANCED 1U #define XPAR_PSU_APM_0_ENABLE_PROFILE 0U #define XPAR_PSU_APM_0_ENABLE_TRACE 0U #define XPAR_PSU_APM_0_S_AXI4_BASEADDR 0x00000000U #define XPAR_PSU_APM_0_S_AXI4_HIGHADDR 0x00000000U #define XPAR_PSU_APM_0_ENABLE_32BIT_FILTER_ID 1U /* Definitions for peripheral PSU_APM_1 */ #define XPAR_PSU_APM_1_DEVICE_ID 1U #define XPAR_PSU_APM_1_BASEADDR 0xFFA00000U #define XPAR_PSU_APM_1_HIGHADDR 0xFFA0FFFFU #define XPAR_PSU_APM_1_GLOBAL_COUNT_WIDTH 32U #define XPAR_PSU_APM_1_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_PSU_APM_1_ENABLE_EVENT_COUNT 1U #define XPAR_PSU_APM_1_NUM_MONITOR_SLOTS 1U #define XPAR_PSU_APM_1_NUM_OF_COUNTERS 3U #define XPAR_PSU_APM_1_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_PSU_APM_1_ENABLE_EVENT_LOG 0U #define XPAR_PSU_APM_1_FIFO_AXIS_DEPTH 32U #define XPAR_PSU_APM_1_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_PSU_APM_1_FIFO_AXIS_TID_WIDTH 1U #define XPAR_PSU_APM_1_METRIC_COUNT_SCALE 1U #define XPAR_PSU_APM_1_ENABLE_ADVANCED 1U #define XPAR_PSU_APM_1_ENABLE_PROFILE 0U #define XPAR_PSU_APM_1_ENABLE_TRACE 0U #define XPAR_PSU_APM_1_S_AXI4_BASEADDR 0x00000000U #define XPAR_PSU_APM_1_S_AXI4_HIGHADDR 0x00000000U #define XPAR_PSU_APM_1_ENABLE_32BIT_FILTER_ID 1U /* Definitions for peripheral PSU_APM_2 */ #define XPAR_PSU_APM_2_DEVICE_ID 2U #define XPAR_PSU_APM_2_BASEADDR 0xFFA10000U #define XPAR_PSU_APM_2_HIGHADDR 0xFFA1FFFFU #define XPAR_PSU_APM_2_GLOBAL_COUNT_WIDTH 32U #define XPAR_PSU_APM_2_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_PSU_APM_2_ENABLE_EVENT_COUNT 1U #define XPAR_PSU_APM_2_NUM_MONITOR_SLOTS 1U #define XPAR_PSU_APM_2_NUM_OF_COUNTERS 3U #define XPAR_PSU_APM_2_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_PSU_APM_2_ENABLE_EVENT_LOG 0U #define XPAR_PSU_APM_2_FIFO_AXIS_DEPTH 32U #define XPAR_PSU_APM_2_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_PSU_APM_2_FIFO_AXIS_TID_WIDTH 1U #define XPAR_PSU_APM_2_METRIC_COUNT_SCALE 1U #define XPAR_PSU_APM_2_ENABLE_ADVANCED 1U #define XPAR_PSU_APM_2_ENABLE_PROFILE 0U #define XPAR_PSU_APM_2_ENABLE_TRACE 0U #define XPAR_PSU_APM_2_S_AXI4_BASEADDR 0x00000000U #define XPAR_PSU_APM_2_S_AXI4_HIGHADDR 0x00000000U #define XPAR_PSU_APM_2_ENABLE_32BIT_FILTER_ID 1U /* Definitions for peripheral PSU_APM_5 */ #define XPAR_PSU_APM_5_DEVICE_ID 3U #define XPAR_PSU_APM_5_BASEADDR 0xFD490000U #define XPAR_PSU_APM_5_HIGHADDR 0xFD49FFFFU #define XPAR_PSU_APM_5_GLOBAL_COUNT_WIDTH 32U #define XPAR_PSU_APM_5_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_PSU_APM_5_ENABLE_EVENT_COUNT 1U #define XPAR_PSU_APM_5_NUM_MONITOR_SLOTS 1U #define XPAR_PSU_APM_5_NUM_OF_COUNTERS 3U #define XPAR_PSU_APM_5_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_PSU_APM_5_ENABLE_EVENT_LOG 0U #define XPAR_PSU_APM_5_FIFO_AXIS_DEPTH 32U #define XPAR_PSU_APM_5_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_PSU_APM_5_FIFO_AXIS_TID_WIDTH 1U #define XPAR_PSU_APM_5_METRIC_COUNT_SCALE 1U #define XPAR_PSU_APM_5_ENABLE_ADVANCED 1U #define XPAR_PSU_APM_5_ENABLE_PROFILE 0U #define XPAR_PSU_APM_5_ENABLE_TRACE 0U #define XPAR_PSU_APM_5_S_AXI4_BASEADDR 0x00000000U #define XPAR_PSU_APM_5_S_AXI4_HIGHADDR 0x00000000U #define XPAR_PSU_APM_5_ENABLE_32BIT_FILTER_ID 1U /******************************************************************/ /* Canonical definitions for peripheral PSU_APM_0 */ #define XPAR_AXIPMON_0_DEVICE_ID XPAR_PSU_APM_0_DEVICE_ID #define XPAR_AXIPMON_0_BASEADDR 0xFD0B0000U #define XPAR_AXIPMON_0_HIGHADDR 0xFD0BFFFFU #define XPAR_AXIPMON_0_GLOBAL_COUNT_WIDTH 32U #define XPAR_AXIPMON_0_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_AXIPMON_0_ENABLE_EVENT_COUNT 1U #define XPAR_AXIPMON_0_NUM_MONITOR_SLOTS 6U #define XPAR_AXIPMON_0_NUM_OF_COUNTERS 10U #define XPAR_AXIPMON_0_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_AXIPMON_0_ENABLE_EVENT_LOG 0U #define XPAR_AXIPMON_0_FIFO_AXIS_DEPTH 32U #define XPAR_AXIPMON_0_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_AXIPMON_0_FIFO_AXIS_TID_WIDTH 1U #define XPAR_AXIPMON_0_METRIC_COUNT_SCALE 1U #define XPAR_AXIPMON_0_ENABLE_ADVANCED 1U #define XPAR_AXIPMON_0_ENABLE_PROFILE 0U #define XPAR_AXIPMON_0_ENABLE_TRACE 0U #define XPAR_AXIPMON_0_S_AXI4_BASEADDR 0x00000000U #define XPAR_AXIPMON_0_S_AXI4_HIGHADDR 0x00000000U #define XPAR_AXIPMON_0_ENABLE_32BIT_FILTER_ID 1U /* Canonical definitions for peripheral PSU_APM_1 */ #define XPAR_AXIPMON_1_DEVICE_ID XPAR_PSU_APM_1_DEVICE_ID #define XPAR_AXIPMON_1_BASEADDR 0xFFA00000U #define XPAR_AXIPMON_1_HIGHADDR 0xFFA0FFFFU #define XPAR_AXIPMON_1_GLOBAL_COUNT_WIDTH 32U #define XPAR_AXIPMON_1_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_AXIPMON_1_ENABLE_EVENT_COUNT 1U #define XPAR_AXIPMON_1_NUM_MONITOR_SLOTS 1U #define XPAR_AXIPMON_1_NUM_OF_COUNTERS 3U #define XPAR_AXIPMON_1_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_AXIPMON_1_ENABLE_EVENT_LOG 0U #define XPAR_AXIPMON_1_FIFO_AXIS_DEPTH 32U #define XPAR_AXIPMON_1_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_AXIPMON_1_FIFO_AXIS_TID_WIDTH 1U #define XPAR_AXIPMON_1_METRIC_COUNT_SCALE 1U #define XPAR_AXIPMON_1_ENABLE_ADVANCED 1U #define XPAR_AXIPMON_1_ENABLE_PROFILE 0U #define XPAR_AXIPMON_1_ENABLE_TRACE 0U #define XPAR_AXIPMON_1_S_AXI4_BASEADDR 0x00000000U #define XPAR_AXIPMON_1_S_AXI4_HIGHADDR 0x00000000U #define XPAR_AXIPMON_1_ENABLE_32BIT_FILTER_ID 1U /* Canonical definitions for peripheral PSU_APM_2 */ #define XPAR_AXIPMON_2_DEVICE_ID XPAR_PSU_APM_2_DEVICE_ID #define XPAR_AXIPMON_2_BASEADDR 0xFFA10000U #define XPAR_AXIPMON_2_HIGHADDR 0xFFA1FFFFU #define XPAR_AXIPMON_2_GLOBAL_COUNT_WIDTH 32U #define XPAR_AXIPMON_2_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_AXIPMON_2_ENABLE_EVENT_COUNT 1U #define XPAR_AXIPMON_2_NUM_MONITOR_SLOTS 1U #define XPAR_AXIPMON_2_NUM_OF_COUNTERS 3U #define XPAR_AXIPMON_2_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_AXIPMON_2_ENABLE_EVENT_LOG 0U #define XPAR_AXIPMON_2_FIFO_AXIS_DEPTH 32U #define XPAR_AXIPMON_2_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_AXIPMON_2_FIFO_AXIS_TID_WIDTH 1U #define XPAR_AXIPMON_2_METRIC_COUNT_SCALE 1U #define XPAR_AXIPMON_2_ENABLE_ADVANCED 1U #define XPAR_AXIPMON_2_ENABLE_PROFILE 0U #define XPAR_AXIPMON_2_ENABLE_TRACE 0U #define XPAR_AXIPMON_2_S_AXI4_BASEADDR 0x00000000U #define XPAR_AXIPMON_2_S_AXI4_HIGHADDR 0x00000000U #define XPAR_AXIPMON_2_ENABLE_32BIT_FILTER_ID 1U /* Canonical definitions for peripheral PSU_APM_5 */ #define XPAR_AXIPMON_3_DEVICE_ID XPAR_PSU_APM_5_DEVICE_ID #define XPAR_AXIPMON_3_BASEADDR 0xFD490000U #define XPAR_AXIPMON_3_HIGHADDR 0xFD49FFFFU #define XPAR_AXIPMON_3_GLOBAL_COUNT_WIDTH 32U #define XPAR_AXIPMON_3_METRICS_SAMPLE_COUNT_WIDTH 32U #define XPAR_AXIPMON_3_ENABLE_EVENT_COUNT 1U #define XPAR_AXIPMON_3_NUM_MONITOR_SLOTS 1U #define XPAR_AXIPMON_3_NUM_OF_COUNTERS 3U #define XPAR_AXIPMON_3_HAVE_SAMPLED_METRIC_CNT 1U #define XPAR_AXIPMON_3_ENABLE_EVENT_LOG 0U #define XPAR_AXIPMON_3_FIFO_AXIS_DEPTH 32U #define XPAR_AXIPMON_3_FIFO_AXIS_TDATA_WIDTH 56U #define XPAR_AXIPMON_3_FIFO_AXIS_TID_WIDTH 1U #define XPAR_AXIPMON_3_METRIC_COUNT_SCALE 1U #define XPAR_AXIPMON_3_ENABLE_ADVANCED 1U #define XPAR_AXIPMON_3_ENABLE_PROFILE 0U #define XPAR_AXIPMON_3_ENABLE_TRACE 0U #define XPAR_AXIPMON_3_S_AXI4_BASEADDR 0x00000000U #define XPAR_AXIPMON_3_S_AXI4_HIGHADDR 0x00000000U #define XPAR_AXIPMON_3_ENABLE_32BIT_FILTER_ID 1U /******************************************************************/ /* Definitions for driver CANPS */ #define XPAR_XCANPS_NUM_INSTANCES 1 /* Definitions for peripheral PSU_CAN_1 */ #define XPAR_PSU_CAN_1_DEVICE_ID 0 #define XPAR_PSU_CAN_1_BASEADDR 0xFF070000 #define XPAR_PSU_CAN_1_HIGHADDR 0xFF07FFFF #define XPAR_PSU_CAN_1_CAN_CLK_FREQ_HZ 99999000 /******************************************************************/ /* Canonical definitions for peripheral PSU_CAN_1 */ #define XPAR_XCANPS_0_DEVICE_ID XPAR_PSU_CAN_1_DEVICE_ID #define XPAR_XCANPS_0_BASEADDR 0xFF070000 #define XPAR_XCANPS_0_HIGHADDR 0xFF07FFFF #define XPAR_XCANPS_0_CAN_CLK_FREQ_HZ 99999000 /******************************************************************/ /* Definitions for driver CLK_WIZ */ #define XPAR_XCLK_WIZ_NUM_INSTANCES 1 /* Definitions for peripheral AUDIO_SS_0_CLK_WIZ */ #define XPAR_AUDIO_SS_0_CLK_WIZ_DEVICE_ID 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_BASEADDR 0x80010000 #define XPAR_AUDIO_SS_0_CLK_WIZ_HIGHADDR 0x8001FFFF #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_CLOCK_MONITOR 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_USER_CLOCK0 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_USER_CLOCK1 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_USER_CLOCK2 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_USER_CLOCK3 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_REF_CLK_FREQ 100.0 #define XPAR_AUDIO_SS_0_CLK_WIZ_USER_CLK_FREQ0 100.0 #define XPAR_AUDIO_SS_0_CLK_WIZ_USER_CLK_FREQ1 100.0 #define XPAR_AUDIO_SS_0_CLK_WIZ_USER_CLK_FREQ2 100.0 #define XPAR_AUDIO_SS_0_CLK_WIZ_USER_CLK_FREQ3 100.0 #define XPAR_AUDIO_SS_0_CLK_WIZ_PRECISION 1 #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_PLL0 0 #define XPAR_AUDIO_SS_0_CLK_WIZ_ENABLE_PLL1 0 /******************************************************************/ /* Canonical definitions for peripheral AUDIO_SS_0_CLK_WIZ */ #define XPAR_CLK_WIZ_0_DEVICE_ID XPAR_AUDIO_SS_0_CLK_WIZ_DEVICE_ID #define XPAR_CLK_WIZ_0_BASEADDR 0x80010000 #define XPAR_CLK_WIZ_0_HIGHADDR 0x8001FFFF #define XPAR_CLK_WIZ_0_ENABLE_CLOCK_MONITOR 0 #define XPAR_CLK_WIZ_0_ENABLE_USER_CLOCK0 0 #define XPAR_CLK_WIZ_0_ENABLE_USER_CLOCK1 0 #define XPAR_CLK_WIZ_0_ENABLE_USER_CLOCK2 0 #define XPAR_CLK_WIZ_0_ENABLE_USER_CLOCK3 0 #define XPAR_CLK_WIZ_0_REF_CLK_FREQ 100.0 #define XPAR_CLK_WIZ_0_USER_CLK_FREQ0 100.0 #define XPAR_CLK_WIZ_0_USER_CLK_FREQ1 100.0 #define XPAR_CLK_WIZ_0_USER_CLK_FREQ2 100.0 #define XPAR_CLK_WIZ_0_USER_CLK_FREQ3 100.0 #define XPAR_CLK_WIZ_0_PRECISION 1 #define XPAR_CLK_WIZ_0_Enable_PLL0 0 #define XPAR_CLK_WIZ_0_Enable_PLL1 0 /******************************************************************/ /* Definitions for driver CSUDMA */ #define XPAR_XCSUDMA_NUM_INSTANCES 1 /* Definitions for peripheral PSU_CSUDMA */ #define XPAR_PSU_CSUDMA_DEVICE_ID 0 #define XPAR_PSU_CSUDMA_BASEADDR 0xFFC80000 #define XPAR_PSU_CSUDMA_HIGHADDR 0xFFC9FFFF #define XPAR_PSU_CSUDMA_CSUDMA_CLK_FREQ_HZ 0 /******************************************************************/ /* Canonical definitions for peripheral PSU_CSUDMA */ #define XPAR_XCSUDMA_0_DEVICE_ID XPAR_PSU_CSUDMA_DEVICE_ID #define XPAR_XCSUDMA_0_BASEADDR 0xFFC80000 #define XPAR_XCSUDMA_0_HIGHADDR 0xFFC9FFFF #define XPAR_XCSUDMA_0_CSUDMA_CLK_FREQ_HZ 0 /******************************************************************/ /* Definitions for driver DDRCPSU */ #define XPAR_XDDRCPSU_NUM_INSTANCES 1 /* Definitions for peripheral PSU_DDRC_0 */ #define XPAR_PSU_DDRC_0_DEVICE_ID 0 #define XPAR_PSU_DDRC_0_BASEADDR 0xFD070000 #define XPAR_PSU_DDRC_0_HIGHADDR 0xFD070FFF #define XPAR_PSU_DDRC_0_HAS_ECC 0 #define XPAR_PSU_DDRC_0_DDRC_CLK_FREQ_HZ 533328000 /******************************************************************/ /* Canonical definitions for peripheral PSU_DDRC_0 */ #define XPAR_DDRCPSU_0_DEVICE_ID XPAR_PSU_DDRC_0_DEVICE_ID #define XPAR_DDRCPSU_0_BASEADDR 0xFD070000 #define XPAR_DDRCPSU_0_HIGHADDR 0xFD070FFF #define XPAR_DDRCPSU_0_DDRC_CLK_FREQ_HZ 533328000 /******************************************************************/ /* Definitions for driver DPDMA */ #define XPAR_XDPDMA_NUM_INSTANCES 1 /* Definitions for peripheral PSU_DPDMA */ #define XPAR_PSU_DPDMA_DEVICE_ID 0 #define XPAR_PSU_DPDMA_BASEADDR 0xFD4C0000 #define XPAR_PSU_DPDMA_HIGHADDR 0xFD4CFFFF /******************************************************************/ /* Canonical definitions for peripheral PSU_DPDMA */ #define XPAR_XDPDMA_0_DEVICE_ID XPAR_PSU_DPDMA_DEVICE_ID #define XPAR_XDPDMA_0_BASEADDR 0xFD4C0000 #define XPAR_XDPDMA_0_HIGHADDR 0xFD4CFFFF /******************************************************************/ /* Definitions for driver EMACPS */ #define XPAR_XEMACPS_NUM_INSTANCES 1 /* Definitions for peripheral PSU_ETHERNET_3 */ #define XPAR_PSU_ETHERNET_3_DEVICE_ID 0 #define XPAR_PSU_ETHERNET_3_BASEADDR 0xFF0E0000 #define XPAR_PSU_ETHERNET_3_HIGHADDR 0xFF0EFFFF #define XPAR_PSU_ETHERNET_3_ENET_CLK_FREQ_HZ 124998750 #define XPAR_PSU_ETHERNET_3_ENET_SLCR_1000MBPS_DIV0 12 #define XPAR_PSU_ETHERNET_3_ENET_SLCR_1000MBPS_DIV1 1 #define XPAR_PSU_ETHERNET_3_ENET_SLCR_100MBPS_DIV0 60 #define XPAR_PSU_ETHERNET_3_ENET_SLCR_100MBPS_DIV1 1 #define XPAR_PSU_ETHERNET_3_ENET_SLCR_10MBPS_DIV0 60 #define XPAR_PSU_ETHERNET_3_ENET_SLCR_10MBPS_DIV1 10 #define XPAR_PSU_ETHERNET_3_ENET_TSU_CLK_FREQ_HZ 249997500 /******************************************************************/ #define XPAR_PSU_ETHERNET_3_IS_CACHE_COHERENT 0 /* Canonical definitions for peripheral PSU_ETHERNET_3 */ #define XPAR_XEMACPS_0_DEVICE_ID XPAR_PSU_ETHERNET_3_DEVICE_ID #define XPAR_XEMACPS_0_BASEADDR 0xFF0E0000 #define XPAR_XEMACPS_0_HIGHADDR 0xFF0EFFFF #define XPAR_XEMACPS_0_ENET_CLK_FREQ_HZ 124998750 #define XPAR_XEMACPS_0_ENET_SLCR_1000Mbps_DIV0 12 #define XPAR_XEMACPS_0_ENET_SLCR_1000Mbps_DIV1 1 #define XPAR_XEMACPS_0_ENET_SLCR_100Mbps_DIV0 60 #define XPAR_XEMACPS_0_ENET_SLCR_100Mbps_DIV1 1 #define XPAR_XEMACPS_0_ENET_SLCR_10Mbps_DIV0 60 #define XPAR_XEMACPS_0_ENET_SLCR_10Mbps_DIV1 10 #define XPAR_XEMACPS_0_ENET_TSU_CLK_FREQ_HZ 249997500 /******************************************************************/ /* Definitions for peripheral AUDIO_SS_0_AUD_PAT_GEN */ #define XPAR_AUDIO_SS_0_AUD_PAT_GEN_BASEADDR 0x90000000 #define XPAR_AUDIO_SS_0_AUD_PAT_GEN_HIGHADDR 0x9000FFFF /* Definitions for peripheral AUDIO_SS_0_HDMI_ACR_CTRL */ #define XPAR_AUDIO_SS_0_HDMI_ACR_CTRL_BASEADDR 0x88000000 #define XPAR_AUDIO_SS_0_HDMI_ACR_CTRL_HIGHADDR 0x8800FFFF /* Definitions for peripheral PSU_AFI_0 */ #define XPAR_PSU_AFI_0_S_AXI_BASEADDR 0xFD360000 #define XPAR_PSU_AFI_0_S_AXI_HIGHADDR 0xFD36FFFF /* Definitions for peripheral PSU_AFI_1 */ #define XPAR_PSU_AFI_1_S_AXI_BASEADDR 0xFD370000 #define XPAR_PSU_AFI_1_S_AXI_HIGHADDR 0xFD37FFFF /* Definitions for peripheral PSU_AFI_2 */ #define XPAR_PSU_AFI_2_S_AXI_BASEADDR 0xFD380000 #define XPAR_PSU_AFI_2_S_AXI_HIGHADDR 0xFD38FFFF /* Definitions for peripheral PSU_AFI_3 */ #define XPAR_PSU_AFI_3_S_AXI_BASEADDR 0xFD390000 #define XPAR_PSU_AFI_3_S_AXI_HIGHADDR 0xFD39FFFF /* Definitions for peripheral PSU_AFI_4 */ #define XPAR_PSU_AFI_4_S_AXI_BASEADDR 0xFD3A0000 #define XPAR_PSU_AFI_4_S_AXI_HIGHADDR 0xFD3AFFFF /* Definitions for peripheral PSU_AFI_5 */ #define XPAR_PSU_AFI_5_S_AXI_BASEADDR 0xFD3B0000 #define XPAR_PSU_AFI_5_S_AXI_HIGHADDR 0xFD3BFFFF /* Definitions for peripheral PSU_AFI_6 */ #define XPAR_PSU_AFI_6_S_AXI_BASEADDR 0xFF9B0000 #define XPAR_PSU_AFI_6_S_AXI_HIGHADDR 0xFF9BFFFF /* Definitions for peripheral PSU_APU */ #define XPAR_PSU_APU_S_AXI_BASEADDR 0xFD5C0000 #define XPAR_PSU_APU_S_AXI_HIGHADDR 0xFD5CFFFF /* Definitions for peripheral PSU_CCI_GPV */ #define XPAR_PSU_CCI_GPV_S_AXI_BASEADDR 0xFD6E0000 #define XPAR_PSU_CCI_GPV_S_AXI_HIGHADDR 0xFD6EFFFF /* Definitions for peripheral PSU_CCI_REG */ #define XPAR_PSU_CCI_REG_S_AXI_BASEADDR 0xFD5E0000 #define XPAR_PSU_CCI_REG_S_AXI_HIGHADDR 0xFD5EFFFF /* Definitions for peripheral PSU_CRL_APB */ #define XPAR_PSU_CRL_APB_S_AXI_BASEADDR 0xFF5E0000 #define XPAR_PSU_CRL_APB_S_AXI_HIGHADDR 0xFF85FFFF /* Definitions for peripheral PSU_CTRL_IPI */ #define XPAR_PSU_CTRL_IPI_S_AXI_BASEADDR 0xFF380000 #define XPAR_PSU_CTRL_IPI_S_AXI_HIGHADDR 0xFF3FFFFF /* Definitions for peripheral PSU_DDR_0 */ #define XPAR_PSU_DDR_0_S_AXI_BASEADDR 0x00000000 #define XPAR_PSU_DDR_0_S_AXI_HIGHADDR 0x7FFFFFFF /* Definitions for peripheral PSU_DDR_PHY */ #define XPAR_PSU_DDR_PHY_S_AXI_BASEADDR 0xFD080000 #define XPAR_PSU_DDR_PHY_S_AXI_HIGHADDR 0xFD08FFFF /* Definitions for peripheral PSU_DDR_QOS_CTRL */ #define XPAR_PSU_DDR_QOS_CTRL_S_AXI_BASEADDR 0xFD090000 #define XPAR_PSU_DDR_QOS_CTRL_S_AXI_HIGHADDR 0xFD09FFFF /* Definitions for peripheral PSU_DDR_XMPU0_CFG */ #define XPAR_PSU_DDR_XMPU0_CFG_S_AXI_BASEADDR 0xFD000000 #define XPAR_PSU_DDR_XMPU0_CFG_S_AXI_HIGHADDR 0xFD00FFFF /* Definitions for peripheral PSU_DDR_XMPU1_CFG */ #define XPAR_PSU_DDR_XMPU1_CFG_S_AXI_BASEADDR 0xFD010000 #define XPAR_PSU_DDR_XMPU1_CFG_S_AXI_HIGHADDR 0xFD01FFFF /* Definitions for peripheral PSU_DDR_XMPU2_CFG */ #define XPAR_PSU_DDR_XMPU2_CFG_S_AXI_BASEADDR 0xFD020000 #define XPAR_PSU_DDR_XMPU2_CFG_S_AXI_HIGHADDR 0xFD02FFFF /* Definitions for peripheral PSU_DDR_XMPU3_CFG */ #define XPAR_PSU_DDR_XMPU3_CFG_S_AXI_BASEADDR 0xFD030000 #define XPAR_PSU_DDR_XMPU3_CFG_S_AXI_HIGHADDR 0xFD03FFFF /* Definitions for peripheral PSU_DDR_XMPU4_CFG */ #define XPAR_PSU_DDR_XMPU4_CFG_S_AXI_BASEADDR 0xFD040000 #define XPAR_PSU_DDR_XMPU4_CFG_S_AXI_HIGHADDR 0xFD04FFFF /* Definitions for peripheral PSU_DDR_XMPU5_CFG */ #define XPAR_PSU_DDR_XMPU5_CFG_S_AXI_BASEADDR 0xFD050000 #define XPAR_PSU_DDR_XMPU5_CFG_S_AXI_HIGHADDR 0xFD05FFFF /* Definitions for peripheral PSU_EFUSE */ #define XPAR_PSU_EFUSE_S_AXI_BASEADDR 0xFFCC0000 #define XPAR_PSU_EFUSE_S_AXI_HIGHADDR 0xFFCCFFFF /* Definitions for peripheral PSU_FPD_GPV */ #define XPAR_PSU_FPD_GPV_S_AXI_BASEADDR 0xFD700000 #define XPAR_PSU_FPD_GPV_S_AXI_HIGHADDR 0xFD7FFFFF /* Definitions for peripheral PSU_FPD_SLCR */ #define XPAR_PSU_FPD_SLCR_S_AXI_BASEADDR 0xFD610000 #define XPAR_PSU_FPD_SLCR_S_AXI_HIGHADDR 0xFD68FFFF /* Definitions for peripheral PSU_FPD_SLCR_SECURE */ #define XPAR_PSU_FPD_SLCR_SECURE_S_AXI_BASEADDR 0xFD690000 #define XPAR_PSU_FPD_SLCR_SECURE_S_AXI_HIGHADDR 0xFD6CFFFF /* Definitions for peripheral PSU_FPD_XMPU_CFG */ #define XPAR_PSU_FPD_XMPU_CFG_S_AXI_BASEADDR 0xFD5D0000 #define XPAR_PSU_FPD_XMPU_CFG_S_AXI_HIGHADDR 0xFD5DFFFF /* Definitions for peripheral PSU_FPD_XMPU_SINK */ #define XPAR_PSU_FPD_XMPU_SINK_S_AXI_BASEADDR 0xFD4F0000 #define XPAR_PSU_FPD_XMPU_SINK_S_AXI_HIGHADDR 0xFD4FFFFF /* Definitions for peripheral PSU_GPU */ #define XPAR_PSU_GPU_S_AXI_BASEADDR 0xFD4B0000 #define XPAR_PSU_GPU_S_AXI_HIGHADDR 0xFD4BFFFF /* Definitions for peripheral PSU_IOU_SCNTR */ #define XPAR_PSU_IOU_SCNTR_S_AXI_BASEADDR 0xFF250000 #define XPAR_PSU_IOU_SCNTR_S_AXI_HIGHADDR 0xFF25FFFF /* Definitions for peripheral PSU_IOU_SCNTRS */ #define XPAR_PSU_IOU_SCNTRS_S_AXI_BASEADDR 0xFF260000 #define XPAR_PSU_IOU_SCNTRS_S_AXI_HIGHADDR 0xFF26FFFF /* Definitions for peripheral PSU_IOUSECURE_SLCR */ #define XPAR_PSU_IOUSECURE_SLCR_S_AXI_BASEADDR 0xFF240000 #define XPAR_PSU_IOUSECURE_SLCR_S_AXI_HIGHADDR 0xFF24FFFF /* Definitions for peripheral PSU_IOUSLCR_0 */ #define XPAR_PSU_IOUSLCR_0_S_AXI_BASEADDR 0xFF180000 #define XPAR_PSU_IOUSLCR_0_S_AXI_HIGHADDR 0xFF23FFFF /* Definitions for peripheral PSU_LPD_SLCR */ #define XPAR_PSU_LPD_SLCR_S_AXI_BASEADDR 0xFF410000 #define XPAR_PSU_LPD_SLCR_S_AXI_HIGHADDR 0xFF4AFFFF /* Definitions for peripheral PSU_LPD_SLCR_SECURE */ #define XPAR_PSU_LPD_SLCR_SECURE_S_AXI_BASEADDR 0xFF4B0000 #define XPAR_PSU_LPD_SLCR_SECURE_S_AXI_HIGHADDR 0xFF4DFFFF /* Definitions for peripheral PSU_LPD_XPPU */ #define XPAR_PSU_LPD_XPPU_S_AXI_BASEADDR 0xFF980000 #define XPAR_PSU_LPD_XPPU_S_AXI_HIGHADDR 0xFF99FFFF /* Definitions for peripheral PSU_LPD_XPPU_SINK */ #define XPAR_PSU_LPD_XPPU_SINK_S_AXI_BASEADDR 0xFF9C0000 #define XPAR_PSU_LPD_XPPU_SINK_S_AXI_HIGHADDR 0xFF9CFFFF /* Definitions for peripheral PSU_MBISTJTAG */ #define XPAR_PSU_MBISTJTAG_S_AXI_BASEADDR 0xFFCF0000 #define XPAR_PSU_MBISTJTAG_S_AXI_HIGHADDR 0xFFCFFFFF /* Definitions for peripheral PSU_MESSAGE_BUFFERS */ #define XPAR_PSU_MESSAGE_BUFFERS_S_AXI_BASEADDR 0xFF990000 #define XPAR_PSU_MESSAGE_BUFFERS_S_AXI_HIGHADDR 0xFF99FFFF /* Definitions for peripheral PSU_OCM */ #define XPAR_PSU_OCM_S_AXI_BASEADDR 0xFF960000 #define XPAR_PSU_OCM_S_AXI_HIGHADDR 0xFF96FFFF /* Definitions for peripheral PSU_OCM_RAM_0 */ #define XPAR_PSU_OCM_RAM_0_S_AXI_BASEADDR 0xFFFC0000 #define XPAR_PSU_OCM_RAM_0_S_AXI_HIGHADDR 0xFFFFFFFF /* Definitions for peripheral PSU_OCM_XMPU_CFG */ #define XPAR_PSU_OCM_XMPU_CFG_S_AXI_BASEADDR 0xFFA70000 #define XPAR_PSU_OCM_XMPU_CFG_S_AXI_HIGHADDR 0xFFA7FFFF /* Definitions for peripheral PSU_PMU_GLOBAL_0 */ #define XPAR_PSU_PMU_GLOBAL_0_S_AXI_BASEADDR 0xFFD80000 #define XPAR_PSU_PMU_GLOBAL_0_S_AXI_HIGHADDR 0xFFDBFFFF /* Definitions for peripheral PSU_QSPI_LINEAR_0 */ #define XPAR_PSU_QSPI_LINEAR_0_S_AXI_BASEADDR 0xC0000000 #define XPAR_PSU_QSPI_LINEAR_0_S_AXI_HIGHADDR 0xDFFFFFFF /* Definitions for peripheral PSU_R5_0_ATCM_GLOBAL */ #define XPAR_PSU_R5_0_ATCM_GLOBAL_S_AXI_BASEADDR 0xFFE00000 #define XPAR_PSU_R5_0_ATCM_GLOBAL_S_AXI_HIGHADDR 0xFFE0FFFF /* Definitions for peripheral PSU_R5_0_BTCM_GLOBAL */ #define XPAR_PSU_R5_0_BTCM_GLOBAL_S_AXI_BASEADDR 0xFFE20000 #define XPAR_PSU_R5_0_BTCM_GLOBAL_S_AXI_HIGHADDR 0xFFE2FFFF /* Definitions for peripheral PSU_R5_1_ATCM_GLOBAL */ #define XPAR_PSU_R5_1_ATCM_GLOBAL_S_AXI_BASEADDR 0xFFE90000 #define XPAR_PSU_R5_1_ATCM_GLOBAL_S_AXI_HIGHADDR 0xFFE9FFFF /* Definitions for peripheral PSU_R5_1_BTCM_GLOBAL */ #define XPAR_PSU_R5_1_BTCM_GLOBAL_S_AXI_BASEADDR 0xFFEB0000 #define XPAR_PSU_R5_1_BTCM_GLOBAL_S_AXI_HIGHADDR 0xFFEBFFFF /* Definitions for peripheral PSU_R5_TCM_RAM_GLOBAL */ #define XPAR_PSU_R5_TCM_RAM_GLOBAL_S_AXI_BASEADDR 0xFFE00000 #define XPAR_PSU_R5_TCM_RAM_GLOBAL_S_AXI_HIGHADDR 0xFFE3FFFF /* Definitions for peripheral PSU_RPU */ #define XPAR_PSU_RPU_S_AXI_BASEADDR 0xFF9A0000 #define XPAR_PSU_RPU_S_AXI_HIGHADDR 0xFF9AFFFF /* Definitions for peripheral PSU_RSA */ #define XPAR_PSU_RSA_S_AXI_BASEADDR 0xFFCE0000 #define XPAR_PSU_RSA_S_AXI_HIGHADDR 0xFFCEFFFF /* Definitions for peripheral PSU_SATA */ #define XPAR_PSU_SATA_S_AXI_BASEADDR 0xFD0C0000 #define XPAR_PSU_SATA_S_AXI_HIGHADDR 0xFD0CFFFF /* Definitions for peripheral PSU_SERDES */ #define XPAR_PSU_SERDES_S_AXI_BASEADDR 0xFD400000 #define XPAR_PSU_SERDES_S_AXI_HIGHADDR 0xFD47FFFF /* Definitions for peripheral PSU_SIOU */ #define XPAR_PSU_SIOU_S_AXI_BASEADDR 0xFD3D0000 #define XPAR_PSU_SIOU_S_AXI_HIGHADDR 0xFD3DFFFF /* Definitions for peripheral PSU_SMMU_GPV */ #define XPAR_PSU_SMMU_GPV_S_AXI_BASEADDR 0xFD800000 #define XPAR_PSU_SMMU_GPV_S_AXI_HIGHADDR 0xFDFFFFFF /* Definitions for peripheral PSU_SMMU_REG */ #define XPAR_PSU_SMMU_REG_S_AXI_BASEADDR 0xFD5F0000 #define XPAR_PSU_SMMU_REG_S_AXI_HIGHADDR 0xFD5FFFFF /* Definitions for peripheral PSU_USB_0 */ #define XPAR_PSU_USB_0_S_AXI_BASEADDR 0xFF9D0000 #define XPAR_PSU_USB_0_S_AXI_HIGHADDR 0xFF9DFFFF /******************************************************************/ /* Definitions for driver GPIO */ #define XPAR_XGPIO_NUM_INSTANCES 1 /* Definitions for peripheral V_TPG_SS_0_AXI_GPIO */ #define XPAR_V_TPG_SS_0_AXI_GPIO_BASEADDR 0x80040000 #define XPAR_V_TPG_SS_0_AXI_GPIO_HIGHADDR 0x80040FFF #define XPAR_V_TPG_SS_0_AXI_GPIO_DEVICE_ID 0 #define XPAR_V_TPG_SS_0_AXI_GPIO_INTERRUPT_PRESENT 0 #define XPAR_V_TPG_SS_0_AXI_GPIO_IS_DUAL 0 /******************************************************************/ /* Canonical definitions for peripheral V_TPG_SS_0_AXI_GPIO */ #define XPAR_GPIO_0_BASEADDR 0x80040000 #define XPAR_GPIO_0_HIGHADDR 0x80040FFF #define XPAR_GPIO_0_DEVICE_ID XPAR_V_TPG_SS_0_AXI_GPIO_DEVICE_ID #define XPAR_GPIO_0_INTERRUPT_PRESENT 0 #define XPAR_GPIO_0_IS_DUAL 0 /******************************************************************/ /* Definitions for driver GPIOPS */ #define XPAR_XGPIOPS_NUM_INSTANCES 1 /* Definitions for peripheral PSU_GPIO_0 */ #define XPAR_PSU_GPIO_0_DEVICE_ID 0 #define XPAR_PSU_GPIO_0_BASEADDR 0xFF0A0000 #define XPAR_PSU_GPIO_0_HIGHADDR 0xFF0AFFFF /******************************************************************/ /* Canonical definitions for peripheral PSU_GPIO_0 */ #define XPAR_XGPIOPS_0_DEVICE_ID XPAR_PSU_GPIO_0_DEVICE_ID #define XPAR_XGPIOPS_0_BASEADDR 0xFF0A0000 #define XPAR_XGPIOPS_0_HIGHADDR 0xFF0AFFFF /******************************************************************/ /* Definitions for driver IIC */ #define XPAR_XIIC_NUM_INSTANCES 1 /* Definitions for peripheral ZYNQ_US_SS_0_FMCH_AXI_IIC */ #define XPAR_ZYNQ_US_SS_0_FMCH_AXI_IIC_DEVICE_ID 0 #define XPAR_ZYNQ_US_SS_0_FMCH_AXI_IIC_BASEADDR 0x80041000 #define XPAR_ZYNQ_US_SS_0_FMCH_AXI_IIC_HIGHADDR 0x80041FFF #define XPAR_ZYNQ_US_SS_0_FMCH_AXI_IIC_TEN_BIT_ADR 0 #define XPAR_ZYNQ_US_SS_0_FMCH_AXI_IIC_GPO_WIDTH 1 /******************************************************************/ /* Canonical definitions for peripheral ZYNQ_US_SS_0_FMCH_AXI_IIC */ #define XPAR_IIC_0_DEVICE_ID XPAR_ZYNQ_US_SS_0_FMCH_AXI_IIC_DEVICE_ID #define XPAR_IIC_0_BASEADDR 0x80041000 #define XPAR_IIC_0_HIGHADDR 0x80041FFF #define XPAR_IIC_0_TEN_BIT_ADR 0 #define XPAR_IIC_0_GPO_WIDTH 1 /******************************************************************/ /* Definitions for driver IICPS */ #define XPAR_XIICPS_NUM_INSTANCES 2 /* Definitions for peripheral PSU_I2C_0 */ #define XPAR_PSU_I2C_0_DEVICE_ID 0 #define XPAR_PSU_I2C_0_BASEADDR 0xFF020000 #define XPAR_PSU_I2C_0_HIGHADDR 0xFF02FFFF #define XPAR_PSU_I2C_0_I2C_CLK_FREQ_HZ 99999000 /* Definitions for peripheral PSU_I2C_1 */ #define XPAR_PSU_I2C_1_DEVICE_ID 1 #define XPAR_PSU_I2C_1_BASEADDR 0xFF030000 #define XPAR_PSU_I2C_1_HIGHADDR 0xFF03FFFF #define XPAR_PSU_I2C_1_I2C_CLK_FREQ_HZ 99999000 /******************************************************************/ /* Canonical definitions for peripheral PSU_I2C_0 */ #define XPAR_XIICPS_0_DEVICE_ID XPAR_PSU_I2C_0_DEVICE_ID #define XPAR_XIICPS_0_BASEADDR 0xFF020000 #define XPAR_XIICPS_0_HIGHADDR 0xFF02FFFF #define XPAR_XIICPS_0_I2C_CLK_FREQ_HZ 99999000 /* Canonical definitions for peripheral PSU_I2C_1 */ #define XPAR_XIICPS_1_DEVICE_ID XPAR_PSU_I2C_1_DEVICE_ID #define XPAR_XIICPS_1_BASEADDR 0xFF030000 #define XPAR_XIICPS_1_HIGHADDR 0xFF03FFFF #define XPAR_XIICPS_1_I2C_CLK_FREQ_HZ 99999000 /******************************************************************/ #define XPAR_XIPIPSU_NUM_INSTANCES 1U /* Parameter definitions for peripheral psu_ipi_0 */ #define XPAR_PSU_IPI_0_DEVICE_ID 0U #define XPAR_PSU_IPI_0_BASE_ADDRESS 0xFF300000U #define XPAR_PSU_IPI_0_BIT_MASK 0x00000001U #define XPAR_PSU_IPI_0_BUFFER_INDEX 2U #define XPAR_PSU_IPI_0_INT_ID 67U /* Canonical definitions for peripheral psu_ipi_0 */ #define XPAR_XIPIPSU_0_DEVICE_ID XPAR_PSU_IPI_0_DEVICE_ID #define XPAR_XIPIPSU_0_BASE_ADDRESS XPAR_PSU_IPI_0_BASE_ADDRESS #define XPAR_XIPIPSU_0_BIT_MASK XPAR_PSU_IPI_0_BIT_MASK #define XPAR_XIPIPSU_0_BUFFER_INDEX XPAR_PSU_IPI_0_BUFFER_INDEX #define XPAR_XIPIPSU_0_INT_ID XPAR_PSU_IPI_0_INT_ID #define XPAR_XIPIPSU_NUM_TARGETS 7U #define XPAR_PSU_IPI_0_BIT_MASK 0x00000001U #define XPAR_PSU_IPI_0_BUFFER_INDEX 2U #define XPAR_PSU_IPI_1_BIT_MASK 0x00000100U #define XPAR_PSU_IPI_1_BUFFER_INDEX 0U #define XPAR_PSU_IPI_2_BIT_MASK 0x00000200U #define XPAR_PSU_IPI_2_BUFFER_INDEX 1U #define XPAR_PSU_IPI_3_BIT_MASK 0x00010000U #define XPAR_PSU_IPI_3_BUFFER_INDEX 7U #define XPAR_PSU_IPI_4_BIT_MASK 0x00020000U #define XPAR_PSU_IPI_4_BUFFER_INDEX 7U #define XPAR_PSU_IPI_5_BIT_MASK 0x00040000U #define XPAR_PSU_IPI_5_BUFFER_INDEX 7U #define XPAR_PSU_IPI_6_BIT_MASK 0x00080000U #define XPAR_PSU_IPI_6_BUFFER_INDEX 7U /* Target List for referring to processor IPI Targets */ #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_0_CH0_MASK XPAR_PSU_IPI_0_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_0_CH0_INDEX 0U #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_1_CH0_MASK XPAR_PSU_IPI_0_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_1_CH0_INDEX 0U #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_2_CH0_MASK XPAR_PSU_IPI_0_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_2_CH0_INDEX 0U #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_3_CH0_MASK XPAR_PSU_IPI_0_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_CORTEXA53_3_CH0_INDEX 0U #define XPAR_XIPIPS_TARGET_PSU_CORTEXR5_0_CH0_MASK XPAR_PSU_IPI_1_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_CORTEXR5_0_CH0_INDEX 1U #define XPAR_XIPIPS_TARGET_PSU_CORTEXR5_1_CH0_MASK XPAR_PSU_IPI_2_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_CORTEXR5_1_CH0_INDEX 2U #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH0_MASK XPAR_PSU_IPI_3_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH0_INDEX 3U #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH1_MASK XPAR_PSU_IPI_4_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH1_INDEX 4U #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH2_MASK XPAR_PSU_IPI_5_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH2_INDEX 5U #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH3_MASK XPAR_PSU_IPI_6_BIT_MASK #define XPAR_XIPIPS_TARGET_PSU_PMU_0_CH3_INDEX 6U /* Definitions for driver QSPIPSU */ #define XPAR_XQSPIPSU_NUM_INSTANCES 1 /* Definitions for peripheral PSU_QSPI_0 */ #define XPAR_PSU_QSPI_0_DEVICE_ID 0 #define XPAR_PSU_QSPI_0_BASEADDR 0xFF0F0000 #define XPAR_PSU_QSPI_0_HIGHADDR 0xFF0FFFFF #define XPAR_PSU_QSPI_0_QSPI_CLK_FREQ_HZ 124998750 #define XPAR_PSU_QSPI_0_QSPI_MODE 0 #define XPAR_PSU_QSPI_0_QSPI_BUS_WIDTH 2 /******************************************************************/ #define XPAR_PSU_QSPI_0_IS_CACHE_COHERENT 0 /* Canonical definitions for peripheral PSU_QSPI_0 */ #define XPAR_XQSPIPSU_0_DEVICE_ID XPAR_PSU_QSPI_0_DEVICE_ID #define XPAR_XQSPIPSU_0_BASEADDR 0xFF0F0000 #define XPAR_XQSPIPSU_0_HIGHADDR 0xFF0FFFFF #define XPAR_XQSPIPSU_0_QSPI_CLK_FREQ_HZ 124998750 #define XPAR_XQSPIPSU_0_QSPI_MODE 0 #define XPAR_XQSPIPSU_0_QSPI_BUS_WIDTH 2 /******************************************************************/ /* Definitions for driver RESETPS */ #define XPAR_XRESETPS_NUM_INSTANCES 1U /* Definitions for peripheral RESETPS */ #define XPAR_XRESETPS_DEVICE_ID 0 #define XPAR_XRESETPS_BASEADDR 0xFFFFFFFFU /******************************************************************/ /* Definitions for driver RTCPSU */ #define XPAR_XRTCPSU_NUM_INSTANCES 1 /* Definitions for peripheral PSU_RTC */ #define XPAR_PSU_RTC_DEVICE_ID 0 #define XPAR_PSU_RTC_BASEADDR 0xFFA60000 #define XPAR_PSU_RTC_HIGHADDR 0xFFA6FFFF /******************************************************************/ /* Canonical definitions for peripheral PSU_RTC */ #define XPAR_XRTCPSU_0_DEVICE_ID XPAR_PSU_RTC_DEVICE_ID #define XPAR_XRTCPSU_0_BASEADDR 0xFFA60000 #define XPAR_XRTCPSU_0_HIGHADDR 0xFFA6FFFF /******************************************************************/ /* Definitions for Fabric interrupts connected to psu_acpu_gic */ #define XPAR_FABRIC_VID_PHY_CONTROLLER_IRQ_INTR 121U #define XPAR_FABRIC_V_HDMI_RX_SS_IRQ_INTR 122U #define XPAR_FABRIC_V_HDMI_TX_SS_IRQ_INTR 123U /******************************************************************/ /* Canonical definitions for Fabric interrupts connected to psu_acpu_gic */ #define XPAR_FABRIC_VPHY_0_VEC_ID XPAR_FABRIC_VID_PHY_CONTROLLER_IRQ_INTR #define XPAR_FABRIC_V_HDMIRXSS_0_VEC_ID XPAR_FABRIC_V_HDMI_RX_SS_IRQ_INTR #define XPAR_FABRIC_V_HDMITXSS_0_VEC_ID XPAR_FABRIC_V_HDMI_TX_SS_IRQ_INTR /******************************************************************/ /* Definitions for driver SCUGIC */ #define XPAR_XSCUGIC_NUM_INSTANCES 1U /* Definitions for peripheral PSU_ACPU_GIC */ #define XPAR_PSU_ACPU_GIC_DEVICE_ID 0U #define XPAR_PSU_ACPU_GIC_BASEADDR 0xF9020000U #define XPAR_PSU_ACPU_GIC_HIGHADDR 0xF9020FFFU #define XPAR_PSU_ACPU_GIC_DIST_BASEADDR 0xF9010000U /******************************************************************/ /* Canonical definitions for peripheral PSU_ACPU_GIC */ #define XPAR_SCUGIC_0_DEVICE_ID 0U #define XPAR_SCUGIC_0_CPU_BASEADDR 0xF9020000U #define XPAR_SCUGIC_0_CPU_HIGHADDR 0xF9020FFFU #define XPAR_SCUGIC_0_DIST_BASEADDR 0xF9010000U /******************************************************************/ /* Definitions for driver SDPS */ #define XPAR_XSDPS_NUM_INSTANCES 1 /* Definitions for peripheral PSU_SD_1 */ #define XPAR_PSU_SD_1_DEVICE_ID 0 #define XPAR_PSU_SD_1_BASEADDR 0xFF170000 #define XPAR_PSU_SD_1_HIGHADDR 0xFF17FFFF #define XPAR_PSU_SD_1_SDIO_CLK_FREQ_HZ 187498125 #define XPAR_PSU_SD_1_HAS_CD 1 #define XPAR_PSU_SD_1_HAS_WP 0 #define XPAR_PSU_SD_1_BUS_WIDTH 4 #define XPAR_PSU_SD_1_MIO_BANK 1 #define XPAR_PSU_SD_1_HAS_EMIO 0 /******************************************************************/ #define XPAR_PSU_SD_1_IS_CACHE_COHERENT 0 /* Canonical definitions for peripheral PSU_SD_1 */ #define XPAR_XSDPS_0_DEVICE_ID XPAR_PSU_SD_1_DEVICE_ID #define XPAR_XSDPS_0_BASEADDR 0xFF170000 #define XPAR_XSDPS_0_HIGHADDR 0xFF17FFFF #define XPAR_XSDPS_0_SDIO_CLK_FREQ_HZ 187498125 #define XPAR_XSDPS_0_HAS_CD 1 #define XPAR_XSDPS_0_HAS_WP 0 #define XPAR_XSDPS_0_BUS_WIDTH 4 #define XPAR_XSDPS_0_MIO_BANK 1 #define XPAR_XSDPS_0_HAS_EMIO 0 /******************************************************************/ /* Definitions for driver SYSMONPSU */ #define XPAR_XSYSMONPSU_NUM_INSTANCES 1 /* Definitions for peripheral PSU_AMS */ #define XPAR_PSU_AMS_DEVICE_ID 0 #define XPAR_PSU_AMS_BASEADDR 0xFFA50000 #define XPAR_PSU_AMS_HIGHADDR 0xFFA5FFFF /******************************************************************/ #define XPAR_PSU_AMS_REF_FREQMHZ 49.999500 /* Canonical definitions for peripheral PSU_AMS */ #define XPAR_XSYSMONPSU_0_DEVICE_ID XPAR_PSU_AMS_DEVICE_ID #define XPAR_XSYSMONPSU_0_BASEADDR 0xFFA50000 #define XPAR_XSYSMONPSU_0_HIGHADDR 0xFFA5FFFF /******************************************************************/ /* Definitions for driver TTCPS */ #define XPAR_XTTCPS_NUM_INSTANCES 12U /* Definitions for peripheral PSU_TTC_0 */ #define XPAR_PSU_TTC_0_DEVICE_ID 0U #define XPAR_PSU_TTC_0_BASEADDR 0XFF110000U #define XPAR_PSU_TTC_0_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_0_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_1_DEVICE_ID 1U #define XPAR_PSU_TTC_1_BASEADDR 0XFF110004U #define XPAR_PSU_TTC_1_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_1_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_2_DEVICE_ID 2U #define XPAR_PSU_TTC_2_BASEADDR 0XFF110008U #define XPAR_PSU_TTC_2_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_2_TTC_CLK_CLKSRC 0U /* Definitions for peripheral PSU_TTC_1 */ #define XPAR_PSU_TTC_3_DEVICE_ID 3U #define XPAR_PSU_TTC_3_BASEADDR 0XFF120000U #define XPAR_PSU_TTC_3_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_3_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_4_DEVICE_ID 4U #define XPAR_PSU_TTC_4_BASEADDR 0XFF120004U #define XPAR_PSU_TTC_4_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_4_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_5_DEVICE_ID 5U #define XPAR_PSU_TTC_5_BASEADDR 0XFF120008U #define XPAR_PSU_TTC_5_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_5_TTC_CLK_CLKSRC 0U /* Definitions for peripheral PSU_TTC_2 */ #define XPAR_PSU_TTC_6_DEVICE_ID 6U #define XPAR_PSU_TTC_6_BASEADDR 0XFF130000U #define XPAR_PSU_TTC_6_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_6_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_7_DEVICE_ID 7U #define XPAR_PSU_TTC_7_BASEADDR 0XFF130004U #define XPAR_PSU_TTC_7_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_7_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_8_DEVICE_ID 8U #define XPAR_PSU_TTC_8_BASEADDR 0XFF130008U #define XPAR_PSU_TTC_8_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_8_TTC_CLK_CLKSRC 0U /* Definitions for peripheral PSU_TTC_3 */ #define XPAR_PSU_TTC_9_DEVICE_ID 9U #define XPAR_PSU_TTC_9_BASEADDR 0XFF140000U #define XPAR_PSU_TTC_9_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_9_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_10_DEVICE_ID 10U #define XPAR_PSU_TTC_10_BASEADDR 0XFF140004U #define XPAR_PSU_TTC_10_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_10_TTC_CLK_CLKSRC 0U #define XPAR_PSU_TTC_11_DEVICE_ID 11U #define XPAR_PSU_TTC_11_BASEADDR 0XFF140008U #define XPAR_PSU_TTC_11_TTC_CLK_FREQ_HZ 100000000U #define XPAR_PSU_TTC_11_TTC_CLK_CLKSRC 0U /******************************************************************/ /* Canonical definitions for peripheral PSU_TTC_0 */ #define XPAR_XTTCPS_0_DEVICE_ID XPAR_PSU_TTC_0_DEVICE_ID #define XPAR_XTTCPS_0_BASEADDR 0xFF110000U #define XPAR_XTTCPS_0_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_0_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_1_DEVICE_ID XPAR_PSU_TTC_1_DEVICE_ID #define XPAR_XTTCPS_1_BASEADDR 0xFF110004U #define XPAR_XTTCPS_1_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_1_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_2_DEVICE_ID XPAR_PSU_TTC_2_DEVICE_ID #define XPAR_XTTCPS_2_BASEADDR 0xFF110008U #define XPAR_XTTCPS_2_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_2_TTC_CLK_CLKSRC 0U /* Canonical definitions for peripheral PSU_TTC_1 */ #define XPAR_XTTCPS_3_DEVICE_ID XPAR_PSU_TTC_3_DEVICE_ID #define XPAR_XTTCPS_3_BASEADDR 0xFF120000U #define XPAR_XTTCPS_3_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_3_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_4_DEVICE_ID XPAR_PSU_TTC_4_DEVICE_ID #define XPAR_XTTCPS_4_BASEADDR 0xFF120004U #define XPAR_XTTCPS_4_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_4_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_5_DEVICE_ID XPAR_PSU_TTC_5_DEVICE_ID #define XPAR_XTTCPS_5_BASEADDR 0xFF120008U #define XPAR_XTTCPS_5_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_5_TTC_CLK_CLKSRC 0U /* Canonical definitions for peripheral PSU_TTC_2 */ #define XPAR_XTTCPS_6_DEVICE_ID XPAR_PSU_TTC_6_DEVICE_ID #define XPAR_XTTCPS_6_BASEADDR 0xFF130000U #define XPAR_XTTCPS_6_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_6_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_7_DEVICE_ID XPAR_PSU_TTC_7_DEVICE_ID #define XPAR_XTTCPS_7_BASEADDR 0xFF130004U #define XPAR_XTTCPS_7_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_7_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_8_DEVICE_ID XPAR_PSU_TTC_8_DEVICE_ID #define XPAR_XTTCPS_8_BASEADDR 0xFF130008U #define XPAR_XTTCPS_8_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_8_TTC_CLK_CLKSRC 0U /* Canonical definitions for peripheral PSU_TTC_3 */ #define XPAR_XTTCPS_9_DEVICE_ID XPAR_PSU_TTC_9_DEVICE_ID #define XPAR_XTTCPS_9_BASEADDR 0xFF140000U #define XPAR_XTTCPS_9_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_9_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_10_DEVICE_ID XPAR_PSU_TTC_10_DEVICE_ID #define XPAR_XTTCPS_10_BASEADDR 0xFF140004U #define XPAR_XTTCPS_10_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_10_TTC_CLK_CLKSRC 0U #define XPAR_XTTCPS_11_DEVICE_ID XPAR_PSU_TTC_11_DEVICE_ID #define XPAR_XTTCPS_11_BASEADDR 0xFF140008U #define XPAR_XTTCPS_11_TTC_CLK_FREQ_HZ 100000000U #define XPAR_XTTCPS_11_TTC_CLK_CLKSRC 0U /******************************************************************/ /* Definitions for driver UARTPS */ #define XPAR_XUARTPS_NUM_INSTANCES 2 /* Definitions for peripheral PSU_UART_0 */ #define XPAR_PSU_UART_0_DEVICE_ID 0 #define XPAR_PSU_UART_0_BASEADDR 0xFF000000 #define XPAR_PSU_UART_0_HIGHADDR 0xFF00FFFF #define XPAR_PSU_UART_0_UART_CLK_FREQ_HZ 99999000 #define XPAR_PSU_UART_0_HAS_MODEM 0 /* Definitions for peripheral PSU_UART_1 */ #define XPAR_PSU_UART_1_DEVICE_ID 1 #define XPAR_PSU_UART_1_BASEADDR 0xFF010000 #define XPAR_PSU_UART_1_HIGHADDR 0xFF01FFFF #define XPAR_PSU_UART_1_UART_CLK_FREQ_HZ 99999000 #define XPAR_PSU_UART_1_HAS_MODEM 0 /******************************************************************/ /* Canonical definitions for peripheral PSU_UART_0 */ #define XPAR_XUARTPS_0_DEVICE_ID XPAR_PSU_UART_0_DEVICE_ID #define XPAR_XUARTPS_0_BASEADDR 0xFF000000 #define XPAR_XUARTPS_0_HIGHADDR 0xFF00FFFF #define XPAR_XUARTPS_0_UART_CLK_FREQ_HZ 99999000 #define XPAR_XUARTPS_0_HAS_MODEM 0 /* Canonical definitions for peripheral PSU_UART_1 */ #define XPAR_XUARTPS_1_DEVICE_ID XPAR_PSU_UART_1_DEVICE_ID #define XPAR_XUARTPS_1_BASEADDR 0xFF010000 #define XPAR_XUARTPS_1_HIGHADDR 0xFF01FFFF #define XPAR_XUARTPS_1_UART_CLK_FREQ_HZ 99999000 #define XPAR_XUARTPS_1_HAS_MODEM 0 /******************************************************************/ /* Definitions for driver USBPSU */ #define XPAR_XUSBPSU_NUM_INSTANCES 1 /* Definitions for peripheral PSU_USB_XHCI_0 */ #define XPAR_PSU_USB_XHCI_0_DEVICE_ID 0 #define XPAR_PSU_USB_XHCI_0_BASEADDR 0xFE200000 #define XPAR_PSU_USB_XHCI_0_HIGHADDR 0xFE20FFFF /******************************************************************/ #define XPAR_PSU_USB_XHCI_0_IS_CACHE_COHERENT 0 /* Canonical definitions for peripheral PSU_USB_XHCI_0 */ #define XPAR_XUSBPSU_0_DEVICE_ID XPAR_PSU_USB_XHCI_0_DEVICE_ID #define XPAR_XUSBPSU_0_BASEADDR 0xFE200000 #define XPAR_XUSBPSU_0_HIGHADDR 0xFE20FFFF /******************************************************************/ /* Definitions for driver V_HDMIRX */ #define XPAR_XV_HDMIRX_NUM_INSTANCES 1 /* Definitions for peripheral V_HDMI_RX_SS_V_HDMI_RX */ #define XPAR_V_HDMI_RX_SS_V_HDMI_RX_DEVICE_ID 0 #define XPAR_V_HDMI_RX_SS_V_HDMI_RX_BASEADDR 0x00000000 #define XPAR_V_HDMI_RX_SS_V_HDMI_RX_HIGHADDR 0x0000FFFF #define XPAR_V_HDMI_RX_SS_V_HDMI_RX_AXI_LITE_FREQ_HZ 99999000 /******************************************************************/ /* Canonical definitions for peripheral V_HDMI_RX_SS_V_HDMI_RX */ #define XPAR_XV_HDMIRX_0_NUM_INSTANCES 0 #define XPAR_XV_HDMIRX_0_DEVICE_ID XPAR_V_HDMI_RX_SS_V_HDMI_RX_DEVICE_ID #define XPAR_XV_HDMIRX_0_BASEADDR 0x00000000 #define XPAR_XV_HDMIRX_0_HIGHADDR 0x0000FFFF #define XPAR_XV_HDMIRX_0_AXI_LITE_FREQ_HZ 99999000 /******************************************************************/ /* Definitions for driver V_HDMIRXSS */ #define XPAR_XV_HDMIRXSS_NUM_INSTANCES 1 /* Definitions for peripheral V_HDMI_RX_SS */ #define XPAR_V_HDMI_RX_SS_BASEADDR 0x80000000 #define XPAR_V_HDMI_RX_SS_HIGHADDR 0x8000FFFF #define XPAR_V_HDMI_RX_SS_DEVICE_ID 0 #define XPAR_V_HDMI_RX_SS_INPUT_PIXELS_PER_CLOCK 2 #define XPAR_V_HDMI_RX_SS_MAX_BITS_PER_COMPONENT 8 /******************************************************************/ /* Canonical definitions for peripheral V_HDMI_RX_SS */ #define XPAR_XV_HDMIRXSS_0_BASEADDR 0x80000000 #define XPAR_XV_HDMIRXSS_0_HIGHADDR 0x8000FFFF #define XPAR_XV_HDMIRXSS_0_DEVICE_ID XPAR_V_HDMI_RX_SS_DEVICE_ID #define XPAR_XV_HDMIRXSS_0_INPUT_PIXELS_PER_CLOCK 2 #define XPAR_XV_HDMIRXSS_0_MAX_BITS_PER_COMPONENT 8 /******************************************************************/ /* Definitions for driver V_HDMITX */ #define XPAR_XV_HDMITX_NUM_INSTANCES 1 /* Definitions for peripheral V_HDMI_TX_SS_V_HDMI_TX */ #define XPAR_V_HDMI_TX_SS_V_HDMI_TX_DEVICE_ID 0 #define XPAR_V_HDMI_TX_SS_V_HDMI_TX_BASEADDR 0x00000000 #define XPAR_V_HDMI_TX_SS_V_HDMI_TX_HIGHADDR 0x0000FFFF #define XPAR_V_HDMI_TX_SS_V_HDMI_TX_AXI_LITE_FREQ_HZ 99999000 /******************************************************************/ /* Canonical definitions for peripheral V_HDMI_TX_SS_V_HDMI_TX */ #define XPAR_XV_HDMITX_0_NUM_INSTANCES 0 #define XPAR_XV_HDMITX_0_DEVICE_ID XPAR_V_HDMI_TX_SS_V_HDMI_TX_DEVICE_ID #define XPAR_XV_HDMITX_0_BASEADDR 0x00000000 #define XPAR_XV_HDMITX_0_HIGHADDR 0x0000FFFF #define XPAR_XV_HDMITX_0_AXI_LITE_FREQ_HZ 99999000 /******************************************************************/ /* Definitions for driver V_HDMITXSS */ #define XPAR_XV_HDMITXSS_NUM_INSTANCES 1 /* Definitions for peripheral V_HDMI_TX_SS */ #define XPAR_V_HDMI_TX_SS_BASEADDR 0x80020000 #define XPAR_V_HDMI_TX_SS_HIGHADDR 0x8003FFFF #define XPAR_V_HDMI_TX_SS_DEVICE_ID 0 #define XPAR_V_HDMI_TX_SS_INPUT_PIXELS_PER_CLOCK 2 #define XPAR_V_HDMI_TX_SS_MAX_BITS_PER_COMPONENT 8 #define XPAR_V_HDMI_TX_SS_INCLUDE_LOW_RESO_VID 0 #define XPAR_V_HDMI_TX_SS_INCLUDE_YUV420_SUP 0 #define XPAR_V_HDMI_TX_SS_AXI_LITE_FREQ_HZ 99999000 /******************************************************************/ /* Canonical definitions for peripheral V_HDMI_TX_SS */ #define XPAR_XV_HDMITXSS_0_BASEADDR 0x80020000 #define XPAR_XV_HDMITXSS_0_HIGHADDR 0x8003FFFF #define XPAR_XV_HDMITXSS_0_DEVICE_ID 0 #define XPAR_XV_HDMITXSS_0_INPUT_PIXELS_PER_CLOCK 2 #define XPAR_XV_HDMITXSS_0_MAX_BITS_PER_COMPONENT 8 #define XPAR_XV_HDMITXSS_0_INCLUDE_LOW_RESO_VID 0 #define XPAR_XV_HDMITXSS_0_INCLUDE_YUV420_SUP 0 #define XPAR_XV_HDMITXSS_0_AXI_LITE_FREQ_HZ 99999000 /******************************************************************/ /* Definitions for driver V_TPG */ #define XPAR_XV_TPG_NUM_INSTANCES 1 /* Definitions for peripheral V_TPG_SS_0_V_TPG */ #define XPAR_V_TPG_SS_0_V_TPG_DEVICE_ID 0 #define XPAR_V_TPG_SS_0_V_TPG_S_AXI_CTRL_BASEADDR 0x80050000 #define XPAR_V_TPG_SS_0_V_TPG_S_AXI_CTRL_HIGHADDR 0x8005FFFF #define XPAR_V_TPG_SS_0_V_TPG_HAS_AXI4S_SLAVE 1 #define XPAR_V_TPG_SS_0_V_TPG_SAMPLES_PER_CLOCK 2 #define XPAR_V_TPG_SS_0_V_TPG_NUM_VIDEO_COMPONENTS 3 #define XPAR_V_TPG_SS_0_V_TPG_MAX_COLS 4096 #define XPAR_V_TPG_SS_0_V_TPG_MAX_ROWS 2160 #define XPAR_V_TPG_SS_0_V_TPG_MAX_DATA_WIDTH 8 #define XPAR_V_TPG_SS_0_V_TPG_SOLID_COLOR 0 #define XPAR_V_TPG_SS_0_V_TPG_RAMP 0 #define XPAR_V_TPG_SS_0_V_TPG_COLOR_BAR 1 #define XPAR_V_TPG_SS_0_V_TPG_DISPLAY_PORT 0 #define XPAR_V_TPG_SS_0_V_TPG_COLOR_SWEEP 0 #define XPAR_V_TPG_SS_0_V_TPG_ZONE_PLATE 0 #define XPAR_V_TPG_SS_0_V_TPG_FOREGROUND 0 /******************************************************************/ /* Canonical definitions for peripheral V_TPG_SS_0_V_TPG */ #define XPAR_XV_TPG_0_DEVICE_ID XPAR_V_TPG_SS_0_V_TPG_DEVICE_ID #define XPAR_XV_TPG_0_S_AXI_CTRL_BASEADDR 0x80050000 #define XPAR_XV_TPG_0_S_AXI_CTRL_HIGHADDR 0x8005FFFF #define XPAR_XV_TPG_0_HAS_AXI4S_SLAVE 1 #define XPAR_XV_TPG_0_SAMPLES_PER_CLOCK 2 #define XPAR_XV_TPG_0_NUM_VIDEO_COMPONENTS 3 #define XPAR_XV_TPG_0_MAX_COLS 4096 #define XPAR_XV_TPG_0_MAX_ROWS 2160 #define XPAR_XV_TPG_0_MAX_DATA_WIDTH 8 #define XPAR_XV_TPG_0_SOLID_COLOR 0 #define XPAR_XV_TPG_0_RAMP 0 #define XPAR_XV_TPG_0_COLOR_BAR 1 #define XPAR_XV_TPG_0_DISPLAY_PORT 0 #define XPAR_XV_TPG_0_COLOR_SWEEP 0 #define XPAR_XV_TPG_0_ZONE_PLATE 0 #define XPAR_XV_TPG_0_FOREGROUND 0 /******************************************************************/ /* Definitions for driver VPHY */ #define XPAR_XVPHY_NUM_INSTANCES 1 /* Definitions for peripheral VID_PHY_CONTROLLER */ #define XPAR_VID_PHY_CONTROLLER_DEVICE_ID 0 #define XPAR_VID_PHY_CONTROLLER_BASEADDR 0x80060000 #define XPAR_VID_PHY_CONTROLLER_TRANSCEIVER_STR "GTHE4" #define XPAR_VID_PHY_CONTROLLER_TRANSCEIVER 5 #define XPAR_VID_PHY_CONTROLLER_TX_NO_OF_CHANNELS 3 #define XPAR_VID_PHY_CONTROLLER_RX_NO_OF_CHANNELS 3 #define XPAR_VID_PHY_CONTROLLER_TX_PROTOCOL 1 #define XPAR_VID_PHY_CONTROLLER_RX_PROTOCOL 1 #define XPAR_VID_PHY_CONTROLLER_TX_REFCLK_SEL 0 #define XPAR_VID_PHY_CONTROLLER_RX_REFCLK_SEL 1 #define XPAR_VID_PHY_CONTROLLER_TX_PLL_SELECTION 6 #define XPAR_VID_PHY_CONTROLLER_RX_PLL_SELECTION 0 #define XPAR_VID_PHY_CONTROLLER_NIDRU 1 #define XPAR_VID_PHY_CONTROLLER_NIDRU_REFCLK_SEL 3 #define XPAR_VID_PHY_CONTROLLER_INPUT_PIXELS_PER_CLOCK 2 #define XPAR_VID_PHY_CONTROLLER_TX_BUFFER_BYPASS 1 #define XPAR_VID_PHY_CONTROLLER_HDMI_FAST_SWITCH 1 #define XPAR_VID_PHY_CONTROLLER_TRANSCEIVER_WIDTH 2 #define XPAR_VID_PHY_CONTROLLER_ERR_IRQ_EN 0 #define XPAR_VID_PHY_CONTROLLER_AXI_LITE_FREQ_HZ 99999000 #define XPAR_VID_PHY_CONTROLLER_DRPCLK_FREQ 99999000 #define XPAR_VID_PHY_CONTROLLER_USE_GT_CH4_HDMI 0 /******************************************************************/ /* Canonical definitions for peripheral VID_PHY_CONTROLLER */ #define XPAR_VPHY_0_DEVICE_ID XPAR_VID_PHY_CONTROLLER_DEVICE_ID #define XPAR_VPHY_0_BASEADDR 0x80060000 #define XPAR_VPHY_0_TRANSCEIVER_STR "GTHE4" #define XPAR_VPHY_0_TRANSCEIVER 5 #define XPAR_VPHY_0_TX_NO_OF_CHANNELS 3 #define XPAR_VPHY_0_RX_NO_OF_CHANNELS 3 #define XPAR_VPHY_0_TX_PROTOCOL 1 #define XPAR_VPHY_0_RX_PROTOCOL 1 #define XPAR_VPHY_0_TX_REFCLK_SEL 0 #define XPAR_VPHY_0_RX_REFCLK_SEL 1 #define XPAR_VPHY_0_TX_PLL_SELECTION 6 #define XPAR_VPHY_0_RX_PLL_SELECTION 0 #define XPAR_VPHY_0_NIDRU 1 #define XPAR_VPHY_0_NIDRU_REFCLK_SEL 3 #define XPAR_VPHY_0_INPUT_PIXELS_PER_CLOCK 2 #define XPAR_VPHY_0_TX_BUFFER_BYPASS 1 #define XPAR_VPHY_0_HDMI_FAST_SWITCH 1 #define XPAR_VPHY_0_TRANSCEIVER_WIDTH 2 #define XPAR_VPHY_0_ERR_IRQ_EN 0 #define XPAR_VPHY_0_AXI_LITE_FREQ_HZ 99999000 #define XPAR_VPHY_0_DRPCLK_FREQ 99999000 #define XPAR_VPHY_0_USE_GT_CH4_HDMI 0 /******************************************************************/ /* Definitions for driver VTC */ #define XPAR_XVTC_NUM_INSTANCES 1 /* Definitions for peripheral V_HDMI_TX_SS_V_TC */ #define XPAR_V_HDMI_TX_SS_V_TC_DEVICE_ID 0 #define XPAR_V_HDMI_TX_SS_V_TC_BASEADDR 0x00010000 #define XPAR_V_HDMI_TX_SS_V_TC_HIGHADDR 0x0001FFFF #define XPAR_V_HDMI_TX_SS_V_TC_GENERATE_EN 1 #define XPAR_V_HDMI_TX_SS_V_TC_DETECT_EN 0 #define XPAR_V_HDMI_TX_SS_V_TC_DET_HSYNC_EN 1 #define XPAR_V_HDMI_TX_SS_V_TC_DET_VSYNC_EN 1 #define XPAR_V_HDMI_TX_SS_V_TC_DET_HBLANK_EN 1 #define XPAR_V_HDMI_TX_SS_V_TC_DET_VBLANK_EN 1 #define XPAR_V_HDMI_TX_SS_V_TC_DET_AVIDEO_EN 1 #define XPAR_V_HDMI_TX_SS_V_TC_DET_ACHROMA_EN 0 /******************************************************************/ /* Canonical definitions for peripheral V_HDMI_TX_SS_V_TC */ #define XPAR_VTC_0_DEVICE_ID XPAR_V_HDMI_TX_SS_V_TC_DEVICE_ID #define XPAR_VTC_0_BASEADDR 0x00010000 #define XPAR_VTC_0_HIGHADDR 0x0001FFFF #define XPAR_VTC_0_GENERATE_EN 1 #define XPAR_VTC_0_DETECT_EN 0 #define XPAR_VTC_0_DET_HSYNC_EN 1 #define XPAR_VTC_0_DET_VSYNC_EN 1 #define XPAR_VTC_0_DET_HBLANK_EN 1 #define XPAR_VTC_0_DET_VBLANK_EN 1 #define XPAR_VTC_0_DET_AVIDEO_EN 1 #define XPAR_VTC_0_DET_ACHROMA_EN 0 /******************************************************************/ /* Definitions for driver WDTPS */ #define XPAR_XWDTPS_NUM_INSTANCES 2 /* Definitions for peripheral PSU_WDT_0 */ #define XPAR_PSU_WDT_0_DEVICE_ID 0 #define XPAR_PSU_WDT_0_BASEADDR 0xFF150000 #define XPAR_PSU_WDT_0_HIGHADDR 0xFF15FFFF #define XPAR_PSU_WDT_0_WDT_CLK_FREQ_HZ 99999001 /* Definitions for peripheral PSU_WDT_1 */ #define XPAR_PSU_WDT_1_DEVICE_ID 1 #define XPAR_PSU_WDT_1_BASEADDR 0xFD4D0000 #define XPAR_PSU_WDT_1_HIGHADDR 0xFD4DFFFF #define XPAR_PSU_WDT_1_WDT_CLK_FREQ_HZ 99999001 /******************************************************************/ /* Canonical definitions for peripheral PSU_WDT_0 */ #define XPAR_XWDTPS_0_DEVICE_ID XPAR_PSU_WDT_0_DEVICE_ID #define XPAR_XWDTPS_0_BASEADDR 0xFF150000 #define XPAR_XWDTPS_0_HIGHADDR 0xFF15FFFF #define XPAR_XWDTPS_0_WDT_CLK_FREQ_HZ 99999001 /* Canonical definitions for peripheral PSU_WDT_1 */ #define XPAR_XWDTPS_1_DEVICE_ID XPAR_PSU_WDT_1_DEVICE_ID #define XPAR_XWDTPS_1_BASEADDR 0xFD4D0000 #define XPAR_XWDTPS_1_HIGHADDR 0xFD4DFFFF #define XPAR_XWDTPS_1_WDT_CLK_FREQ_HZ 99999001 /******************************************************************/ /* Definitions for driver ZDMA */ #define XPAR_XZDMA_NUM_INSTANCES 16 /* Definitions for peripheral PSU_ADMA_0 */ #define XPAR_PSU_ADMA_0_DEVICE_ID 0 #define XPAR_PSU_ADMA_0_BASEADDR 0xFFA80000 #define XPAR_PSU_ADMA_0_DMA_MODE 1 #define XPAR_PSU_ADMA_0_HIGHADDR 0xFFA8FFFF #define XPAR_PSU_ADMA_0_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_1 */ #define XPAR_PSU_ADMA_1_DEVICE_ID 1 #define XPAR_PSU_ADMA_1_BASEADDR 0xFFA90000 #define XPAR_PSU_ADMA_1_DMA_MODE 1 #define XPAR_PSU_ADMA_1_HIGHADDR 0xFFA9FFFF #define XPAR_PSU_ADMA_1_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_2 */ #define XPAR_PSU_ADMA_2_DEVICE_ID 2 #define XPAR_PSU_ADMA_2_BASEADDR 0xFFAA0000 #define XPAR_PSU_ADMA_2_DMA_MODE 1 #define XPAR_PSU_ADMA_2_HIGHADDR 0xFFAAFFFF #define XPAR_PSU_ADMA_2_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_3 */ #define XPAR_PSU_ADMA_3_DEVICE_ID 3 #define XPAR_PSU_ADMA_3_BASEADDR 0xFFAB0000 #define XPAR_PSU_ADMA_3_DMA_MODE 1 #define XPAR_PSU_ADMA_3_HIGHADDR 0xFFABFFFF #define XPAR_PSU_ADMA_3_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_4 */ #define XPAR_PSU_ADMA_4_DEVICE_ID 4 #define XPAR_PSU_ADMA_4_BASEADDR 0xFFAC0000 #define XPAR_PSU_ADMA_4_DMA_MODE 1 #define XPAR_PSU_ADMA_4_HIGHADDR 0xFFACFFFF #define XPAR_PSU_ADMA_4_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_5 */ #define XPAR_PSU_ADMA_5_DEVICE_ID 5 #define XPAR_PSU_ADMA_5_BASEADDR 0xFFAD0000 #define XPAR_PSU_ADMA_5_DMA_MODE 1 #define XPAR_PSU_ADMA_5_HIGHADDR 0xFFADFFFF #define XPAR_PSU_ADMA_5_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_6 */ #define XPAR_PSU_ADMA_6_DEVICE_ID 6 #define XPAR_PSU_ADMA_6_BASEADDR 0xFFAE0000 #define XPAR_PSU_ADMA_6_DMA_MODE 1 #define XPAR_PSU_ADMA_6_HIGHADDR 0xFFAEFFFF #define XPAR_PSU_ADMA_6_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_ADMA_7 */ #define XPAR_PSU_ADMA_7_DEVICE_ID 7 #define XPAR_PSU_ADMA_7_BASEADDR 0xFFAF0000 #define XPAR_PSU_ADMA_7_DMA_MODE 1 #define XPAR_PSU_ADMA_7_HIGHADDR 0xFFAFFFFF #define XPAR_PSU_ADMA_7_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_0 */ #define XPAR_PSU_GDMA_0_DEVICE_ID 8 #define XPAR_PSU_GDMA_0_BASEADDR 0xFD500000 #define XPAR_PSU_GDMA_0_DMA_MODE 0 #define XPAR_PSU_GDMA_0_HIGHADDR 0xFD50FFFF #define XPAR_PSU_GDMA_0_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_1 */ #define XPAR_PSU_GDMA_1_DEVICE_ID 9 #define XPAR_PSU_GDMA_1_BASEADDR 0xFD510000 #define XPAR_PSU_GDMA_1_DMA_MODE 0 #define XPAR_PSU_GDMA_1_HIGHADDR 0xFD51FFFF #define XPAR_PSU_GDMA_1_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_2 */ #define XPAR_PSU_GDMA_2_DEVICE_ID 10 #define XPAR_PSU_GDMA_2_BASEADDR 0xFD520000 #define XPAR_PSU_GDMA_2_DMA_MODE 0 #define XPAR_PSU_GDMA_2_HIGHADDR 0xFD52FFFF #define XPAR_PSU_GDMA_2_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_3 */ #define XPAR_PSU_GDMA_3_DEVICE_ID 11 #define XPAR_PSU_GDMA_3_BASEADDR 0xFD530000 #define XPAR_PSU_GDMA_3_DMA_MODE 0 #define XPAR_PSU_GDMA_3_HIGHADDR 0xFD53FFFF #define XPAR_PSU_GDMA_3_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_4 */ #define XPAR_PSU_GDMA_4_DEVICE_ID 12 #define XPAR_PSU_GDMA_4_BASEADDR 0xFD540000 #define XPAR_PSU_GDMA_4_DMA_MODE 0 #define XPAR_PSU_GDMA_4_HIGHADDR 0xFD54FFFF #define XPAR_PSU_GDMA_4_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_5 */ #define XPAR_PSU_GDMA_5_DEVICE_ID 13 #define XPAR_PSU_GDMA_5_BASEADDR 0xFD550000 #define XPAR_PSU_GDMA_5_DMA_MODE 0 #define XPAR_PSU_GDMA_5_HIGHADDR 0xFD55FFFF #define XPAR_PSU_GDMA_5_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_6 */ #define XPAR_PSU_GDMA_6_DEVICE_ID 14 #define XPAR_PSU_GDMA_6_BASEADDR 0xFD560000 #define XPAR_PSU_GDMA_6_DMA_MODE 0 #define XPAR_PSU_GDMA_6_HIGHADDR 0xFD56FFFF #define XPAR_PSU_GDMA_6_ZDMA_CLK_FREQ_HZ 0 /* Definitions for peripheral PSU_GDMA_7 */ #define XPAR_PSU_GDMA_7_DEVICE_ID 15 #define XPAR_PSU_GDMA_7_BASEADDR 0xFD570000 #define XPAR_PSU_GDMA_7_DMA_MODE 0 #define XPAR_PSU_GDMA_7_HIGHADDR 0xFD57FFFF #define XPAR_PSU_GDMA_7_ZDMA_CLK_FREQ_HZ 0 /******************************************************************/ #define XPAR_PSU_ADMA_0_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_1_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_2_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_3_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_4_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_5_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_6_IS_CACHE_COHERENT 0 #define XPAR_PSU_ADMA_7_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_0_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_1_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_2_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_3_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_4_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_5_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_6_IS_CACHE_COHERENT 0 #define XPAR_PSU_GDMA_7_IS_CACHE_COHERENT 0 /* Canonical definitions for peripheral PSU_ADMA_0 */ #define XPAR_XZDMA_0_DEVICE_ID XPAR_PSU_ADMA_0_DEVICE_ID #define XPAR_XZDMA_0_BASEADDR 0xFFA80000 #define XPAR_XZDMA_0_DMA_MODE 1 #define XPAR_XZDMA_0_HIGHADDR 0xFFA8FFFF #define XPAR_XZDMA_0_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_1 */ #define XPAR_XZDMA_1_DEVICE_ID XPAR_PSU_ADMA_1_DEVICE_ID #define XPAR_XZDMA_1_BASEADDR 0xFFA90000 #define XPAR_XZDMA_1_DMA_MODE 1 #define XPAR_XZDMA_1_HIGHADDR 0xFFA9FFFF #define XPAR_XZDMA_1_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_2 */ #define XPAR_XZDMA_2_DEVICE_ID XPAR_PSU_ADMA_2_DEVICE_ID #define XPAR_XZDMA_2_BASEADDR 0xFFAA0000 #define XPAR_XZDMA_2_DMA_MODE 1 #define XPAR_XZDMA_2_HIGHADDR 0xFFAAFFFF #define XPAR_XZDMA_2_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_3 */ #define XPAR_XZDMA_3_DEVICE_ID XPAR_PSU_ADMA_3_DEVICE_ID #define XPAR_XZDMA_3_BASEADDR 0xFFAB0000 #define XPAR_XZDMA_3_DMA_MODE 1 #define XPAR_XZDMA_3_HIGHADDR 0xFFABFFFF #define XPAR_XZDMA_3_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_4 */ #define XPAR_XZDMA_4_DEVICE_ID XPAR_PSU_ADMA_4_DEVICE_ID #define XPAR_XZDMA_4_BASEADDR 0xFFAC0000 #define XPAR_XZDMA_4_DMA_MODE 1 #define XPAR_XZDMA_4_HIGHADDR 0xFFACFFFF #define XPAR_XZDMA_4_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_5 */ #define XPAR_XZDMA_5_DEVICE_ID XPAR_PSU_ADMA_5_DEVICE_ID #define XPAR_XZDMA_5_BASEADDR 0xFFAD0000 #define XPAR_XZDMA_5_DMA_MODE 1 #define XPAR_XZDMA_5_HIGHADDR 0xFFADFFFF #define XPAR_XZDMA_5_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_6 */ #define XPAR_XZDMA_6_DEVICE_ID XPAR_PSU_ADMA_6_DEVICE_ID #define XPAR_XZDMA_6_BASEADDR 0xFFAE0000 #define XPAR_XZDMA_6_DMA_MODE 1 #define XPAR_XZDMA_6_HIGHADDR 0xFFAEFFFF #define XPAR_XZDMA_6_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_ADMA_7 */ #define XPAR_XZDMA_7_DEVICE_ID XPAR_PSU_ADMA_7_DEVICE_ID #define XPAR_XZDMA_7_BASEADDR 0xFFAF0000 #define XPAR_XZDMA_7_DMA_MODE 1 #define XPAR_XZDMA_7_HIGHADDR 0xFFAFFFFF #define XPAR_XZDMA_7_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_0 */ #define XPAR_XZDMA_8_DEVICE_ID XPAR_PSU_GDMA_0_DEVICE_ID #define XPAR_XZDMA_8_BASEADDR 0xFD500000 #define XPAR_XZDMA_8_DMA_MODE 0 #define XPAR_XZDMA_8_HIGHADDR 0xFD50FFFF #define XPAR_XZDMA_8_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_1 */ #define XPAR_XZDMA_9_DEVICE_ID XPAR_PSU_GDMA_1_DEVICE_ID #define XPAR_XZDMA_9_BASEADDR 0xFD510000 #define XPAR_XZDMA_9_DMA_MODE 0 #define XPAR_XZDMA_9_HIGHADDR 0xFD51FFFF #define XPAR_XZDMA_9_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_2 */ #define XPAR_XZDMA_10_DEVICE_ID XPAR_PSU_GDMA_2_DEVICE_ID #define XPAR_XZDMA_10_BASEADDR 0xFD520000 #define XPAR_XZDMA_10_DMA_MODE 0 #define XPAR_XZDMA_10_HIGHADDR 0xFD52FFFF #define XPAR_XZDMA_10_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_3 */ #define XPAR_XZDMA_11_DEVICE_ID XPAR_PSU_GDMA_3_DEVICE_ID #define XPAR_XZDMA_11_BASEADDR 0xFD530000 #define XPAR_XZDMA_11_DMA_MODE 0 #define XPAR_XZDMA_11_HIGHADDR 0xFD53FFFF #define XPAR_XZDMA_11_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_4 */ #define XPAR_XZDMA_12_DEVICE_ID XPAR_PSU_GDMA_4_DEVICE_ID #define XPAR_XZDMA_12_BASEADDR 0xFD540000 #define XPAR_XZDMA_12_DMA_MODE 0 #define XPAR_XZDMA_12_HIGHADDR 0xFD54FFFF #define XPAR_XZDMA_12_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_5 */ #define XPAR_XZDMA_13_DEVICE_ID XPAR_PSU_GDMA_5_DEVICE_ID #define XPAR_XZDMA_13_BASEADDR 0xFD550000 #define XPAR_XZDMA_13_DMA_MODE 0 #define XPAR_XZDMA_13_HIGHADDR 0xFD55FFFF #define XPAR_XZDMA_13_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_6 */ #define XPAR_XZDMA_14_DEVICE_ID XPAR_PSU_GDMA_6_DEVICE_ID #define XPAR_XZDMA_14_BASEADDR 0xFD560000 #define XPAR_XZDMA_14_DMA_MODE 0 #define XPAR_XZDMA_14_HIGHADDR 0xFD56FFFF #define XPAR_XZDMA_14_ZDMA_CLK_FREQ_HZ 0 /* Canonical definitions for peripheral PSU_GDMA_7 */ #define XPAR_XZDMA_15_DEVICE_ID XPAR_PSU_GDMA_7_DEVICE_ID #define XPAR_XZDMA_15_BASEADDR 0xFD570000 #define XPAR_XZDMA_15_DMA_MODE 0 #define XPAR_XZDMA_15_HIGHADDR 0xFD57FFFF #define XPAR_XZDMA_15_ZDMA_CLK_FREQ_HZ 0 /******************************************************************/ #endif /* end of protection macro */
29,282
338
#include "RenderPass.hpp" namespace myvk { std::shared_ptr<RenderPass> RenderPass::Create(const std::shared_ptr<Device> &device, const VkRenderPassCreateInfo &create_info) { std::shared_ptr<RenderPass> ret = std::make_shared<RenderPass>(); ret->m_device_ptr = device; if (vkCreateRenderPass(device->GetHandle(), &create_info, nullptr, &ret->m_render_pass) != VK_SUCCESS) return nullptr; return ret; } RenderPass::~RenderPass() { if (m_render_pass) vkDestroyRenderPass(m_device_ptr->GetHandle(), m_render_pass, nullptr); } } // namespace myvk
249
317
/* OTB patches: replace "f2c.h" by "otb_6S.h" */ /*#include "f2c.h"*/ #include "otb_6S.h" #ifdef __cplusplus extern "C" { #endif struct { doublereal ee, thm, sthm, cthm; } ladak_; #ifdef __cplusplus } #endif
111
8,586
<reponame>liuqian1990/nebula /* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #ifndef CODEC_COMMON_H_ #define CODEC_COMMON_H_ #include "common/base/Base.h" namespace nebula { template <typename IntType> typename std::enable_if<std::is_integral<typename std::remove_cv< typename std::remove_reference<IntType>::type>::type>::value, bool>::type intToBool(IntType iVal) { return iVal != 0; } inline bool strToBool(folly::StringPiece str) { return str == "Y" || str == "y" || str == "T" || str == "t" || str == "yes" || str == "Yes" || str == "YES" || str == "true" || str == "True" || str == "TRUE"; } inline std::string toHexStr(folly::StringPiece str) { // clang-format off static const char* hex[] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", }; // clang-format on if (str.empty()) { return std::string(); } std::string buf; buf.reserve(str.size() * 3 - 1); buf.append(hex[static_cast<uint8_t>(str[0])]); for (size_t i = 1; i < str.size(); i++) { buf.append(" "); buf.append(hex[static_cast<uint8_t>(str[i])]); } return buf; } } // namespace nebula #endif // CODEC_COMMON_H_
1,539
436
/** * The MIT License * Copyright (c) 2018 Estonian Information System Authority (RIA), * Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK) * Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.niis.xroad.restapi.util; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import java.util.Optional; /** * Utility for extracting currently logged in user's username from security context */ @Component @Slf4j public class UsernameHelper { public static final String UNKNOWN_USERNAME = null; /** * String that represents value for unknown username * @return */ public String getUnknownUsername() { return UNKNOWN_USERNAME; } /** * Returns optional that holds currently logged in user's username, if it could be determined. * Exceptions are logged, not thrown, and empty optional is returned if they happen. * Other Throwables are thrown. */ public Optional<String> getOptionalUsername() { String username = null; try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Object principal = authentication.getPrincipal(); if (principal instanceof String) { username = (String) principal; } } } catch (Exception e) { log.error("exception while determining username", e); } if (username == null) { return Optional.empty(); } else { return Optional.of(username); } } /** * Returns String with currently logged in user's username, or UNKNOWN_USERNAME if username could not be determined. * Any Exceptions are caught and UNKNOWN_USERNAME is returned. * Throwables are thrown. */ public String getUsername() { return getOptionalUsername().orElse(UNKNOWN_USERNAME); } }
1,043
3,372
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisanalyticsv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Specifies dependency JARs, as well as JAR files that contain user-defined functions (UDF). * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/CustomArtifactConfiguration" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CustomArtifactConfiguration implements Serializable, Cloneable, StructuredPojo { /** * <p> * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * </p> */ private String artifactType; private S3ContentLocation s3ContentLocation; /** * <p> * The parameters required to fully specify a Maven reference. * </p> */ private MavenReference mavenReference; /** * <p> * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * </p> * * @param artifactType * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * @see ArtifactType */ public void setArtifactType(String artifactType) { this.artifactType = artifactType; } /** * <p> * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * </p> * * @return <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * @see ArtifactType */ public String getArtifactType() { return this.artifactType; } /** * <p> * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * </p> * * @param artifactType * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * @return Returns a reference to this object so that method calls can be chained together. * @see ArtifactType */ public CustomArtifactConfiguration withArtifactType(String artifactType) { setArtifactType(artifactType); return this; } /** * <p> * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * </p> * * @param artifactType * <code>UDF</code> stands for user-defined functions. This type of artifact must be in an S3 bucket. A * <code>DEPENDENCY_JAR</code> can be in either Maven or an S3 bucket. * @return Returns a reference to this object so that method calls can be chained together. * @see ArtifactType */ public CustomArtifactConfiguration withArtifactType(ArtifactType artifactType) { this.artifactType = artifactType.toString(); return this; } /** * @param s3ContentLocation */ public void setS3ContentLocation(S3ContentLocation s3ContentLocation) { this.s3ContentLocation = s3ContentLocation; } /** * @return */ public S3ContentLocation getS3ContentLocation() { return this.s3ContentLocation; } /** * @param s3ContentLocation * @return Returns a reference to this object so that method calls can be chained together. */ public CustomArtifactConfiguration withS3ContentLocation(S3ContentLocation s3ContentLocation) { setS3ContentLocation(s3ContentLocation); return this; } /** * <p> * The parameters required to fully specify a Maven reference. * </p> * * @param mavenReference * The parameters required to fully specify a Maven reference. */ public void setMavenReference(MavenReference mavenReference) { this.mavenReference = mavenReference; } /** * <p> * The parameters required to fully specify a Maven reference. * </p> * * @return The parameters required to fully specify a Maven reference. */ public MavenReference getMavenReference() { return this.mavenReference; } /** * <p> * The parameters required to fully specify a Maven reference. * </p> * * @param mavenReference * The parameters required to fully specify a Maven reference. * @return Returns a reference to this object so that method calls can be chained together. */ public CustomArtifactConfiguration withMavenReference(MavenReference mavenReference) { setMavenReference(mavenReference); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getArtifactType() != null) sb.append("ArtifactType: ").append(getArtifactType()).append(","); if (getS3ContentLocation() != null) sb.append("S3ContentLocation: ").append(getS3ContentLocation()).append(","); if (getMavenReference() != null) sb.append("MavenReference: ").append(getMavenReference()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CustomArtifactConfiguration == false) return false; CustomArtifactConfiguration other = (CustomArtifactConfiguration) obj; if (other.getArtifactType() == null ^ this.getArtifactType() == null) return false; if (other.getArtifactType() != null && other.getArtifactType().equals(this.getArtifactType()) == false) return false; if (other.getS3ContentLocation() == null ^ this.getS3ContentLocation() == null) return false; if (other.getS3ContentLocation() != null && other.getS3ContentLocation().equals(this.getS3ContentLocation()) == false) return false; if (other.getMavenReference() == null ^ this.getMavenReference() == null) return false; if (other.getMavenReference() != null && other.getMavenReference().equals(this.getMavenReference()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getArtifactType() == null) ? 0 : getArtifactType().hashCode()); hashCode = prime * hashCode + ((getS3ContentLocation() == null) ? 0 : getS3ContentLocation().hashCode()); hashCode = prime * hashCode + ((getMavenReference() == null) ? 0 : getMavenReference().hashCode()); return hashCode; } @Override public CustomArtifactConfiguration clone() { try { return (CustomArtifactConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisanalyticsv2.model.transform.CustomArtifactConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
3,366
28,056
package com.alibaba.json.bvt; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import com.alibaba.json.test.entity.case2.Category; public class CircularReferenceTest extends TestCase { public void test_0() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(out); Category p = new Category(); p.setId(1); p.setName("root"); { Category child = new Category(); child.setId(2); child.setName("child"); p.getChildren().add(child); child.setParent(p); } objectOut.writeObject(p); } }
343
348
{"nom":"Saint-Judoce","circ":"2ème circonscription","dpt":"Côtes-d'Armor","inscrits":439,"abs":170,"votants":269,"blancs":8,"nuls":2,"exp":259,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":82},{"nuance":"DVD","nom":"<NAME>","voix":57},{"nuance":"FI","nom":"M. <NAME>","voix":32},{"nuance":"FN","nom":"Mme <NAME>","voix":30},{"nuance":"LR","nom":"<NAME>","voix":22},{"nuance":"SOC","nom":"Mme <NAME>","voix":20},{"nuance":"DVD","nom":"<NAME>","voix":7},{"nuance":"ECO","nom":"Mme <NAME>","voix":5},{"nuance":"ECO","nom":"M. <NAME>","voix":2},{"nuance":"DIV","nom":"M. <NAME>","voix":2},{"nuance":"DVG","nom":"<NAME>","voix":0},{"nuance":"REG","nom":"M. <NAME>","voix":0},{"nuance":"EXG","nom":"Mme <NAME>","voix":0},{"nuance":"REG","nom":"<NAME>","voix":0}]}
310
348
{"nom":"Lavardin","circ":"1ère circonscription","dpt":"Sarthe","inscrits":575,"abs":315,"votants":260,"blancs":19,"nuls":6,"exp":235,"res":[{"nuance":"LR","nom":"<NAME>","voix":125},{"nuance":"REM","nom":"<NAME>","voix":110}]}
89
307
package com.tairanchina.csp.avm.service; import com.tairanchina.csp.avm.dto.ServiceResult; /** * Created by hzlizx on 2018/6/22 0022 */ public interface RnService { /** * 获取Rn路由列表 * @param version 版本号 * @param appId 应用 * @param platform 平台(ios\android) * @param routeStatus 路由状态 0:关闭 1:线上开启 2:测试需要 * @return 路由列表 */ ServiceResult route(String version,String appId,String platform, int routeStatus); /** * 获取Rn包信息 * @param version 版本号 * @param appId 应用 * @param platform 平台(ios\android) * @param rnStatus 路由状态 0:关闭 1:线上开启 2:测试需要 * @return 包列表 */ ServiceResult bundles(String version,String appId,String platform, int rnStatus); }
464
1,442
#ifndef ION_DEVICE_BENCH_CONFIG_CONSOLE_H #define ION_DEVICE_BENCH_CONFIG_CONSOLE_H #include <regs/regs.h> namespace Ion { namespace Device { namespace Console { namespace Config { using namespace Regs; constexpr static USART Port = USART(6); constexpr static GPIOPin RxPin = GPIOPin(GPIOC, 7); constexpr static GPIOPin TxPin = GPIOPin(GPIOC, 6); constexpr static GPIO::AFR::AlternateFunction AlternateFunction = GPIO::AFR::AlternateFunction::AF8; /* The baud rate of the UART is set by the following equation: * BaudRate = f/USARTDIV, where f is the clock frequency and USARTDIV a divider. * In other words, USARTDIV = f/BaudRate. All frequencies in Hz. * * In our case, we configure the minicom to use a 115200 BaudRate and * f = fAPB2 = 96 MHz, so USARTDIV = 833.333 */ constexpr static int USARTDIVValue = 833; } } } } #endif
307
416
#ifndef _LIB_STRINGS_H #define _LIB_STRINGS_H #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif /* _LIB_STRINGS_H */
69
934
package knife; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import javax.swing.JMenuItem; import burp.BurpExtender; import burp.HelperPlus; import burp.IBurpExtenderCallbacks; import burp.IContextMenuInvocation; import burp.IExtensionHelpers; import burp.IHttpRequestResponse; import config.DismissedTargets; public class DismissCancelMenu extends JMenuItem {//JMenuItem vs. JMenu public DismissCancelMenu(BurpExtender burp){ this.setText("^_^ Dismissed Cancle"); this.addActionListener(new Dismiss_Cancel_Action(burp,burp.invocation)); } } class Dismiss_Cancel_Action implements ActionListener{ //scope matching is actually String matching!! private IContextMenuInvocation invocation; public BurpExtender myburp; public IExtensionHelpers helpers; public PrintWriter stdout; public PrintWriter stderr; public IBurpExtenderCallbacks callbacks; //callbacks.printOutput(Integer.toString(invocation.getToolFlag()));//issue tab of target map is 16 public Dismiss_Cancel_Action(BurpExtender burp,IContextMenuInvocation invocation) { this.invocation = invocation; this.myburp = burp; this.helpers = burp.helpers; this.callbacks = BurpExtender.callbacks; this.stderr = burp.stderr; } @Override public void actionPerformed(ActionEvent e) { try{ IHttpRequestResponse[] messages = invocation.getSelectedMessages(); for(IHttpRequestResponse message:messages) { String url = new HelperPlus(helpers).getFullURL(message).toString(); String host = message.getHttpService().getHost(); if (url.contains("?")){ url = url.substring(0,url.indexOf("?")); } DismissedTargets.targets.remove(url); DismissedTargets.targets.remove(host); DismissedTargets.ShowToGUI(); } }catch (Exception e1) { e1.printStackTrace(stderr); } } }
677
316
{ "tags": { "allowUnknownTags": true }, "plugins": [ "plugins/markdown", "/Users/christrevino/Workspace/oss/chart-parts/packages/docs/docsite/node_modules/tsdoc/template/plugins/TSDoc.js" ], "opts": { "template": "/Users/christrevino/Workspace/oss/chart-parts/packages/docs/docsite/node_modules/tsdoc/template", "recurse": "true" }, "templates": { "cleverLinks": false, "monospaceLinks": false }, "source": { "includePattern": "(\\.d)?\\.ts$" }, "markdown": { "parser": "gfm", "hardwrap": true }, "tsdoc": { "source": "/Users/christrevino/Workspace/oss/chart-parts/packages/docs/docsite/src/", "destination": "/Users/christrevino/Workspace/oss/chart-parts/packages/docs/docsite/docs", "tutorials": "", "systemName": "docsite", "footer": "", "copyright": "docsite Copyright © 2019 christrevino.", "outputSourceFiles": true, "commentsOnly": true } }
380
409
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright <NAME> (<EMAIL>) 2006-2016 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CDSLIB_GC_IMPL_DHP_IMPL_H #define CDSLIB_GC_IMPL_DHP_IMPL_H #include <cds/threading/model.h> //@cond namespace cds { namespace gc { namespace dhp { inline Guard::Guard() { cds::threading::getGC<DHP>().allocGuard( *this ); } inline Guard::~Guard() { cds::threading::getGC<DHP>().freeGuard( *this ); } template <size_t Count> inline GuardArray<Count>::GuardArray() { cds::threading::getGC<DHP>().allocGuard( *this ); } template <size_t Count> inline GuardArray<Count>::~GuardArray() { cds::threading::getGC<DHP>().freeGuard( *this ); } } // namespace dhp inline DHP::thread_gc::thread_gc( bool bPersistent ) : m_bPersistent( bPersistent ) { if ( !cds::threading::Manager::isThreadAttached() ) cds::threading::Manager::attachThread(); } inline DHP::thread_gc::~thread_gc() { if ( !m_bPersistent ) cds::threading::Manager::detachThread(); } inline /*static*/ void DHP::thread_gc::alloc_guard( cds::gc::dhp::details::guard& g ) { return cds::threading::getGC<DHP>().allocGuard(g); } inline /*static*/ void DHP::thread_gc::free_guard( cds::gc::dhp::details::guard& g ) { cds::threading::getGC<DHP>().freeGuard(g); } inline void DHP::scan() { cds::threading::getGC<DHP>().scan(); } }} // namespace cds::gc //@endcond #endif // #ifndef CDSLIB_GC_IMPL_DHP_IMPL_H
1,272
359
<filename>learntools/time_series/ex1.py from learntools.core import * from learntools.time_series.checking_utils import load_average_sales average_sales = load_average_sales()['sales'] # Interpret linear regression with the time dummy class Q1(ThoughtExperiment): _hint = """Do you remember the slope-intercept equation of a line? The slope is 3.33, so `Hardcover` will change on average by 3.33 units for every 1 step change in `Time`, according to this model. """ _solution = """A change of 6 steps in `Time` corresponds to an average change of 6 * 3.33 = 19.98 in `Hardcover` sales. """ # Interpret linear regression with a lag feature class Q2(ThoughtExperiment): _hint = """The series with the 0.95 weight will tend to have values with signs that stay the same. The series with the -0.95 weight will tend to have values with signs that change back and forth. """ _solution = """**Series 1** was generated by `target = 0.95 * lag_1 + error` and **Series 2** was generated by `target = -0.95 * lag_1 + error`. """ class Q3(EqualityCheckProblem): import numpy as np df = average_sales.to_frame() time = np.arange(len(df.index)) df['time'] = time X = df.loc[:, ['time']] y = df.loc[:, 'sales'] _vars = ['time', 'X', 'y'] _expected = [time, X, y] _hint = """Your solution should look like: ```python from sklearn.linear_model import LinearRegression df = average_sales.to_frame() time = np.arange(____) df['time'] = time X = df.loc[:, [____]] y = df.loc[:, ____] model = LinearRegression() model.fit(X, y) y_pred = pd.Series(model.predict(X), index=X.index) ``` """ _solution = CS(""" from sklearn.linear_model import LinearRegression df = average_sales.to_frame() time = np.arange(len(df.index)) # time dummy df['time'] = time X = df.loc[:, ['time']] # features y = df.loc[:, 'sales'] # target model = LinearRegression() model.fit(X, y) y_pred = pd.Series(model.predict(X), index=X.index) """) class Q4(EqualityCheckProblem): import pandas as pd from sklearn.linear_model import LinearRegression df = average_sales.to_frame() lag_1 = df['sales'].shift(1) df['lag_1'] = lag_1 X = df.loc[:, ['lag_1']] X.dropna(inplace=True) # drop missing values in the feature set y = df.loc[:, 'sales'] # create the target y, X = y.align(X, join='inner') # drop corresponding values in target model = LinearRegression() model.fit(X, y) y_pred = pd.Series(model.predict(X), index=X.index) _vars = ['lag_1', 'y_pred'] _expected = [lag_1, y_pred] _hint = """Your solution should look like: ```python df = average_sales.to_frame() lag_1 = df['sales'].____(____) df['lag_1'] = lag_1 X = df.loc[:, ['lag_1']] X.dropna(inplace=True) # drop missing values in the feature set y = df.loc[:, 'sales'] # create the target y, X = y.align(X, join='inner') # drop corresponding values in target model = LinearRegression() model.fit(____, ____) y_pred = pd.Series(model.____(____), index=X.index) ``` """ _solution = CS(""" df = average_sales.to_frame() lag_1 = df['sales'].shift(1) df['lag_1'] = lag_1 X = df.loc[:, ['lag_1']] X.dropna(inplace=True) # drop missing values in the feature set y = df.loc[:, 'sales'] # create the target y, X = y.align(X, join='inner') # drop corresponding values in target model = LinearRegression() model.fit(X, y) y_pred = pd.Series(model.predict(X), index=X.index) """) qvars = bind_exercises(globals(), [Q1, Q2, Q3, Q4], var_format="q_{n}") __all__ = list(qvars)
1,346
377
/******************************************************************************* * * Copyright 2016 Impetus Infotech. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. ******************************************************************************/ package com.impetus.client.kudu; import java.util.List; import org.apache.kudu.ColumnSchema; import org.apache.kudu.Schema; import org.apache.kudu.Type; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.PartialRow; import org.apache.kudu.client.RowResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.impetus.kundera.KunderaException; import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata; /** * The Class KuduDBDataHandler. * * @author karthikp.manchala */ public class KuduDBDataHandler { /** The logger. */ private static Logger logger = LoggerFactory.getLogger(KuduDBDataHandler.class); /** The kundera metadata. */ private KunderaMetadata kunderaMetadata; /** * Instantiates a new kudu db data handler. * * @param kunderaMetadata * the kundera metadata */ public KuduDBDataHandler(KunderaMetadata kunderaMetadata) { this.kunderaMetadata = kunderaMetadata; } /** * Adds the to row. * * @param row * the row * @param jpaColumnName * the jpa column name * @param value * the value * @param type * the type */ public static void addToRow(PartialRow row, String jpaColumnName, Object value, Type type) { if (value == null) { row.setNull(jpaColumnName); } else { switch (type) { case BINARY: row.addBinary(jpaColumnName, (byte[]) value); break; case BOOL: row.addBoolean(jpaColumnName, (Boolean) value); break; case DOUBLE: row.addDouble(jpaColumnName, (Double) value); break; case FLOAT: row.addFloat(jpaColumnName, (Float) value); break; case INT16: row.addShort(jpaColumnName, (Short) value); break; case INT32: row.addInt(jpaColumnName, (Integer) value); break; case INT64: row.addLong(jpaColumnName, (Long) value); break; case INT8: row.addByte(jpaColumnName, (Byte) value); break; case STRING: row.addString(jpaColumnName, (String) value); break; case UNIXTIME_MICROS: default: logger.error(type + " type is not supported by Kudu"); throw new KunderaException(type + " type is not supported by Kudu"); } } } /** * Gets the predicate. * * @param column * the column * @param operator * the operator * @param type * the type * @param key * the key * @return the predicate */ public static KuduPredicate getPredicate(ColumnSchema column, KuduPredicate.ComparisonOp operator, Type type, Object key) { switch (type) { case BINARY: return KuduPredicate.newComparisonPredicate(column, operator, (byte[]) key); case BOOL: return KuduPredicate.newComparisonPredicate(column, operator, (Boolean) key); case DOUBLE: return KuduPredicate.newComparisonPredicate(column, operator, (Double) key); case FLOAT: return KuduPredicate.newComparisonPredicate(column, operator, (Float) key); case INT16: return KuduPredicate.newComparisonPredicate(column, operator, (Short) key); case INT32: return KuduPredicate.newComparisonPredicate(column, operator, (Integer) key); case INT64: return KuduPredicate.newComparisonPredicate(column, operator, (Long) key); case INT8: return KuduPredicate.newComparisonPredicate(column, operator, (Byte) key); case STRING: return KuduPredicate.newComparisonPredicate(column, operator, (String) key); case UNIXTIME_MICROS: default: logger.error(type + " type is not supported by Kudu"); throw new KunderaException(type + " type is not supported by Kudu"); } } /** * Gets the equal comparison predicate. * * @param column * the column * @param type * the type * @param key * the key * @return the equal comparison predicate */ public static KuduPredicate getEqualComparisonPredicate(ColumnSchema column, Type type, Object key) { return getPredicate(column, KuduPredicate.ComparisonOp.EQUAL, type, key); } /** * Gets the column value. * * @param result * the result * @param jpaColumnName * the jpa column name * @return the column value */ public static Object getColumnValue(RowResult result, String jpaColumnName) { if (result.isNull(jpaColumnName)) { return null; } switch (result.getColumnType(jpaColumnName)) { case BINARY: return result.getBinary(jpaColumnName); case BOOL: return result.getBoolean(jpaColumnName); case DOUBLE: return result.getDouble(jpaColumnName); case FLOAT: return result.getFloat(jpaColumnName); case INT16: return result.getShort(jpaColumnName); case INT32: return result.getInt(jpaColumnName); case INT64: return result.getLong(jpaColumnName); case INT8: return result.getByte(jpaColumnName); case STRING: return result.getString(jpaColumnName); case UNIXTIME_MICROS: default: logger.error(jpaColumnName + " type is not supported by Kudu"); throw new KunderaException(jpaColumnName + " type is not supported by Kudu"); } } /** * Parses the. * * @param type * the type * @param value * the value * @return the object */ public static Object parse(Type type, String value) { value = value.replaceAll("^['\\\"]|['\\\"]$", ""); switch (type) { case BINARY: return value.getBytes(); case BOOL: return Boolean.parseBoolean(value); case DOUBLE: return Double.parseDouble(value); case FLOAT: return Float.parseFloat(value); case INT16: return Short.parseShort(value); case INT32: return Integer.parseInt(value); case INT64: return Long.parseLong(value); case INT8: return Byte.parseByte(value); case STRING: return value; case UNIXTIME_MICROS: default: logger.error(type + " type is not supported by Kudu"); throw new KunderaException(type + " type is not supported by Kudu"); } } /** * Checks for column. * * @param schema * the schema * @param columnName * the column name * @return true, if successful */ public static boolean hasColumn(Schema schema, String columnName) { try { schema.getColumn(columnName); return true; } catch (IllegalArgumentException e) { return false; } } public static KuduPredicate getInPredicate(ColumnSchema column, List<Object> values) { return KuduPredicate.newInListPredicate(column, values); } }
4,038
735
// NOTE: This file was generated by the ServiceGenerator. // ---------------------------------------------------------------------------- // API: // Cloud Monitoring API (monitoring/v3) // Description: // Manages your Cloud Monitoring data and configurations. // Documentation: // https://cloud.google.com/monitoring/api/ #import "GTLRMonitoringObjects.h" #import "GTLRMonitoringQuery.h" #import "GTLRMonitoringService.h"
116
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _UNO_CURRENT_CONTEXT_H_ #define _UNO_CURRENT_CONTEXT_H_ #include <rtl/ustring.h> #ifdef __cplusplus extern "C" { #endif /** Gets the current task's context. @attention Don't spread the returned interface around to other threads. Every thread has its own current context. @param ppCurrentContext inout param current context of type com.sun.star.uno.XCurrentContext @param pEnvDcp descriptor of returned interface's environment @param pEnvContext context of returned interface's environment (commonly 0) @return true, if context ref was transferred (even if null ref) */ sal_Bool SAL_CALL uno_getCurrentContext( void ** ppCurrentContext, rtl_uString * pEnvDcp, void * pEnvContext ) SAL_THROW_EXTERN_C(); /** Sets the current task's context. @param pCurrentContext in param current context of type com.sun.star.uno.XCurrentContext @param pEnvDcp descriptor of interface's environment @param pEnvContext context of interface's environment (commonly 0) @return true, if context ref was transferred (even if null ref) */ sal_Bool SAL_CALL uno_setCurrentContext( void * pCurrentContext, rtl_uString * pEnvDcp, void * pEnvContext ) SAL_THROW_EXTERN_C(); #ifdef __cplusplus } #endif #endif
695
872
<reponame>krishna13052001/LeetCode #!/usr/bin/python3 """ A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. Example 1: Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. Note: S will have length in range [1, 500]. S will consist of lowercase letters ('a' to 'z') only. """ from typing import List class Solution: def partitionLabels(self, S: str) -> List[int]: lasts = {} n = len(S) for i in range(n-1, -1, -1): if S[i] not in lasts: lasts[S[i]] = i indexes = [-1] # last partition ending index cur_last = 0 for i in range(n): cur_last = max(cur_last, lasts[S[i]]) if cur_last == i: indexes.append(cur_last) ret = [] for i in range(len(indexes) - 1): ret.append(indexes[i+1] - indexes[i]) return ret if __name__ == "__main__": assert Solution().partitionLabels("ababcbacadefegdehijhklij") == [9, 7, 8]
580
2,414
/* * Copyright 2019 WeBank * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.wedatasphere.linkis.cli.application.interactor.execution.jobexec; import com.webank.wedatasphere.linkis.cli.common.entity.execution.jobexec.JobStatus; import com.webank.wedatasphere.linkis.cli.core.interactor.execution.jobexec.JobManExec; public class LinkisJobKill extends JobManExec { private String taskID; private String execID; private String user; private JobStatus jobStatus; public String getTaskID() { return taskID; } public void setTaskID(String taskID) { this.taskID = taskID; } public String getExecID() { return execID; } public void setExecID(String execID) { this.execID = execID; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public JobStatus getJobStatus() { return jobStatus; } public final void setJobStatus(JobStatus jobStatus) { this.jobStatus = jobStatus; } public final boolean isJobSubmitted() { return !(this.getJobStatus() == JobStatus.UNSUBMITTED || this.getJobStatus() == JobStatus.SUBMITTING); } public final boolean isJobCompleted() { return this.isJobSuccess() || this.isJobFailure() || this.isJobCancelled() || this.isJobTimeout(); } public final boolean isJobSuccess() { return this.getJobStatus() == JobStatus.SUCCEED; } public final boolean isJobFailure() { return this.getJobStatus() == JobStatus.FAILED; } public final boolean isJobCancelled() { return this.getJobStatus() == JobStatus.CANCELLED; } public final boolean isJobTimeout() { return this.getJobStatus() == JobStatus.TIMEOUT; } public final boolean isJobAbnormalStatus() { return this.getJobStatus() == JobStatus.UNKNOWN; } }
860
953
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.graphql.data.method.annotation.support; import java.util.Optional; import graphql.GraphQLContext; import graphql.schema.DataFetchingEnvironment; import org.springframework.core.MethodParameter; import org.springframework.graphql.data.method.HandlerMethodArgumentResolver; import org.springframework.graphql.data.method.annotation.ContextValue; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Resolver for {@link ContextValue @ContextValue} annotated method parameters. * Values are resolved through one of the following: * <ul> * <li>{@link DataFetchingEnvironment#getLocalContext()} -- if it is an * instance of {@link GraphQLContext}. * <li>{@link DataFetchingEnvironment#getGraphQlContext()} * </ul> * * @author <NAME> * @since 1.0.0 */ public class ContextValueMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return (parameter.getParameterAnnotation(ContextValue.class) != null); } @Override public Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) { return resolveContextValue(parameter, environment.getLocalContext(), environment.getGraphQlContext()); } @Nullable static Object resolveContextValue( MethodParameter parameter, @Nullable Object localContext, GraphQLContext graphQlContext) { ContextValue annotation = parameter.getParameterAnnotation(ContextValue.class); Assert.state(annotation != null, "Expected @ContextValue annotation"); String name = getValueName(parameter, annotation); Class<?> parameterType = parameter.getParameterType(); Object value = null; if (localContext instanceof GraphQLContext) { value = ((GraphQLContext) localContext).get(name); } if (value != null) { return wrapAsOptionalIfNecessary(value, parameterType); } value = graphQlContext.get(name); if (value == null && annotation.required() && !parameterType.equals(Optional.class)) { throw new IllegalStateException("Missing required context value for " + parameter); } return wrapAsOptionalIfNecessary(value, parameterType); } private static String getValueName(MethodParameter parameter, ContextValue annotation) { if (StringUtils.hasText(annotation.name())) { return annotation.name(); } String parameterName = parameter.getParameterName(); if (parameterName != null) { return parameterName; } throw new IllegalArgumentException("Name for @ContextValue argument " + "of type [" + parameter.getNestedParameterType().getName() + "] not specified, " + "and parameter name information not found in class file either."); } @Nullable private static Object wrapAsOptionalIfNecessary(@Nullable Object value, Class<?> type) { return (type.equals(Optional.class) ? Optional.ofNullable(value) : value); } }
1,019
12,278
/*============================================================================= Copyright (c) 2001-2014 <NAME> http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_X3_IS_SUBSTITUTE_JAN_9_2012_1049PM) #define BOOST_SPIRIT_X3_IS_SUBSTITUTE_JAN_9_2012_1049PM #include <boost/spirit/home/x3/support/traits/container_traits.hpp> #include <boost/fusion/include/is_sequence.hpp> #include <boost/fusion/include/map.hpp> #include <boost/fusion/include/value_at_key.hpp> #include <boost/fusion/adapted/mpl.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/equal.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/filter_view.hpp> #include <boost/mpl/size.hpp> #include <boost/mpl/logical.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/count_if.hpp> #include <boost/utility/enable_if.hpp> #include <boost/optional/optional.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace spirit { namespace x3 { namespace traits { /////////////////////////////////////////////////////////////////////////// // Find out if T can be a (strong) substitute for Attribute /////////////////////////////////////////////////////////////////////////// template <typename T, typename Attribute, typename Enable = void> struct is_substitute; template <typename Variant, typename Attribute> struct variant_has_substitute; namespace detail { template <typename T, typename Attribute> struct value_type_is_substitute : is_substitute< typename container_value<T>::type , typename container_value<Attribute>::type> {}; template <typename T, typename Attribute, typename Enable = void> struct is_substitute_impl : is_same<T, Attribute> {}; template <typename T, typename Attribute> struct is_substitute_impl<T, Attribute, typename enable_if< mpl::and_< fusion::traits::is_sequence<T>, fusion::traits::is_sequence<Attribute>, mpl::equal<T, Attribute, is_substitute<mpl::_1, mpl::_2>> > >::type> : mpl::true_ {}; template <typename T, typename Attribute> struct is_substitute_impl<T, Attribute, typename enable_if< mpl::and_< is_container<T>, is_container<Attribute>, value_type_is_substitute<T, Attribute> > >::type> : mpl::true_ {}; template <typename T, typename Attribute> struct is_substitute_impl<T, Attribute, typename enable_if< is_variant<Attribute> >::type> : mpl::or_< is_same<T, Attribute> , variant_has_substitute<Attribute, T> > {}; } template <typename T, typename Attribute, typename Enable /*= void*/> struct is_substitute : detail::is_substitute_impl<T, Attribute> {}; // for reference T template <typename T, typename Attribute, typename Enable> struct is_substitute<T&, Attribute, Enable> : is_substitute<T, Attribute, Enable> {}; // for reference Attribute template <typename T, typename Attribute, typename Enable> struct is_substitute<T, Attribute&, Enable> : is_substitute<T, Attribute, Enable> {}; // 2 element mpl tuple is compatible with fusion::map if: // - it's first element type is existing key in map // - it second element type is compatible to type stored at the key in map template <typename T, typename Attribute> struct is_substitute<T, Attribute , typename enable_if< typename mpl::eval_if< mpl::and_<fusion::traits::is_sequence<T> , fusion::traits::is_sequence<Attribute>> , mpl::and_<traits::has_size<T, 2> , fusion::traits::is_associative<Attribute>> , mpl::false_>::type>::type> { // checking that "p_key >> p_value" parser can // store it's result in fusion::map attribute typedef typename mpl::at_c<T, 0>::type p_key; typedef typename mpl::at_c<T, 1>::type p_value; // for simple p_key type we just check that // such key can be found in attr and that value under that key // matches p_value template <typename Key, typename Value, typename Map> struct has_kv_in_map : mpl::eval_if< fusion::result_of::has_key<Map, Key> , mpl::apply< is_substitute< fusion::result_of::value_at_key<mpl::_1, Key> , Value> , Map> , mpl::false_> {}; // if p_key is variant over multiple types (as a result of // "(key1|key2|key3) >> p_value" parser) check that all // keys are found in fusion::map attribute and that values // under these keys match p_value template <typename Variant> struct variant_kv : mpl::equal_to< mpl::size< typename Variant::types> , mpl::size< mpl::filter_view<typename Variant::types , has_kv_in_map<mpl::_1, p_value, Attribute>>> > {}; typedef typename mpl::eval_if< is_variant<p_key> , variant_kv<p_key> , has_kv_in_map<p_key, p_value, Attribute> >::type type; }; template <typename T, typename Attribute> struct is_substitute<optional<T>, optional<Attribute>> : is_substitute<T, Attribute> {}; }}}} #endif
2,673
852
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms harvestingdatacertification = cms.EDFilter("HarvestingDataCertification", Verbosity = cms.untracked.int32(0), Name = cms.untracked.string('HarvestingDataCertification') )
88
1,144
<filename>backend/de.metas.contracts/src/main/java/de/metas/contracts/impl/SubscriptionTermEventListener.java package de.metas.contracts.impl; import java.util.List; import org.adempiere.exceptions.AdempiereException; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.util.TimeUtil; import de.metas.contracts.FlatrateTermPricing; import de.metas.contracts.model.I_C_Flatrate_Conditions; import de.metas.contracts.model.I_C_Flatrate_Term; import de.metas.contracts.model.I_C_SubscriptionProgress; import de.metas.contracts.model.X_C_Flatrate_Conditions; import de.metas.contracts.model.X_C_Flatrate_Term; import de.metas.contracts.spi.FallbackFlatrateTermEventListener; import de.metas.contracts.subscription.ISubscriptionDAO; import de.metas.contracts.subscription.ISubscriptionDAO.SubscriptionProgressQuery; import de.metas.pricing.IPricingResult; import de.metas.product.ProductId; import de.metas.tax.api.TaxCategoryId; import de.metas.uom.UomId; import de.metas.util.Services; import lombok.NonNull; /* * #%L * de.metas.contracts * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public class SubscriptionTermEventListener extends FallbackFlatrateTermEventListener { public static final String TYPE_CONDITIONS_SUBSCRIPTION = X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription; private static final String MSG_TERM_ERROR_DELIVERY_ALREADY_HAS_SHIPMENT_SCHED_0P = "Term_Error_Delivery_Already_Has_Shipment_Sched"; @Override public void beforeFlatrateTermReactivate(@NonNull final I_C_Flatrate_Term term) { // Delete subscription progress entries final ISubscriptionDAO subscriptionBL = Services.get(ISubscriptionDAO.class); final List<I_C_SubscriptionProgress> entries = subscriptionBL.retrieveSubscriptionProgresses(SubscriptionProgressQuery.builder() .term(term).build()); for (final I_C_SubscriptionProgress entry : entries) { if (entry.getM_ShipmentSchedule_ID() > 0) { throw new AdempiereException("@" + MSG_TERM_ERROR_DELIVERY_ALREADY_HAS_SHIPMENT_SCHED_0P + "@"); } InterfaceWrapperHelper.delete(entry); } } @Override public void beforeSaveOfNextTermForPredecessor( @NonNull final I_C_Flatrate_Term next, @NonNull final I_C_Flatrate_Term predecessor) { final I_C_Flatrate_Conditions conditions = next.getC_Flatrate_Conditions(); if (X_C_Flatrate_Conditions.ONFLATRATETERMEXTEND_CalculatePrice.equals(conditions.getOnFlatrateTermExtend())) { final IPricingResult pricingInfo = FlatrateTermPricing.builder() .termRelatedProductId(ProductId.ofRepoIdOrNull(next.getM_Product_ID())) .term(next) .priceDate(TimeUtil.asLocalDate(next.getStartDate())) .qty(next.getPlannedQtyPerUnit()) .build() .computeOrThrowEx(); next.setPriceActual(pricingInfo.getPriceStd()); next.setC_Currency_ID(pricingInfo.getCurrencyRepoId()); next.setC_UOM_ID(UomId.toRepoId(pricingInfo.getPriceUomId())); next.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingInfo.getTaxCategoryId())); next.setIsTaxIncluded(pricingInfo.isTaxIncluded()); } else if (X_C_Flatrate_Conditions.ONFLATRATETERMEXTEND_CopyPrice.equals(conditions.getOnFlatrateTermExtend())) { next.setPriceActual(predecessor.getPriceActual()); next.setC_Currency_ID(predecessor.getC_Currency_ID()); next.setC_UOM_ID(predecessor.getC_UOM_ID()); next.setC_TaxCategory_ID(predecessor.getC_TaxCategory_ID()); next.setIsTaxIncluded(predecessor.isTaxIncluded()); } else { throw new AdempiereException("Unexpected OnFlatrateTermExtend=" + conditions.getOnFlatrateTermExtend()) .appendParametersToMessage() .setParameter("conditions", conditions) .setParameter("predecessor", predecessor) .setParameter("next", next); } } }
1,609
387
<reponame>MonkeyMo/MdCharm<filename>src/MdCharm/util/gui/markdowncheatsheetdialog.cpp #include <QHBoxLayout> #include "markdowncheatsheetdialog.h" #include "configuration.h" #include "markdowntohtml.h" MarkdownCheatSheetDialog::MarkdownCheatSheetDialog(QWidget *parent) : QDialog(parent, Qt::WindowTitleHint|Qt::WindowSystemMenuHint|Qt::WindowMinMaxButtonsHint|Qt::WindowCloseButtonHint) { webView = new MarkdownWebView(this); QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->setMargin(0); setLayout(mainLayout); mainLayout->addWidget(webView); resize(800, 600); Configuration *conf = Configuration::getInstance(); QFile htmlTemplate(":/markdown/markdown.html"); if(!htmlTemplate.open(QIODevice::ReadOnly)) { Utils::showFileError(htmlTemplate.error(), ":/markdown/markdown.html"); return; } QString htmlContent = htmlTemplate.readAll(); htmlTemplate.close(); QFile cheatSheetMdFile(":/markdown/markdown_cheat_sheet.md"); cheatSheetMdFile.open(QFile::ReadOnly); QByteArray content = cheatSheetMdFile.readAll(); std::string textResult; MarkdownToHtml::translateMarkdownToHtml(MarkdownToHtml::PHPMarkdownExtra, content.data(), content.length(), textResult); htmlContent = htmlContent.arg(conf->getMarkdownCSS()) .arg("") .arg("") .arg(QString::fromUtf8(textResult.c_str(), textResult.length())); webView->setHtml(htmlContent); cheatSheetMdFile.close(); } MarkdownCheatSheetDialog::~MarkdownCheatSheetDialog() { } void MarkdownCheatSheetDialog::showAndPopup() { show(); raise(); activateWindow(); setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); }
715
1,449
<reponame>catap/xhyve /*- * Copyright (c) 2011 NetApp, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #pragma once /* Pin-Based VM-Execution Controls */ #define PINBASED_EXTINT_EXITING (1u << 0) #define PINBASED_NMI_EXITING (1u << 3) #define PINBASED_VIRTUAL_NMI (1u << 5) #define PINBASED_PREMPTION_TIMER (1u << 6) #define PINBASED_POSTED_INTERRUPT (1u << 7) /* Primary Processor-Based VM-Execution Controls */ #define PROCBASED_INT_WINDOW_EXITING (1u << 2) #define PROCBASED_TSC_OFFSET (1u << 3) #define PROCBASED_HLT_EXITING (1u << 7) #define PROCBASED_INVLPG_EXITING (1u << 9) #define PROCBASED_MWAIT_EXITING (1u << 10) #define PROCBASED_RDPMC_EXITING (1u << 11) #define PROCBASED_RDTSC_EXITING (1u << 12) #define PROCBASED_CR3_LOAD_EXITING (1u << 15) #define PROCBASED_CR3_STORE_EXITING (1u << 16) #define PROCBASED_CR8_LOAD_EXITING (1u << 19) #define PROCBASED_CR8_STORE_EXITING (1u << 20) #define PROCBASED_USE_TPR_SHADOW (1u << 21) #define PROCBASED_NMI_WINDOW_EXITING (1u << 22) #define PROCBASED_MOV_DR_EXITING (1u << 23) #define PROCBASED_IO_EXITING (1u << 24) #define PROCBASED_IO_BITMAPS (1u << 25) #define PROCBASED_MTF (1u << 27) #define PROCBASED_MSR_BITMAPS (1u << 28) #define PROCBASED_MONITOR_EXITING (1u << 29) #define PROCBASED_PAUSE_EXITING (1u << 30) #define PROCBASED_SECONDARY_CONTROLS (1U << 31) /* Secondary Processor-Based VM-Execution Controls */ #define PROCBASED2_VIRTUALIZE_APIC_ACCESSES (1u << 0) #define PROCBASED2_ENABLE_EPT (1u << 1) #define PROCBASED2_DESC_TABLE_EXITING (1u << 2) #define PROCBASED2_ENABLE_RDTSCP (1u << 3) #define PROCBASED2_VIRTUALIZE_X2APIC_MODE (1u << 4) #define PROCBASED2_ENABLE_VPID (1u << 5) #define PROCBASED2_WBINVD_EXITING (1u << 6) #define PROCBASED2_UNRESTRICTED_GUEST (1u << 7) #define PROCBASED2_APIC_REGISTER_VIRTUALIZATION (1u << 8) #define PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY (1u << 9) #define PROCBASED2_PAUSE_LOOP_EXITING (1u << 10) #define PROCBASED2_RDRAND_EXITING (1u << 11) #define PROCBASED2_ENABLE_INVPCID (1u << 12) #define PROCBASED2_VMCS_SHADOW (1u << 14) #define PROCBASED2_RDSEED_EXITING (1u << 16) #define PROCBASED2_ENABLE_XSAVES_XRSTORS (1u << 20) /* VM Exit Controls */ #define VM_EXIT_SAVE_DEBUG_CONTROLS (1u << 2) #define VM_EXIT_HOST_LMA (1u << 9) #define VM_EXIT_LOAD_PERF_GLOBAL_CTRL (1u << 12) #define VM_EXIT_ACKNOWLEDGE_INTERRUPT (1u << 15) #define VM_EXIT_SAVE_PAT (1u << 18) #define VM_EXIT_LOAD_PAT (1u << 19) #define VM_EXIT_SAVE_EFER (1u << 20) #define VM_EXIT_LOAD_EFER (1u << 21) #define VM_EXIT_SAVE_PREEMPTION_TIMER (1u << 22) /* VM Entry Controls */ #define VM_ENTRY_LOAD_DEBUG_CONTROLS (1u << 2) #define VM_ENTRY_GUEST_LMA (1u << 9) #define VM_ENTRY_INTO_SMM (1u << 10) #define VM_ENTRY_DEACTIVATE_DUAL_MONITOR (1u << 11) #define VM_ENTRY_LOAD_PERF_GLOBAL_CTRL (1u << 13) #define VM_ENTRY_LOAD_PAT (1u << 14) #define VM_ENTRY_LOAD_EFER (1u << 15)
1,855
511
struct cpuinfo_mock_file filesystem[] = { { .path = "/proc/cpuinfo", .size = 1141, .content = "processor\t: 0\n" "model name\t: ARMv7 Processor rev 0 (v7l)\n" "BogoMIPS\t: 38.40\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xd03\n" "CPU revision\t: 0\n" "\n" "processor\t: 1\n" "model name\t: ARMv7 Processor rev 0 (v7l)\n" "BogoMIPS\t: 38.40\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xd03\n" "CPU revision\t: 0\n" "\n" "processor\t: 2\n" "model name\t: ARMv7 Processor rev 0 (v7l)\n" "BogoMIPS\t: 38.40\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xd03\n" "CPU revision\t: 0\n" "\n" "processor\t: 3\n" "model name\t: ARMv7 Processor rev 0 (v7l)\n" "BogoMIPS\t: 38.40\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xd03\n" "CPU revision\t: 0\n" "\n" "Hardware\t: Qualcomm Technologies, Inc MSM8916\n" "Revision\t: 0009\n" "Serial\t\t: 0000000000000000\n" "Processor\t: ARMv7 Processor rev 0 (v7l)\n", }, { .path = "/system/build.prop", .size = 9576, .content = "\n" "# begin build properties\n" "# autogenerated by buildinfo.sh\n" "ro.build.id=LMY47V\n" "ro.build.display.id=LMY47V\n" "ro.build.version.incremental=1611917394609\n" "ro.build.version.sdk=22\n" "ro.build.version.codename=REL\n" "ro.build.version.all_codenames=REL\n" "ro.build.version.release=5.1.1\n" "ro.build.version.security_patch=2016-04-01\n" "ro.build.version.base_os=\n" "ro.build.date=Thu Apr 28 17:42:11 KST 2016\n" "ro.build.date.utc=1461832931\n" "ro.build.type=user\n" "ro.build.user=jenkins\n" "ro.build.host=LGEACI6R2\n" "ro.build.tags=release-keys\n" "ro.build.flavor=m216_global_com-user\n" "ro.product.model=LG-K420\n" "ro.product.brand=lge\n" "ro.product.name=m216_global_com\n" "ro.product.device=m216\n" "ro.product.board=msm8916\n" "# ro.product.cpu.abi and ro.product.cpu.abi2 are obsolete,\n" "# use ro.product.cpu.abilist instead.\n" "ro.product.cpu.abi=armeabi-v7a\n" "ro.product.cpu.abi2=armeabi\n" "ro.product.cpu.abilist=armeabi-v7a,armeabi\n" "ro.product.cpu.abilist32=armeabi-v7a,armeabi\n" "ro.product.cpu.abilist64=\n" "ro.product.manufacturer=LGE\n" "ro.product.locale.language=en\n" "ro.product.locale.region=GB\n" "ro.wifi.channels=11\n" "ro.board.platform=msm8916\n" "# ro.build.product is obsolete; use ro.product.device\n" "ro.build.product=m216\n" "# Do not try to parse description, fingerprint, or thumbprint\n" "ro.build.description=m216_global_com-user 5.1.1 LMY47V 1611917394609 release-keys\n" "ro.build.fingerprint=lge/m216_global_com/m216:5.1.1/LMY47V/1611917394609:user/release-keys\n" "ro.build.characteristics=default\n" "ro.lge.lguiversion=4.2\n" "# end build properties\n" "#\n" "# from device/lge/epsilon0c/qcom/device/msm8916_32/system.prop\n" "#\n" "#\n" "# system.prop for msm8916\n" "#\n" "\n" "#rild.libpath=/system/lib/libreference-ril.so\n" "rild.libpath=/system/vendor/lib/libril-qc-qmi-1.so\n" "rild.libargs=-d /dev/smd0\n" "persist.rild.nitz_plmn=\n" "persist.rild.nitz_long_ons_0=\n" "persist.rild.nitz_long_ons_1=\n" "persist.rild.nitz_long_ons_2=\n" "persist.rild.nitz_long_ons_3=\n" "persist.rild.nitz_short_ons_0=\n" "persist.rild.nitz_short_ons_1=\n" "persist.rild.nitz_short_ons_2=\n" "persist.rild.nitz_short_ons_3=\n" "#persist.radio.rat_on=combine\n" "ril.subscription.types=NV,RUIM\n" "DEVICE_PROVISIONED=1\n" "# Start in cdma mode\n" "#ro.telephony.default_network=5\n" "\n" "debug.sf.hw=1\n" "debug.egl.hw=1\n" "persist.hwc.mdpcomp.enable=true\n" "debug.mdpcomp.logs=0\n" "dalvik.vm.heapsize=36m\n" "dev.pm.dyn_samplingrate=1\n" "persist.demo.hdmirotationlock=false\n" "debug.enable.sglscale=1\n" "\n" "#ro.hdmi.enable=true\n" "#tunnel.decode=true\n" "#tunnel.audiovideo.decode=true\n" "#lpa.decode=false\n" "#lpa.use-stagefright=true\n" "#persist.speaker.prot.enable=false\n" "\n" "#\n" "# system props for the cne module\n" "#\n" "persist.cne.feature=1\n" "\n" "#system props for the MM modules\n" "media.stagefright.enable-player=true\n" "media.stagefright.enable-http=true\n" "media.stagefright.enable-aac=true\n" "media.stagefright.enable-qcp=true\n" "media.stagefright.enable-fma2dp=true\n" "media.stagefright.enable-scan=true\n" "media.msm8939hw=0\n" "media.msm8929hw=0\n" "media.swhevccodectype=0\n" "mm.enable.smoothstreaming=true\n" "mmp.enable.3g2=true\n" "media.aac_51_output_enabled=true\n" "#codecs: DivX DivXHD AVI AC3 ASF AAC QCP DTS 3G2 MP2TS\n" "mm.enable.qcom_parser=3183219\n" "\n" "#Trim properties\n" "ro.sys.fw.use_trim_settings=true\n" "ro.sys.fw.empty_app_percent=50\n" "ro.sys.fw.trim_empty_percent=100\n" "ro.sys.fw.trim_cache_percent=100\n" "ro.sys.fw.trim_enable_memory=1073741824\n" "\n" "# Default to AwesomePlayer\n" "#media.stagefright.use-awesome=true\n" "\n" "#\n" "# system props for the data modules\n" "#\n" "ro.use_data_netmgrd=true\n" "persist.data.netmgrd.qos.enable=true\n" "\n" "#system props for time-services\n" "persist.timed.enable=true\n" "\n" "#\n" "# system prop for opengles version\n" "#\n" "# 196608 is decimal for 0x30000 to report version 3\n" "ro.opengles.version=196608\n" "\n" "# System property for cabl\n" "ro.qualcomm.cabl=0\n" "\n" "#\n" "# System props for telephony\n" "# System prop to turn on CdmaLTEPhone always\n" "#telephony.lteOnCdmaDevice=1\n" "#\n" "# System props for bluetooh\n" "# System prop to turn on hfp client\n" "bluetooth.hfp.client=1\n" "\n" "#Simulate sdcard on /data/media\n" "#\n" "persist.fuse_sdcard=true\n" "\n" "#\n" "#snapdragon value add features\n" "#\n" "ro.qc.sdk.audio.ssr=false\n" "##fluencetype can be \"fluence\" or \"fluencepro\" or \"none\"\n" "ro.qc.sdk.audio.fluencetype=none\n" "persist.audio.fluence.voicecall=true\n" "persist.audio.fluence.voicerec=false\n" "persist.audio.fluence.speaker=true\n" "#Set for msm8916\n" "tunnel.audio.encode = false\n" "#Buffer size in kbytes for compress offload playback\n" "audio.offload.buffer.size.kb=32\n" "#Minimum duration for offload playback in secs\n" "audio.offload.min.duration.secs=30\n" "#Enable offload audio video playback by default\n" "av.offload.enable=false\n" "#enable voice path for PCM VoIP by default\n" "use.voice.path.for.pcm.voip=true\n" "#\n" "#System property for FM transmitter\n" "#\n" "#ro.fm.transmitter=false\n" "#enable dsp gapless mode by default\n" "audio.offload.gapless.enabled=true\n" "\n" "#// LGE_CHANGE_S, [Net_Patch_0300][CALL_FRW][COMMON], 2012-05-25, Airplane Mode Pop-Up display property value {\n" "ro.airplane.phoneapp=1\n" "#// LGE_CHANGE_E, [Net_Patch_0300][CALL_FRW][COMMON], 2012-05-25, Airplane Mode Pop-Up display property value }\n" "\n" "#Audio voice concurrency related flags\n" "voice.playback.conc.disabled=true\n" "voice.record.conc.disabled=true\n" "voice.voip.conc.disabled=true\n" "\n" "#Set composition for USB\n" "#persist.sys.usb.config=diag,serial_smd,rmnet_bam,adb\n" "\n" "#Set read only default composition for USB\n" "#ro.sys.usb.default.config=diag,serial_smd,rmnet_bam,adb\n" "\n" "#property to enable user to access Google WFD settings\n" "persist.debug.wfd.enable=1\n" "#propery to enable VDS WFD solution\n" "persist.hwc.enable_vds=1\n" "\n" "#selects CoreSight configuration to enable\n" "persist.debug.coresight.config=stm-events\n" "\n" "#property to enable DS2 dap\n" "audio.dolby.ds2.enabled=false\n" "\n" "#\n" "# ADDITIONAL_BUILD_PROPERTIES\n" "#\n" "log.tag.GpsLocationProvider=DEBUG\n" "log.tag.LocationManagerService=DEBUG\n" "log.tag.NlpProxy=DEBUG\n" "log.tag.LocSvc_java=DEBUG\n" "log.tag.LgeGpsIndicator=DEBUG\n" "ro.com.lge.mada=gms_3.1\n" "persist.sys.strictmode.disable=true\n" "persist.sys.cust.lte_config=true\n" "ro.lge.lcd_default_brightness=166\n" "ro.lge.sensor_chip=qct_kernel\n" "persist.lg.data.llkklk=true\n" "ro.frp.pst=/dev/block/bootdevice/by-name/persistent\n" "net.tethering.noprovisioning=true\n" "persist.lg.data.llkklk.exact=true\n" "persist.lg.data.fd=-1\n" "persist.qcril.disable_retry=true\n" "persist.data.netmgrd.qos.enable=false\n" "persist.lg.data.vdbg=false\n" "persist.lge.appman.firstboot=1\n" "persist.service.postboot.enable=0\n" "ro.lge.revshare=2015\n" "voice.playback.conc.disabled=false\n" "voice.record.conc.disabled=false\n" "voice.voip.conc.disabled=false\n" "persist.sys.media.use-awesome=false\n" "wifi.lge.fcc=true\n" "sys.knockon.knockoff.distance=10\n" "ro.lge.lcd_auto_brightness_mode=false\n" "ro.lge.audio_soundexception=true\n" "sys.lge.bnrd=0\n" "ro.lge.capp_ZDi_O=true\n" "lge.zdi.actionsend=false\n" "lge.zdi.onactivityresult=true\n" "lge.zdi.dragdropintent=false\n" "persist.service.main.enable=0\n" "persist.service.system.enable=0\n" "persist.service.radio.enable=0\n" "persist.service.events.enable=0\n" "persist.service.kernel.enable=0\n" "persist.service.power.enable=0\n" "persist.service.memory.enable=0\n" "persist.service.packet.enable=0\n" "persist.service.crash.enable=0\n" "persist.service.storage.low=0\n" "persist.service.ccaudit.enable=0\n" "persist.service.packet.max=0\n" "ro.vendor.extension_library=libqti-perfd-client.so\n" "persist.radio.apm_sim_not_pwdn=1\n" "ro.carrier=unknown\n" "dalvik.vm.heapstartsize=8m\n" "dalvik.vm.heapgrowthlimit=96m\n" "dalvik.vm.heapsize=256m\n" "dalvik.vm.heaptargetutilization=0.75\n" "dalvik.vm.heapminfree=2m\n" "dalvik.vm.heapmaxfree=8m\n" "lge.signed_image=true\n" "wlan.chip.vendor=qcom\n" "wlan.chip.version=wcn\n" "wifi.lge.patch=true\n" "wifi.lge.sleeppolicy=0\n" "wifi.lge.offdelay=false\n" "wlan.lge.concurrency=MCC\n" "wlan.lge.supportsimaka=YES\n" "wifi.lge.ftm_test=2\n" "wifi.lge.common_hotspot=true\n" "wlan.lge.dcf.enable=true\n" "wlan.lge.passpoint_setting=true\n" "wlan.lge.softapwps=true\n" "ro.setupwizard.mode=DISABLED\n" "ro.lge.sensors_multihal=false\n" "persist.service.bt.support.sap=true\n" "service.bt.support.busytone=true\n" "persist.service.avrcp.browsing=1\n" "ro.config.ringtone=01_Life_Is_Good.ogg\n" "ro.config.notification_sound=Crystal.ogg\n" "ro.config.alarm_alert=Melody_Alarm.ogg\n" "ro.config.timer_alert=Timer.ogg\n" "persist.audio.nxp=OFF\n" "persist.audio.nsenabled=OFF\n" "persist.audio.spkcall_2mic=OFF\n" "persist.audio.headset_fluence=false\n" "persist.audio.sm_fluence=OFF\n" "persist.audio.spk_sm_fluence=OFF\n" "persist.audio.voip_nsenabled=OFF\n" "ro.config.vc_call_vol_steps=6\n" "ro.config.vc_call_vol_default=3\n" "persist.audio.voice.clarity=none\n" "persist.audio.handset_rx_type=DEFAULT\n" "persist.audio.fluence.voicecall=none\n" "persist.audio.fluence.voicerec=none\n" "persist.audio.fluence.speaker=none\n" "lge.fm_gain_control_headset=0.53\n" "lge.fm_gain_control_speaker=0.70\n" "ro.lge.vib_magnitude_index=0,20,40,60,80,100,120,127\n" "lge.normalizer.param=version2.0/true/10.0/true/19000/0.5/2500/0.62\n" "ro.sdcrypto.syscall=398\n" "ro.com.google.gmsversion=5.1_r3\n" "ro.com.google.apphider=on\n" "ro.lge.capp_cupss.rootdir=/cust\n" "persist.data.sbp.update=0\n" "drm.service.enabled=true\n" "use.voice.path.for.pcm.voip=false\n" "ro.build.target_operator=GLOBAL\n" "ro.build.target_country=COM\n" "ro.lge.swversion=K42010n\n" "ro.lge.swversion_short=V10n\n" "ro.lge.swversion_rev=0\n" "ro.lge.factoryversion=LGK420AT-00-V10n-GLOBAL-COM-APR-28-2016+0\n" "ro.telephony.default_network=9\n" "ro.lge.custLanguageSet=true\n" "ro.build.sbp=1\n" "ro.device.hapticfeedback=0\n" "ro.lge.singleca.enable=1\n" "persist.gsm.sms.disablelog=64\n" "ro.sys.fw.bg_apps_limit=24\n" "ro.sys.fw.bg_cached_ratio=0.5\n" "ro.sys.fw.mOomAdj1=0\n" "ro.sys.fw.mOomAdj2=1\n" "ro.sys.fw.mOomAdj3=2\n" "ro.sys.fw.mOomAdj4=3\n" "ro.sys.fw.mOomAdj5=9\n" "ro.sys.fw.mOomAdj6=15\n" "ro.sys.fw.mOomMinFree1=73728\n" "ro.sys.fw.mOomMinFree2=92160\n" "ro.sys.fw.mOomMinFree3=110592\n" "ro.sys.fw.mOomMinFree4=129024\n" "ro.sys.fw.mOomMinFree5=221184\n" "ro.sys.fw.mOomMinFree6=322560\n" "ro.lge.sar.value=1\n" "ro.lge.deny.minfree.change=1\n" "persist.sys.dalvik.vm.lib.2=libart.so\n" "dalvik.vm.isa.arm.features=div,needfix_835769\n" "net.bt.name=Android\n" "dalvik.vm.stack-trace-file=/data/anr/traces.txt\n" "persist.gps.qc_nlp_in_use=0\n" "ro.gps.agps_provider=1\n" "ro.pip.gated=0\n" "\n", }, { .path = "/sys/devices/system/cpu/kernel_max", .size = 2, .content = "3\n", }, { .path = "/sys/devices/system/cpu/possible", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/present", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/online", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/offline", .size = 1, .content = "\n", }, { .path = "/sys/devices/system/cpu/cpuidle/current_driver", .size = 9, .content = "msm_idle\n", }, { .path = "/sys/devices/system/cpu/cpuidle/current_governor_ro", .size = 5, .content = "menu\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1209600\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq", .size = 7, .content = "200000\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_transition_latency", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", .size = 60, .content = "200000 400000 533333 800000 998400 1094400 1152000 1209600 \n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", .size = 54, .content = "interactive ondemand userspace powersave performance \n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", .size = 8, .content = "1209600\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver", .size = 4, .content = "msm\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state", .size = 84, .content = "200000 0\n" "400000 0\n" "533333 0\n" "800000 141\n" "998400 290\n" "1094400 74\n" "1152000 82\n" "1209600 4075\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/stats/total_trans", .size = 3, .content = "96\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/physical_package_id", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/core_siblings", .size = 2, .content = "f\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/core_id", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/thread_siblings", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1209600\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_min_freq", .size = 7, .content = "200000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_transition_latency", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_available_frequencies", .size = 60, .content = "200000 400000 533333 800000 998400 1094400 1152000 1209600 \n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_available_governors", .size = 54, .content = "interactive ondemand userspace powersave performance \n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq", .size = 7, .content = "800000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_driver", .size = 4, .content = "msm\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/stats/time_in_state", .size = 84, .content = "200000 0\n" "400000 0\n" "533333 0\n" "800000 347\n" "998400 295\n" "1094400 74\n" "1152000 95\n" "1209600 4085\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/stats/total_trans", .size = 4, .content = "100\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/physical_package_id", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/core_siblings", .size = 2, .content = "f\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/core_id", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/thread_siblings_list", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/thread_siblings", .size = 2, .content = "2\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1209600\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_min_freq", .size = 7, .content = "200000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_transition_latency", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_available_frequencies", .size = 60, .content = "200000 400000 533333 800000 998400 1094400 1152000 1209600 \n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_available_governors", .size = 54, .content = "interactive ondemand userspace powersave performance \n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq", .size = 7, .content = "800000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_driver", .size = 4, .content = "msm\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/stats/time_in_state", .size = 84, .content = "200000 0\n" "400000 0\n" "533333 0\n" "800000 568\n" "998400 306\n" "1094400 74\n" "1152000 95\n" "1209600 4085\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/stats/total_trans", .size = 4, .content = "102\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/physical_package_id", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/core_siblings", .size = 2, .content = "f\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/core_id", .size = 2, .content = "2\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/thread_siblings_list", .size = 2, .content = "2\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/thread_siblings", .size = 2, .content = "4\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1209600\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_min_freq", .size = 7, .content = "200000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_transition_latency", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_available_frequencies", .size = 60, .content = "200000 400000 533333 800000 998400 1094400 1152000 1209600 \n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_available_governors", .size = 54, .content = "interactive ondemand userspace powersave performance \n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_cur_freq", .size = 7, .content = "800000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_driver", .size = 4, .content = "msm\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/stats/time_in_state", .size = 84, .content = "200000 0\n" "400000 0\n" "533333 0\n" "800000 805\n" "998400 306\n" "1094400 74\n" "1152000 95\n" "1209600 4085\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/stats/total_trans", .size = 4, .content = "102\n", }, { .path = "/sys/devices/system/cpu/cpu3/topology/physical_package_id", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu3/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu3/topology/core_siblings", .size = 2, .content = "f\n", }, { .path = "/sys/devices/system/cpu/cpu3/topology/core_id", .size = 2, .content = "3\n", }, { .path = "/sys/devices/system/cpu/cpu3/topology/thread_siblings_list", .size = 2, .content = "3\n", }, { .path = "/sys/devices/system/cpu/cpu3/topology/thread_siblings", .size = 2, .content = "8\n", }, { NULL }, }; #ifdef __ANDROID__ struct cpuinfo_mock_property properties[] = { { .key = "DEVICE_PROVISIONED", .value = "1", }, { .key = "audio.dolby.ds2.enabled", .value = "false", }, { .key = "audio.offload.buffer.size.kb", .value = "32", }, { .key = "audio.offload.gapless.enabled", .value = "true", }, { .key = "audio.offload.min.duration.secs", .value = "30", }, { .key = "av.offload.enable", .value = "false", }, { .key = "bluetooth.chip.vendor", .value = "qcom", }, { .key = "bluetooth.hfp.client", .value = "1", }, { .key = "bluetooth.pan", .value = "true", }, { .key = "camera2.portability.force_api", .value = "1", }, { .key = "<KEY>", .value = "64m", }, { .key = "<KEY>", .value = "512m", }, { .key = "dalvik.vm.heapgrowthlimit", .value = "96m", }, { .key = "dalvik.vm.heapmaxfree", .value = "8m", }, { .key = "dalvik.vm.heapminfree", .value = "2m", }, { .key = "dalvik.vm.heapsize", .value = "256m", }, { .key = "dalvik.vm.heapstartsize", .value = "8m", }, { .key = "dalvik.vm.heaptargetutilization", .value = "0.75", }, { .key = "dalvik.vm.image-dex2oat-Xms", .value = "64m", }, { .key = "dalvik.vm.image-dex2oat-Xmx", .value = "64m", }, { .key = "dalvik.vm.isa.arm.features", .value = "div,needfix_835769", }, { .key = "dalvik.vm.stack-trace-file", .value = "/data/anr/traces.txt", }, { .key = "debug.egl.hw", .value = "1", }, { .key = "debug.enable.sglscale", .value = "1", }, { .key = "debug.force_rtl", .value = "0", }, { .key = "debug.mdpcomp.logs", .value = "0", }, { .key = "debug.sf.hw", .value = "1", }, { .key = "dev.bootcomplete", .value = "1", }, { .key = "dev.pm.dyn_samplingrate", .value = "1", }, { .key = "drm.service.enabled", .value = "true", }, { .key = "gsm.current.phone-type", .value = "1", }, { .key = "gsm.network.type", .value = "Unknown", }, { .key = "gsm.operator.alpha", .value = "", }, { .key = "gsm.operator.iso-country", .value = "", }, { .key = "gsm.operator.isroaming", .value = "false", }, { .key = "gsm.operator.numeric", .value = "", }, { .key = "gsm.sim.operator.alpha", .value = "", }, { .key = "gsm.sim.operator.iso-country", .value = "", }, { .key = "gsm.sim.operator.numeric", .value = "", }, { .key = "gsm.sim.state", .value = "ABSENT", }, { .key = "gsm.version.baseband", .value = "MPSS.DPM.2.0.c11-00049-M8936FAAAANUZM-1.38285.1.39832.1", }, { .key = "gsm.version.ril-impl", .value = "Qualcomm RIL 1.0", }, { .key = "hw.camcorder.fpsrange", .value = "30000,30000", }, { .key = "ime_handwriting_apply", .value = "false", }, { .key = "init.svc.adbd", .value = "running", }, { .key = "init.svc.atd", .value = "running", }, { .key = "init.svc.atfwd", .value = "running", }, { .key = "init.svc.audiod", .value = "running", }, { .key = "init.svc.bms-sh", .value = "stopped", }, { .key = "init.svc.bnrd", .value = "running", }, { .key = "init.svc.bootanim", .value = "stopped", }, { .key = "init.svc.chcon_keystore", .value = "stopped", }, { .key = "init.svc.cnd", .value = "running", }, { .key = "init.svc.cnss-daemon", .value = "running", }, { .key = "init.svc.config-zram", .value = "stopped", }, { .key = "init.svc.config_bluetooth", .value = "stopped", }, { .key = "init.svc.debuggerd", .value = "running", }, { .key = "init.<KEY>", .value = "stopped", }, { .key = "init.svc.drm", .value = "running", }, { .key = "init.<KEY>", .value = "stopped", }, { .key = "init.svc.enable_uninstall", .value = "stopped", }, { .key = "init.svc.flash_recovery", .value = "stopped", }, { .key = "init.svc.healthd", .value = "running", }, { .key = "init.svc.hidden-post", .value = "stopped", }, { .key = "init.svc.installd", .value = "running", }, { .key = "init.svc.ipsecstarter", .value = "running", }, { .key = "init.svc.irsc_util", .value = "stopped", }, { .key = "init.svc.keystore", .value = "running", }, { .key = "init.svc.lgdrm", .value = "running", }, { .key = "init.svc.lge-usb-sh", .value = "stopped", }, { .key = "init.svc.lghashstorage", .value = "running", }, { .key = "init.svc.lgsecclk", .value = "running", }, { .key = "init.svc.lmkd", .value = "running", }, { .key = "init.svc.loc_launcher", .value = "running", }, { .key = "init.svc.log-kernel", .value = "stopped", }, { .key = "init.svc.log-packet", .value = "stopped", }, { .key = "init.svc.log-power", .value = "stopped", }, { .key = "init.svc.logcat-events", .value = "stopped", }, { .key = "init.svc.logcat-main", .value = "stopped", }, { .key = "init.svc.logcat-memory", .value = "stopped", }, { .key = "init.svc.logcat-radio", .value = "stopped", }, { .key = "init.svc.logcat-system", .value = "stopped", }, { .key = "init.svc.media", .value = "running", }, { .key = "init.svc.modem_debug_info", .value = "stopped", }, { .key = "init.svc.netd", .value = "running", }, { .key = "init.svc.netmgrd", .value = "running", }, { .key = "init.svc.ntcode_listing", .value = "stopped", }, { .key = "init.svc.p2p_supplicant", .value = "running", }, { .key = "init.svc.perfd", .value = "running", }, { .key = "init.svc.ptt_socket_app", .value = "stopped", }, { .key = "init.svc.qcamerasvr", .value = "running", }, { .key = "init.svc.qcom-c_core-sh", .value = "stopped", }, { .key = "init.svc.qcom-c_main-sh", .value = "stopped", }, { .key = "init.svc.qcom-debug", .value = "stopped", }, { .key = "init.svc.qcom-post-boot", .value = "stopped", }, { .key = "init.svc.qcom-sh", .value = "stopped", }, { .key = "init.svc.qcomsysd", .value = "running", }, { .key = "init.svc.qmuxd", .value = "running", }, { .key = "init.svc.qseecomd", .value = "running", }, { .key = "init.svc.ramoops_backup", .value = "stopped", }, { .key = "init.svc.rctd", .value = "running", }, { .key = "init.svc.rfs_access", .value = "running", }, { .key = "init.svc.ril-daemon", .value = "running", }, { .key = "init.svc.rmplb", .value = "stopped", }, { .key = "init.svc.rmt_storage", .value = "running", }, { .key = "init.svc.run_cache_res", .value = "stopped", }, { .key = "init.svc.runtime_boot_res", .value = "stopped", }, { .key = "init.svc.sdcard", .value = "running", }, { .key = "init.svc.sensord", .value = "running", }, { .key = "init.svc.service-crash", .value = "stopped", }, { .key = "init.svc.servicemanager", .value = "running", }, { .key = "init.svc.set_emmc_size", .value = "stopped", }, { .key = "init.svc.smpl_count", .value = "stopped", }, { .key = "init.svc.sreadahead-check", .value = "stopped", }, { .key = "init.svc.sreadahead", .value = "stopped", }, { .key = "init.svc.ssr_setup", .value = "stopped", }, { .key = "init.svc.surfaceflinger", .value = "running", }, { .key = "init.svc.thermal-engine", .value = "running", }, { .key = "init.svc.time_daemon", .value = "running", }, { .key = "init.svc.ueventd", .value = "running", }, { .key = "init.svc.usb_uicc_daemon", .value = "stopped", }, { .key = "init.svc.usb_uicc_enable", .value = "stopped", }, { .key = "init.svc.vm_bms", .value = "running", }, { .key = "init.svc.vold", .value = "running", }, { .key = "init.svc.zygote", .value = "running", }, { .key = "lg.data.bandwidth.enable", .value = "1", }, { .key = "lge.fm_gain_control_headset", .value = "0.53", }, { .key = "lge.fm_gain_control_speaker", .value = "0.70", }, { .key = "lge.nfc.vendor", .value = "bcm", }, { .key = "lge.normalizer.param", .value = "version2.0/true/10.0/true/19000/0.5/2500/0.62", }, { .key = "lge.signed_image", .value = "true", }, { .key = "lge.zdi.actionsend", .value = "false", }, { .key = "lge.zdi.dragdropintent", .value = "false", }, { .key = "lge.zdi.onactivityresult", .value = "true", }, { .key = "log.tag.GpsLocationProvider", .value = "DEBUG", }, { .key = "log.tag.LgeGpsIndicator", .value = "DEBUG", }, { .key = "log.tag.LocSvc_java", .value = "DEBUG", }, { .key = "log.tag.LocationManagerService", .value = "DEBUG", }, { .key = "log.tag.NlpProxy", .value = "DEBUG", }, { .key = "media.aac_51_output_enabled", .value = "true", }, { .key = "media.<KEY>", .value = "0", }, { .key = "media.<KEY>", .value = "0", }, { .key = "media.stagefright.enable-aac", .value = "true", }, { .key = "media.stagefright.enable-fma2dp", .value = "true", }, { .key = "media.stagefright.enable-http", .value = "true", }, { .key = "media.stagefright.enable-player", .value = "true", }, { .key = "media.stagefright.enable-qcp", .value = "true", }, { .key = "media.stagefright.enable-scan", .value = "true", }, { .key = "media.swhevccodectype", .value = "0", }, { .key = "mm.enable.qcom_parser", .value = "3183219", }, { .key = "mm.enable.smoothstreaming", .value = "true", }, { .key = "mmp.enable.3g2", .value = "true", }, { .key = "net.Is_phone_booted", .value = "true", }, { .key = "net.bt.name", .value = "Android", }, { .key = "net.change", .value = "net.qtaguid_enabled", }, { .key = "net.hostname", .value = "android-ff84ffc19101b34e", }, { .key = "net.max_property", .value = "350", }, { .key = "net.qtaguid_enabled", .value = "1", }, { .key = "net.tcp.buffersize.default", .value = "4096,87380,524288,4096,16384,110208", }, { .key = "net.tcp.buffersize.edge", .value = "4093,26280,35040,4096,16384,35040", }, { .key = "net.tcp.buffersize.evdo", .value = "4094,87380,524288,4096,16384,262144", }, { .key = "net.tcp.buffersize.gprs", .value = "4092,8760,11680,4096,8760,11680", }, { .key = "net.tcp.buffersize.hsdpa", .value = "4094,87380,1220608,4096,16384,1220608", }, { .key = "net.tcp.buffersize.hspa", .value = "4094,87380,1220608,4096,16384,1220608", }, { .key = "net.tcp.buffersize.hspap", .value = "4094,87380,1220608,4096,16384,1220608", }, { .key = "net.tcp.buffersize.hsupa", .value = "4094,87380,1220608,4096,16384,1220608", }, { .key = "net.tcp.buffersize.lte", .value = "2097152,4194304,8388608,262144,524288,1048576", }, { .key = "net.tcp.buffersize.umts", .value = "4094,87380,110208,4096,16384,110208", }, { .key = "net.tcp.buffersize.wifi", .value = "524288,2097152,4194304,262144,524288,1048576", }, { .key = "net.tcp.default_init_rwnd", .value = "60", }, { .key = "net.tethering.noprovisioning", .value = "true", }, { .key = "persist.audio.fluence.speaker", .value = "none", }, { .key = "persist.audio.fluence.voicecall", .value = "none", }, { .key = "persist.audio.fluence.voicerec", .value = "none", }, { .key = "persist.audio.handset_rx_type", .value = "DEFAULT", }, { .key = "persist.audio.headset_fluence", .value = "false", }, { .key = "persist.audio.nsenabled", .value = "OFF", }, { .key = "persist.audio.nxp", .value = "OFF", }, { .key = "persist.audio.sm_fluence", .value = "OFF", }, { .key = "persist.audio.spk_sm_fluence", .value = "OFF", }, { .key = "persist.audio.spkcall_2mic", .value = "OFF", }, { .key = "persist.audio.voice.clarity", .value = "none", }, { .key = "persist.audio.voip_nsenabled", .value = "OFF", }, { .key = "persist.boot.reset", .value = "pwr", }, { .key = "persist.cne.feature", .value = "1", }, { .key = "persist.data.netmgrd.qos.enable", .value = "false", }, { .key = "persist.data.sbp.update", .value = "2", }, { .key = "persist.debug.coresight.config", .value = "stm-events", }, { .key = "persist.debug.wfd.enable", .value = "1", }, { .key = "persist.demo.hdmirotationlock", .value = "false", }, { .key = "persist.fuse_sdcard", .value = "true", }, { .key = "persist.gps.qc_nlp_in_use", .value = "0", }, { .key = "persist.gsm.mms.enabled", .value = "true", }, { .key = "persist.gsm.mms.roaming.enabled", .value = "false", }, { .key = "persist.gsm.sms.disablelog", .value = "64", }, { .key = "persist.gsm.sms.forcegsm7", .value = "1", }, { .key = "persist.hwc.enable_vds", .value = "1", }, { .key = "persist.hwc.mdpcomp.enable", .value = "true", }, { .key = "persist.lg.data.dsqn", .value = "0", }, { .key = "persist.lg.data.fd", .value = "-1", }, { .key = "persist.lg.data.llkklk.exact", .value = "true", }, { .key = "persist.lg.data.llkklk", .value = "true", }, { .key = "persist.lg.data.vdbg", .value = "false", }, { .key = "persist.lge.appbox.ntcode", .value = "1611917394609", }, { .key = "persist.lge.appman.errc_done", .value = "1611917394609", }, { .key = "persist.lge.appman.firstboot", .value = "0", }, { .key = "persist.lge.appman.installstart", .value = "0", }, { .key = "persist.logd.size", .value = "262144", }, { .key = "persist.mms.pre-install", .value = "true", }, { .key = "persist.profiled.build.version", .value = "1611917394609", }, { .key = "persist.qcril.disable_retry", .value = "true", }, { .key = "persist.radio.adb_log_on", .value = "0", }, { .key = "persist.radio.add_power_save", .value = "1", }, { .key = "persist.radio.apm_sim_not_pwdn", .value = "1", }, { .key = "persist.radio.eons.enabled", .value = "false", }, { .key = "persist.radio.gsm.cota", .value = "0", }, { .key = "persist.radio.keyBlockByCall", .value = "0", }, { .key = "persist.radio.multisim.config", .value = "none", }, { .key = "persist.radio.ril_payload_on", .value = "0", }, { .key = "persist.radio.sms.phoneid", .value = "0", }, { .key = "persist.radio.sms_ims", .value = "false", }, { .key = "persist.rild.nitz_long_ons_0", .value = "", }, { .key = "persist.rild.nitz_long_ons_1", .value = "", }, { .key = "persist.rild.nitz_long_ons_2", .value = "", }, { .key = "persist.rild.nitz_long_ons_3", .value = "", }, { .key = "persist.rild.nitz_plmn", .value = "", }, { .key = "persist.rild.nitz_short_ons_0", .value = "", }, { .key = "persist.rild.nitz_short_ons_1", .value = "", }, { .key = "persist.rild.nitz_short_ons_2", .value = "", }, { .key = "persist.rild.nitz_short_ons_3", .value = "", }, { .key = "persist.service.avrcp.browsing", .value = "1", }, { .key = "persist.service.bdroid.bdaddr", .value = "2C:59:8A:CF:F1:CC", }, { .key = "persist.service.bt.support.sap", .value = "true", }, { .key = "persist.service.ccaudit.enable", .value = "0", }, { .key = "persist.service.crash.enable", .value = "0", }, { .key = "persist.service.events.enable", .value = "0", }, { .key = "persist.service.kernel.enable", .value = "0", }, { .key = "persist.service.main.enable", .value = "0", }, { .key = "persist.service.memory.enable", .value = "0", }, { .key = "persist.service.packet.enable", .value = "0", }, { .key = "persist.service.packet.max", .value = "0", }, { .key = "persist.service.postboot.enable", .value = "0", }, { .key = "persist.service.power.enable", .value = "0", }, { .key = "persist.service.radio.enable", .value = "0", }, { .key = "persist.service.storage.low", .value = "0", }, { .key = "persist.service.system.enable", .value = "0", }, { .key = "persist.sys.clientid-changed", .value = "0", }, { .key = "persist.sys.cupss.changed", .value = "0", }, { .key = "persist.sys.cupss.default", .value = "/cust/OPEN_COM", }, { .key = "persist.sys.cupss.integration", .value = "1", }, { .key = "persist.sys.cupss.next-root", .value = "/data/local/cust", }, { .key = "persist.sys.cupss.prev-rootdir", .value = "/data/local/cust", }, { .key = "persist.sys.cupss.subca-prev", .value = "/cust/OPEN_COM/cust_OPEN_EU.prop", }, { .key = "persist.sys.cupss.subca-prop", .value = "/cust/OPEN_COM/cust_OPEN_EU.prop", }, { .key = "persist.sys.cust.lte_config", .value = "true", }, { .key = "persist.sys.dalvik.<KEY>", .value = "libart.so", }, { .key = "persist.sys.emmc_size", .value = "16G", }, { .key = "persist.sys.factory.status", .value = "6", }, { .key = "persist.sys.first-boot", .value = "1", }, { .key = "persist.sys.first-mcc", .value = "FFF", }, { .key = "persist.sys.first-mccmnc", .value = "FFFFFF", }, { .key = "persist.sys.freezerotation", .value = "0", }, { .key = "persist.sys.iccid-mcc", .value = "", }, { .key = "persist.sys.iccid", .value = "", }, { .key = "persist.sys.lg.sound_enable", .value = "2", }, { .key = "persist.sys.mcc-list", .value = "FFF", }, { .key = "persist.sys.mccmnc-list", .value = "FFFFFF", }, { .key = "persist.sys.media.use-awesome", .value = "false", }, { .key = "persist.sys.mlt_swupdt", .value = "1", }, { .key = "persist.sys.multi-cust", .value = "0", }, { .key = "persist.sys.ntcode-changed", .value = "0", }, { .key = "persist.sys.ntcode", .value = "\"1\",\"FFF,FFF,FFFFFFFF,FFFFFFFF,11\"", }, { .key = "persist.sys.ntcode_list", .value = "1", }, { .key = "persist.sys.profiler_ms", .value = "0", }, { .key = "persist.sys.sim-changed", .value = "2", }, { .key = "persist.sys.ssr.restart_level", .value = "ALL_ENABLE", }, { .key = "persist.sys.strictmode.disable", .value = "true", }, { .key = "persist.sys.subset-list", .value = "11", }, { .key = "persist.sys.swfv.flag", .value = "1", }, { .key = "persist.sys.theme0", .value = "com.lge.launcher2.theme.optimus", }, { .key = "persist.sys.theme", .value = "", }, { .key = "persist.sys.thermald_miti_off", .value = "true", }, { .key = "persist.sys.timezone", .value = "Europe/London", }, { .key = "persist.sys.usb.config", .value = "auto_conf,adb", }, { .key = "persist.sys.wificountrymcc", .value = "", }, { .key = "persist.timed.enable", .value = "true", }, { .key = "ril.cdma.voiceinservice", .value = "false", }, { .key = "ril.ecclist.autoprofile", .value = "", }, { .key = "ril.ecclist", .value = "911,112,000,08,110,999,118,119", }, { .key = "ril.modembsp.bootup", .value = "1", }, { .key = "ril.qcril_pre_init_lock_held", .value = "0", }, { .key = "ril.subscription.types", .value = "NV,RUIM", }, { .key = "rild.libargs", .value = "-d /dev/smd0", }, { .key = "rild.libpath", .value = "/system/vendor/lib/libril-qc-qmi-1.so", }, { .key = "ro.adb.secure", .value = "1", }, { .key = "ro.airplane.phoneapp", .value = "1", }, { .key = "ro.alarm_boot", .value = "false", }, { .key = "ro.allow.mock.location", .value = "0", }, { .key = "ro.baseband", .value = "msm", }, { .key = "ro.bluetooth.dun", .value = "true", }, { .key = "ro.bluetooth.hfp.ver", .value = "1.6", }, { .key = "ro.bluetooth.sap", .value = "true", }, { .key = "ro.board.platform", .value = "msm8916", }, { .key = "ro.boot.baseband", .value = "msm", }, { .key = "ro.boot.bootdevice", .value = "7824900.sdhci", }, { .key = "ro.boot.console", .value = "ttyHSL0", }, { .key = "ro.boot.ddr_info", .value = "0x0", }, { .key = "ro.boot.ddr_size", .value = "1610612736", }, { .key = "ro.boot.dlcomplete", .value = "0", }, { .key = "ro.boot.emmc", .value = "true", }, { .key = "ro.boot.hardware", .value = "m216", }, { .key = "ro.boot.serialno", .value = "LGK4202a379b4b", }, { .key = "ro.bootloader", .value = "unknown", }, { .key = "ro.bootmode", .value = "unknown", }, { .key = "ro.build.characteristics", .value = "default", }, { .key = "ro.build.date.utc", .value = "1461832931", }, { .key = "ro.build.date", .value = "Thu Apr 28 17:42:11 KST 2016", }, { .key = "ro.build.description", .value = "m216n_global_com-user 5.1.1 LMY47V 1611917394609 release-keys", }, { .key = "ro.build.display.id", .value = "LMY47V", }, { .key = "ro.build.fingerprint", .value = "lge/m216n_global_com/m216n:5.1.1/LMY47V/1611917394609:user/release-keys", }, { .key = "ro.build.flavor", .value = "m216n_global_com-user", }, { .key = "ro.build.host", .value = "LGEACI6R2", }, { .key = "ro.build.id", .value = "LMY47V", }, { .key = "ro.build.product", .value = "m216n", }, { .key = "ro.build.sbp", .value = "1", }, { .key = "ro.build.tags", .value = "release-keys", }, { .key = "ro.build.target_country", .value = "EU", }, { .key = "ro.build.target_operator", .value = "OPEN", }, { .key = "ro.build.target_region", .value = "EU", }, { .key = "ro.build.type", .value = "user", }, { .key = "ro.build.user", .value = "jenkins", }, { .key = "ro.build.version.all_codenames", .value = "REL", }, { .key = "ro.build.version.base_os", .value = "", }, { .key = "ro.build.version.codename", .value = "REL", }, { .key = "ro.build.version.incremental", .value = "1611917394609", }, { .key = "ro.build.version.release", .value = "5.1.1", }, { .key = "ro.build.version.sdk", .value = "22", }, { .key = "ro.build.version.security_patch", .value = "2016-04-01", }, { .key = "ro.carrier", .value = "unknown", }, { .key = "ro.com.google.apphider", .value = "on", }, { .key = "ro.com.google.clientidbase.am", .value = "android-om-lge", }, { .key = "ro.com.google.clientidbase.gmm", .value = "android-om-lge", }, { .key = "ro.com.google.clientidbase.ms", .value = "android-om-lge", }, { .key = "ro.com.google.clientidbase.yt", .value = "android-om-lge", }, { .key = "ro.com.google.clientidbase", .value = "android-om-lge", }, { .key = "ro.com.google.gmsversion", .value = "5.1_r3", }, { .key = "ro.com.lge.mada", .value = "gms_3.1", }, { .key = "ro.config.alarm_alert", .value = "Melody_Alarm.ogg", }, { .key = "ro.config.notification_sound", .value = "Crystal.ogg", }, { .key = "ro.config.ringtone", .value = "01_Life_Is_Good.ogg", }, { .key = "ro.config.timer_alert", .value = "Timer.ogg", }, { .key = "ro.config.vc_call_vol_default", .value = "3", }, { .key = "ro.config.vc_call_vol_steps", .value = "6", }, { .key = "ro.crypto.state", .value = "unencrypted", }, { .key = "ro.dalvik.vm.native.bridge", .value = "0", }, { .key = "ro.debuggable", .value = "0", }, { .key = "ro.device.hapticfeedback", .value = "1", }, { .key = "ro.device.memory.internal", .value = "16", }, { .key = "ro.earlyboot_cpus", .value = "unknown", }, { .key = "ro.factorytest", .value = "0", }, { .key = "ro.frp.pst", .value = "/dev/block/bootdevice/by-name/persistent", }, { .key = "ro.fuse_sdcard", .value = "true", }, { .key = "ro.gps.agps_provider", .value = "1", }, { .key = "ro.hardware", .value = "m216", }, { .key = "ro.<KEY>", .value = "1", }, { .key = "ro.lge.audio_soundexception", .value = "true", }, { .key = "ro.lge.callduration", .value = "1", }, { .key = "ro.lge.capp_ZDi_O", .value = "true", }, { .key = "ro.lge.capp_cupss.rootdir", .value = "/data/local/cust", }, { .key = "ro.lge.cupssgroup", .value = "GLOBAL-COM", }, { .key = "ro.lge.custLanguageSet", .value = "true", }, { .key = "ro.lge.deny.minfree.change", .value = "1", }, { .key = "ro.lge.factoryversion", .value = "LGK420AT-00-V10n-GLOBAL-COM-APR-28-2016+0", }, { .key = "ro.lge.hiddenreset", .value = "0", }, { .key = "ro.lge.hw.revision", .value = "rev_12", }, { .key = "ro.lge.lcd_auto_brightness_mode", .value = "false", }, { .key = "ro.lge.lcd_default_brightness", .value = "166", }, { .key = "ro.lge.lguiversion", .value = "4.2", }, { .key = "ro.lge.ntcode_mcc", .value = "FFF", }, { .key = "ro.lge.opensw", .value = "EUR-XX", }, { .key = "ro.lge.petname", .value = "LG K10 LTE", }, { .key = "ro.lge.radio_gpri", .value = "1", }, { .key = "ro.lge.radio_gpri_v2", .value = "1", }, { .key = "ro.lge.revshare", .value = "2015", }, { .key = "ro.lge.sar.value", .value = "1", }, { .key = "ro.lge.sensor_chip", .value = "qct_kernel", }, { .key = "ro.lge.sensors_multihal", .value = "false", }, { .key = "ro.lge.sim_num", .value = "1", }, { .key = "ro.lge.singleca.enable", .value = "1", }, { .key = "ro.lge.suffix", .value = "BPOLBK", }, { .key = "ro.lge.swversion", .value = "K42010c", }, { .key = "ro.lge.swversion_rev", .value = "0", }, { .key = "ro.lge.swversion_short", .value = "V10c", }, { .key = "ro.lge.swversion_svn", .value = "13", }, { .key = "ro.lge.vib_magnitude_index", .value = "0,20,40,60,80,100,120,127", }, { .key = "ro.min_freq_0", .value = "800000", }, { .key = "ro.minios.enable", .value = "0", }, { .key = "ro.model.name", .value = "LG-K420n", }, { .key = "ro.opengles.version", .value = "196608", }, { .key = "ro.pip.gated", .value = "0", }, { .key = "ro.product.board", .value = "msm8916", }, { .key = "ro.product.brand", .value = "lge", }, { .key = "ro.product.cpu.abi2", .value = "armeabi", }, { .key = "ro.product.cpu.abi", .value = "armeabi-v7a", }, { .key = "ro.product.cpu.abilist32", .value = "armeabi-v7a,armeabi", }, { .key = "ro.product.cpu.abilist64", .value = "", }, { .key = "ro.product.cpu.abilist", .value = "armeabi-v7a,armeabi", }, { .key = "ro.product.device", .value = "m216n", }, { .key = "ro.product.locale.language", .value = "en", }, { .key = "ro.product.locale.region", .value = "GB", }, { .key = "ro.product.manufacturer", .value = "LGE", }, { .key = "ro.product.model", .value = "LG-K420", }, { .key = "ro.product.name", .value = "m216n_global_com", }, { .key = "ro.qc.sdk.audio.fluencetype", .value = "none", }, { .key = "ro.qc.sdk.audio.ssr", .value = "false", }, { .key = "ro.qualcomm.bluetooth.ftp", .value = "true", }, { .key = "ro.qualcomm.bluetooth.hfp", .value = "true", }, { .key = "ro.qualcomm.bluetooth.hsp", .value = "true", }, { .key = "ro.qualcomm.bluetooth.map", .value = "true", }, { .key = "ro.qualcomm.bluetooth.nap", .value = "true", }, { .key = "ro.qualcomm.bluetooth.opp", .value = "true", }, { .key = "ro.qualcomm.bluetooth.pbap", .value = "true", }, { .key = "ro.qualcomm.bt.hci_transport", .value = "smd", }, { .key = "ro.qualcomm.cabl", .value = "0", }, { .key = "ro.revision", .value = "9", }, { .key = "ro.ril.svdo", .value = "false", }, { .key = "ro.ril.svlte1x", .value = "false", }, { .key = "ro.runtime.firstboot", .value = "1421372180913", }, { .key = "ro.sdcrypto.syscall", .value = "398", }, { .key = "ro.secure", .value = "1", }, { .key = "ro.serialno", .value = "LGK4202a379b4b", }, { .key = "ro.setupwizard.mode", .value = "DISABLED", }, { .key = "ro.sf.lcd_density", .value = "320", }, { .key = "ro.ssbd.offset", .value = "0", }, { .key = "ro.ssbd.session", .value = "/dev/block/bootdevice/by-name/eksst", }, { .key = "ro.sys.fw.bg_apps_limit", .value = "24", }, { .key = "ro.sys.fw.bg_cached_ratio", .value = "0.5", }, { .key = "ro.sys.fw.empty_app_percent", .value = "50", }, { .key = "ro.sys.fw.mOomAdj1", .value = "0", }, { .key = "ro.sys.fw.mOomAdj2", .value = "1", }, { .key = "ro.sys.fw.mOomAdj3", .value = "2", }, { .key = "ro.sys.fw.mOomAdj4", .value = "3", }, { .key = "ro.sys.fw.mOomAdj5", .value = "9", }, { .key = "ro.sys.fw.mOomAdj6", .value = "15", }, { .key = "ro.sys.fw.mOomMinFree1", .value = "73728", }, { .key = "ro.sys.fw.mOomMinFree2", .value = "92160", }, { .key = "ro.sys.fw.mOomMinFree3", .value = "110592", }, { .key = "ro.sys.fw.mOomMinFree4", .value = "129024", }, { .key = "ro.sys.fw.mOomMinFree5", .value = "221184", }, { .key = "ro.sys.fw.mOomMinFree6", .value = "322560", }, { .key = "ro.sys.fw.trim_cache_percent", .value = "100", }, { .key = "ro.sys.fw.trim_empty_percent", .value = "100", }, { .key = "ro.sys.fw.trim_enable_memory", .value = "1073741824", }, { .key = "ro.sys.fw.use_trim_settings", .value = "true", }, { .key = "ro.telephony.call_ring.multiple", .value = "false", }, { .key = "ro.telephony.default_network", .value = "9", }, { .key = "ro.use_data_netmgrd", .value = "true", }, { .key = "ro.vendor.extension_library", .value = "libqti-perfd-client.so", }, { .key = "ro.wifi.channels", .value = "11", }, { .key = "ro.zygote", .value = "zygote32", }, { .key = "sbp.bootanim", .value = "1", }, { .key = "sbp.load_props_done", .value = "1", }, { .key = "selinux.init_rc_finished", .value = "yes", }, { .key = "selinux.reload_policy", .value = "1", }, { .key = "service.bootanim.begin", .value = "0", }, { .key = "service.bootanim.exit", .value = "1", }, { .key = "service.bt.support.busytone", .value = "true", }, { .key = "service.keyguard.status", .value = "1", }, { .key = "service.plushome.currenthome", .value = "standard", }, { .key = "sys.boot_completed", .value = "1", }, { .key = "sys.factory.qem", .value = "0", }, { .key = "sys.keymaster.loaded", .value = "true", }, { .key = "sys.knockon.knockoff.distance", .value = "10", }, { .key = "<KEY>", .value = "1", }, { .key = "sys.lge.caldata_check", .value = "1", }, { .key = "sys.lge.dsdp.mode", .value = "stop", }, { .key = "sys.lge.pif", .value = "0", }, { .key = "sys.lge.touchcrack_mode", .value = "0", }, { .key = "sys.listeners.registered", .value = "true", }, { .key = "sys.navibar.color", .value = "#ff000000", }, { .key = "sys.radio.gpri.complete", .value = "false", }, { .key = "sys.secpolicy.camera.disabled", .value = "0", }, { .key = "sys.settings_system_version", .value = "31", }, { .key = "sys.sysctl.extra_free_kbytes", .value = "10800", }, { .key = "sys.usb.config", .value = "auto_conf,adb", }, { .key = "sys.usb.rps_mask", .value = "0", }, { .key = "sys.usb.state", .value = "auto_conf,adb", }, { .key = "sys.usb_uicc.enabled", .value = "0", }, { .key = "sys.usb_uicc.loading", .value = "1", }, { .key = "sys.wfdservice", .value = "enable", }, { .key = "tunnel.audio.encode", .value = "false", }, { .key = "use.voice.path.for.pcm.voip", .value = "false", }, { .key = "vidc.enc.narrow.searchrange", .value = "0", }, { .key = "voice.playback.conc.disabled", .value = "false", }, { .key = "voice.record.conc.disabled", .value = "false", }, { .key = "voice.voip.conc.disabled", .value = "false", }, { .key = "vold.pfe", .value = "deactivated", }, { .key = "vold.post_fs_data_done", .value = "1", }, { .key = "wifi.interface", .value = "wlan0", }, { .key = "wifi.lge.common_hotspot", .value = "true", }, { .key = "wifi.lge.fcc", .value = "true", }, { .key = "wifi.lge.ftm_test", .value = "2", }, { .key = "wifi.lge.offdelay", .value = "false", }, { .key = "wifi.lge.patch", .value = "true", }, { .key = "wifi.lge.sleeppolicy", .value = "0", }, { .key = "wlan.chip.vendor", .value = "qcom", }, { .key = "wlan.chip.version", .value = "wcn", }, { .key = "wlan.driver.ath", .value = "0", }, { .key = "wlan.driver.config", .value = "/data/misc/wifi/WCNSS_qcom_cfg.ini", }, { .key = "wlan.driver.status", .value = "ok", }, { .key = "wlan.lge.concurrency", .value = "MCC", }, { .key = "wlan.lge.dcf.enable", .value = "true", }, { .key = "wlan.lge.gons.scan.completed", .value = "true", }, { .key = "wlan.lge.multisimaka", .value = "yes", }, { .key = "wlan.lge.passpoint_setting", .value = "true", }, { .key = "wlan.lge.softapwps", .value = "true", }, { .key = "wlan.lge.supportsimaka", .value = "YES", }, { .key = "wlan.monitor.status", .value = "attach", }, { NULL }, }; #endif /* __ANDROID__ */
29,398
310
package org.seasar.doma.internal.apt.processor.embeddable; import org.seasar.doma.Embeddable; import org.seasar.doma.internal.apt.lombok.Value; @Embeddable @Value public class LombokValue { @SuppressWarnings("unused") private String street; @SuppressWarnings("unused") private String city; public LombokValue(String street, String city) {} }
123
324
<reponame>vergeml/VergeML<gh_stars>100-1000 """ Sample caching support. """ import struct import pickle import mmap import io import numpy as np import lz4.frame from vergeml import VergeMLError class Cache: """Abstract base class for caches. """ def write(self, data, meta): """Write data and metadata to the cache. """ raise NotImplementedError def read(self, index, n_samples): """Read n_samples at index from the cache. """ raise NotImplementedError class MemoryCache(Cache): """Cache samples in memory. """ def __init__(self): self.data = [] def __len__(self): return len(self.data) def write(self, data, meta): self.data.append((data, meta)) def read(self, index, n_samples): return self.data[index:index+n_samples] class _CacheFileContent: def __init__(self): # An index of the positions of the stored data items. self.index = [] # Sample metadata. self.meta = [] # Info (Used to store data types) self.info = None def read(self, file, path): """Read the content index from file. """ pos, = struct.unpack('<Q', file.read(8)) if pos == 0: raise VergeMLError("Invalid cache file: {}".format(path)) file.seek(pos) self.index, self.meta, self.info = pickle.load(file) def write(self, file): """Write the content index to file and update the header. """ pos = file.tell() pickle.dump((self.index, self.meta, self.info), file) file.seek(0) # update the header with the position of the content index. file.write(struct.pack('<Q', pos)) class FileCache(Cache): """Cache raw bytes in a mmapped file. """ def __init__(self, path, mode): assert mode in ("r", "w") self.path = path self.file = open(self.path, mode + "b") self.mmfile = None self.mode = mode self.cnt = _CacheFileContent() if mode == "r": # Read the last part of the file which contains the contents of the # cache. self.cnt.read(self.file, self.path) self.mmfile = mmap.mmap(self.file.fileno(), 0, access=mmap.ACCESS_READ) else: # The 8 bytes header contain the position of the content index. # We fill this header with zeroes and write the actual position # once all samples have been written to the cache self.file.write(struct.pack('<Q', 0)) def __len__(self): return len(self.cnt.index) def write(self, data, meta): assert self.mode == "w" pos = self.file.tell() entry = (pos, pos + len(data)) # write position and metadata of the data to the content index self.cnt.index.append(entry) self.cnt.meta.append(meta) self.file.write(data) def read(self, index, n_samples): assert self.mode == "r" c_ix = self.cnt.index # get the absolute start and end adresses of the whole chunk abs_start, _ = c_ix[index] _, abs_end = c_ix[index+n_samples-1] # read the bytes and wrap in memory view to avoid copying chunk = memoryview(self.mmfile[abs_start:abs_end]) res = [] for i in range(n_samples): start, end = c_ix[index+i] # convert addresses to be relative to the chunk we read start = start - abs_start end = end - abs_start data = chunk[start:end] res.append((data, self.cnt.meta[index+i])) return res def close(self): """Close the cache file. When the cache file is being written to, this method will write the content index at the end of the file. """ if self.mode == "w": # Write the content index self.cnt.write(self.file) self.file.close() # The three basic serialization methods: # raw bytes, numpy format or python pickle. _BYTES, _NUMPY, _PICKLE = range(3) class SerializedFileCache(FileCache): """Cache serialized objects in a mmapped file. """ def __init__(self, path, mode, compress=True): """Create an optionally compressed serialized cache. """ super().__init__(path, mode) # we use info to store type information self.cnt.info = self.cnt.info or [] self.compress = compress def _serialize_data(self, data): # Default to raw bytes type_ = _BYTES if isinstance(data, np.ndarray): # When the data is a numpy array, use the more compact native # numpy format. buf = io.BytesIO() np.save(buf, data) data = buf.getvalue() type_ = _NUMPY elif not isinstance(data, (bytearray, bytes)): # Everything else except byte data is serialized in pickle format. data = pickle.dumps(data) type_ = _PICKLE if self.compress: # Optional compression data = lz4.frame.compress(data) return type_, data def _deserialize(self, data, type_): if self.compress: # decompress the data if needed data = lz4.frame.decompress(data) if type_ == _NUMPY: # deserialize numpy arrays buf = io.BytesIO(data) data = np.load(buf) elif type_ == _PICKLE: # deserialize other python objects data = pickle.loads(data) else: # Otherwise we just return data as it is (bytes) pass return data def write(self, data, meta): if isinstance(data, tuple) and len(data) == 2: # write (x,y) pairs # serialize independent from each other type1, data1 = self._serialize_data(data[0]) type2, data2 = self._serialize_data(data[1]) pos = len(data1) data = io.BytesIO() # an entry wich consists of two items carries the position # of the second item in its header. data.write(struct.pack('<Q', pos)) data.write(data1) data.write(data2) data = data.getvalue() # mark the entry as pair type_ = (type1, type2) else: type_, data = self._serialize_data(data) super().write(data, meta) self.cnt.info.append(type_) def read(self, index, n_samples): # get the entries as raw bytes from the superclass implementation entries = super().read(index, n_samples) res = [] for i, entry in enumerate(entries): data, meta = entry type_ = self.cnt.info[index+i] if isinstance(type_, tuple): # If the type is a pair (x,y), deserialize independently buf = io.BytesIO(data) # First, get the position of the second item from the header pos, = struct.unpack('<Q', buf.read(8)) # Read the first and second item data1 = buf.read(pos) data2 = buf.read() # Then deserialize the independently. data1 = self._deserialize(data1, type_[0]) data2 = self._deserialize(data2, type_[1]) res.append(((data1, data2), meta)) else: data = self._deserialize(data, type_) res.append((data, meta)) return res
3,470
10,225
<filename>extensions/cache/deployment/src/test/java/io/quarkus/cache/test/devmode/CacheHotReloadResource.java package io.quarkus.cache.test.devmode; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import io.quarkus.cache.CacheResult; @ApplicationScoped @Path("/cache-hot-reload-test") public class CacheHotReloadResource { private int invocations; @GET @Path("/greet") @CacheResult(cacheName = "hotReloadCache") public String greet(@QueryParam("key") String key) { invocations++; return "hello " + key + "!"; } @GET @Path("/invocations") public int getInvocations() { return invocations; } }
293
5,169
{ "name": "sqliteClasses", "version": "1.1.0", "summary": "Framework to utilize the SQLite with simple methods", "description": "sqliteClasses to utilize the SQLite with simple methods", "homepage": "http://osoftz.com", "license": "MIT", "authors": { "osoftz": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/osoftz/sqliteClasses.git", "branch": "master" }, "swift_version": "4.2", "source_files": [ "sqliteClasees", "Classes/**/*.swift" ], "exclude_files": "Classes/Exclude", "dependencies": { "SQLite.swift": [ "~> 0.11.5" ] } }
280
3,075
package org.powermock.reflect.internal.proxy; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFrameworks { private static final UnproxiedTypeFactory UNPROXIED_TYPE_FACTORY = new UnproxiedTypeFactory(); public UnproxiedType getUnproxiedType(Class<?> type) { if (type == null){ return null; } if (isJavaProxy(type)){ return UNPROXIED_TYPE_FACTORY.createFromInterfaces(type.getInterfaces()); } if (isCglibProxyClass(type)) { return UNPROXIED_TYPE_FACTORY.createFromSuperclassAndInterfaces(type.getSuperclass(), type.getInterfaces()); } return UNPROXIED_TYPE_FACTORY.createFromType(type); } public UnproxiedType getUnproxiedType(Object o) { if (o == null) { return null; } return getUnproxiedType(o.getClass()); } private boolean isJavaProxy(Class<?> clazz) { return (clazz != null && Proxy.isProxyClass(clazz)); } private boolean isCglibProxyClass(Class<?> clazz) { if (clazz == null){ return false; } Method[] methods = clazz.getDeclaredMethods(); for(Method m: methods){ if(isCglibCallbackMethod(m)) { return true; } } return false; } private boolean isCglibCallbackMethod(Method m) { return "CGLIB$SET_THREAD_CALLBACKS".equals(m.getName()) && m.getParameterTypes().length == 1; } }
689
1,510
<gh_stars>1000+ /* * Copyright Ctrip. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ctrip.wireless.android.crn.utils; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringWriter; import ctrip.wireless.android.crn.ContextHolder; public class FileUtil { private static final String TAG = "FileUtil"; public static boolean copyDirFromAsset(Context context, String assetFolderName, String desDir) { AssetManager assetManager = context.getAssets(); try { File desDirFile = new File(desDir); desDirFile.delete(); desDirFile.mkdirs(); String[] files = assetManager.list(assetFolderName); for (String filename : files) { String[] assets = assetManager.list(assetFolderName + "/" + filename); if (assets == null || assets.length == 0) { InputStream in = assetManager.open(assetFolderName + "/" + filename); OutputStream out = new FileOutputStream(desDir + "/" + filename); copyFile(in, out); in.close(); out.flush(); out.close(); } else { copyDirFromAsset(context, assetFolderName + "/" + filename, desDir + "/" + filename); } } return true; } catch (IOException e) { Log.e(TAG, "Failed to get asset file list.", e); return false; } } private static void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } public static String readFileAsString(InputStream inputStream) { InputStreamReader reader = null; StringWriter writer = new StringWriter(); try { reader = new InputStreamReader(inputStream); char[] buffer = new char[1024]; int n = 0; while (-1 != (n = reader.read(buffer))) { writer.write(buffer, 0, n); } } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (reader != null) reader.close(); if (inputStream != null){ inputStream.close(); } }catch (IOException e){ e.printStackTrace(); } } return writer.toString(); } public static String readFileAsString(File file) { try { return readFileAsString(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } /** * * @param path * 删除目录,包括自己 */ public static void delDir(String path) { delFile(path); new File(path).delete(); } /** * 功能描述:删除文件夹下所有文件和文件夹 * <p/> * <pre> * 苟俊: 2013-1-16 新建 * </pre> * * @param path */ public static void delFile(String path) { File cacheFile = new File(path); if (!cacheFile.exists()) { return; } File[] files = cacheFile.listFiles(); if (files == null) { return; } for (int i = 0; i < files.length; i++) { // 是文件则直接删除 if (files[i].exists() && files[i].isFile()) { files[i].delete(); } else if (files[i].exists() && files[i].isDirectory()) { // 递归删除文件 delFile(files[i].getAbsolutePath()); // 删除完目录下面的所有文件后再删除该文件夹 files[i].delete(); } } } }
2,272
1,773
<reponame>psunde/primefaces<gh_stars>1000+ /* * The MIT License * * Copyright (c) 2009-2021 PrimeTek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.primefaces.integrationtests.datepicker; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.primefaces.selenium.AbstractPrimePage; import org.primefaces.selenium.component.CommandButton; import org.primefaces.selenium.component.DatePicker; public class DatePicker002Test extends AbstractDatePickerTest { @Test @Order(1) public void testWithoutShowOtherMonths(Page page) { // Arrange DatePicker datePicker = page.datePicker1; // Act datePicker.click(); // focus to bring up panel // Assert assertNoJavascriptErrors(); WebElement panel = datePicker.getPanel(); Assertions.assertNotNull(panel); List<WebElement> elements = panel.findElements(By.cssSelector("table.ui-datepicker-calendar")); Assertions.assertNotNull(elements); Assertions.assertEquals(1, elements.size()); WebElement table = elements.get(0); List<WebElement> days = table.findElements(By.cssSelector("td a")); Assertions.assertNotNull(days); Assertions.assertEquals(28, days.size()); List<WebElement> daysOtherMonths = table.findElements(By.cssSelector("td.ui-datepicker-other-month")); Assertions.assertNotNull(daysOtherMonths); Assertions.assertEquals(7, daysOtherMonths.size()); Assertions.assertEquals(0, daysOtherMonths.stream().filter(dayOtherMonth -> dayOtherMonth.isDisplayed()).count()); } @Test @Order(2) public void testWithShowOtherMonths(Page page) { // Arrange DatePicker datePicker = page.datePicker2; // Act datePicker.click(); // focus to bring up panel // Assert assertNoJavascriptErrors(); WebElement panel = datePicker.getPanel(); Assertions.assertNotNull(panel); List<WebElement> elements = panel.findElements(By.cssSelector("table.ui-datepicker-calendar")); Assertions.assertNotNull(elements); Assertions.assertEquals(1, elements.size()); WebElement table = elements.get(0); List<WebElement> days = table.findElements(By.cssSelector("td a")); Assertions.assertNotNull(days); Assertions.assertEquals(28, days.size()); List<WebElement> daysOtherMonths = table.findElements(By.cssSelector("td.ui-datepicker-other-month")); Assertions.assertNotNull(daysOtherMonths); Assertions.assertEquals(7, daysOtherMonths.size()); Assertions.assertEquals(7, daysOtherMonths.stream().filter(dayOtherMonth -> dayOtherMonth.isDisplayed()).count()); } public static class Page extends AbstractPrimePage { @FindBy(id = "form:datepicker1") DatePicker datePicker1; @FindBy(id = "form:datepicker2") DatePicker datePicker2; @FindBy(id = "form:button") CommandButton button; @Override public String getLocation() { return "datepicker/datePicker002.xhtml"; } } }
1,597
389
<reponame>andyyangdong/vester // // QSImageRenderer.h // Q Branch Standard Kit // // Created by <NAME> on 10/23/13. // Copyright (c) 2013 Q Branch LLC. All rights reserved. // @import Foundation; #if TARGET_OS_IPHONE @import UIKit; #else @import AppKit; #endif #import "QSPlatform.h" #import "QSBlocks.h" /*Used to render an image based on another image. (Thumbnails, for instance.) Thread-safe. Renders in a background queue. imageRenderBlock is responsible for dealing with graphics context; it returns the rendered image. imageResultBlock may be called on any thread. None of the parameters may be nil. */ @interface QSImageRenderer : NSObject - (instancetype)initWithRenderer:(QSImageRenderBlock)imageRenderBlock; - (void)renderImage:(QS_IMAGE *)originalImage imageResultBlock:(QSImageResultBlock)imageResultBlock; @end
276
715
<gh_stars>100-1000 # Generated by the protocol buffer compiler. DO NOT EDIT! # source: onehot-param.proto import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor(name='onehot-param.proto', package='com.webank.ai.fate.core.mlmodel.buffer', syntax='proto3', serialized_options=_b('B\020OneHotParamProto'), serialized_pb=_b( '\n\x12onehot-param.proto\x12&com.webank.ai.fate.core.mlmodel.buffer\"6\n\x07\x43olsMap\x12\x0e\n\x06values\x18\x01 \x03(\t\x12\x1b\n\x13transformed_headers\x18\x02 \x03(\t\"\xd6\x01\n\x0bOneHotParam\x12P\n\x07\x63ol_map\x18\x01 \x03(\x0b\x32?.com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.ColMapEntry\x12\x15\n\rresult_header\x18\x02 \x03(\t\x1a^\n\x0b\x43olMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12>\n\x05value\x18\x02 \x01(\x0b\x32/.com.webank.ai.fate.core.mlmodel.buffer.ColsMap:\x02\x38\x01\x42\x12\x42\x10OneHotParamProtob\x06proto3')) _COLSMAP = _descriptor.Descriptor( name='ColsMap', full_name='com.webank.ai.fate.core.mlmodel.buffer.ColsMap', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='values', full_name='com.webank.ai.fate.core.mlmodel.buffer.ColsMap.values', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='transformed_headers', full_name='com.webank.ai.fate.core.mlmodel.buffer.ColsMap.transformed_headers', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[], serialized_start=62, serialized_end=116, ) _ONEHOTPARAM_COLMAPENTRY = _descriptor.Descriptor( name='ColMapEntry', full_name='com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.ColMapEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.ColMapEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.ColMapEntry.value', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=239, serialized_end=333, ) _ONEHOTPARAM = _descriptor.Descriptor( name='OneHotParam', full_name='com.webank.ai.fate.core.mlmodel.buffer.OneHotParam', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='col_map', full_name='com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.col_map', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='result_header', full_name='com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.result_header', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_ONEHOTPARAM_COLMAPENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=119, serialized_end=333, ) _ONEHOTPARAM_COLMAPENTRY.fields_by_name['value'].message_type = _COLSMAP _ONEHOTPARAM_COLMAPENTRY.containing_type = _ONEHOTPARAM _ONEHOTPARAM.fields_by_name['col_map'].message_type = _ONEHOTPARAM_COLMAPENTRY DESCRIPTOR.message_types_by_name['ColsMap'] = _COLSMAP DESCRIPTOR.message_types_by_name['OneHotParam'] = _ONEHOTPARAM _sym_db.RegisterFileDescriptor(DESCRIPTOR) ColsMap = _reflection.GeneratedProtocolMessageType('ColsMap', (_message.Message,), dict( DESCRIPTOR=_COLSMAP, __module__='onehot_param_pb2' # @@protoc_insertion_point(class_scope:com.webank.ai.fate.core.mlmodel.buffer.ColsMap) )) _sym_db.RegisterMessage(ColsMap) OneHotParam = _reflection.GeneratedProtocolMessageType('OneHotParam', (_message.Message,), dict( ColMapEntry=_reflection.GeneratedProtocolMessageType('ColMapEntry', (_message.Message,), dict( DESCRIPTOR=_ONEHOTPARAM_COLMAPENTRY, __module__='onehot_param_pb2' # @@protoc_insertion_point(class_scope:com.webank.ai.fate.core.mlmodel.buffer.OneHotParam.ColMapEntry) )), DESCRIPTOR=_ONEHOTPARAM, __module__='onehot_param_pb2' # @@protoc_insertion_point(class_scope:com.webank.ai.fate.core.mlmodel.buffer.OneHotParam) )) _sym_db.RegisterMessage(OneHotParam) _sym_db.RegisterMessage(OneHotParam.ColMapEntry) DESCRIPTOR._options = None _ONEHOTPARAM_COLMAPENTRY._options = None # @@protoc_insertion_point(module_scope)
3,234
335
<reponame>Safal08/Hacktoberfest-1<filename>T/Transpire_verb.json<gh_stars>100-1000 { "word": "Transpire", "definitions": [ "(of a secret or something unknown) come to be known; be revealed.", "Prove to be the case.", "Occur; happen.", "(of a plant or leaf) give off water vapour through the stomata." ], "parts-of-speech": "Verb" }
159
816
<gh_stars>100-1000 /* * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.dynamic.sql.insert.render; import static org.mybatis.dynamic.sql.util.StringUtilities.spaceBefore; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.mybatis.dynamic.sql.insert.GeneralInsertModel; import org.mybatis.dynamic.sql.render.RenderingStrategy; public class GeneralInsertRenderer { private final GeneralInsertModel model; private final RenderingStrategy renderingStrategy; private GeneralInsertRenderer(Builder builder) { model = Objects.requireNonNull(builder.model); renderingStrategy = Objects.requireNonNull(builder.renderingStrategy); } public GeneralInsertStatementProvider render() { GeneralInsertValuePhraseVisitor visitor = new GeneralInsertValuePhraseVisitor(renderingStrategy); List<Optional<FieldAndValueAndParameters>> fieldsAndValues = model.mapColumnMappings(m -> m.accept(visitor)) .collect(Collectors.toList()); return DefaultGeneralInsertStatementProvider.withInsertStatement(calculateInsertStatement(fieldsAndValues)) .withParameters(calculateParameters(fieldsAndValues)) .build(); } private String calculateInsertStatement(List<Optional<FieldAndValueAndParameters>> fieldsAndValues) { return "insert into" //$NON-NLS-1$ + spaceBefore(model.table().tableNameAtRuntime()) + spaceBefore(calculateColumnsPhrase(fieldsAndValues)) + spaceBefore(calculateValuesPhrase(fieldsAndValues)); } private String calculateColumnsPhrase(List<Optional<FieldAndValueAndParameters>> fieldsAndValues) { return fieldsAndValues.stream() .filter(Optional::isPresent) .map(Optional::get) .map(FieldAndValueAndParameters::fieldName) .collect(Collectors.joining(", ", "(", ")")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private String calculateValuesPhrase(List<Optional<FieldAndValueAndParameters>> fieldsAndValues) { return fieldsAndValues.stream() .filter(Optional::isPresent) .map(Optional::get) .map(FieldAndValueAndParameters::valuePhrase) .collect(Collectors.joining(", ", "values (", ")")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private Map<String, Object> calculateParameters(List<Optional<FieldAndValueAndParameters>> fieldsAndValues) { return fieldsAndValues.stream() .filter(Optional::isPresent) .map(Optional::get) .map(FieldAndValueAndParameters::parameters) .collect(HashMap::new, HashMap::putAll, HashMap::putAll); } public static Builder withInsertModel(GeneralInsertModel model) { return new Builder().withInsertModel(model); } public static class Builder { private GeneralInsertModel model; private RenderingStrategy renderingStrategy; public Builder withInsertModel(GeneralInsertModel model) { this.model = model; return this; } public Builder withRenderingStrategy(RenderingStrategy renderingStrategy) { this.renderingStrategy = renderingStrategy; return this; } public GeneralInsertRenderer build() { return new GeneralInsertRenderer(this); } } }
1,566
663
<gh_stars>100-1000 # (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import functools from ddtrace import tracer from ..config import is_affirmative try: import datadog_agent except ImportError: # Integration Tracing is only available with Agent 6 datadog_agent = None def traced(fn): """ Traced decorator is intended to be used on a method of AgentCheck subclasses. Example: class MyCheck(AgentCheck): @traced def check(self, instance): self.gauge('dummy.metric', 10) @traced def submit(self): self.gauge('dummy.metric', 10) """ @functools.wraps(fn) def traced_wrapper(self, *args, **kwargs): if datadog_agent is None: return fn(self, *args, **kwargs) trace_check = is_affirmative(self.init_config.get('trace_check')) integration_tracing = is_affirmative(datadog_agent.get_config('integration_tracing')) if integration_tracing and trace_check: with tracer.trace(self.name, service='integrations-tracing', resource=fn.__name__): return fn(self, *args, **kwargs) return fn(self, *args, **kwargs) return traced_wrapper
548
7,746
{ "Version": "1.0.0", "Intent": "ProductRelease", "ContentType": "Binaries", "ContentOrigin": "1stParty", "ProductState": "Next", "Audience": "ExternalBroad" }
67
332
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- """A usdview plugin that replaces the "Load" and "Unload" buttons in usdview.""" # IMPORT STANDARD LIBRARIES import functools import logging import sys # IMPORT THIRD-PARTY LIBRARIES from pxr import Sdf, Tf, Usd from pxr.Usdviewq import plugin LOGGER = logging.getLogger("root_loader") _HANDLER = logging.StreamHandler(sys.stdout) _FORMATTER = logging.Formatter( "%(asctime)s [%(levelname)s] %(module)s: %(message)s", datefmt="%m/%d/%Y %H:%M:%S" ) _HANDLER.setFormatter(_FORMATTER) LOGGER.addHandler(_HANDLER) LOGGER.setLevel(logging.INFO) class RootLoaderContainer(plugin.PluginContainer): """The main registry class that initializes and runs the Root-Loader plugin.""" def registerPlugins(self, registry, _): """Add this Root-Loader plugin to usdview on-startup. Args: registry (`pxr.Usdviewq.plugin.PluginRegistry`): The USD-provided object that this plugin will be added to. """ self._toggle_root_load_command = registry.registerCommandPlugin( "RootLoaderContainer.Load", "Root Load", functools.partial(load_gui, load=True), ) self._toggle_root_unload_command = registry.registerCommandPlugin( "RootLoaderContainer.Unload", "Root Unload", functools.partial(load_gui, load=False), ) def configureView(self, _, builder): """Add a new menu item for the Root-Loader function.""" menu = builder.findOrCreateMenu("Root Loader") menu.addItem(self._toggle_root_load_command) menu.addItem(self._toggle_root_unload_command) def _load(paths, stage, load): """Load or unload the given Prim paths. Args: paths (set[`pxr.Sdf.Path`]): The paths that will be loaded or unloaded. stage (`pxr.Usd.Stage`): The user's current stage that contains `paths` as Prims. load (bool): A value that controls if selected Prims are loaded or unloaded. """ for root in Sdf.Path.RemoveDescendentPaths(paths): root = stage.GetPrimAtPath(root) if load: root.Load() else: root.Unload() def load_gui(viewer, load): """Load or Unload the user's selected Prims. Args: viewer (`pxr.Usdviewq.usdviewApi.UsdviewApi`): usdview's current state. load (bool): A value that controls if selected Prims are loaded or unloaded. """ _load(set(viewer.dataModel.selection.getPrimPaths()), viewer.stage, load) Tf.Type.Define(RootLoaderContainer)
1,072
973
package com.xw.project.gracefulmovies.data.db.entity; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import com.google.gson.annotations.SerializedName; /** * <p> * Created by woxingxiao on 2018-08-08. */ @Entity(tableName = "cities") public class CityEntity { @PrimaryKey private int id; @SerializedName("n") private String name; @Deprecated private boolean isUpper; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isUpper() { return isUpper; } public void setUpper(boolean upper) { isUpper = upper; } }
341
403
import os import math from flask import Flask from flask import Response from flask import json from shapely.geometry import Point app = Flask(__name__) @app.route('/') def index(): patch = Point(0.0, 0.0).buffer(10.0) patch print ("Area is: " + str(patch.area)) print("Index method is called.") return "Hello Shapely, Area is: "+ str(math.ceil(patch.area)) @app.route('/cities.json') def cities(): data = {"cities" : ["Amsterdam","Berlin","New York","San Francisco","Tokyo"]} resp = Response(json.dumps(data), status=200, mimetype='application/json') return resp if __name__ == '__main__': port = int(os.environ.get('PORT', 3000)) app.run(host='0.0.0.0', port=port, debug=True)
267
2,772
# ------------------------------------------------------------------------- # Copyright (c) 2020 <NAME>. All rights reserved. # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ Converter for Spark-ML VectorAssembler """ import torch import numpy as np from onnxconverter_common.topology import Variable from onnxconverter_common.registration import register_converter from .._physical_operator import PhysicalOperator from .._pipeline_implementations import Concat def convert_sparkml_vector_assembler(operator, device, extra_config): """ Converter for `pyspark.ml.feature.VectorAssembler` Args: operator: An operator wrapping a `pyspark.ml.feature.VectorAssembler` device: String defining the type of device the converted operator should be run on extra_config: Extra configuration used to select the best conversion strategy Returns: A PyTorch model """ return Concat(operator) register_converter("SparkMLVectorAssembler", convert_sparkml_vector_assembler)
330
19,529
<reponame>funrunskypalace/vnpy """""" import importlib class StructGenerator: """Struct生成器""" def __init__(self, filename: str, prefix: str): """Constructor""" self.filename = filename self.prefix = prefix self.typedefs = {} self.current_struct = {} self.load_constant() def load_constant(self): """""" module_name = f"{self.prefix}_typedef" module = importlib.import_module(module_name) for name in dir(module): if "__" not in name: self.typedefs[name] = getattr(module, name) def run(self): """运行生成""" self.f_cpp = open(self.filename, "r") self.f_struct = open(f"{self.prefix}_struct.py", "w") for n, line in enumerate(self.f_cpp): if "*" in line: continue try: self.process_line(line) except Exception: print(n, line) import traceback traceback.print_exc() return self.f_cpp.close() self.f_struct.close() print("Struct生成成功") def process_line(self, line: str): """处理每行""" line = line.replace(";", "") line = line.replace("\n", "") line = line.replace("\t", " ") if self.prefix == "nh_stock" and line.startswith(" "): line = line[4:] if "///" in line: return elif line.startswith("struct") or line.startswith("typedef"): self.process_declare(line) elif line.startswith("{"): self.process_start(line) elif line.startswith("}"): self.process_end(line) elif line.startswith(" "): self.process_member(line) def process_declare(self, line: str): """处理声明""" words = line.split(" ") words = [word for word in words if word] if "typedef" in words: name = words[2] else: name = words[1] end = "{" new_line = f"{name} = {end}\n" self.f_struct.write(new_line) self.current_struct = name def process_start(self, line: str): """处理开始""" pass def process_end(self, line: str): """处理结束""" new_line = "}\n\n" self.f_struct.write(new_line) def process_member(self, line: str): """处理成员""" if "//" in line: ix = line.index("//") line = line[:ix] words = line.split(" ") words = [word for word in words if word] if words[0] == "ReqOrderInsertData": return elif words[0] == "Commi_Info_t": return elif words[0] == "char": py_type = "string" elif words[0] == "int": py_type = "int" else: py_type = self.typedefs[words[0]] name = words[1] new_line = f" \"{name}\": \"{py_type}\",\n" self.f_struct.write(new_line) if __name__ == "__main__": generator = StructGenerator("../../include/nh/futures/NhFtdcUserApiStruct.h", "nh") generator.run()
1,687
3,459
#ifndef __MDFN_MDCD_TIMER_H #define __MDFN_MDCD_TIMER_H void MDCD_Timer_Reset(void); void MDCD_Timer_Run(int32 clocks); void MDCD_Timer_Write(uint8 V); uint8 MDCD_Timer_Read(void); #endif
89
12,718
/* * ntddmou.h * * Mouse device IOCTL interface. * * This file is part of the w32api package. * * Contributors: * Created by <NAME> <<EMAIL>> * * THIS SOFTWARE IS NOT COPYRIGHTED * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #pragma once #ifdef __cplusplus extern "C" { #endif #define DD_MOUSE_DEVICE_NAME "\\Device\\PointerClass" #define DD_MOUSE_DEVICE_NAME_U L"\\Device\\PointerClass" #define IOCTL_MOUSE_QUERY_ATTRIBUTES \ CTL_CODE(FILE_DEVICE_MOUSE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_MOUSE_INSERT_DATA \ CTL_CODE(FILE_DEVICE_MOUSE, 1, METHOD_BUFFERED, FILE_ANY_ACCESS) DEFINE_GUID(GUID_DEVINTERFACE_MOUSE, \ 0x378de44c, 0x56ef, 0x11d1, 0xbc, 0x8c, 0x00, 0xa0, 0xc9, 0x14, 0x05, 0xdd); #define GUID_CLASS_MOUSE GUID_DEVINTERFACE_MOUSE /* Obsolete */ #define MOUSE_ERROR_VALUE_BASE 20000 /* MOUSE_INPUT_DATA.ButtonFlags constants */ #define MOUSE_LEFT_BUTTON_DOWN 0x0001 #define MOUSE_LEFT_BUTTON_UP 0x0002 #define MOUSE_RIGHT_BUTTON_DOWN 0x0004 #define MOUSE_RIGHT_BUTTON_UP 0x0008 #define MOUSE_MIDDLE_BUTTON_DOWN 0x0010 #define MOUSE_MIDDLE_BUTTON_UP 0x0020 #define MOUSE_BUTTON_4_DOWN 0x0040 #define MOUSE_BUTTON_4_UP 0x0080 #define MOUSE_BUTTON_5_DOWN 0x0100 #define MOUSE_BUTTON_5_UP 0x0200 #define MOUSE_WHEEL 0x0400 #define MOUSE_HWHEEL 0x0800 #define MOUSE_BUTTON_1_DOWN MOUSE_LEFT_BUTTON_DOWN #define MOUSE_BUTTON_1_UP MOUSE_LEFT_BUTTON_UP #define MOUSE_BUTTON_2_DOWN MOUSE_RIGHT_BUTTON_DOWN #define MOUSE_BUTTON_2_UP MOUSE_RIGHT_BUTTON_UP #define MOUSE_BUTTON_3_DOWN MOUSE_MIDDLE_BUTTON_DOWN #define MOUSE_BUTTON_3_UP MOUSE_MIDDLE_BUTTON_UP /* MOUSE_INPUT_DATA.Flags constants */ #define MOUSE_MOVE_RELATIVE 0 #define MOUSE_MOVE_ABSOLUTE 1 #define MOUSE_VIRTUAL_DESKTOP 0x02 #define MOUSE_ATTRIBUTES_CHANGED 0x04 #if(_WIN32_WINNT >= 0x0600) #define MOUSE_MOVE_NOCOALESCE 0x08 #endif #define MOUSE_TERMSRV_SRC_SHADOW 0x100 typedef struct _MOUSE_INPUT_DATA { USHORT UnitId; USHORT Flags; __C89_NAMELESS union { ULONG Buttons; __C89_NAMELESS struct { USHORT ButtonFlags; USHORT ButtonData; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; ULONG RawButtons; LONG LastX; LONG LastY; ULONG ExtraInformation; } MOUSE_INPUT_DATA, *PMOUSE_INPUT_DATA; typedef struct _MOUSE_UNIT_ID_PARAMETER { USHORT UnitId; } MOUSE_UNIT_ID_PARAMETER, *PMOUSE_UNIT_ID_PARAMETER; /* MOUSE_ATTRIBUTES.MouseIdentifier constants */ #define MOUSE_INPORT_HARDWARE 0x0001 #define MOUSE_I8042_HARDWARE 0x0002 #define MOUSE_SERIAL_HARDWARE 0x0004 #define BALLPOINT_I8042_HARDWARE 0x0008 #define BALLPOINT_SERIAL_HARDWARE 0x0010 #define WHEELMOUSE_I8042_HARDWARE 0x0020 #define WHEELMOUSE_SERIAL_HARDWARE 0x0040 #define MOUSE_HID_HARDWARE 0x0080 #define WHEELMOUSE_HID_HARDWARE 0x0100 #define HORIZONTAL_WHEEL_PRESENT 0x8000 typedef struct _MOUSE_ATTRIBUTES { USHORT MouseIdentifier; USHORT NumberOfButtons; USHORT SampleRate; ULONG InputDataQueueLength; } MOUSE_ATTRIBUTES, *PMOUSE_ATTRIBUTES; #ifdef __cplusplus } #endif
1,939
530
/* * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.agent.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * One-time use loader for reflective class inspection. Don't keep static reference to one of these. */ public class InspectionClassLoader extends ClassLoader { public InspectionClassLoader(ClassLoader parent) { super(parent); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith("java.")) { return getParent().loadClass(name); } try { return loadClass(name, true); } catch (ClassNotFoundException e) { return getParent().loadClass(name); } } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = findLoadedClass(name); if (clazz != null) { return clazz; } clazz = findClass(name); if (resolve) { resolveClass(clazz); } return clazz; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { InputStream is = getParent().getResourceAsStream(TypeUtils.getInternalName(name) + ".class"); if (is == null) { throw new ClassNotFoundException(name); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; // 1024 is chosen arbitrarily try { while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); buffer.flush(); } } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = buffer.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } }
1,051
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.core.windows; /** * Enumerates event types to be fired when the window system loads/saves. * * @since 2.31 * @author <NAME> */ public enum WindowSystemEventType { beforeLoad, afterLoad, beforeSave, afterSave }
285
430
{ "operations": [ { "operationName": "QueryWithStructs", "query": "\nquery QueryWithStructs {\n\tuser {\n\t\tauthMethods {\n\t\t\tprovider\n\t\t\temail\n\t\t}\n\t}\n}\n", "sourceLocation": "testdata/queries/QueryWithStructs.graphql" } ] }
128
1,056
<reponame>Antholoj/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.lib.v8debug.connection; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.ContainerFactory; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.netbeans.lib.v8debug.JSONReader; import org.netbeans.lib.v8debug.JSONWriter; import org.netbeans.lib.v8debug.V8Command; import org.netbeans.lib.v8debug.V8Event; import org.netbeans.lib.v8debug.V8Request; import org.netbeans.lib.v8debug.V8Response; import static org.netbeans.lib.v8debug.connection.DebuggerConnection.*; /** * A debugger server connection. This is a main server debugger class. * Create an instance of this class to listen for incoming debugger connections. * <p> * The typical usage is: * <pre><tt> * final ServerConnection sn = new ServerConnection(); * final Map&lt;String, String&gt; properties = ... // See HeaderProperties. * new Thread() { * public void run() { * try { * sn.runConnectionLoop(map, new ServerConnection.Listener() { * public ServerConnection.ResponseProvider request(V8Request request) { * return ServerConnection.ResponseProvider.create( * request.createSuccessResponse(...)); * } * }); * } catch (IOException ex) { * ... * } * } * }.start(); * ... * V8Event event = new V8Event(...); * sn.send(event); * </tt></pre> * * @author <NAME> */ public final class ServerConnection { private static final Logger LOG = Logger.getLogger(ServerConnection.class.getName()); private static final String SERVER_PROTOCOL_VERSION = "1"; private final ServerSocket server; private Socket currentSocket; private InputStream clientIn; private OutputStream clientOut; private final Object outLock = new Object(); private final byte[] buffer = new byte[BUFFER_SIZE]; private final ContainerFactory containerFactory = new LinkedJSONContainterFactory(); private final Set<IOListener> ioListeners = new CopyOnWriteArraySet<>(); /** * Create a new server listening connection with automatically selected port * number. The actual port number that was selected can be retrieved by * calling {@link #getPort()}. * @throws IOException when an IO problem occurs. */ public ServerConnection() throws IOException { server = new ServerSocket(0); } /** * Create a new server listening connection on the specific port. * @param serverPort The port the connection is listening on. * @throws IOException when an IO problem occurs. * @throws IllegalArgumentException if the port parameter is outside the * specified range of valid port values, which is between 0 and 65535, inclusive. */ public ServerConnection(int serverPort) throws IOException, IllegalArgumentException { server = new ServerSocket(serverPort); } /** * Execute the debugger events loop. Run this in an application thread, this * class does not provide any threading. This method waits until some client * debugger is connected, keeps processing the debugger requests and keeps * blocking until the connection is closed. Then the method can be called * again to accept another client debugger connection. * @param properties The map of properties to provide to the client as a header. * See {@link HeaderProperties} * @param listener The listener to receive the debugger events. * @throws IOException thrown when an IO problem occurs. */ public void runConnectionLoop(Map<String, String> properties, Listener listener) throws IOException { Socket socket = server.accept(); socket.setTcpNoDelay(true); currentSocket = socket; clientIn = socket.getInputStream(); clientOut = socket.getOutputStream(); sendProperties(properties); runEventLoop(listener); } /** * Get the port number this connection is listening on. * @return The port number. */ public int getPort() { return server.getLocalPort(); } private void runEventLoop(Listener listener) throws IOException { int n; int contentLength = -1; int[] beginPos = new int[] { 0 }; int[] fromPtr = new int[] { 0 }; int readOffset = 0; String tools = null; byte[] emptyArray = new byte[] {}; byte[] messageBytes = emptyArray; while ((n = clientIn.read(buffer, readOffset, BUFFER_SIZE - readOffset)) > 0) { n += readOffset; int from = 0; do { if (contentLength < 0) { fromPtr[0] = from; contentLength = readContentLength(buffer, fromPtr, n, beginPos); if (contentLength < 0) { break; } from = fromPtr[0]; } if (tools == null) { fromPtr[0] = from; tools = readTools(buffer, fromPtr, n); if (tools == null) { break; } else { from = fromPtr[0]; } } int length = Math.min(contentLength - messageBytes.length, n - from); messageBytes = Utils.joinArrays(messageBytes, buffer, from, length); from += length; if (messageBytes.length == contentLength) { String message = new String(messageBytes, CHAR_SET); try { received(listener, tools, message); } catch (ThreadDeath td) { throw td; } catch (ParseException pex) { throw new IOException(pex.getLocalizedMessage(), pex); } catch (Throwable t) { LOG.log(Level.SEVERE, message, t); } contentLength = -1; tools = null; messageBytes = emptyArray; } } while (from < n); if (from < n) { System.arraycopy(buffer, from, buffer, 0, n - from); readOffset = n - from; } else { readOffset = 0; } } } private void received(Listener listener, String tools, String message) throws ParseException, IOException { //System.out.println("RECEIVED: tools: '"+tools+"', message: '"+message+"'"); fireReceived(message); LOG.log(Level.FINE, "RECEIVED: {0}, {1}", new Object[]{tools, message}); if (message.isEmpty()) { return ; } JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(message, containerFactory); V8Request request = JSONReader.getRequest(obj); ResponseProvider rp = listener.request(request); if (V8Command.Disconnect.equals(request.getCommand())) { try { closeCurrentConnection(); } catch (IOException ioex) {} } if (rp != null) { rp.sendTo(this); } } private void sendProperties(Map<String, String> properties) throws IOException { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> prop : properties.entrySet()) { sb.append(prop.getKey()); sb.append(": "); sb.append(prop.getValue()); sb.append(EOL_STR); } if (!properties.keySet().contains(HeaderProperties.PROTOCOL_VERSION)) { sb.append(HeaderProperties.PROTOCOL_VERSION + ": "+SERVER_PROTOCOL_VERSION + EOL_STR); } sb.append(CONTENT_LENGTH_STR+"0" + EOL_STR + EOL_STR); byte[] bytes = sb.toString().getBytes(CHAR_SET); synchronized (outLock) { clientOut.write(bytes); } } private void send(V8Response response) throws IOException { JSONObject obj = JSONWriter.store(response); sendJSON(obj); } /** * Send a debugger event. * @param event An event to send to the client. * @throws IOException thrown when an IO problem occurs. */ public void send(V8Event event) throws IOException { JSONObject obj = JSONWriter.store(event); sendJSON(obj); } private void sendJSON(JSONObject obj) throws IOException { String text = obj.toJSONString(); text = text.replace("\\/", "/"); // Replace escaped slash "\/" with shash "/". Unescape slashes. //System.out.println("SEND: "+text); fireSent(text); LOG.log(Level.FINE, "SEND: {0}", text); byte[] bytes = text.getBytes(CHAR_SET); String contentLength = CONTENT_LENGTH_STR+bytes.length + EOL_STR + EOL_STR; synchronized (outLock) { if (clientOut == null) { throw new IOException("No client connection is opened."); } clientOut.write(contentLength.getBytes(CHAR_SET)); clientOut.write(bytes); } } public boolean isConnected() { return currentSocket != null && clientOut != null; } /** * Close the currently established client-server connection, if any. * The {@link #runConnectionLoop(java.util.Map, org.netbeans.lib.v8debug.connection.ServerConnection.Listener)} * can then be executed again to accept another client connection. * @throws IOException thrown when an IO problem occurs. */ public void closeCurrentConnection() throws IOException { if (currentSocket != null) { currentSocket.close(); currentSocket = null; } } /** * Close the server connection. Stop accepting incoming connections. * @throws IOException thrown when an IO problem occurs. */ public void closeServer() throws IOException { if (server != null) { server.close(); } fireClosed(); } /** * Add an I/O listener to monitor the debugger communication. * @param iol an IOListener */ public void addIOListener(IOListener iol) { ioListeners.add(iol); } /** * Remove an I/O listener monitoring the communication. * @param iol an IOListener */ public void removeIOListener(IOListener iol) { ioListeners.remove(iol); } private void fireSent(String str) { for (IOListener iol : ioListeners) { iol.sent(str); } } private void fireReceived(String str) { for (IOListener iol : ioListeners) { iol.received(str); } } private void fireClosed() { for (IOListener iol : ioListeners) { iol.closed(); } } /** * Listener receiving debugger events. */ public interface Listener { /** * Called when a request is received. The implementation should compose * a response and provide it either synchronously or asynchronously via * the returned {@link ResponseProvider}. * @param request The received request. * @return The response provider allowing either synchronous or asynchronous response. */ ResponseProvider request(V8Request request); } /** * Debugger response provider. Allows synchronous or asynchronous responses. * Create the response by calling * {@link V8Request#createSuccessResponse(long, org.netbeans.lib.v8debug.V8Body, org.netbeans.lib.v8debug.vars.ReferencedValue[], boolean)} * or {@link V8Request#createErrorResponse(long, boolean, java.lang.String)}. */ public static final class ResponseProvider { private V8Response response; private ServerConnection sc; private ResponseProvider(V8Response response) { this.response = response; } /** * Create a synchronous response to a debugger request. * @param response The response. * Use {@link V8Request#createSuccessResponse(long, org.netbeans.lib.v8debug.V8Body, org.netbeans.lib.v8debug.vars.ReferencedValue[], boolean)} * or {@link V8Request#createErrorResponse(long, boolean, java.lang.String)} * to create the response. * @return A synchronous response provider. */ public static ResponseProvider create(V8Response response) { return new ResponseProvider(response); } /** * Create an ampty asynchronous response provider. * @return an asynchronous response, call * {@link #setResponse(org.netbeans.lib.v8debug.V8Response)} on the * returned object to set the response asynchronously. */ public static ResponseProvider createLazy() { return new ResponseProvider(null); } /** * Set the asynchronous response. * @param response The response. * Use {@link V8Request#createSuccessResponse(long, org.netbeans.lib.v8debug.V8Body, org.netbeans.lib.v8debug.vars.ReferencedValue[], boolean)} * or {@link V8Request#createErrorResponse(long, boolean, java.lang.String)} * to create the response. * @throws IOException thrown when an IO problem occurs. */ public void setResponse(V8Response response) throws IOException { ServerConnection sc; synchronized (this) { if (this.response != null) { throw new IllegalStateException("Response has been set already."); } this.response = response; sc = this.sc; } if (sc != null) { sc.send(response); } } void sendTo(ServerConnection sc) throws IOException { V8Response response; synchronized (this) { response = this.response; this.sc = sc; } if (response != null) { sc.send(response); } } } }
6,590
346
{ "pip": [ "https://s3-us-west-2.amazonaws.com/cassandra-framework-dev/testing/dcos-cassandra-0.1.0.tar.gz" ] }
62
348
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000 {"nom":"Salindres","circ":"4ème circonscription","dpt":"Gard","inscrits":2639,"abs":1629,"votants":1010,"blancs":80,"nuls":45,"exp":885,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":451},{"nuance":"FN","nom":"Mme <NAME>","voix":434}]}
122
358
<reponame>AirGuanZ/Atrc #include <QLabel> #include <QLineEdit> #include <agz/editor/geometry/sphere.h> #include <agz/tracer/create/geometry.h> AGZ_EDITOR_BEGIN SphereWidget::SphereWidget(const CloneState &clone_state) { QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(new QLabel("Radius", this)); radius_edit_validator_ = newBox<QDoubleValidator>(); radius_edit_ = new QLineEdit(this); radius_edit_->setText(QString::number(clone_state.radius)); radius_edit_->setValidator(radius_edit_validator_.get()); radius_edit_->setAlignment(Qt::AlignCenter); layout->addWidget(radius_edit_); setContentsMargins(0, 0, 0, 0); layout->setContentsMargins(0, 0, 0, 0); connect(radius_edit_, &QLineEdit::returnPressed, [=] { set_geometry_vertices_dirty(); set_dirty_flag(); }); do_update_tracer_object(); } ResourceWidget<tracer::Geometry> *SphereWidget::clone() { CloneState clone_state; clone_state.radius = radius_edit_->text().toFloat(); return new SphereWidget(clone_state); } void SphereWidget::save_asset(AssetSaver &saver) { saver.write(real(radius_edit_->text().toFloat())); } void SphereWidget::load_asset(AssetLoader &loader) { radius_edit_->setText(QString::number(loader.read<real>())); do_update_tracer_object(); } RC<tracer::ConfigNode> SphereWidget::to_config(JSONExportContext &ctx) const { auto grp = newRC<tracer::ConfigGroup>(); grp->insert_str("type", "sphere"); grp->insert_real("radius", radius_edit_->text().toFloat()); grp->insert_child("transform", newRC<tracer::ConfigArray>()); return grp; } std::vector<EntityInterface::Vertex> SphereWidget::get_vertices() const { static const auto UNIT_VERTICES = unit_vertices(); auto ret = UNIT_VERTICES; for(auto &v : ret) v.pos *= radius_edit_->text().toFloat(); return ret; } void SphereWidget::update_tracer_object_impl() { do_update_tracer_object(); } void SphereWidget::do_update_tracer_object() { const real radius = radius_edit_->text().toFloat(); tracer_object_ = tracer::create_sphere(radius, {}); } ResourceWidget<tracer::Geometry> *SphereWidgetCreator::create_widget( ObjectContext &obj_ctx) const { return new SphereWidget({}); } std::vector<EntityInterface::Vertex> SphereWidget::unit_vertices() { std::vector<Vertex> ret; constexpr int X_GRID_COUNT = 32; constexpr int Y_GRID_COUNT = 32; const real DELTA_X_RAD = 2 * PI_r / X_GRID_COUNT; const real DELTA_Y_RAD = PI_r / Y_GRID_COUNT; auto rad_to_pos = [](real x_rad, real y_rad) { return Vec3{ std::cos(y_rad) * std::cos(x_rad), std::cos(y_rad) * std::sin(x_rad), std::sin(y_rad) }; }; auto add_pos = [&](const Vec3 &pos) { ret.push_back({ pos, pos.normalize() }); }; real y_rad = -PI_r / 2 + DELTA_Y_RAD; real x_rad = 0; for(int xi = 0; xi < X_GRID_COUNT; ++xi) { const real next_x_rad = x_rad + DELTA_X_RAD; add_pos({ 0, 0, -1 }); add_pos(rad_to_pos(x_rad, y_rad)); add_pos(rad_to_pos(next_x_rad, y_rad)); x_rad = next_x_rad; } for(int yi = 1; yi < Y_GRID_COUNT - 1; ++yi) { const real next_y_rad = y_rad + DELTA_Y_RAD; x_rad = 0; for(int xi = 0; xi < X_GRID_COUNT; ++xi) { const real next_x_rad = x_rad + DELTA_X_RAD; const Vec3 lb = rad_to_pos(x_rad, y_rad); const Vec3 rb = rad_to_pos(next_x_rad, y_rad); const Vec3 lt = rad_to_pos(x_rad, next_y_rad); const Vec3 rt = rad_to_pos(next_x_rad, next_y_rad); add_pos(lb); add_pos(lt); add_pos(rt); add_pos(lb); add_pos(rt); add_pos(rb); x_rad = next_x_rad; } y_rad = next_y_rad; } x_rad = 0; for(int xi = 0; xi < X_GRID_COUNT; ++xi) { const real next_x_rad = x_rad + DELTA_X_RAD; add_pos(rad_to_pos(x_rad, y_rad)); add_pos({ 0, 0, 1 }); add_pos(rad_to_pos(next_x_rad, y_rad)); x_rad = next_x_rad; } return ret; } AGZ_EDITOR_END
1,950
38,667
<reponame>Istiakmorsalin/ML-Data-Science """ colorLib.table_builder: Generic helper for filling in BaseTable derivatives from tuples and maps and such. """ import collections import enum from fontTools.ttLib.tables.otBase import ( BaseTable, FormatSwitchingBaseTable, UInt8FormatSwitchingBaseTable, ) from fontTools.ttLib.tables.otConverters import ( ComputedInt, SimpleValue, Struct, Short, UInt8, UShort, VarInt16, VarUInt16, IntValue, FloatValue, ) from fontTools.misc.roundTools import otRound class BuildCallback(enum.Enum): """Keyed on (BEFORE_BUILD, class[, Format if available]). Receives (dest, source). Should return (dest, source), which can be new objects. """ BEFORE_BUILD = enum.auto() """Keyed on (AFTER_BUILD, class[, Format if available]). Receives (dest). Should return dest, which can be a new object. """ AFTER_BUILD = enum.auto() """Keyed on (CREATE_DEFAULT, class). Receives no arguments. Should return a new instance of class. """ CREATE_DEFAULT = enum.auto() def _assignable(convertersByName): return {k: v for k, v in convertersByName.items() if not isinstance(v, ComputedInt)} def convertTupleClass(tupleClass, value): if isinstance(value, tupleClass): return value if isinstance(value, tuple): return tupleClass(*value) return tupleClass(value) def _isNonStrSequence(value): return isinstance(value, collections.abc.Sequence) and not isinstance(value, str) def _set_format(dest, source): if _isNonStrSequence(source): assert len(source) > 0, f"{type(dest)} needs at least format from {source}" dest.Format = source[0] source = source[1:] elif isinstance(source, collections.abc.Mapping): assert "Format" in source, f"{type(dest)} needs at least Format from {source}" dest.Format = source["Format"] else: raise ValueError(f"Not sure how to populate {type(dest)} from {source}") assert isinstance( dest.Format, collections.abc.Hashable ), f"{type(dest)} Format is not hashable: {dest.Format}" assert ( dest.Format in dest.convertersByName ), f"{dest.Format} invalid Format of {cls}" return source class TableBuilder: """ Helps to populate things derived from BaseTable from maps, tuples, etc. A table of lifecycle callbacks may be provided to add logic beyond what is possible based on otData info for the target class. See BuildCallbacks. """ def __init__(self, callbackTable=None): if callbackTable is None: callbackTable = {} self._callbackTable = callbackTable def _convert(self, dest, field, converter, value): tupleClass = getattr(converter, "tupleClass", None) enumClass = getattr(converter, "enumClass", None) if tupleClass: value = convertTupleClass(tupleClass, value) elif enumClass: if isinstance(value, enumClass): pass elif isinstance(value, str): try: value = getattr(enumClass, value.upper()) except AttributeError: raise ValueError(f"{value} is not a valid {enumClass}") else: value = enumClass(value) elif isinstance(converter, IntValue): value = otRound(value) elif isinstance(converter, FloatValue): value = float(value) elif isinstance(converter, Struct): if converter.repeat: if _isNonStrSequence(value): value = [self.build(converter.tableClass, v) for v in value] else: value = [self.build(converter.tableClass, value)] setattr(dest, converter.repeat, len(value)) else: value = self.build(converter.tableClass, value) elif callable(converter): value = converter(value) setattr(dest, field, value) def build(self, cls, source): assert issubclass(cls, BaseTable) if isinstance(source, cls): return source callbackKey = (cls,) dest = self._callbackTable.get( (BuildCallback.CREATE_DEFAULT,) + callbackKey, lambda: cls() )() assert isinstance(dest, cls) convByName = _assignable(cls.convertersByName) skippedFields = set() # For format switchers we need to resolve converters based on format if issubclass(cls, FormatSwitchingBaseTable): source = _set_format(dest, source) convByName = _assignable(convByName[dest.Format]) skippedFields.add("Format") callbackKey = (cls, dest.Format) # Convert sequence => mapping so before thunk only has to handle one format if _isNonStrSequence(source): # Sequence (typically list or tuple) assumed to match fields in declaration order assert len(source) <= len( convByName ), f"Sequence of {len(source)} too long for {cls}; expected <= {len(convByName)} values" source = dict(zip(convByName.keys(), source)) dest, source = self._callbackTable.get( (BuildCallback.BEFORE_BUILD,) + callbackKey, lambda d, s: (d, s) )(dest, source) if isinstance(source, collections.abc.Mapping): for field, value in source.items(): if field in skippedFields: continue converter = convByName.get(field, None) if not converter: raise ValueError( f"Unrecognized field {field} for {cls}; expected one of {sorted(convByName.keys())}" ) self._convert(dest, field, converter, value) else: # let's try as a 1-tuple dest = self.build(cls, (source,)) dest = self._callbackTable.get( (BuildCallback.AFTER_BUILD,) + callbackKey, lambda d: d )(dest) return dest class TableUnbuilder: def __init__(self, callbackTable=None): if callbackTable is None: callbackTable = {} self._callbackTable = callbackTable def unbuild(self, table): assert isinstance(table, BaseTable) source = {} callbackKey = (type(table),) if isinstance(table, FormatSwitchingBaseTable): source["Format"] = int(table.Format) callbackKey += (table.Format,) for converter in table.getConverters(): if isinstance(converter, ComputedInt): continue value = getattr(table, converter.name) tupleClass = getattr(converter, "tupleClass", None) enumClass = getattr(converter, "enumClass", None) if tupleClass: source[converter.name] = tuple(value) elif enumClass: source[converter.name] = value.name.lower() elif isinstance(converter, Struct): if converter.repeat: source[converter.name] = [self.unbuild(v) for v in value] else: source[converter.name] = self.unbuild(value) elif isinstance(converter, SimpleValue): # "simple" values (e.g. int, float, str) need no further un-building source[converter.name] = value else: raise NotImplementedError( "Don't know how unbuild {value!r} with {converter!r}" ) source = self._callbackTable.get(callbackKey, lambda s: s)(source) return source
3,411