blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f1773c963885d4441078ecd272b25852fadd28ec | 0e44257aa418a506b1bb2f76c715e403cb893f13 | /NWNXLib/API/Mac/API/Task__CExoTaskThread__LinkGroup__TemplatedlambdaOpenParenTask__CExoTaskGroupPtrTask__CExoTaskGroupPtrCloseParen.hpp | 72924ddc4dabfb68db85cf5972135db470b58d56 | [
"MIT"
] | permissive | Silvard/nwnxee | 58bdfa023348edcc88f9d3cfd9ff77fdd6194058 | 0989acb86e4d2b2bdcf25f6eabc16df7a72fb315 | refs/heads/master | 2020-04-15T22:04:43.925619 | 2019-10-10T14:18:53 | 2019-10-10T14:18:53 | 165,058,523 | 0 | 0 | MIT | 2019-10-10T14:18:57 | 2019-01-10T12:44:36 | C++ | UTF-8 | C++ | false | false | 202 | hpp | #pragma once
#include <cstdint>
namespace NWNXLib {
namespace API {
struct Task__CExoTaskThread__LinkGroup__TemplatedlambdaOpenParenTask__CExoTaskGroupPtrTask__CExoTaskGroupPtrCloseParen
{
};
}
}
| [
"[email protected]"
] | |
bccd70ca6687930af868ddfe643ac29a87c74c8c | b7e97047616d9343be5b9bbe03fc0d79ba5a6143 | /src/protocols/simple_moves/FavorSequenceProfileCreator.hh | 7a68c3716e209b886ba742141852442bc3ddd387 | [] | no_license | achitturi/ROSETTA-main-source | 2772623a78e33e7883a453f051d53ea6cc53ffa5 | fe11c7e7cb68644f404f4c0629b64da4bb73b8f9 | refs/heads/master | 2021-05-09T15:04:34.006421 | 2018-01-26T17:10:33 | 2018-01-26T17:10:33 | 119,081,547 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,402 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: [email protected].
/// @file protocols/simple_moves/FavorSequenceProfileCreator.hh
/// @brief Declaration of the protocols::moves::MoverCreator class for the FavorSequenceProfile
#ifndef INCLUDED_protocols_simple_moves_FavorSequenceProfileCreator_hh
#define INCLUDED_protocols_simple_moves_FavorSequenceProfileCreator_hh
// Project headers
#include <protocols/moves/MoverCreator.hh>
namespace protocols {
namespace simple_moves {
class FavorSequenceProfileCreator : public moves::MoverCreator
{
public:
// XRW TEMP moves::MoverOP create_mover() const override;
// XRW TEMP std::string keyname() const override;
// XRW TEMP static std::string mover_name();
protocols::moves::MoverOP create_mover() const override;
std::string keyname() const override;
void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ) const override;
};
} //moves
} //protocols
#endif
| [
"[email protected]"
] | |
b2b3f27f9a770050d95c5dcd4caff6560e49a9dc | 75082d692d5e2b08a04700d55d50f5afa52255a4 | /tests/lib/googletest/src/gtest-internal-inl.h | 9c1bdef712e773d6097845dd2e60507053bad897 | [
"BSD-3-Clause"
] | permissive | dvshapkin/transcat2 | c92942d7f7286bf88eca63d6ce6d4897b285f5fa | 10a808b646f88252b02a2a2dbb20ea0e65243e91 | refs/heads/master | 2023-07-03T17:06:11.754964 | 2021-08-10T09:30:52 | 2021-08-10T09:30:52 | 392,998,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,373 | h | // Copyright 2005, 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:
//
// * 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.
// Utility functions and classes used by the Google C++ testing framework.//
// This file contains purely Google Test's internal implementation. Please
// DO NOT #INCLUDE IT IN A USER PROGRAM.
#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
#ifndef _WIN32_WCE
# include <errno.h>
#endif // !_WIN32_WCE
#include <stddef.h>
#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
#include <string.h> // For memmove.
#include <algorithm>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "gtest/internal/gtest-port.h"
#if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT
#endif
#if GTEST_OS_WINDOWS
# include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
namespace testing {
// Declares the flags.
//
// We don't want the users to modify this flag in the code, but want
// Google Test's own unit tests to be able to access it. Therefore we
// declare it here as opposed to in gtest.h.
GTEST_DECLARE_bool_(death_test_use_fork);
namespace internal {
// The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId().
GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
// Names of the flags (needed for parsing Google Test flags).
const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
const char kBreakOnFailureFlag[] = "break_on_failure";
const char kCatchExceptionsFlag[] = "catch_exceptions";
const char kColorFlag[] = "color";
const char kFailFast[] = "fail_fast";
const char kFilterFlag[] = "filter";
const char kListTestsFlag[] = "list_tests";
const char kOutputFlag[] = "output";
const char kBriefFlag[] = "brief";
const char kPrintTimeFlag[] = "print_time";
const char kPrintUTF8Flag[] = "print_utf8";
const char kRandomSeedFlag[] = "random_seed";
const char kRepeatFlag[] = "repeat";
const char kShuffleFlag[] = "shuffle";
const char kStackTraceDepthFlag[] = "stack_trace_depth";
const char kStreamResultToFlag[] = "stream_result_to";
const char kThrowOnFailureFlag[] = "throw_on_failure";
const char kFlagfileFlag[] = "flagfile";
// A valid random seed must be in [1, kMaxRandomSeed].
const int kMaxRandomSeed = 99999;
// g_help_flag is true if and only if the --help flag or an equivalent form
// is specified on the command line.
GTEST_API_ extern bool g_help_flag;
// Returns the current time in milliseconds.
GTEST_API_ TimeInMillis GetTimeInMillis();
// Returns true if and only if Google Test should use colors in the output.
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
// Formats the given time in milliseconds as seconds.
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
// Converts the given time in milliseconds to a date string in the ISO 8601
// format, without the timezone information. N.B.: due to the use the
// non-reentrant localtime() function, this function is not thread safe. Do
// not use it in any code that can be called from multiple threads.
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
// Parses a string for an Int32 flag, in the form of "--flag=value".
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
GTEST_API_ bool ParseInt32Flag(
const char* str, const char* flag, int32_t* value);
// Returns a random seed in range [1, kMaxRandomSeed] based on the
// given --gtest_random_seed flag value.
inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
const unsigned int raw_seed = (random_seed_flag == 0) ?
static_cast<unsigned int>(GetTimeInMillis()) :
static_cast<unsigned int>(random_seed_flag);
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that
// it's easy to type.
const int normalized_seed =
static_cast<int>((raw_seed - 1U) %
static_cast<unsigned int>(kMaxRandomSeed)) + 1;
return normalized_seed;
}
// Returns the first valid random seed after 'seed'. The behavior is
// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
// considered to be 1.
inline int GetNextRandomSeed(int seed) {
GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
<< "Invalid random seed " << seed << " - must be in [1, "
<< kMaxRandomSeed << "].";
const int next_seed = seed + 1;
return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
}
// This class saves the values of all Google Test flags in its c'tor, and
// restores them in its d'tor.
class GTestFlagSaver {
public:
// The c'tor.
GTestFlagSaver() {
also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
break_on_failure_ = GTEST_FLAG(break_on_failure);
catch_exceptions_ = GTEST_FLAG(catch_exceptions);
color_ = GTEST_FLAG(color);
death_test_style_ = GTEST_FLAG(death_test_style);
death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
fail_fast_ = GTEST_FLAG(fail_fast);
filter_ = GTEST_FLAG(filter);
internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
list_tests_ = GTEST_FLAG(list_tests);
output_ = GTEST_FLAG(output);
brief_ = GTEST_FLAG(brief);
print_time_ = GTEST_FLAG(print_time);
print_utf8_ = GTEST_FLAG(print_utf8);
random_seed_ = GTEST_FLAG(random_seed);
repeat_ = GTEST_FLAG(repeat);
shuffle_ = GTEST_FLAG(shuffle);
stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
stream_result_to_ = GTEST_FLAG(stream_result_to);
throw_on_failure_ = GTEST_FLAG(throw_on_failure);
}
// The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver() {
GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
GTEST_FLAG(break_on_failure) = break_on_failure_;
GTEST_FLAG(catch_exceptions) = catch_exceptions_;
GTEST_FLAG(color) = color_;
GTEST_FLAG(death_test_style) = death_test_style_;
GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
GTEST_FLAG(filter) = filter_;
GTEST_FLAG(fail_fast) = fail_fast_;
GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
GTEST_FLAG(list_tests) = list_tests_;
GTEST_FLAG(output) = output_;
GTEST_FLAG(brief) = brief_;
GTEST_FLAG(print_time) = print_time_;
GTEST_FLAG(print_utf8) = print_utf8_;
GTEST_FLAG(random_seed) = random_seed_;
GTEST_FLAG(repeat) = repeat_;
GTEST_FLAG(shuffle) = shuffle_;
GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
GTEST_FLAG(stream_result_to) = stream_result_to_;
GTEST_FLAG(throw_on_failure) = throw_on_failure_;
}
private:
// Fields for saving the original values of flags.
bool also_run_disabled_tests_;
bool break_on_failure_;
bool catch_exceptions_;
std::string color_;
std::string death_test_style_;
bool death_test_use_fork_;
bool fail_fast_;
std::string filter_;
std::string internal_run_death_test_;
bool list_tests_;
std::string output_;
bool brief_;
bool print_time_;
bool print_utf8_;
int32_t random_seed_;
int32_t repeat_;
bool shuffle_;
int32_t stack_trace_depth_;
std::string stream_result_to_;
bool throw_on_failure_;
} GTEST_ATTRIBUTE_UNUSED_;
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
// wide enough to contain a code point.
// If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// to "(Invalid Unicode 0xXXXXXXXX)".
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
// Converts a wide string to a narrow string in UTF-8 encoding.
// The wide string is assumed to have the following encoding:
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
// Parameter str points to a null-terminated wide string.
// Parameter num_chars may additionally limit the number
// of wchar_t characters processed. -1 is used when the entire string
// should be processed.
// If the string contains code points that are not valid Unicode code points
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane.
GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this
// function will write over it. If the variable is present, but the file cannot
// be created, prints an error and exits.
void WriteToShardStatusFileIfNeeded();
// Checks whether sharding is enabled by examining the relevant
// environment variable values. If the variables are present,
// but inconsistent (e.g., shard_index >= total_shards), prints
// an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute.
GTEST_API_ bool ShouldShard(const char* total_shards_str,
const char* shard_index_str,
bool in_subprocess_for_death_test);
// Parses the environment variable var as a 32-bit integer. If it is unset,
// returns default_val. If it is not a 32-bit integer, prints an error and
// and aborts.
GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
// Given the total number of shards, the shard index, and the test id,
// returns true if and only if the test should be run on this shard. The test id
// is some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards.
GTEST_API_ bool ShouldRunTestOnShard(
int total_shards, int shard_index, int test_id);
// STL container utilities.
// Returns the number of elements in the given container that satisfy
// the given predicate.
template <class Container, typename Predicate>
inline int CountIf(const Container& c, Predicate predicate) {
// Implemented as an explicit loop since std::count_if() in libCstd on
// Solaris has a non-standard signature.
int count = 0;
for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
if (predicate(*it))
++count;
}
return count;
}
// Applies a function/functor to each element in the container.
template <class Container, typename Functor>
void ForEach(const Container& c, Functor functor) {
std::for_each(c.begin(), c.end(), functor);
}
// Returns the i-th element of the vector, or default_value if i is not
// in range [0, v.size()).
template <typename E>
inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
: v[static_cast<size_t>(i)];
}
// Performs an in-place shuffle of a range of the vector's elements.
// 'begin' and 'end' are element indices as an STL-style range;
// i.e. [begin, end) are shuffled, where 'end' == size() means to
// shuffle to the end of the vector.
template <typename E>
void ShuffleRange(internal::Random* random, int begin, int end,
std::vector<E>* v) {
const int size = static_cast<int>(v->size());
GTEST_CHECK_(0 <= begin && begin <= size)
<< "Invalid shuffle range start " << begin << ": must be in range [0, "
<< size << "].";
GTEST_CHECK_(begin <= end && end <= size)
<< "Invalid shuffle range finish " << end << ": must be in range ["
<< begin << ", " << size << "].";
// Fisher-Yates shuffle, from
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
for (int range_width = end - begin; range_width >= 2; range_width--) {
const int last_in_range = begin + range_width - 1;
const int selected =
begin +
static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
std::swap((*v)[static_cast<size_t>(selected)],
(*v)[static_cast<size_t>(last_in_range)]);
}
}
// Performs an in-place shuffle of the vector's elements.
template <typename E>
inline void Shuffle(internal::Random* random, std::vector<E>* v) {
ShuffleRange(random, 0, static_cast<int>(v->size()), v);
}
// A function for deleting an object. Handy for being used as a
// functor.
template <typename T>
static void Delete(T* x) {
delete x;
}
// A predicate that checks the key of a TestProperty against a known key.
//
// TestPropertyKeyIs is copyable.
class TestPropertyKeyIs {
public:
// Constructor.
//
// TestPropertyKeyIs has NO default constructor.
explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
// Returns true if and only if the test name of test property matches on key_.
bool operator()(const TestProperty& test_property) const {
return test_property.key() == key_;
}
private:
std::string key_;
};
// Class UnitTestOptions.
//
// This class contains functions for processing options the user
// specifies when running the tests. It has only static members.
//
// In most cases, the user can specify an option using either an
// environment variable or a command line flag. E.g. you can set the
// test filter using either GTEST_FILTER or --gtest_filter. If both
// the variable and the flag are present, the latter overrides the
// former.
class GTEST_API_ UnitTestOptions {
public:
// Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output.
static std::string GetOutputFormat();
// Returns the absolute path of the requested output file, or the
// default (test_detail.xml in the original working directory) if
// none was explicitly specified.
static std::string GetAbsolutePathToOutputFile();
// Functions for processing the gtest_filter flag.
// Returns true if and only if the user-specified filter matches the test
// suite name and the test name.
static bool FilterMatchesTest(const std::string& test_suite_name,
const std::string& test_name);
#if GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag.
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
static int GTestShouldProcessSEH(DWORD exception_code);
#endif // GTEST_OS_WINDOWS
// Returns true if "name" matches the ':' separated list of glob-style
// filters in "filter".
static bool MatchesFilter(const std::string& name, const char* filter);
};
// Returns the current application's name, removing directory path if that
// is present. Used by UnitTestOptions::GetOutputFile.
GTEST_API_ FilePath GetCurrentExecutableName();
// The role interface for getting the OS stack trace as a string.
class OsStackTraceGetterInterface {
public:
OsStackTraceGetterInterface() {}
virtual ~OsStackTraceGetterInterface() {}
// Returns the current OS stack trace as an std::string. Parameters:
//
// max_depth - the maximum number of stack frames to be included
// in the trace.
// skip_count - the number of Top frames to be skipped; doesn't count
// against max_depth.
virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
// UponLeavingGTest() should be called immediately before Google Test calls
// user code. It saves some information about the current stack that
// CurrentStackTrace() will use to find and hide Google Test stack frames.
virtual void UponLeavingGTest() = 0;
// This string is inserted in place of stack frames that are part of
// Google Test's implementation.
static const char* const kElidedFramesMarker;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
};
// A working implementation of the OsStackTraceGetterInterface interface.
class OsStackTraceGetter : public OsStackTraceGetterInterface {
public:
OsStackTraceGetter() {}
std::string CurrentStackTrace(int max_depth, int skip_count) override;
void UponLeavingGTest() override;
private:
#if GTEST_HAS_ABSL
Mutex mutex_; // Protects all internal state.
// We save the stack frame below the frame that calls user code.
// We do this because the address of the frame immediately below
// the user code changes between the call to UponLeavingGTest()
// and any calls to the stack trace code from within the user code.
void* caller_frame_ = nullptr;
#endif // GTEST_HAS_ABSL
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
};
// Information about a Google Test trace point.
struct TraceInfo {
const char* file;
int line;
std::string message;
};
// This is the default global test part result reporter used in UnitTestImpl.
// This class should only be used by UnitTestImpl.
class DefaultGlobalTestPartResultReporter
: public TestPartResultReporterInterface {
public:
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. Reports the test part
// result in the current test.
void ReportTestPartResult(const TestPartResult& result) override;
private:
UnitTestImpl* const unit_test_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
};
// This is the default per thread test part result reporter used in
// UnitTestImpl. This class should only be used by UnitTestImpl.
class DefaultPerThreadTestPartResultReporter
: public TestPartResultReporterInterface {
public:
explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. The implementation just
// delegates to the current global test part result reporter of *unit_test_.
void ReportTestPartResult(const TestPartResult& result) override;
private:
UnitTestImpl* const unit_test_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
};
// The private implementation of the UnitTest class. We don't protect
// the methods under a mutex, as this class is not accessible by a
// user and the UnitTest class that delegates work to this class does
// proper locking.
class GTEST_API_ UnitTestImpl {
public:
explicit UnitTestImpl(UnitTest* parent);
virtual ~UnitTestImpl();
// There are two different ways to register your own TestPartResultReporter.
// You can register your own repoter to listen either only for test results
// from the current thread or for results from all threads.
// By default, each per-thread test result repoter just passes a new
// TestPartResult to the global test result reporter, which registers the
// test part result for the currently running test.
// Returns the global test part result reporter.
TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
// Sets the global test part result reporter.
void SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter);
// Returns the test part result reporter for the current thread.
TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
// Sets the test part result reporter for the current thread.
void SetTestPartResultReporterForCurrentThread(
TestPartResultReporterInterface* reporter);
// Gets the number of successful test suites.
int successful_test_suite_count() const;
// Gets the number of failed test suites.
int failed_test_suite_count() const;
// Gets the number of all test suites.
int total_test_suite_count() const;
// Gets the number of all test suites that contain at least one test
// that should run.
int test_suite_to_run_count() const;
// Gets the number of successful tests.
int successful_test_count() const;
// Gets the number of skipped tests.
int skipped_test_count() const;
// Gets the number of failed tests.
int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
// Gets the number of disabled tests.
int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
// Gets the number of all tests.
int total_test_count() const;
// Gets the number of tests that should run.
int test_to_run_count() const;
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const { return start_timestamp_; }
// Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
// Returns true if and only if the unit test passed (i.e. all test suites
// passed).
bool Passed() const { return !Failed(); }
// Returns true if and only if the unit test failed (i.e. some test suite
// failed or something outside of all tests failed).
bool Failed() const {
return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
}
// Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
const TestSuite* GetTestSuite(int i) const {
const int index = GetElementOr(test_suite_indices_, i, -1);
return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
TestSuite* GetMutableSuiteCase(int i) {
const int index = GetElementOr(test_suite_indices_, i, -1);
return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
}
// Provides access to the event listener list.
TestEventListeners* listeners() { return &listeners_; }
// Returns the TestResult for the test that's currently running, or
// the TestResult for the ad hoc test if no test is running.
TestResult* current_test_result();
// Returns the TestResult for the ad hoc test.
const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
// Sets the OS stack trace getter.
//
// Does nothing if the input and the current OS stack trace getter
// are the same; otherwise, deletes the old getter and makes the
// input the current getter.
void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
// Returns the current OS stack trace getter if it is not NULL;
// otherwise, creates an OsStackTraceGetter, makes it the current
// getter, and returns it.
OsStackTraceGetterInterface* os_stack_trace_getter();
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter
// specifies the number of Top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
// Finds and returns a TestSuite with the given name. If one doesn't
// exist, creates one and returns it.
//
// Arguments:
//
// test_suite_name: name of the test suite
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc);
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
TestCase* GetTestCase(const char* test_case_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc) {
return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Adds a TestInfo to the unit test.
//
// Arguments:
//
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
// test_info: the TestInfo object
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
TestInfo* test_info) {
#if GTEST_HAS_DEATH_TEST
// In order to support thread-safe death tests, we need to
// remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
// the user may have changed the current directory before calling
// RUN_ALL_TESTS(). Therefore we capture the current directory in
// AddTestInfo(), which is called to register a TEST or TEST_F
// before main() is reached.
if (original_working_dir_.IsEmpty()) {
original_working_dir_.Set(FilePath::GetCurrentDir());
GTEST_CHECK_(!original_working_dir_.IsEmpty())
<< "Failed to get the current working directory.";
}
#endif // GTEST_HAS_DEATH_TEST
GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
set_up_tc, tear_down_tc)
->AddTestInfo(test_info);
}
// Returns ParameterizedTestSuiteRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
return parameterized_test_registry_;
}
std::set<std::string>* ignored_parameterized_test_suites() {
return &ignored_parameterized_test_suites_;
}
// Returns TypeParameterizedTestSuiteRegistry object used to keep track of
// type-parameterized tests and instantiations of them.
internal::TypeParameterizedTestSuiteRegistry&
type_parameterized_test_registry() {
return type_parameterized_test_registry_;
}
// Sets the TestSuite object for the test that's currently running.
void set_current_test_suite(TestSuite* a_current_test_suite) {
current_test_suite_ = a_current_test_suite;
}
// Sets the TestInfo object for the test that's currently running. If
// current_test_info is NULL, the assertion results will be stored in
// ad_hoc_test_result_.
void set_current_test_info(TestInfo* a_current_test_info) {
current_test_info_ = a_current_test_info;
}
// Registers all parameterized tests defined using TEST_P and
// INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
// combination. This method can be called more then once; it has guards
// protecting from registering the tests more then once. If
// value-parameterized tests are disabled, RegisterParameterizedTests is
// present but does nothing.
void RegisterParameterizedTests();
// Runs all tests in this UnitTest object, prints the result, and
// returns true if all tests are successful. If any exception is
// thrown during a test, this test is considered to be failed, but
// the rest of the tests will still be run.
bool RunAllTests();
// Clears the results of all tests, except the ad hoc tests.
void ClearNonAdHocTestResult() {
ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
}
// Clears the results of ad-hoc test assertions.
void ClearAdHocTestResult() {
ad_hoc_test_result_.Clear();
}
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test or a test suite, or to the global property set. If the
// result already contains a property with the same key, the value will be
// updated.
void RecordProperty(const TestProperty& test_property);
enum ReactionToSharding {
HONOR_SHARDING_PROTOCOL,
IGNORE_SHARDING_PROTOCOL
};
// Matches the full name of each test against the user-specified
// filter to decide whether the test should run, then records the
// result in each TestSuite and TestInfo object.
// If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
// based on sharding variables in the environment.
// Returns the number of tests that should run.
int FilterTests(ReactionToSharding shard_tests);
// Prints the names of the tests matching the user-specified filter flag.
void ListTestsMatchingFilter();
const TestSuite* current_test_suite() const { return current_test_suite_; }
TestInfo* current_test_info() { return current_test_info_; }
const TestInfo* current_test_info() const { return current_test_info_; }
// Returns the vector of environments that need to be set-up/torn-down
// before/after the tests are run.
std::vector<Environment*>& environments() { return environments_; }
// Getters for the per-thread Google Test trace stack.
std::vector<TraceInfo>& gtest_trace_stack() {
return *(gtest_trace_stack_.pointer());
}
const std::vector<TraceInfo>& gtest_trace_stack() const {
return gtest_trace_stack_.get();
}
#if GTEST_HAS_DEATH_TEST
void InitDeathTestSubprocessControlInfo() {
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
}
// Returns a pointer to the parsed --gtest_internal_run_death_test
// flag, or NULL if that flag was not specified.
// This information is useful only in a death test child process.
// Must not be called before a call to InitGoogleTest.
const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
return internal_run_death_test_flag_.get();
}
// Returns a pointer to the current death test factory.
internal::DeathTestFactory* death_test_factory() {
return death_test_factory_.get();
}
void SuppressTestEventsIfInSubprocess();
friend class ReplaceDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
// Initializes the event listener performing XML output as specified by
// UnitTestOptions. Must not be called before InitGoogleTest.
void ConfigureXmlOutput();
#if GTEST_CAN_STREAM_RESULTS_
// Initializes the event listener for streaming test results to a socket.
// Must not be called before InitGoogleTest.
void ConfigureStreamingOutput();
#endif
// Performs initialization dependent upon flag values obtained in
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
// this function is also called from RunAllTests. Since this function can be
// called more than once, it has to be idempotent.
void PostFlagParsingInit();
// Gets the random seed used at the start of the current test iteration.
int random_seed() const { return random_seed_; }
// Gets the random number generator.
internal::Random* random() { return &random_; }
// Shuffles all test suites, and the tests within each test suite,
// making sure that death tests are still run first.
void ShuffleTests();
// Restores the test suites and tests to their order before the first shuffle.
void UnshuffleTests();
// Returns the value of GTEST_FLAG(catch_exceptions) at the moment
// UnitTest::Run() starts.
bool catch_exceptions() const { return catch_exceptions_; }
private:
friend class ::testing::UnitTest;
// Used by UnitTest::Run() to capture the state of
// GTEST_FLAG(catch_exceptions) at the moment it starts.
void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
// The UnitTest object that owns this implementation object.
UnitTest* const parent_;
// The working directory when the first TEST() or TEST_F() was
// executed.
internal::FilePath original_working_dir_;
// The default test part result reporters.
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
DefaultPerThreadTestPartResultReporter
default_per_thread_test_part_result_reporter_;
// Points to (but doesn't own) the global test part result reporter.
TestPartResultReporterInterface* global_test_part_result_repoter_;
// Protects read and write access to global_test_part_result_reporter_.
internal::Mutex global_test_part_result_reporter_mutex_;
// Points to (but doesn't own) the per-thread test part result reporter.
internal::ThreadLocal<TestPartResultReporterInterface*>
per_thread_test_part_result_reporter_;
// The vector of environments that need to be set-up/torn-down
// before/after the tests are run.
std::vector<Environment*> environments_;
// The vector of TestSuites in their original order. It owns the
// elements in the vector.
std::vector<TestSuite*> test_suites_;
// Provides a Level of indirection for the test suite list to allow
// easy shuffling and restoring the test suite order. The i-th
// element of this vector is the index of the i-th test suite in the
// shuffled order.
std::vector<int> test_suite_indices_;
// ParameterizedTestRegistry object used to register value-parameterized
// tests.
internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
internal::TypeParameterizedTestSuiteRegistry
type_parameterized_test_registry_;
// The set holding the name of parameterized
// test suites that may go uninstantiated.
std::set<std::string> ignored_parameterized_test_suites_;
// Indicates whether RegisterParameterizedTests() has been called already.
bool parameterized_tests_registered_;
// Index of the last death test suite registered. Initially -1.
int last_death_test_suite_;
// This points to the TestSuite for the currently running test. It
// changes as Google Test goes through one test suite after another.
// When no test is running, this is set to NULL and Google Test
// stores assertion results in ad_hoc_test_result_. Initially NULL.
TestSuite* current_test_suite_;
// This points to the TestInfo for the currently running test. It
// changes as Google Test goes through one test after another. When
// no test is running, this is set to NULL and Google Test stores
// assertion results in ad_hoc_test_result_. Initially NULL.
TestInfo* current_test_info_;
// Normally, a user only writes assertions inside a TEST or TEST_F,
// or inside a function called by a TEST or TEST_F. Since Google
// Test keeps track of which test is current running, it can
// associate such an assertion with the test it belongs to.
//
// If an assertion is encountered when no TEST or TEST_F is running,
// Google Test attributes the assertion result to an imaginary "ad hoc"
// test, and records the result in ad_hoc_test_result_.
TestResult ad_hoc_test_result_;
// The list of event listeners that can be used to track events inside
// Google Test.
TestEventListeners listeners_;
// The OS stack trace getter. Will be deleted when the UnitTest
// object is destructed. By default, an OsStackTraceGetter is used,
// but the user can set this field to use a custom getter if that is
// desired.
OsStackTraceGetterInterface* os_stack_trace_getter_;
// True if and only if PostFlagParsingInit() has been called.
bool post_flag_parse_init_performed_;
// The random number seed used at the beginning of the test run.
int random_seed_;
// Our random number generator.
internal::Random random_;
// The time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp_;
// How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_;
#if GTEST_HAS_DEATH_TEST
// The decomposed components of the gtest_internal_run_death_test flag,
// parsed when RUN_ALL_TESTS is called.
std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
#endif // GTEST_HAS_DEATH_TEST
// A per-thread stack of traces created by the SCOPED_TRACE() macro.
internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
// The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
// starts.
bool catch_exceptions_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
}; // class UnitTestImpl
// Convenience function for accessing the global UnitTest
// implementation object.
inline UnitTestImpl* GetUnitTestImpl() {
return UnitTest::GetInstance()->impl();
}
#if GTEST_USES_SIMPLE_RE
// Internal helper functions for implementing the simple regular
// expression matcher.
GTEST_API_ bool IsInSet(char ch, const char* str);
GTEST_API_ bool IsAsciiDigit(char ch);
GTEST_API_ bool IsAsciiPunct(char ch);
GTEST_API_ bool IsRepeat(char ch);
GTEST_API_ bool IsAsciiWhiteSpace(char ch);
GTEST_API_ bool IsAsciiWordChar(char ch);
GTEST_API_ bool IsValidEscape(char ch);
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
GTEST_API_ bool ValidateRegex(const char* regex);
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
GTEST_API_ bool MatchRepetitionAndRegexAtHead(
bool escaped, char ch, char repeat, const char* regex, const char* str);
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
#endif // GTEST_USES_SIMPLE_RE
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test.
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
#if GTEST_HAS_DEATH_TEST
// Returns the message describing the last system error, regardless of the
// platform.
GTEST_API_ std::string GetLastErrnoDescription();
// Attempts to parse a string into a positive integer pointed to by the
// number parameter. Returns true if that is possible.
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
// it here.
template <typename Integer>
bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
// Fail fast if the given string does not begin with a digit;
// this bypasses strtoXXX's "optional leading whitespace and plus
// or minus sign" semantics, which are undesirable here.
if (str.empty() || !IsDigit(str[0])) {
return false;
}
errno = 0;
char* end;
// BiggestConvertible is the largest integer type that system-provided
// string-to-number conversion routines can return.
using BiggestConvertible = unsigned long long; // NOLINT
const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
const bool parse_success = *end == '\0' && errno == 0;
GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
const Integer result = static_cast<Integer>(parsed);
if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
*number = result;
return true;
}
return false;
}
#endif // GTEST_HAS_DEATH_TEST
// TestResult contains some private methods that should be hidden from
// Google Test user but are required for testing. This class allow our tests
// to access them.
//
// This class is supplied only for the purpose of testing Google Test's own
// constructs. Do not use it in user tests, either directly or indirectly.
class TestResultAccessor {
public:
static void RecordProperty(TestResult* test_result,
const std::string& xml_element,
const TestProperty& property) {
test_result->RecordProperty(xml_element, property);
}
static void ClearTestPartResults(TestResult* test_result) {
test_result->ClearTestPartResults();
}
static const std::vector<testing::TestPartResult>& test_part_results(
const TestResult& test_result) {
return test_result.test_part_results();
}
};
#if GTEST_CAN_STREAM_RESULTS_
// Streams test results to the given port on the given host machine.
class StreamingListener : public EmptyTestEventListener {
public:
// Abstract base class for writing strings to a socket.
class AbstractSocketWriter {
public:
virtual ~AbstractSocketWriter() {}
// Sends a string to the socket.
virtual void Send(const std::string& message) = 0;
// Closes the socket.
virtual void CloseConnection() {}
// Sends a string and a newline to the socket.
void SendLn(const std::string& message) { Send(message + "\n"); }
};
// Concrete class for actually writing strings to a socket.
class SocketWriter : public AbstractSocketWriter {
public:
SocketWriter(const std::string& host, const std::string& port)
: sockfd_(-1), host_name_(host), port_num_(port) {
MakeConnection();
}
~SocketWriter() override {
if (sockfd_ != -1)
CloseConnection();
}
// Sends a string to the socket.
void Send(const std::string& message) override {
GTEST_CHECK_(sockfd_ != -1)
<< "Send() can be called only when there is a connection.";
const auto len = static_cast<size_t>(message.length());
if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
GTEST_LOG_(WARNING)
<< "stream_result_to: failed to stream to "
<< host_name_ << ":" << port_num_;
}
}
private:
// Creates a client socket and connects to the server.
void MakeConnection();
// Closes the socket.
void CloseConnection() override {
GTEST_CHECK_(sockfd_ != -1)
<< "CloseConnection() can be called only when there is a connection.";
close(sockfd_);
sockfd_ = -1;
}
int sockfd_; // socket file descriptor
const std::string host_name_;
const std::string port_num_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
}; // class SocketWriter
// Escapes '=', '&', '%', and '\n' characters in str as "%xx".
static std::string UrlEncode(const char* str);
StreamingListener(const std::string& host, const std::string& port)
: socket_writer_(new SocketWriter(host, port)) {
Start();
}
explicit StreamingListener(AbstractSocketWriter* socket_writer)
: socket_writer_(socket_writer) { Start(); }
void OnTestProgramStart(const UnitTest& /* unit_test */) override {
SendLn("event=TestProgramStart");
}
void OnTestProgramEnd(const UnitTest& unit_test) override {
// Note that Google Test current only report elapsed time for each
// test iteration, not for the entire test program.
SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
// Notify the streaming server to stop.
socket_writer_->CloseConnection();
}
void OnTestIterationStart(const UnitTest& /* unit_test */,
int iteration) override {
SendLn("event=TestIterationStart&iteration=" +
StreamableToString(iteration));
}
void OnTestIterationEnd(const UnitTest& unit_test,
int /* iteration */) override {
SendLn("event=TestIterationEnd&passed=" +
FormatBool(unit_test.Passed()) + "&elapsed_time=" +
StreamableToString(unit_test.elapsed_time()) + "ms");
}
// Note that "event=TestCaseStart" is a wire format and has to remain
// "case" for compatibility
void OnTestCaseStart(const TestCase& test_case) override {
SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
}
// Note that "event=TestCaseEnd" is a wire format and has to remain
// "case" for compatibility
void OnTestCaseEnd(const TestCase& test_case) override {
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
"&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
"ms");
}
void OnTestStart(const TestInfo& test_info) override {
SendLn(std::string("event=TestStart&name=") + test_info.name());
}
void OnTestEnd(const TestInfo& test_info) override {
SendLn("event=TestEnd&passed=" +
FormatBool((test_info.result())->Passed()) +
"&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms");
}
void OnTestPartResult(const TestPartResult& test_part_result) override {
const char* file_name = test_part_result.file_name();
if (file_name == nullptr) file_name = "";
SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
"&line=" + StreamableToString(test_part_result.line_number()) +
"&message=" + UrlEncode(test_part_result.message()));
}
private:
// Sends the given message and a newline to the socket.
void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
// Called at the start of streaming to notify the receiver what
// protocol we are using.
void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
std::string FormatBool(bool value) { return value ? "1" : "0"; }
const std::unique_ptr<AbstractSocketWriter> socket_writer_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
}; // class StreamingListener
#endif // GTEST_CAN_STREAM_RESULTS_
} // namespace internal
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
| [
"[email protected]"
] | |
c2220295d0e6a9cd0f8377469ed80b91b8951e6d | be8b9231c92e6c184f0692c92df9667be3770cb1 | /Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/USBHost_t36/hid.cpp | 367558afb4b1434387cfaa93d8312737384b4bdf | [
"MIT"
] | permissive | Pocketart/typhoonclawvex | def0f4a607c90b1bafb180466dfa12ddd8a480c1 | eb4b523c13541b2b9136d32259bd0399b46a289e | refs/heads/master | 2021-09-15T07:26:07.218099 | 2018-05-07T02:20:15 | 2018-05-07T02:20:15 | 105,268,399 | 4 | 3 | MIT | 2018-05-04T17:30:49 | 2017-09-29T12:12:32 | C++ | UTF-8 | C++ | false | false | 21,656 | cpp | /* USB EHCI Host for Teensy 3.6
* Copyright 2017 Paul Stoffregen ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <Arduino.h>
#include "USBHost_t36.h" // Read this header first for key info
// This HID driver claims a USB interface and parses its incoming
// data (reports). It doesn't actually use the data, but it allows
// drivers which inherit the USBHIDInput base class to claim the
// top level collections within the reports. Those drivers get
// callbacks with the arriving data full decoded to data/usage
// pairs.
#define print USBHost::print_
#define println USBHost::println_
void USBHIDParser::init()
{
contribute_Pipes(mypipes, sizeof(mypipes)/sizeof(Pipe_t));
contribute_Transfers(mytransfers, sizeof(mytransfers)/sizeof(Transfer_t));
contribute_String_Buffers(mystring_bufs, sizeof(mystring_bufs)/sizeof(strbuf_t));
driver_ready_for_device(this);
}
bool USBHIDParser::claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len)
{
println("HIDParser claim this=", (uint32_t)this, HEX);
// only claim at interface level
if (type != 1) return false;
if (len < 9+9+7) return false;
// interface descriptor
uint32_t numendpoint = descriptors[4];
if (numendpoint < 1 || numendpoint > 2) return false;
if (descriptors[5] != 3) return false; // bInterfaceClass, 3 = HID
println(" bInterfaceClass = ", descriptors[5]);
println(" bInterfaceSubClass = ", descriptors[6]);
println(" bInterfaceProtocol = ", descriptors[7]);
// do not claim boot protocol keyboards
if (descriptors[6] == 1 && descriptors[7] == 1) return false;
print("HID Parser Claim: ");
print_hexbytes(descriptors, len);
// hid interface descriptor
uint32_t hidlen = descriptors[9];
if (hidlen < 9) return false;
if (descriptors[10] != 33) return false; // descriptor type, 33=HID
if (descriptors[14] < 1) return false; // must be at least 1 extra descriptor
if (hidlen != (uint32_t)(6 + descriptors[14] * 3)) return false; // must be correct size
if (9 + hidlen > len) return false;
uint32_t i=0;
while (1) {
if (descriptors[15 + i * 3] == 34) { // found HID report descriptor
descsize = descriptors[16 + i * 3] | (descriptors[17 + i * 3] << 8);
println("report descriptor size = ", descsize);
break;
}
i++;
if (i >= descriptors[14]) return false;
}
if (descsize > sizeof(descriptor)) return false; // can't fit the report descriptor
// endpoint descriptor(s)
uint32_t offset = 9 + hidlen;
if (len < offset + numendpoint * 7) return false; // not enough data
if (numendpoint == 1) {
println("Single endpoint HID:");
if (descriptors[offset] != 7) return false;
if (descriptors[offset+1] != 5) return false; // endpoint descriptor
if (descriptors[offset+3] != 3) return false; // must be interrupt type
uint32_t endpoint = descriptors[offset+2];
uint32_t size = descriptors[offset+4] | (descriptors[offset+5] << 8);
uint32_t interval = descriptors[offset+6];
println(" endpoint = ", endpoint, HEX);
println(" size = ", size);
println(" interval = ", interval);
if ((endpoint & 0x0F) == 0) return false;
if ((endpoint & 0xF0) != 0x80) return false; // must be IN direction
in_pipe = new_Pipe(dev, 3, endpoint & 0x0F, 1, size, interval);
out_pipe = NULL;
in_size = size;
} else {
println("Two endpoint HID:");
if (descriptors[offset] != 7) return false;
if (descriptors[offset+1] != 5) return false; // endpoint descriptor
if (descriptors[offset+3] != 3) return false; // must be interrupt type
uint32_t endpoint1 = descriptors[offset+2];
uint32_t size1 = descriptors[offset+4] | (descriptors[offset+5] << 8);
uint32_t interval1 = descriptors[offset+6];
println(" endpoint = ", endpoint1, HEX);
println(" size = ", size1);
println(" interval = ", interval1);
if ((endpoint1 & 0x0F) == 0) return false;
if (descriptors[offset+7] != 7) return false;
if (descriptors[offset+8] != 5) return false; // endpoint descriptor
if (descriptors[offset+10] != 3) return false; // must be interrupt type
uint32_t endpoint2 = descriptors[offset+9];
uint32_t size2 = descriptors[offset+11] | (descriptors[offset+12] << 8);
uint32_t interval2 = descriptors[offset+13];
println(" endpoint = ", endpoint2, HEX);
println(" size = ", size2);
println(" interval = ", interval2);
if ((endpoint2 & 0x0F) == 0) return false;
if (((endpoint1 & 0xF0) == 0x80) && ((endpoint2 & 0xF0) == 0)) {
// first endpoint is IN, second endpoint is OUT
in_pipe = new_Pipe(dev, 3, endpoint1 & 0x0F, 1, size1, interval1);
out_pipe = new_Pipe(dev, 3, endpoint2, 0, size2, interval2);
in_size = size1;
out_size = size2;
} else if (((endpoint1 & 0xF0) == 0) && ((endpoint2 & 0xF0) == 0x80)) {
// first endpoint is OUT, second endpoint is IN
in_pipe = new_Pipe(dev, 3, endpoint2 & 0x0F, 1, size2, interval2);
out_pipe = new_Pipe(dev, 3, endpoint1, 0, size1, interval1);
in_size = size2;
out_size = size1;
} else {
return false;
}
out_pipe->callback_function = out_callback;
}
in_pipe->callback_function = in_callback;
for (uint32_t i=0; i < TOPUSAGE_LIST_LEN; i++) {
//topusage_list[i] = 0;
topusage_drivers[i] = NULL;
}
// request the HID report descriptor
mk_setup(setup, 0x81, 6, 0x2200, descriptors[2], descsize); // get report desc
queue_Control_Transfer(dev, &setup, descriptor, this);
return true;
}
void USBHIDParser::control(const Transfer_t *transfer)
{
println("control callback (hid)");
print_hexbytes(transfer->buffer, transfer->length);
// To decode hex dump to human readable HID report summary:
// http://eleccelerator.com/usbdescreqparser/
uint32_t mesg = transfer->setup.word1;
println(" mesg = ", mesg, HEX);
if (mesg == 0x22000681 && transfer->length == descsize) { // HID report descriptor
println(" got report descriptor");
parse();
queue_Data_Transfer(in_pipe, report, in_size, this);
if (device->idVendor == 0x054C && device->idProduct == 0x0268) {
println("send special PS3 feature command");
mk_setup(setup, 0x21, 9, 0x03F4, 0, 4); // ps3 tell to send report 1?
static uint8_t ps3_feature_F4_report[] = {0x42, 0x0c, 0x00, 0x00};
queue_Control_Transfer(device, &setup, ps3_feature_F4_report, this);
}
}
}
void USBHIDParser::in_callback(const Transfer_t *transfer)
{
if (transfer->driver) {
((USBHIDParser*)(transfer->driver))->in_data(transfer);
}
}
void USBHIDParser::out_callback(const Transfer_t *transfer)
{
//println("USBHIDParser:: out_callback (static)");
if (transfer->driver) {
((USBHIDParser*)(transfer->driver))->out_data(transfer);
}
}
// When the device goes away, we need to call disconnect_collection()
// for all drivers which claimed a top level collection
void USBHIDParser::disconnect()
{
for (uint32_t i=0; i < TOPUSAGE_LIST_LEN; i++) {
USBHIDInput *driver = topusage_drivers[i];
if (driver) {
driver->disconnect_collection(device);
topusage_drivers[i] = NULL;
}
}
}
// Called when the HID device sends a report
void USBHIDParser::in_data(const Transfer_t *transfer)
{
/*Serial.printf("HID: ");
uint8_t *pb = (uint8_t*)transfer->buffer;
for (uint8_t i = 0; i < transfer->length; i++) {
Serial.printf("%x ",pb[i]);
}
Serial.printf("\n"); */
print("HID: ");
print(use_report_id);
print(" - ");
print_hexbytes(transfer->buffer, transfer->length);
const uint8_t *buf = (const uint8_t *)transfer->buffer;
uint32_t len = transfer->length;
// See if the first top report wishes to bypass the
// parse...
if (!(topusage_drivers[0] && topusage_drivers[0]->hid_process_in_data(transfer))) {
if (use_report_id == false) {
parse(0x0100, buf, len);
} else {
if (len > 1) {
parse(0x0100 | buf[0], buf + 1, len - 1);
}
}
}
queue_Data_Transfer(in_pipe, report, in_size, this);
}
void USBHIDParser::out_data(const Transfer_t *transfer)
{
println("USBHIDParser:out_data called (instance)");
// A packet completed. lets mark it as done and call back
// to top reports handler. We unmark our checkmark to
// handle case where they may want to queue up another one.
if (transfer->buffer == tx1) txstate &= ~1;
if (transfer->buffer == tx2) txstate &= ~2;
if (topusage_drivers[0]) {
topusage_drivers[0]->hid_process_out_data(transfer);
}
}
bool USBHIDParser::sendPacket(const uint8_t *buffer, int cb) {
if (!out_size || !out_pipe) return false;
if (!tx1) {
// Was not init before, for now lets put it at end of descriptor
// TODO: should verify that either don't exceed overlap descsize
// Or that we have taken over this device
tx1 = &descriptor[sizeof(descriptor) - out_size];
tx2 = tx1 - out_size;
}
if ((txstate & 3) == 3) return false; // both transmit buffers are full
if (cb == -1)
cb = out_size;
uint8_t *p = tx1;
if ((txstate & 1) == 0) {
txstate |= 1;
} else {
if (!tx2)
return false; // only one buffer
txstate |= 2;
p = tx2;
}
// copy the users data into our out going buffer
memcpy(p, buffer, cb);
println("USBHIDParser Send packet");
print_hexbytes(buffer, cb);
queue_Data_Transfer(out_pipe, p, cb, this);
println(" Queue_data transfer returned");
return true;
}
void USBHIDParser::setTXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb)
{
tx1 = buffer1;
tx2 = buffer2;
}
bool USBHIDParser::sendControlPacket(uint32_t bmRequestType, uint32_t bRequest,
uint32_t wValue, uint32_t wIndex, uint32_t wLength, void *buf)
{
// Use setup structure to build packet
mk_setup(setup, bmRequestType, bRequest, wValue, wIndex, wLength); // ps3 tell to send report 1?
return queue_Control_Transfer(device, &setup, buf, this);
}
// This no-inputs parse is meant to be used when we first get the
// HID report descriptor. It finds all the top level collections
// and allows drivers to claim them. This is always where we
// learn whether the reports will or will not use a Report ID byte.
void USBHIDParser::parse()
{
const uint8_t *p = descriptor;
const uint8_t *end = p + descsize;
uint16_t usage_page = 0;
uint16_t usage = 0;
uint8_t collection_level = 0;
uint8_t topusage_count = 0;
use_report_id = false;
while (p < end) {
uint8_t tag = *p;
if (tag == 0xFE) { // Long Item
p += *p + 3;
continue;
}
uint32_t val;
switch (tag & 0x03) { // Short Item data
case 0: val = 0;
p++;
break;
case 1: val = p[1];
p += 2;
break;
case 2: val = p[1] | (p[2] << 8);
p += 3;
break;
case 3: val = p[1] | (p[2] << 8) | (p[3] << 16) | (p[4] << 24);
p += 5;
break;
}
if (p > end) break;
switch (tag & 0xFC) {
case 0x84: // Report ID (global)
use_report_id = true;
break;
case 0x04: // Usage Page (global)
usage_page = val;
break;
case 0x08: // Usage (local)
usage = val;
break;
case 0xA0: // Collection
if (collection_level == 0 && topusage_count < TOPUSAGE_LIST_LEN) {
uint32_t topusage = ((uint32_t)usage_page << 16) | usage;
println("Found top level collection ", topusage, HEX);
//topusage_list[topusage_count] = topusage;
topusage_drivers[topusage_count] = find_driver(topusage);
topusage_count++;
}
collection_level++;
usage = 0;
break;
case 0xC0: // End Collection
if (collection_level > 0) {
collection_level--;
}
case 0x80: // Input
case 0x90: // Output
case 0xB0: // Feature
usage = 0;
break;
}
}
while (topusage_count < TOPUSAGE_LIST_LEN) {
//topusage_list[topusage_count] = 0;
topusage_drivers[topusage_count] = NULL;
topusage_count++;
}
}
// This is a list of all the drivers inherited from the USBHIDInput class.
// Unlike the list of USBDriver (managed in enumeration.cpp), drivers stay
// on this list even when they have claimed a top level collection.
USBHIDInput * USBHIDParser::available_hid_drivers_list = NULL;
void USBHIDParser::driver_ready_for_hid_collection(USBHIDInput *driver)
{
driver->next = NULL;
if (available_hid_drivers_list == NULL) {
available_hid_drivers_list = driver;
} else {
USBHIDInput *last = available_hid_drivers_list;
while (last->next) last = last->next;
last->next = driver;
}
}
// When a new top level collection is found, this function asks drivers
// if they wish to claim it. The driver taking ownership of the
// collection is returned, or NULL if no driver wants it.
USBHIDInput * USBHIDParser::find_driver(uint32_t topusage)
{
println("find_driver");
USBHIDInput *driver = available_hid_drivers_list;
hidclaim_t claim_type;
while (driver) {
println(" driver ", (uint32_t)driver, HEX);
if ((claim_type = driver->claim_collection(this, device, topusage)) != CLAIM_NO) {
if (claim_type == CLAIM_INTERFACE) hid_driver_claimed_control_ = true;
return driver;
}
driver = driver->next;
}
return NULL;
}
// Extract 1 to 32 bits from the data array, starting at bitindex.
static uint32_t bitfield(const uint8_t *data, uint32_t bitindex, uint32_t numbits)
{
uint32_t output = 0;
uint32_t bitcount = 0;
data += (bitindex >> 3);
uint32_t offset = bitindex & 7;
if (offset) {
output = (*data++) >> offset;
bitcount = 8 - offset;
}
while (bitcount < numbits) {
output |= (uint32_t)(*data++) << bitcount;
bitcount += 8;
}
if (bitcount > numbits && numbits < 32) {
output &= ((1 << numbits) - 1);
}
return output;
}
// convert a number with the specified number of bits from unsigned to signed,
// so the result is a proper 32 bit signed integer.
static int32_t signext(uint32_t num, uint32_t bitcount)
{
if (bitcount < 32 && bitcount > 0 && (num & (1 << (bitcount-1)))) {
num |= ~((1 << bitcount) - 1);
}
return (int32_t)num;
}
// convert a tag's value to a signed integer.
static int32_t signedval(uint32_t num, uint8_t tag)
{
tag &= 3;
if (tag == 1) return (int8_t)num;
if (tag == 2) return (int16_t)num;
return (int32_t)num;
}
// parse the report descriptor and use it to feed the fields of the report
// to the drivers which have claimed its top level collections
void USBHIDParser::parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len)
{
const uint8_t *p = descriptor;
const uint8_t *end = p + descsize;
USBHIDInput *driver = NULL;
uint32_t topusage = 0;
uint8_t topusage_index = 0;
uint8_t collection_level = 0;
uint16_t usage[USAGE_LIST_LEN] = {0, 0};
uint8_t usage_count = 0;
uint8_t report_id = 0;
uint16_t report_size = 0;
uint16_t report_count = 0;
uint16_t usage_page = 0;
uint32_t last_usage = 0;
int32_t logical_min = 0;
int32_t logical_max = 0;
uint32_t bitindex = 0;
while (p < end) {
uint8_t tag = *p;
if (tag == 0xFE) { // Long Item (unsupported)
p += p[1] + 3;
continue;
}
uint32_t val;
switch (tag & 0x03) { // Short Item data
case 0: val = 0;
p++;
break;
case 1: val = p[1];
p += 2;
break;
case 2: val = p[1] | (p[2] << 8);
p += 3;
break;
case 3: val = p[1] | (p[2] << 8) | (p[3] << 16) | (p[4] << 24);
p += 5;
break;
}
if (p > end) break;
bool reset_local = false;
switch (tag & 0xFC) {
case 0x04: // Usage Page (global)
usage_page = val;
break;
case 0x14: // Logical Minimum (global)
logical_min = signedval(val, tag);
break;
case 0x24: // Logical Maximum (global)
logical_max = signedval(val, tag);
break;
case 0x74: // Report Size (global)
report_size = val;
break;
case 0x94: // Report Count (global)
report_count = val;
break;
case 0x84: // Report ID (global)
report_id = val;
break;
case 0x08: // Usage (local)
if (usage_count < USAGE_LIST_LEN) {
// Usages: 0 is reserved 0x1-0x1f is sort of reserved for top level things like
// 0x1 - Pointer - A collection... So lets try ignoring these
if (val > 0x1f) {
usage[usage_count++] = val;
}
}
break;
case 0x18: // Usage Minimum (local)
usage[0] = val;
usage_count = 255;
break;
case 0x28: // Usage Maximum (local)
usage[1] = val;
usage_count = 255;
break;
case 0xA0: // Collection
if (collection_level == 0) {
topusage = ((uint32_t)usage_page << 16) | usage[0];
driver = NULL;
if (topusage_index < TOPUSAGE_LIST_LEN) {
driver = topusage_drivers[topusage_index++];
}
}
// discard collection info if not top level, hopefully that's ok?
collection_level++;
reset_local = true;
break;
case 0xC0: // End Collection
if (collection_level > 0) {
collection_level--;
if (collection_level == 0 && driver != NULL) {
driver->hid_input_end();
driver = NULL;
}
}
reset_local = true;
break;
case 0x80: // Input
if (use_report_id && (report_id != (type_and_report_id & 0xFF))) {
// completely ignore and do not advance bitindex
// for descriptors of other report IDs
reset_local = true;
break;
}
if ((val & 1) || (driver == NULL)) {
// skip past constant fields or when no driver is listening
bitindex += report_count * report_size;
} else {
println("begin, usage=", topusage, HEX);
println(" type= ", val, HEX);
println(" min= ", logical_min);
println(" max= ", logical_max);
println(" reportcount=", report_count);
println(" usage count=", usage_count);
driver->hid_input_begin(topusage, val, logical_min, logical_max);
println("Input, total bits=", report_count * report_size);
if ((val & 2)) {
// ordinary variable format
uint32_t uindex = 0;
uint32_t uindex_max = 0xffff; // assume no MAX
bool uminmax = false;
if (usage_count > USAGE_LIST_LEN) {
// usage numbers by min/max, not from list
uindex = usage[0];
uindex_max = usage[1];
uminmax = true;
} else if ((report_count > 1) && (usage_count <= 1)) {
// Special cases: Either only one or no usages specified and there are more than one
// report counts .
if (usage_count == 1) {
uindex = usage[0];
} else {
// BUGBUG:: Not sure good place to start? maybe round up from last usage to next higher group up of 0x100?
uindex = (last_usage & 0xff00) + 0x100;
}
uminmax = true;
}
//Serial.printf("TU:%x US:%x %x %d %d: C:%d, %d, MM:%d, %x %x\n", topusage, usage_page, val, logical_min, logical_max,
// report_count, usage_count, uminmax, usage[0], usage[1]);
for (uint32_t i=0; i < report_count; i++) {
uint32_t u;
if (uminmax) {
u = uindex;
if (uindex < uindex_max) uindex++;
} else {
u = usage[uindex++];
if (uindex >= USAGE_LIST_LEN-1) {
uindex = USAGE_LIST_LEN-1;
}
}
last_usage = u; // remember the last one we used...
u |= (uint32_t)usage_page << 16;
print(" usage = ", u, HEX);
uint32_t n = bitfield(data, bitindex, report_size);
if (logical_min >= 0) {
println(" data = ", n);
driver->hid_input_data(u, n);
} else {
int32_t sn = signext(n, report_size);
println(" sdata = ", sn);
driver->hid_input_data(u, sn);
}
bitindex += report_size;
}
} else {
// array format, each item is a usage number
for (uint32_t i=0; i < report_count; i++) {
uint32_t u = bitfield(data, bitindex, report_size);
int n = u;
if (n >= logical_min && n <= logical_max) {
u |= (uint32_t)usage_page << 16;
print(" usage = ", u, HEX);
println(" data = 1");
driver->hid_input_data(u, 1);
} else {
print (" usage =", u, HEX);
print(" out of range: ", logical_min, HEX);
println(" ", logical_max, HEX);
}
bitindex += report_size;
}
}
}
reset_local = true;
break;
case 0x90: // Output
// TODO.....
reset_local = true;
break;
case 0xB0: // Feature
// TODO.....
reset_local = true;
break;
case 0x34: // Physical Minimum (global)
case 0x44: // Physical Maximum (global)
case 0x54: // Unit Exponent (global)
case 0x64: // Unit (global)
break; // Ignore these commonly used tags. Hopefully not needed?
case 0xA4: // Push (yikes! Hope nobody really uses this?!)
case 0xB4: // Pop (yikes! Hope nobody really uses this?!)
case 0x38: // Designator Index (local)
case 0x48: // Designator Minimum (local)
case 0x58: // Designator Maximum (local)
case 0x78: // String Index (local)
case 0x88: // String Minimum (local)
case 0x98: // String Maximum (local)
case 0xA8: // Delimiter (local)
default:
println("Ruh Roh, unsupported tag, not a good thing Scoob ", tag, HEX);
break;
}
if (reset_local) {
usage_count = 0;
usage[0] = 0;
usage[1] = 0;
}
}
}
| [
"[email protected]"
] | |
f0243fc0f99234c3523a5ac16937a959d1cbd091 | e1ec12d94876cdf320354d621b387b2e126bd3c6 | /compsci403_assignment5/src/RemovedMethods.cpp | 4ccb1106cc9dcc0fbb29e47b987e7f5e87bdcf9d | [] | no_license | haseoxform/Fetch- | c2772b43c60e1e0190601e2b9762312c68cde382 | bcf934f004b9ff3158422630ff884889aded5cba | refs/heads/master | 2020-03-12T02:35:57.624143 | 2018-04-20T21:44:44 | 2018-04-20T21:44:44 | 130,406,625 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,763 | cpp | // Helper function to find the free path length
bool FreePathLength(float* free_path_length, const Vector2f& point, const Vector2f& vel) {
int is_obstacle = false;
*free_path_length = gLaserMaxRange;
if(vel(1) == 0) {
*free_path_length = point(0) - gRobotRadius;
is_obstacle = true;
return is_obstacle;
}
// radius of rotation
float R = fabs(vel(0)/vel(1));
Vector2f center(0, 0);
center(1) = (vel(1) > 0)? R : -R;
Vector2f center_to_obstacle(point(0) - center(0), point(1) - center(1));
float dist_to_center = sqrt(center_to_obstacle(0) * center_to_obstacle(0) +
center_to_obstacle(1) * center_to_obstacle(1));
float min_dist = R - gRobotRadius;
float max_dist = R + gRobotRadius;
if(min_dist <= dist_to_center && dist_to_center <= max_dist) {
is_obstacle = true;
float obstacle_angle = atan2(center_to_obstacle(1), center_to_obstacle(0));
*free_path_length = (obstacle_angle < 0) ? ( M_PI/2 + obstacle_angle) * R :
( M_PI/2 - obstacle_angle) * R;
float delta = fabs(dist_to_center - R);
float correction = sqrt(gRobotRadius * gRobotRadius - delta * delta);
*free_path_length -= correction;
}
return is_obstacle;
}
// Evaluate a cost function over the dynamic window and return the index of
// the best cell
void GetBestCommand(const MatrixXf& win_v, const MatrixXf& win_w, const vector<Vector2f>& obstacles, MatrixXf& scores, MatrixXd& is_admissible, Vector2f& index_best) {
float v_coeff = 1;
float angle_coeff = -0.003; // -5;
float dist_coeff = 1; //10;
size_t size = win_v.rows();
Vector2f current_best_index(-1, -1);
float current_best_score = -1000000;
Vector2f vel;
MatrixXf free_path_m(size, size);
for(size_t i = 0; i < size; ++i) {
for(size_t j = 0; j < size; ++j) {
vel(0) = win_v(i,j);
vel(1) = win_w(i,j);
float free_path_length = gLaserMaxRange;
float distance = gLaserMaxRange;
// Go over all the obstacle points in the laser scan to find the free
// path length
for(size_t k = 0; k < obstacles.size(); ++k) {
float free_path_length_current;
bool current_obstacle =
FreePathLength(&free_path_length_current, obstacles[k], vel);
if(free_path_length_current < free_path_length) {
free_path_length = free_path_length_current;
}
if (!current_obstacle && free_path_length_current < distance) {
distance = free_path_length_current;
}
}
// Check if the current velocity is admissible
bool is_admissible_tmp = true;
if(vel(0) > sqrt(2 * gAMaxLin * free_path_length)){
is_admissible_tmp = false;
}
is_admissible(i,j) = (is_admissible_tmp == true) ? 1: 0;
// Calculate the score for current velocity
scores(i, j) = (v_coeff * vel(0)) +
(angle_coeff * fabs(vel(1)) * gDT) +
(dist_coeff * distance);
// Keep the best score so far
if(is_admissible_tmp == 1 && scores(i, j) > current_best_score) {
current_best_score = scores(i, j);
current_best_index << i, j;
}
free_path_m(i,j) = free_path_length;
}
}
index_best = current_best_index;
}
void PredictTrajectory(vector<Vector3f>& points, float v, float w) {
Vector2f vel(v, w);
float step_size = 0.1; // meters
int step_num = (int)(4.0 / step_size);
if(vel(1) == 0) {
// Straight Path
float length = 0;
for(int i = 0; i < step_num; ++i) {
length += step_size;
Vector3f new_point;
new_point(0) = 0;
new_point(1) = length;
new_point(2) = 0;
points.push_back(new_point);
}
} else {
// radius of rotation
float R = fabs(vel(0)/vel(1));
Vector2f center(0, 0);
center(1) = (vel(1) > 0)? R: -R;
float angle_increment = step_size / fabs(R);
float theta = 0;
for(int i = 0; i < step_num; ++i) {
theta += angle_increment;
float del_x = R * sin(theta);
float del_y = R * cos(theta);
Vector3f new_point;
new_point(0) = center(0) + del_x;
new_point(1) = (center(1) > 0)? -del_y + center(1) : del_y + center(1);
new_point(2) = 0;
points.push_back(new_point);
}
}
}
bool CheckPointService(compsci403_assignment5::CheckPointSrv::Request& req, compsci403_assignment5::CheckPointSrv::Response& res) {
// Observed point.
const Vector2f P(req.P.x, req.P.y);
// Desired velocity vector.
const Vector2f V(req.v, req.w);
bool is_obstacle = false;
float free_path_length = 0.0;
// Compute is_obstacle and free_path_length.
is_obstacle = FreePathLength(&free_path_length, P, V);
res.free_path_length = free_path_length;
res.is_obstacle = is_obstacle;
return true;
}
bool GetFreePathService(compsci403_assignment5::GetFreePathSrv::Request& req, compsci403_assignment5::GetFreePathSrv::Response& res) {
const LaserScan& laser_scan = req.laser_scan;
const Vector2f V(req.v, req.w);
bool is_obstacle = false;
float free_path_length = laser_scan.range_max + gRobotRadius;
for (size_t i = 0; i < laser_scan.ranges.size(); i++) {
if (laser_scan.ranges[i] < laser_scan.range_min ||
laser_scan.ranges[i] > laser_scan.range_max) {
continue;
}
const float angle = laser_scan.angle_min +
laser_scan.angle_increment * static_cast<float>(i);
const Vector2f P = laser_scan.ranges[i] * Vector2f(cos(angle), sin(angle));
// Ignore points "behind" the robot
if (P(0) <= 0.0) {
continue;
}
float current_path_length = laser_scan.range_max + gRobotRadius;
bool current_obstacle = false;
current_obstacle = FreePathLength(¤t_path_length, P, V);
free_path_length = min(current_path_length, free_path_length);
is_obstacle = current_obstacle || is_obstacle;
}
res.is_obstacle = is_obstacle;
res.free_path_length = free_path_length;
return true;
}
//CUT BUT WILL USE SIMILAR IDEAS
bool GetCommandVelService(compsci403_assignment5::GetCommandVelSrv::Request& req, compsci403_assignment5::GetCommandVelSrv::Response& res) {
// The input v0 and w0 are each vectors. The x component of v0 is the linear
// velocity towards forward direction and the z component of w0 is the
// rotational velocity around the z axis, i.e. around the center of rotation
// of the robot and in counter-clockwise direction
const Vector2f V(req.v_0, req.w_0);
// Convert the laser scan to 2D points in cartesian coordinate system
vector<Vector2f> obstacles;
LaserScanToPoint(obstacle_laser_scan_.ranges, obstacles);
// Implement dynamic windowing approach to find the best velocity command for next time step
int win_size = 41;
MatrixXf win_v(win_size, win_size);
MatrixXf win_w(win_size, win_size);
MatrixXf scores(win_size, win_size); //REMOVED
MatrixXd is_admissible(win_size, win_size);
Vector2f index_best;
InitializeDynamicWindow(win_v, win_w, V);
GetBestCommand(win_v, win_w, obstacles, scores, is_admissible, index_best); //REMOVED
// Return the best velocity command
// Cv is of type Point32 and its x component is the linear velocity towards
// forward direction; you do not need to fill its other components
// Take the best velocity based on the cost function contingent upon there
// has been any admissible velocities
if(index_best(0) != -1)
res.C_v = win_v(index_best(0), index_best(1));
else
res.C_v = 0;
// Cw is of type Point32 and its z component is the rotational velocity
// around z axis; you do not need to fill its other components
if(index_best(0) != -1)
res.C_w = win_w(index_best(0), index_best(1));
else
res.C_w = 0;
return true;
} | [
"[email protected]"
] | |
1a2a5154d2b698ff1acdcc8b094f88824f46b0ee | 5b1d7d18e5ec2d01746af4a98a167c56472a6384 | /list1/Source.cpp | 54cb819d06db1f22f2bdf5b64ccc465d0f240220 | [] | no_license | kurctory/list | 205a16c1c0ee628df1d27ebee64f56b7f745ff7e | f8dd68a7055a122286ab6202e7da6ca9ff4fa83a | refs/heads/master | 2022-07-11T10:18:37.041076 | 2020-05-18T01:03:32 | 2020-05-18T01:03:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,312 | cpp | #include "list.h"
int main()
{
int key, y, v;
list<int>::iterator it;
list <int> l;
cout << "0 - create(clear) list" << endl;
cout << "1 - print list" << endl;
cout << "2 - insert element value before element x" << endl;
cout << "3 - insert element value after element x" << endl;
cout << "4 - insert element value in the tail of the list" << endl;
cout << "5 - delete element value" << endl;
cout << "6 - make lists l1, which contains positive numbers, and list l2, which contains negative numbers" << endl;
cout << "9 - exit" << endl;
cout << "input selected menu item ";
cin >> key;
while (key != 9)
{
switch (key)
{
case 0:
l.clear();
break;
case 1:
if (l.empty()) cout << "The list is empty" << endl;
else
cout << "current list: ";
for (it = l.begin(); it != l.end(); cout << *it << ' ', it++);
cout << "\n";
break;
case 2:
if (l.empty()) cout << "The list is empty" << endl;
else
{
cout << "Enter the input element value: ";
cin >> v;
cout << "Enter the element x: ";
cin >> y;
it = find(l.begin(), l.end(), y);
if (it == l.end()) cout << "There isn't such element in the list" << endl;
else
l.emplace(it, v);
}
break;
case 3:
if (l.empty()) cout << "The list is empty" << endl;
else
{
cout << "Enter the input element value: ";
cin >> v;
cout << "Enter the element x: ";
cin >> y;
it = find(l.begin(), l.end(), y);
if (it == l.end()) cout << "There isn't such element in the list" << endl;
else
{
it++;
l.emplace(it, v);
}
}
break;
case 4:
cout << "Enter the input value: ";
cin >> v;
l.emplace_back(v);
break;
case 5:
if (l.empty()) cout << "The list is empty" << endl;
else
{
cout << "Enter the value: ";
cin >> v;
it = find(l.begin(), l.end(), v);
if (it == l.end()) cout << "There isn't such element in the list" << endl;
else
l.erase(it);
}
break;
case 6:
if (l.empty()) cout << "The list is empty" << endl;
else
{
pair < list<int>, list<int> > a = pml(l);
cout << "The '+' list is: ";
for (it = a.first.begin(); it != a.first.end(); cout << *it << ' ', it++);
cout << "\nThe '-' list is: ";
for (it = a.second.begin(); it != a.second.end(); cout << *it << ' ', it++);
cout << "\n";
}
break;
default:
cout << "There isn't such command" << endl;
break;
}
cout << "input selected menu item ";
cin >> key;
}
}
| [
"[email protected]"
] | |
d9ba358879875a04161587468c49d53b16867afb | 2173d3770303ebb85ace125071b44ab601ce452d | /BattleRoyale/Source/BattleRoyale/Private/Player/BuggyPawn.cpp | f7c2765ca523b5400e3764a1cd1aaca85a3d77e2 | [] | no_license | TransformersOnline/BattleRoyale | cea073c8121bd7c63c967a8fd3ccccfa9f8a2d1b | e8a00c296cb49b56679e4a02519c16f3dc8b9c4e | refs/heads/master | 2023-01-06T11:51:34.590884 | 2017-09-12T14:26:54 | 2017-09-12T14:26:54 | 97,491,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,182 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "BattleRoyale.h"
#include "BuggyPawn.h"
#include "VehicleWheel.h"
#include "Particles/ParticleSystemComponent.h"
#include "WheeledVehicleMovementComponent.h"
#include "Effects/VehicleImpactEffect.h"
#include "Effects/VehicleDustType.h"
#include "AudioThread.h"
TMap<uint32, ABuggyPawn::FVehicleDesiredRPM> ABuggyPawn::BuggyDesiredRPMs;
ABuggyPawn::ABuggyPawn(const FObjectInitializer& ObjectInitializer) :
Super(ObjectInitializer)
{
/** Camera strategy:
* We want to keep a constant distance between car's location and camera.
* We want to keep roll and pitch fixed
* We want to interpolate yaw very slightly
* We want to keep car almost constant in screen space width and height (i.e. if you draw a box around the car its center would be near constant and its dimensions would only vary on sharp turns or declines */
// Create a spring arm component
SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm0"));
SpringArm->TargetOffset = FVector(0.f, 0.f, 400.f);
SpringArm->SetRelativeRotation(FRotator(0.f, 0.f, 0.f));
SpringArm->SetupAttachment(RootComponent);
SpringArm->TargetArmLength = 675.0f;
SpringArm->bEnableCameraRotationLag = true;
SpringArm->CameraRotationLagSpeed = 7.f;
SpringArm->bInheritPitch = false;
SpringArm->bInheritRoll = false;
// Create camera component
Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera0"));
Camera->SetupAttachment(SpringArm, USpringArmComponent::SocketName);
Camera->bUsePawnControlRotation = false;
Camera->FieldOfView = 90.f;
EngineAC = CreateDefaultSubobject<UAudioComponent>(TEXT("EngineAudio"));
EngineAC->SetupAttachment(GetMesh());
SkidAC = CreateDefaultSubobject<UAudioComponent>(TEXT("SkidAudio"));
SkidAC->bAutoActivate = false; //we don't want to start skid right away
SkidAC->SetupAttachment(GetMesh());
SkidThresholdVelocity = 30;
SkidFadeoutTime = 0.1f;
LongSlipSkidThreshold = 0.3f;
LateralSlipSkidThreshold = 0.3f;
SkidDurationRequiredForStopSound = 1.5f;
SpringCompressionLandingThreshold = 250000.f;
bTiresTouchingGround = false;
ImpactEffectNormalForceThreshold = 100000.f;
}
void ABuggyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
check(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &ABuggyPawn::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &ABuggyPawn::MoveRight);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ABuggyPawn::OnHandbrakePressed);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ABuggyPawn::OnHandbrakeReleased);
}
void ABuggyPawn::PostInitializeComponents()
{
Super::PostInitializeComponents();
if (EngineAC)
{
EngineAC->SetSound(EngineSound);
EngineAC->Play();
}
if (SkidAC)
{
SkidAC->SetSound(SkidSound);
SkidAC->Stop();
}
SeatsState.Empty();
SeatsState.AddZeroed(SeatsList.Num());
}
void ABuggyPawn::MoveForward(float Val)
{
UE_LOG(LogOnlineGame, Log, TEXT("ABuggyPawn::MoveForward"));
UWheeledVehicleMovementComponent* VehicleMovementComp = GetVehicleMovementComponent();
if (VehicleMovementComp == nullptr)
{
return;
}
VehicleMovementComp->SetThrottleInput(Val);
}
void ABuggyPawn::MoveRight(float Val)
{
UWheeledVehicleMovementComponent* VehicleMovementComp = GetVehicleMovementComponent();
if (VehicleMovementComp == nullptr)
{
return;
}
VehicleMovementComp->SetSteeringInput(Val);
}
void ABuggyPawn::OnHandbrakePressed()
{
UWheeledVehicleMovementComponent* VehicleMovementComp = GetVehicleMovementComponent();
if (VehicleMovementComp != nullptr)
{
VehicleMovementComp->SetHandbrakeInput(true);
}
}
void ABuggyPawn::OnHandbrakeReleased()
{
bHandbrakeActive = false;
UWheeledVehicleMovementComponent* VehicleMovementComp = GetVehicleMovementComponent();
if (VehicleMovementComp != nullptr)
{
GetVehicleMovementComponent()->SetHandbrakeInput(false);
}
}
void ABuggyPawn::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
UpdateWheelEffects(DeltaSeconds);
/*if (AVehiclePlayerController* VehiclePC = Cast<AVehiclePlayerController>(GetController()))
{
const uint32 VehiclePCID = VehiclePC->GetUniqueID();
FVehicleDesiredRPM DesiredRPM;
DesiredRPM.DesiredRPM = GetEngineRotationSpeed();
DesiredRPM.TimeStamp = GetWorld()->GetTimeSeconds();
FAudioThread::RunCommandOnAudioThread([VehiclePCID, DesiredRPM]()
{
BuggyDesiredRPMs.Add(VehiclePCID, DesiredRPM);
});
}*/
if (HasAuthority() && SeatsState.IsValidIndex(0) && SeatsState[0] == nullptr)
{
UWheeledVehicleMovementComponent* VehicleMovementComp = GetVehicleMovementComponent();
if (VehicleMovementComp)
{
VehicleMovementComp->StopMovementImmediately();
}
}
}
void ABuggyPawn::UnPossessed()
{
/*if (AVehiclePlayerController* VehiclePC = Cast<AVehiclePlayerController>(GetController()))
{
const uint32 VehiclePCID = VehiclePC->GetUniqueID();
FAudioThread::RunCommandOnAudioThread([VehiclePCID]()
{
BuggyDesiredRPMs.Remove(VehiclePCID);
});
}*/
// Super clears controller, so do the behavior first
Super::UnPossessed();
}
bool ABuggyPawn::GetVehicleDesiredRPM_AudioThread(const uint32 VehicleID, FVehicleDesiredRPM& OutDesiredRPM)
{
check(IsInAudioThread());
if (FVehicleDesiredRPM* DesiredRPM = BuggyDesiredRPMs.Find(VehicleID))
{
OutDesiredRPM = *DesiredRPM;
return true;
}
return false;
}
void ABuggyPawn::SpawnNewWheelEffect(int WheelIndex)
{
DustPSC[WheelIndex] = NewObject<UParticleSystemComponent>(this);
DustPSC[WheelIndex]->bAutoActivate = true;
DustPSC[WheelIndex]->bAutoDestroy = false;
DustPSC[WheelIndex]->RegisterComponentWithWorld(GetWorld());
DustPSC[WheelIndex]->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, GetVehicleMovement()->WheelSetups[WheelIndex].BoneName);
}
void ABuggyPawn::UpdateWheelEffects(float DeltaTime)
{
if (GetVehicleMovement() && bTiresTouchingGround == false && LandingSound) //we don't update bTiresTouchingGround until later in this function, so we can use it here to determine whether we're landing
{
float MaxSpringForce = GetVehicleMovement()->GetMaxSpringForce();
if (MaxSpringForce > SpringCompressionLandingThreshold)
{
UGameplayStatics::PlaySoundAtLocation(this, LandingSound, GetActorLocation());
}
}
bTiresTouchingGround = false;
if (DustType && !bIsDying &&
GetVehicleMovement() && GetVehicleMovement()->Wheels.Num() > 0)
{
const float CurrentSpeed = GetVehicleSpeed();
for (int32 i = 0; i < ARRAY_COUNT(DustPSC); i++)
{
UPhysicalMaterial* ContactMat = GetVehicleMovement()->Wheels[i]->GetContactSurfaceMaterial();
if (ContactMat != nullptr)
{
bTiresTouchingGround = true;
}
UParticleSystem* WheelFX = DustType->GetDustFX(ContactMat, CurrentSpeed);
const bool bIsActive = DustPSC[i] != nullptr && !DustPSC[i]->bWasDeactivated && !DustPSC[i]->bWasCompleted;
UParticleSystem* CurrentFX = DustPSC[i] != nullptr ? DustPSC[i]->Template : nullptr;
if (WheelFX != nullptr && (CurrentFX != WheelFX || !bIsActive))
{
if (DustPSC[i] == nullptr || !DustPSC[i]->bWasDeactivated)
{
if (DustPSC[i] != nullptr)
{
DustPSC[i]->SetActive(false);
DustPSC[i]->bAutoDestroy = true;
}
SpawnNewWheelEffect(i);
}
DustPSC[i]->SetTemplate(WheelFX);
DustPSC[i]->ActivateSystem();
}
else if (WheelFX == nullptr && bIsActive)
{
DustPSC[i]->SetActive(false);
}
}
}
if (SkidAC != nullptr)
{
FVector Vel = GetVelocity();
bool bVehicleStopped = Vel.SizeSquared2D() < SkidThresholdVelocity*SkidThresholdVelocity;
bool TireSlipping = GetVehicleMovement()->CheckSlipThreshold(LongSlipSkidThreshold, LateralSlipSkidThreshold);
bool bWantsToSkid = bTiresTouchingGround && !bVehicleStopped && TireSlipping;
float CurrTime = GetWorld()->GetTimeSeconds();
if (bWantsToSkid && !bSkidding)
{
bSkidding = true;
SkidAC->Play();
SkidStartTime = CurrTime;
}
if (!bWantsToSkid && bSkidding)
{
bSkidding = false;
SkidAC->FadeOut(SkidFadeoutTime, 0);
if (CurrTime - SkidStartTime > SkidDurationRequiredForStopSound)
{
UGameplayStatics::PlaySoundAtLocation(this, SkidSoundStop, GetActorLocation());
}
}
}
}
//
//void ABuggyPawn::OnTrackPointReached(AVehicleTrackPoint* NewCheckpoint)
//{
// AVehiclePlayerController* MyPC = Cast<AVehiclePlayerController>(GetController());
// if (MyPC)
// {
// MyPC->OnTrackPointReached(NewCheckpoint);
// }
//}
bool ABuggyPawn::IsHandbrakeActive() const
{
return bHandbrakeActive;
}
float ABuggyPawn::GetVehicleSpeed() const
{
return (GetVehicleMovement()) ? FMath::Abs(GetVehicleMovement()->GetForwardSpeed()) : 0.0f;
}
float ABuggyPawn::GetEngineRotationSpeed() const
{
return (GetVehicleMovement()) ? FMath::Abs(GetVehicleMovement()->GetEngineRotationSpeed()) : 0.0f;
}
float ABuggyPawn::GetEngineMaxRotationSpeed() const
{
return (GetVehicleMovement()) ? FMath::Abs(GetVehicleMovement()->MaxEngineRPM) : 1.f;
}
void ABuggyPawn::NotifyHit(UPrimitiveComponent* MyComp, AActor* Other, UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalForce, const FHitResult& Hit)
{
Super::NotifyHit(MyComp, Other, OtherComp, bSelfMoved, HitLocation, HitNormal, NormalForce, Hit);
if (ImpactTemplate && NormalForce.SizeSquared() > FMath::Square(ImpactEffectNormalForceThreshold))
{
FTransform const SpawnTransform(HitNormal.Rotation(), HitLocation);
AVehicleImpactEffect* EffectActor = GetWorld()->SpawnActorDeferred<AVehicleImpactEffect>(ImpactTemplate, SpawnTransform);
if (EffectActor)
{
float DotBetweenHitAndUpRotation = FVector::DotProduct(HitNormal, GetMesh()->GetUpVector());
EffectActor->HitSurface = Hit;
EffectActor->HitForce = NormalForce;
EffectActor->bWheelLand = DotBetweenHitAndUpRotation > 0.8f;
UGameplayStatics::FinishSpawningActor(EffectActor, SpawnTransform);
}
}
if (ImpactCameraShake)
{
AShooterPlayerController* PC = Cast<AShooterPlayerController>(Controller);
if (PC != nullptr && PC->IsLocalController())
{
PC->ClientPlayCameraShake(ImpactCameraShake, 1);
}
}
}
float ABuggyPawn::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
if (Cast<APainCausingVolume>(DamageCauser) != nullptr)
{
Die();
}
return Super::TakeDamage(Damage, DamageEvent, EventInstigator, DamageCauser);
}
void ABuggyPawn::FellOutOfWorld(const class UDamageType& dmgType)
{
Die();
}
bool ABuggyPawn::CanDie() const
{
if ( bIsDying // already dying
|| IsPendingKill() // already destroyed
|| Role != ROLE_Authority) // not authority
{
return false;
}
return true;
}
void ABuggyPawn::Die()
{
if (CanDie())
{
OnDeath();
}
}
void ABuggyPawn::OnRep_Dying()
{
if (bIsDying == true)
{
OnDeath();
}
}
void ABuggyPawn::TornOff()
{
Super::TornOff();
SetLifeSpan(1.0f);
}
void ABuggyPawn::OnDeath()
{
bReplicateMovement = false;
bTearOff = true;
bIsDying = true;
DetachFromControllerPendingDestroy();
// hide and disable
TurnOff();
SetActorHiddenInGame(true);
if (EngineAC)
{
EngineAC->Stop();
}
if (SkidAC)
{
SkidAC->Stop();
}
PlayDestructionFX();
// Give use a finite lifespan
SetLifeSpan( 0.2f );
}
void ABuggyPawn::PlayDestructionFX()
{
if (DeathFX)
{
UGameplayStatics::SpawnEmitterAtLocation(this, DeathFX, GetActorLocation(), GetActorRotation());
}
if (DeathSound)
{
UGameplayStatics::PlaySoundAtLocation(this, DeathSound, GetActorLocation());
}
}
void ABuggyPawn::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ABuggyPawn, bIsDying);
}
void ABuggyPawn::CalcCamera(float DeltaTime, FMinimalViewInfo& OutResult)
{
if (bFindCameraComponentWhenViewTarget && Camera && Camera->bIsActive)
{
// don't allow FOV override, we handle that in UTPlayerController/UTPlayerCameraManager
Camera->GetCameraView(DeltaTime, OutResult);
}
else
{
GetActorEyesViewPoint(OutResult.Location, OutResult.Rotation);
}
}
void ABuggyPawn::TryEnter(AShooterCharacter* Char)
{
UE_LOG(LogOnlineGame, Log, TEXT("ABuggyPawn::ServerTryEnter"));
if (!Char || !Char->IsAlive() )
{
return;
}
int32 SeatIndex = FindANearestSeat(Char->GetActorLocation());
if (SeatIndex < 0)
{
return;
}
if (Char->IsInCar() && Char->GetCurrentCar() != this)
{
Char->GetCurrentCar()->CharacterLeave(Char);
}
CharacterEnter(Char, SeatIndex);
}
void ABuggyPawn::CharacterEnter_Implementation(AShooterCharacter* Char, int32 SeatIndex)
{
if (!Char || SeatIndex < 0)
{
return;
}
if (!SeatsState.IsValidIndex(SeatIndex))
{
return;
}
SeatsState[SeatIndex] = Char;
Char->HandleEnterCar(this,SeatIndex);
}
bool ABuggyPawn::ServerTryLeave_Validate(AShooterCharacter* Char)
{
return true;
}
void ABuggyPawn::ServerTryLeave_Implementation(AShooterCharacter* Char)
{
int32 SeatIndex = GetSeatIndex(Char);
if (SeatIndex >= 0)
{
CharacterLeave(Char);
}
}
void ABuggyPawn::CharacterLeave_Implementation(AShooterCharacter* Char)
{
int32 SeatIndex = GetSeatIndex(Char);
if (SeatIndex >= 0)
{
if (SeatIndex == 0)
{
UWheeledVehicleMovementComponent* VehicleMovementComp = GetVehicleMovementComponent();
if (VehicleMovementComp)
{
VehicleMovementComp->StopMovementImmediately();
}
}
SeatsState[SeatIndex] = nullptr;
Char->HandleLeaveCar(SeatIndex);
}
}
bool ABuggyPawn::ServerTrySwitchSeat_Validate(AShooterCharacter* Char, int32 SeatIndex)
{
return true;
}
void ABuggyPawn::ServerTrySwitchSeat_Implementation(AShooterCharacter* Char, int32 SeatIndex)
{
;
}
int32 ABuggyPawn::FindANearestSeat(const FVector& Location)
{
if (!GetMesh())
{
return -1;
}
int32 NearestIndex = -1;
float NearestDistance = 99999.f;
for (int32 SeatIndex = 0; SeatIndex < SeatsList.Num(); ++SeatIndex)
{
if (!SeatsState.IsValidIndex(SeatIndex) || SeatsState[SeatIndex] != nullptr)
{
continue;
}
FVector SeatLocation = GetMesh()->GetSocketLocation(SeatsList[SeatIndex]);
float SeatDistance = (SeatLocation - Location).Size();
if (SeatDistance < NearestDistance)
{
NearestDistance = SeatDistance;
NearestIndex = SeatIndex;
}
}
return NearestIndex;
}
FVector ABuggyPawn::GetOffLocation(int32 SeatIndex)
{
if (!GetMesh())
{
return GetActorLocation() + FVector(0.f,0.f,50.f);
}
if (GetOffList.IsValidIndex(SeatIndex))
{
return GetMesh()->GetSocketLocation(GetOffList[SeatIndex]);
}
return GetActorLocation() + FVector(0.f, 0.f, 50.f);
} | [
"[email protected]"
] | |
af13873cb6cea15fede8c08cf9cb300a3bafd99f | 9ec67e83200f643f9f55ed90e0b2cae4581ebcb6 | /SupportLib/ImageCelSourceGrid.cpp | c5dfdc1bf3bcc8707268a29a26ae410e41c94bd0 | [] | no_license | andrewpaterson/Codaphela.Library | 465770eaf2839589fc305660725abb38033f8aa2 | 2a4722ba0a4b98a304a297a9d74c9b6811fa4ac5 | refs/heads/master | 2023-05-25T13:01:45.587888 | 2023-05-14T11:46:36 | 2023-05-14T11:46:36 | 3,248,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,241 | cpp | /** ---------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE ------------- **
Copyright (c) 2012 Andrew Paterson
This file is part of The Codaphela Project: Codaphela SupportLib
Codaphela SupportLib is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Codaphela SupportLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Codaphela SupportLib. If not, see <http://www.gnu.org/licenses/>.
libpng is Copyright Glenn Randers-Pehrson
zlib is Copyright Jean-loup Gailly and Mark Adler
** ------------------------------------------------------------------------ **/
#include "ImageCelSourceGrid.h"
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void CImageCelSourceGrid::Init(CImageDividerNumbers* pcNumbers, SImageColour* psTransparentColour, bool bIgnoreEmpty, bool bCropTransparentBorders)
{
CImageCelSource::Init(psTransparentColour, bIgnoreEmpty, bCropTransparentBorders);
memcpy(&mcNumbers, pcNumbers, sizeof(CImageDividerNumbers));
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void CImageCelSourceGrid::Divide(CImage* pcImage, CArrayUnknown* pcDestImageCels, CImage* pcMask)
{
CImageDivider cDivider;
cDivider.Init(pcImage, mpsTransparentColour, mbIgnoreEmpty, mbCropTransparentBorders);
cDivider.GenerateFromNumbers(&mcNumbers);
cDivider.CopyCellsTo(pcDestImageCels);
cDivider.Kill();
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void CImageCelSourceGrid::Kill(void)
{
CImageCelSource::Kill();
}
| [
"[email protected]"
] | |
610bacff30e98790b0c5df64145b4a024ff953b8 | b86d7ba26f9ec19fcd29a03370870c1b41de6d6a | /RigidBodies/PhysicsProject/GroundContact.cpp | c75500376f35ff9e6bd8236f0369fbcf8a699b39 | [
"MIT"
] | permissive | mattstruble/PhysicSimulations | 68f1583a7568e4462f2fa6220555cd89ce2f4121 | 29e6b4c07a9faed5997a0023e953bf345f2e7323 | refs/heads/master | 2021-01-18T21:30:47.030298 | 2016-03-28T01:06:39 | 2016-03-28T01:06:39 | 30,939,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | //======================================================================
//File: GroundContact.cpp
//Author: Matt Struble
//======================================================================
#include "GroundContact.h"
//======================================================================
GroundContact::GroundContact(float groundY)
{
m_GroundY = groundY;
}
void GroundContact::AddContact(CollisionHandler* handler) const
{
std::vector<PhysicObject*> objects = handler->GetPhysicObjects();
std::vector<PhysicObject*>::iterator iter;
for (iter = objects.begin(); iter != objects.end(); iter++)
{
float objectY = (*iter)->GetPosition().Y - (*iter)->GetRadius();
if (objectY < m_GroundY)
{
float penetration = m_GroundY - objectY;
Contact contact;
contact.Object[0] = (*iter);
contact.Object[1] = nullptr;
contact.Penetration = penetration;
contact.Restitution = (*iter)->GetRestitution();
contact.ContactNormal = Vector3D(0, 1, 0);
handler->AddContact(contact);
}
}
} | [
"[email protected]"
] | |
b281a90ef20c42f49e45508dffb8404f17b2040f | d51674480aad7fb6a5a954271b14e565711c1113 | /ARGameTests/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp | d020a2426ddf2b84146bdd14aa06930278bcb970 | [] | no_license | cedricfoucault/AsteRoids | 9e91198525579e20393e60b22df71c331892aa2c | 43ded100505e3c949b3655825672c07c936423bf | refs/heads/master | 2021-01-10T21:30:03.609152 | 2014-10-15T03:36:20 | 2014-10-15T03:36:20 | 20,145,265 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,422 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btSimpleBroadphase.h"
#include "btDispatcher.h"
#include "btCollisionAlgorithm.h"
#include "btVector3.h"
#include "btTransform.h"
#include "btMatrix3x3.h"
#include "btAabbUtil2.h"
#include <new>
extern int gOverlappingPairs;
void btSimpleBroadphase::validate()
{
for (int i=0;i<m_numHandles;i++)
{
for (int j=i+1;j<m_numHandles;j++)
{
btAssert(&m_pHandles[i] != &m_pHandles[j]);
}
}
}
btSimpleBroadphase::btSimpleBroadphase(int maxProxies, btOverlappingPairCache* overlappingPairCache)
:m_pairCache(overlappingPairCache),
m_ownsPairCache(false),
m_invalidPair(0)
{
if (!overlappingPairCache)
{
void* mem = btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16);
m_pairCache = new (mem)btHashedOverlappingPairCache();
m_ownsPairCache = true;
}
// allocate handles buffer and put all handles on free list
m_pHandlesRawPtr = btAlignedAlloc(sizeof(btSimpleBroadphaseProxy)*maxProxies,16);
m_pHandles = new(m_pHandlesRawPtr) btSimpleBroadphaseProxy[maxProxies];
m_maxHandles = maxProxies;
m_numHandles = 0;
m_firstFreeHandle = 0;
m_LastHandleIndex = -1;
{
for (int i = m_firstFreeHandle; i < maxProxies; i++)
{
m_pHandles[i].SetNextFree(i + 1);
m_pHandles[i].m_uniqueId = i+2;//any UID will do, we just avoid too trivial values (0,1) for debugging purposes
}
m_pHandles[maxProxies - 1].SetNextFree(0);
}
}
btSimpleBroadphase::~btSimpleBroadphase()
{
btAlignedFree(m_pHandlesRawPtr);
if (m_ownsPairCache)
{
m_pairCache->~btOverlappingPairCache();
btAlignedFree(m_pairCache);
}
}
btBroadphaseProxy* btSimpleBroadphase::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* /*dispatcher*/,void* multiSapProxy)
{
if (m_numHandles >= m_maxHandles)
{
btAssert(0);
return 0; //should never happen, but don't let the game crash ;-)
}
btAssert(aabbMin[0]<= aabbMax[0] && aabbMin[1]<= aabbMax[1] && aabbMin[2]<= aabbMax[2]);
int newHandleIndex = allocHandle();
btSimpleBroadphaseProxy* proxy = new (&m_pHandles[newHandleIndex])btSimpleBroadphaseProxy(aabbMin,aabbMax,shapeType,userPtr,collisionFilterGroup,collisionFilterMask,multiSapProxy);
return proxy;
}
class RemovingOverlapCallback : public btOverlapCallback
{
protected:
virtual bool processOverlap(btBroadphasePair& pair)
{
(void)pair;
btAssert(0);
return false;
}
};
class RemovePairContainingProxy
{
btBroadphaseProxy* m_targetProxy;
public:
virtual ~RemovePairContainingProxy()
{
}
protected:
virtual bool processOverlap(btBroadphasePair& pair)
{
btSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy0);
btSimpleBroadphaseProxy* proxy1 = static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy1);
return ((m_targetProxy == proxy0 || m_targetProxy == proxy1));
};
};
void btSimpleBroadphase::destroyProxy(btBroadphaseProxy* proxyOrg,btDispatcher* dispatcher)
{
btSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(proxyOrg);
freeHandle(proxy0);
m_pairCache->removeOverlappingPairsContainingProxy(proxyOrg,dispatcher);
//validate();
}
void btSimpleBroadphase::getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const
{
const btSimpleBroadphaseProxy* sbp = getSimpleProxyFromProxy(proxy);
aabbMin = sbp->m_aabbMin;
aabbMax = sbp->m_aabbMax;
}
void btSimpleBroadphase::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* /*dispatcher*/)
{
btSimpleBroadphaseProxy* sbp = getSimpleProxyFromProxy(proxy);
sbp->m_aabbMin = aabbMin;
sbp->m_aabbMax = aabbMax;
}
void btSimpleBroadphase::rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin,const btVector3& aabbMax)
{
for (int i=0; i <= m_LastHandleIndex; i++)
{
btSimpleBroadphaseProxy* proxy = &m_pHandles[i];
if(!proxy->m_clientObject)
{
continue;
}
rayCallback.process(proxy);
}
}
void btSimpleBroadphase::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback)
{
for (int i=0; i <= m_LastHandleIndex; i++)
{
btSimpleBroadphaseProxy* proxy = &m_pHandles[i];
if(!proxy->m_clientObject)
{
continue;
}
if (TestAabbAgainstAabb2(aabbMin,aabbMax,proxy->m_aabbMin,proxy->m_aabbMax))
{
callback.process(proxy);
}
}
}
bool btSimpleBroadphase::aabbOverlap(btSimpleBroadphaseProxy* proxy0,btSimpleBroadphaseProxy* proxy1)
{
return proxy0->m_aabbMin[0] <= proxy1->m_aabbMax[0] && proxy1->m_aabbMin[0] <= proxy0->m_aabbMax[0] &&
proxy0->m_aabbMin[1] <= proxy1->m_aabbMax[1] && proxy1->m_aabbMin[1] <= proxy0->m_aabbMax[1] &&
proxy0->m_aabbMin[2] <= proxy1->m_aabbMax[2] && proxy1->m_aabbMin[2] <= proxy0->m_aabbMax[2];
}
//then remove non-overlapping ones
class CheckOverlapCallback : public btOverlapCallback
{
public:
virtual bool processOverlap(btBroadphasePair& pair)
{
return (!btSimpleBroadphase::aabbOverlap(static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy0),static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy1)));
}
};
void btSimpleBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher)
{
//first check for new overlapping pairs
int i,j;
if (m_numHandles >= 0)
{
int new_largest_index = -1;
for (i=0; i <= m_LastHandleIndex; i++)
{
btSimpleBroadphaseProxy* proxy0 = &m_pHandles[i];
if(!proxy0->m_clientObject)
{
continue;
}
new_largest_index = i;
for (j=i+1; j <= m_LastHandleIndex; j++)
{
btSimpleBroadphaseProxy* proxy1 = &m_pHandles[j];
btAssert(proxy0 != proxy1);
if(!proxy1->m_clientObject)
{
continue;
}
btSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0);
btSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1);
if (aabbOverlap(p0,p1))
{
if ( !m_pairCache->findPair(proxy0,proxy1))
{
m_pairCache->addOverlappingPair(proxy0,proxy1);
}
} else
{
if (!m_pairCache->hasDeferredRemoval())
{
if ( m_pairCache->findPair(proxy0,proxy1))
{
m_pairCache->removeOverlappingPair(proxy0,proxy1,dispatcher);
}
}
}
}
}
m_LastHandleIndex = new_largest_index;
if (m_ownsPairCache && m_pairCache->hasDeferredRemoval())
{
btBroadphasePairArray& overlappingPairArray = m_pairCache->getOverlappingPairArray();
//perform a sort, to find duplicates and to sort 'invalid' pairs to the end
overlappingPairArray.quickSort(btBroadphasePairSortPredicate());
overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);
m_invalidPair = 0;
btBroadphasePair previousPair;
previousPair.m_pProxy0 = 0;
previousPair.m_pProxy1 = 0;
previousPair.m_algorithm = 0;
for (i=0;i<overlappingPairArray.size();i++)
{
btBroadphasePair& pair = overlappingPairArray[i];
bool isDuplicate = (pair == previousPair);
previousPair = pair;
bool needsRemoval = false;
if (!isDuplicate)
{
bool hasOverlap = testAabbOverlap(pair.m_pProxy0,pair.m_pProxy1);
if (hasOverlap)
{
needsRemoval = false;//callback->processOverlap(pair);
} else
{
needsRemoval = true;
}
} else
{
//remove duplicate
needsRemoval = true;
//should have no algorithm
btAssert(!pair.m_algorithm);
}
if (needsRemoval)
{
m_pairCache->cleanOverlappingPair(pair,dispatcher);
// m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1);
// m_overlappingPairArray.pop_back();
pair.m_pProxy0 = 0;
pair.m_pProxy1 = 0;
m_invalidPair++;
gOverlappingPairs--;
}
}
///if you don't like to skip the invalid pairs in the array, execute following code:
#define CLEAN_INVALID_PAIRS 1
#ifdef CLEAN_INVALID_PAIRS
//perform a sort, to sort 'invalid' pairs to the end
overlappingPairArray.quickSort(btBroadphasePairSortPredicate());
overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);
m_invalidPair = 0;
#endif//CLEAN_INVALID_PAIRS
}
}
}
bool btSimpleBroadphase::testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)
{
btSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0);
btSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1);
return aabbOverlap(p0,p1);
}
void btSimpleBroadphase::resetPool(btDispatcher* dispatcher)
{
//not yet
}
| [
"[email protected]"
] | |
12ba7fa62779cda1943deffcd13fc312ccd89a77 | f791c1d59ec412dc89cfec1d1720bd1415d8a610 | /C_NOTES/6qt/4th/code/17Uart_Linux/17Uart_Linux-build-desktop/moc_Uart_Demo.cpp | c65f67b959d9cca71a91be07ffe1e52e5e4cb4d5 | [] | no_license | md-jamal/arm | 77080500f8f98ab9a0bc8320564170fc7cd38481 | a46ed1db6f78e417f0236c70494c0ba46743168a | refs/heads/master | 2020-05-18T22:48:59.155897 | 2017-03-22T11:29:49 | 2017-03-22T11:29:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,250 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'Uart_Demo.h'
**
** Created: Sun Oct 16 16:16:43 2016
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../Uart/Uart_Demo.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'Uart_Demo.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_Uart_Demo[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
8, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
11, 10, 10, 10, 0x08,
41, 10, 10, 10, 0x08,
73, 10, 10, 10, 0x08,
108, 10, 10, 10, 0x08,
137, 10, 10, 10, 0x08,
154, 10, 10, 10, 0x08,
178, 174, 10, 10, 0x08,
205, 200, 10, 10, 0x08,
0 // eod
};
static const char qt_meta_stringdata_Uart_Demo[] = {
"Uart_Demo\0\0on_pushButton_Clear_clicked()\0"
"on_pushButton_Connect_clicked()\0"
"on_pushButton_Disconnect_clicked()\0"
"on_pushButton_Send_clicked()\0"
"Slot_Connected()\0Slot_DisConnected()\0"
"msg\0Slot_PushMsg(QString)\0data\0"
"Slot_ReciveData(QByteArray)\0"
};
const QMetaObject Uart_Demo::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_Uart_Demo,
qt_meta_data_Uart_Demo, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &Uart_Demo::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *Uart_Demo::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *Uart_Demo::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_Uart_Demo))
return static_cast<void*>(const_cast< Uart_Demo*>(this));
return QMainWindow::qt_metacast(_clname);
}
int Uart_Demo::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: on_pushButton_Clear_clicked(); break;
case 1: on_pushButton_Connect_clicked(); break;
case 2: on_pushButton_Disconnect_clicked(); break;
case 3: on_pushButton_Send_clicked(); break;
case 4: Slot_Connected(); break;
case 5: Slot_DisConnected(); break;
case 6: Slot_PushMsg((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 7: Slot_ReciveData((*reinterpret_cast< QByteArray(*)>(_a[1]))); break;
default: ;
}
_id -= 8;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
b995bbead7e4eceebd66455c2db38a334005167d | 23346e53a5b4d7f0110a737f04af510215b97742 | /Source/main.cpp | a64b4548176529bc7e159ada4cf490076d512094 | [
"MIT"
] | permissive | Balajanovski/3D-Tetris | f0a5196961736f12b5ace9a4aab5f90461e9fdfe | 82e605a7f6504c64c932080514e5a5aefc8332aa | refs/heads/master | 2020-03-12T04:04:18.573610 | 2018-06-23T04:06:51 | 2018-06-23T04:06:51 | 130,437,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152 | cpp | //
// Created by Balajanovski on 21/04/2018.
//
#include "Game.h"
#include <memory>
int main() {
Game game;
game.begin();
return 0;
}
| [
"[email protected]"
] | |
6b8476a43cc10aa5e6b0b377ad6a26b04bd25d5f | 57ccce3a8cf3c498ce56e5263e1d9b8ed39bd8c3 | /Arduino/_5ana10digi/edge_detection/edge_detection.ino | b1502f7e6e502af5d27ae73dbfd9ccd63125d1c9 | [] | no_license | andychuong/arduinocontrollers | 1abcde593eaa27befa6b3debd5232974f0e1cda0 | 05bc14289cfa11fd40896db1b6b545ed9362be55 | refs/heads/master | 2021-08-31T13:21:52.204972 | 2017-12-21T12:47:01 | 2017-12-21T12:47:01 | 103,429,841 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,496 | ino | /*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time, but
you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
- pushbutton attached to pin 2 from +5V
- 10 kilohm resistor attached to pin 2 from ground
- LED attached from pin 13 to ground (or use the built-in LED on most
Arduino boards)
created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/ButtonStateChange
*/
// this constant won't change:
const int buttonPin = 7; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
// turns on the LED every four button pushes by checking the modulo of the
// button push counter. the modulo function gives you the remainder of the
// division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
| [
"[email protected]"
] | |
bad7d62c15e124a42f1ef4f6c8e7418b942a215f | 6c2b9b9fd3c5d6db83f426b54ba3472be2007926 | /examples/flycapture/src/HighDynamicRangeEx/HighDynamicRangeEx.cpp | d5269539721e2e0315d72a4c2ff998dfdf1186e0 | [] | no_license | TempleWaterfOWLS/stereovision | 6f3ecd3200e4495e3cd7a74e0b66bcae5d3e3453 | 1a474b3632bfa54f6f120fd0613dbf8768224215 | refs/heads/master | 2016-08-06T08:39:54.379351 | 2014-10-26T21:41:46 | 2014-10-26T21:41:46 | 25,792,082 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 7,411 | cpp | //=============================================================================
// Copyright © 2008 Point Grey Research, Inc. All Rights Reserved.
//
// This software is the confidential and proprietary information of Point
// Grey Research, Inc. ("Confidential Information"). You shall not
// disclose such Confidential Information and shall use it only in
// accordance with the terms of the license agreement you entered into
// with PGR.
//
// PGR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
// SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE, OR NON-INFRINGEMENT. PGR SHALL NOT BE LIABLE FOR ANY DAMAGES
// SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
// THIS SOFTWARE OR ITS DERIVATIVES.
//=============================================================================
//=============================================================================
// $Id: HighDynamicRangeEx.cpp,v 1.18 2010-04-01 20:34:47 oscarp Exp $
//=============================================================================
#include "stdafx.h"
#include "FlyCapture2.h"
using namespace FlyCapture2;
const unsigned int k_HDRCtrl = 0x1800;
const unsigned int k_HDRShutter1 = 0x1820;
const unsigned int k_HDRShutter2 = 0x1840;
const unsigned int k_HDRShutter3 = 0x1860;
const unsigned int k_HDRShutter4 = 0x1880;
const unsigned int k_HDRGain1 = 0x1824;
const unsigned int k_HDRGain2 = 0x1844;
const unsigned int k_HDRGain3 = 0x1864;
const unsigned int k_HDRGain4 = 0x1884;
const unsigned int k_HDROn = 0x82000000;
const unsigned int k_HDROff = 0x80000000;
void PrintBuildInfo()
{
FC2Version fc2Version;
Utilities::GetLibraryVersion( &fc2Version );
char version[128];
sprintf(
version,
"FlyCapture2 library version: %d.%d.%d.%d\n",
fc2Version.major, fc2Version.minor, fc2Version.type, fc2Version.build );
printf( "%s", version );
char timeStamp[512];
sprintf( timeStamp, "Application build date: %s %s\n\n", __DATE__, __TIME__ );
printf( "%s", timeStamp );
}
void PrintCameraInfo( CameraInfo* pCamInfo )
{
printf(
"\n*** CAMERA INFORMATION ***\n"
"Serial number - %u\n"
"Camera model - %s\n"
"Camera vendor - %s\n"
"Sensor - %s\n"
"Resolution - %s\n"
"Firmware version - %s\n"
"Firmware build time - %s\n\n",
pCamInfo->serialNumber,
pCamInfo->modelName,
pCamInfo->vendorName,
pCamInfo->sensorInfo,
pCamInfo->sensorResolution,
pCamInfo->firmwareVersion,
pCamInfo->firmwareBuildTime );
}
void PrintError( Error error )
{
error.PrintErrorTrace();
}
bool IsHDRSupported( Camera* pCam )
{
Error error;
unsigned int RegVal;
error = pCam->ReadRegister( k_HDRCtrl, &RegVal );
if (error != PGRERROR_OK)
{
PrintError( error );
return false;
}
return ( !0x80000000 & RegVal ) ? false : true;
}
void ToggleHDRMode( Camera* pCam, bool hdrOn )
{
Error error;
error = pCam->WriteRegister( k_HDRCtrl, hdrOn ? k_HDROn : k_HDROff );
if (error != PGRERROR_OK)
{
PrintError( error );
}
printf( "HDR mode turned to %s\n", hdrOn ? "on" : "off" );
}
void InitializeHDRRegisters( Camera* pCam )
{
Error error;
error = pCam->WriteRegister( k_HDRShutter1, 0x000 );
error = pCam->WriteRegister( k_HDRShutter2, 0x120 );
error = pCam->WriteRegister( k_HDRShutter3, 0x240 );
error = pCam->WriteRegister( k_HDRShutter4, 0x360 );
error = pCam->WriteRegister( k_HDRGain1, 0x000 );
error = pCam->WriteRegister( k_HDRGain2, 0x0E3 );
error = pCam->WriteRegister( k_HDRGain3, 0x1C6 );
error = pCam->WriteRegister( k_HDRGain4, 0x2A9 );
printf( "Initialized HDR registers...\n" );
}
int main(int /*argc*/, char** /*argv*/)
{
PrintBuildInfo();
Error error;
// Since this application saves images in the current folder
// we must ensure that we have permission to write to this folder.
// If we do not have permission, fail right away.
FILE* tempFile = fopen("test.txt", "w+");
if (tempFile == NULL)
{
printf("Failed to create file in current folder. Please check permissions.\n");
return -1;
}
fclose(tempFile);
remove("test.txt");
BusManager busMgr;
unsigned int numCameras;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Number of cameras detected: %u\n", numCameras );
if ( numCameras < 1 )
{
printf( "Insufficient number of cameras... exiting\n" );
return -1;
}
PGRGuid guid;
error = busMgr.GetCameraFromIndex(0, &guid);
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
Camera cam;
// Connect to a camera
error = cam.Connect(&guid);
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Get the camera information
CameraInfo camInfo;
error = cam.GetCameraInfo(&camInfo);
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
PrintCameraInfo(&camInfo);
error = cam.StartCapture();
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
bool supported = IsHDRSupported( &cam );
if ( supported != true )
{
printf( "HDR is not supported! Exiting...\n" );
return -1;
}
InitializeHDRRegisters( &cam );
ToggleHDRMode( &cam, true );
// Grab 4 images
Image rawImage[4];
for ( int imageCnt=0; imageCnt < 4; imageCnt++ )
{
error = cam.RetrieveBuffer( &rawImage[ imageCnt] );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Grabbed image %d\n", imageCnt );
}
// Process and save the 4 images
for ( int imageCnt=0; imageCnt < 4; imageCnt++ )
{
// Create a converted image
Image convertedImage;
// Convert the raw image
error = rawImage[ imageCnt].Convert( PIXEL_FORMAT_BGRU, &convertedImage );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Converted image %d\n", imageCnt );
// Create a unique filename
char filename[512];
sprintf( filename, "HDR-%u-%d.ppm", camInfo.serialNumber, imageCnt );
// Save the image. If a file format is not passed in, then the file
// extension is parsed to attempt to determine the file format.
error = convertedImage.Save( filename );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Saved image %d\n", imageCnt );
}
printf( "\nFinished grabbing images\n" );
// Stop capturing images
error = cam.StopCapture();
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
ToggleHDRMode( &cam, false );
// Disconnect the camera
error = cam.Disconnect();
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Done! Press Enter to exit...\n" );
getchar();
return 0;
}
| [
"[email protected]"
] | |
b2bb8ee9ee16014597c5b9996b7a82cd54b5d982 | 3b0e0479671b78e9b3354950dbe4e0c678966260 | /Examples/SDL/LazyFoo_SDL_Examples/12_color_modulation/12_color_modulation.cpp | 300f06b5531ad859f2e03136c58a5f2d6bde6c8f | [] | no_license | aatwo/examples-and-tests | 67af5c8ebb0999e4555117b7642003335dd4b673 | b332274762bed6dfb40e6f0ab60959fcfc9c83b0 | refs/heads/master | 2022-04-03T23:16:58.596559 | 2020-01-19T13:27:36 | 2020-01-19T13:27:36 | 56,585,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,520 | cpp | /*This source code copyrighted by Lazy Foo' Productions (2004-2015)
and may not be redistributed without written permission.*/
//Using SDL, SDL_image, standard IO, and strings
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <string>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
//Texture wrapper class
class LTexture
{
public:
//Initializes variables
LTexture();
//Deallocates memory
~LTexture();
//Loads image at specified path
bool loadFromFile( std::string path );
//Deallocates texture
void free();
//Set color modulation
void setColor( Uint8 red, Uint8 green, Uint8 blue );
//Renders texture at given point
void render( int x, int y, SDL_Rect* clip = NULL );
//Gets image dimensions
int getWidth();
int getHeight();
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
};
//Starts up SDL and creates window
bool init();
//Loads media
bool loadMedia();
//Frees media and shuts down SDL
void close();
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The window renderer
SDL_Renderer* gRenderer = NULL;
//Scene texture
LTexture gModulatedTexture;
LTexture::LTexture()
{
//Initialize
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
LTexture::~LTexture()
{
//Deallocate
free();
}
bool LTexture::loadFromFile( std::string path )
{
//Get rid of preexisting texture
free();
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL )
{
printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
}
else
{
//Color key image
SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
{
printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
else
{
//Get image dimensions
mWidth = loadedSurface->w;
mHeight = loadedSurface->h;
}
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
}
//Return success
mTexture = newTexture;
return mTexture != NULL;
}
void LTexture::free()
{
//Free texture if it exists
if( mTexture != NULL )
{
SDL_DestroyTexture( mTexture );
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
void LTexture::setColor( Uint8 red, Uint8 green, Uint8 blue )
{
//Modulate texture
SDL_SetTextureColorMod( mTexture, red, green, blue );
}
void LTexture::render( int x, int y, SDL_Rect* clip )
{
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, mWidth, mHeight };
//Set clip rendering dimensions
if( clip != NULL )
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
//Render to screen
SDL_RenderCopy( gRenderer, mTexture, clip, &renderQuad );
}
int LTexture::getWidth()
{
return mWidth;
}
int LTexture::getHeight()
{
return mHeight;
}
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Set texture filtering to linear
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning: Linear texture filtering not enabled!" );
}
//Create window
gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! %s\n", SDL_GetError() );
success = false;
}
else
{
//Create renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
if( gRenderer == NULL )
{
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
}
}
}
return success;
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Load texture
if( !gModulatedTexture.loadFromFile( "12_color_modulation/colors.png" ) )
{
printf( "Failed to load colors texture!\n" );
success = false;
}
return success;
}
void close()
{
//Free loaded images
gModulatedTexture.free();
//Destroy window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
int main( int argc, char* args[] )
{
//Start up SDL and create window
if( !init() )
{
printf( "Failed to initialize!\n" );
}
else
{
//Load media
if( !loadMedia() )
{
printf( "Failed to load media!\n" );
}
else
{
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//Modulation components
Uint8 r = 255;
Uint8 g = 255;
Uint8 b = 255;
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit = true;
}
//On keypress change rgb values
else if( e.type == SDL_KEYDOWN )
{
switch( e.key.keysym.sym )
{
//Increase red
case SDLK_q:
r += 32;
break;
//Increase green
case SDLK_w:
g += 32;
break;
//Increase blue
case SDLK_e:
b += 32;
break;
//Decrease red
case SDLK_a:
r -= 32;
break;
//Decrease green
case SDLK_s:
g -= 32;
break;
//Decrease blue
case SDLK_d:
b -= 32;
break;
}
}
}
//Clear screen
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gRenderer );
//Modulate and render texture
gModulatedTexture.setColor( r, g, b );
gModulatedTexture.render( 0, 0 );
//Update screen
SDL_RenderPresent( gRenderer );
}
}
}
//Free resources and close SDL
close();
return 0;
}
| [
"[email protected]"
] | |
487e4231316647d1e5e4ed18f39294844d378243 | 6406ffa37fd4b705e61b79312f0ebe1035228365 | /src/edge/PacketClassifier.cc | 229888145f0a428c4f6bad230716ffe02eb81ce5 | [] | no_license | kitakita/omnetpp_obs | 65904d4e37637706a385476f7c33656c491e2fbd | 19e7c8f0eafcd293d381e733712ecbb2a3564b08 | refs/heads/master | 2021-01-02T12:55:37.328995 | 2011-01-30T10:42:56 | 2011-01-30T10:42:56 | 1,189,202 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,593 | cc | //
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "PacketClassifier.h"
#include "IPControlInfo.h"
Define_Module(PacketClassifier);
void PacketClassifier::initialize()
{
// nothing
}
void PacketClassifier::handleMessage(cMessage *msg)
{
send(msg, "out", getQueueIndex(msg));
}
int PacketClassifier::getQueueIndex(cMessage *msg)
{
cPacket *pkt = check_and_cast<cPacket*>(msg);
IPControlInfo *ctrl = (IPControlInfo *)pkt->getControlInfo();
IPAddress destAddr = ctrl->getDestAddr();
std::vector<IPAddress>::iterator it = destAddresses.begin();
for(int i = 0; it != destAddresses.end(); i++, it++)
if (*it == destAddr) return i;
destAddresses.push_back(destAddr);
// if ((int)destAddresses.size() > gate("out")->getVectorSize())
// opp_error("Queue index is out of range. (Destinations: %d, Gates: %d)", destAddresses.size(), gate("out")->getVectorSize());
return destAddresses.size() - 1;
}
| [
"[email protected]"
] | |
d664c68f05d841f0c2d0b5f1d2924549666c3691 | e4417f38ab4f54f8f3099261c80bc36f0c0ba703 | /resources/sources/Physics/PhysicsModule.cpp | 106b6ecdd259768989a183817cd9df66464dcf22 | [] | no_license | Codibri/HardrockHoliday | 65b68ca81312903e33dc4e0e307a4050e81789a0 | 5c9b4f92196ba0f2da010b0da91633f4f7347589 | refs/heads/master | 2016-09-05T13:22:02.351272 | 2015-01-16T01:51:05 | 2015-01-16T01:51:05 | 26,432,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,962 | cpp | #include "Physics\PhysicsModule.h"
/***************************************
#PhysicsModule.cpp
@(#)Author: Alexander Thoma
▄████▄ ▒█████ ▓█████▄ ▓█████ ▒██ ██▒
▒██▀ ▀█ ▒██▒ ██▒▒██▀ ██▌▓█ ▀ ▒▒ █ █ ▒░
▒▓█ ▄▒██░ ██▒░██ █▌▒███ ░░ █ ░
▒▓▓▄ ▄██▒██ ██░░▓█▄ ▌▒▓█ ▄ ░ █ █ ▒
▒ ▓███▀ ░ ████▓▒░░▒████▓ ░▒████▒▒██▒ ▒██▒
░ ░▒ ▒ ░ ▒░▒░▒░ ▒▒▓ ▒ ░░ ▒░ ░▒▒ ░ ░▓ ░
░ ▒ ░ ▒ ▒░ ░ ▒ ▒ ░ ░ ░░░ ░▒ ░
░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
****************************************/
PhysicsModule::PhysicsModule() : EngineModule()
{
m_physics = phyX::CPhysiX::GetInstance();
}
PhysicsModule::~PhysicsModule()
{
m_physics->Destroy();
}
void PhysicsModule::postUpdate(float deltaTime, float time)
{
m_physics->PostRenderUpdate(deltaTime);
}
void PhysicsModule::PostRenderUpdate(float fTimeDelta)
{
m_physics->PostRenderUpdate(fTimeDelta);
}
void PhysicsModule::RefreshPhysiX()
{
m_physics->RefreshPhysiX();
}
int PhysicsModule::AddPhysiXLayer(std::string layer)
{
return m_physics->AddPhysiXLayer(layer);
}
std::string PhysicsModule::TranslateLayer(unsigned int LayerNumber)
{
return m_physics->TranslateLayer(LayerNumber);
}
int PhysicsModule::GetLayerNumber(std::string layerName)
{
return m_physics->GetLayerNumber(layerName);
}
bool PhysicsModule::SetLayerProperty(std::string layer, std::string layer1, bool collision)
{
return m_physics->SetLayerProperty(layer, layer1, collision);
}
void PhysicsModule::PrintLayerMatrix()
{
m_physics->PrintLayerMatrix();
} | [
"[email protected]"
] | |
d7c9657b069954ee8e142e2ac6dafe97067d8fce | 73f60774d2f915dad00a21eabd9cfd149794fcc8 | /GameEngine/GameEngine/src/Transform.cpp | 3529d48f2707dcd83440956aa1eaac6a1c0473ef | [
"Apache-2.0"
] | permissive | SamCooksley/GameEngine | 58e015f6e21755193439c0d4afb75276320e9786 | 3c32eba545428c8aa3227abcb815d8d799ab92d9 | refs/heads/master | 2021-04-12T11:06:53.832122 | 2018-08-30T19:22:38 | 2018-08-30T19:22:38 | 126,532,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,325 | cpp | #include "stdafx.h"
#include "Transform.h"
namespace engine {
glm::mat4 Transform::getTransform(
const glm::vec3 & _position,
const glm::quat & _rotation,
const glm::vec3 & _scale
)
{
return glm::translate(_position) * glm::mat4_cast(_rotation) * glm::scale(_scale);
}
glm::vec3 Transform::getRight(const glm::mat4 & _transform)
{
return glm::normalize(glm::vec3(_transform[0]));
}
glm::vec3 Transform::getUp(const glm::mat4 & _transform)
{
return glm::normalize(glm::vec3(_transform[1]));
}
glm::vec3 Transform::getForward(const glm::mat4 & _transform)
{
return glm::normalize(glm::vec3(_transform[2]));
}
Transform::Transform()
{ }
Transform::~Transform()
{ }
void Transform::get(glm::vec3 * _position, glm::quat * _rotation, glm::vec3 * _scale, glm::mat4 * _transform) const
{
glm::mat4 transform(1.f);
glm::quat rotation;
glm::vec3 scale(1.f);
std::shared_ptr<const Transform> trs = Transform::getShared();
while (trs)
{
transform = trs->getLocalTransform() * transform;
rotation = trs->m_localRotation * rotation;
scale = trs->m_localScale * scale;
trs = trs->m_parent.lock();
}
if (_position != nullptr)
{
*_position = glm::vec3(transform * glm::vec4(0.f, 0.f, 0.f, 1.f));
}
if (_rotation != nullptr)
{
*_rotation = rotation;
}
if (_scale != nullptr)
{
*_scale = scale;
}
if (_transform != nullptr)
{
*_transform = transform;
}
}
glm::vec3 Transform::getPosition() const
{
glm::vec3 pos;
get(&pos);
return pos;
}
glm::quat Transform::getRotation() const
{
glm::quat rot;
get(nullptr, &rot);
return rot;
}
glm::vec3 Transform::getScale() const
{
glm::vec3 scale;
get(nullptr, nullptr, &scale);
return scale;
}
glm::vec3 Transform::getLocalPosition() const
{
return m_localPosition;
}
glm::quat Transform::getLocalRotation() const
{
return m_localRotation;
}
glm::vec3 Transform::getLocalScale() const
{
return m_localScale;
}
glm::vec3 Transform::getRight() const
{
glm::vec3 pos; glm::quat rot;
get(&pos, &rot);
return getRight(getTransform(pos, rot, glm::vec3(1.f)));
}
glm::vec3 Transform::getUp() const
{
glm::vec3 pos; glm::quat rot;
get(&pos, &rot);
return getUp(getTransform(pos, rot, glm::vec3(1.f)));
}
glm::vec3 Transform::getForward() const
{
glm::vec3 pos; glm::quat rot;
get(&pos, &rot);
return getForward(getTransform(pos, rot, glm::vec3(1.f)));
}
glm::vec3 Transform::TransformPoint(const glm::vec3 & _point) const
{
glm::mat4 trs;
get(nullptr, nullptr, nullptr, &trs);
return glm::vec3(trs * glm::vec4(_point, 1.f));
}
glm::vec3 Transform::InverseTransformPoint(const glm::vec3 & _point) const
{
glm::mat4 trs;
get(nullptr, nullptr, nullptr, &trs);
return glm::vec3(glm::inverse(trs) * glm::vec4(_point, 1.f));
}
Transform & Transform::setPosition(const glm::vec3 & _position)
{
std::shared_ptr<Transform> parent = m_parent.lock();
if (parent)
{
glm::mat4 transform(1.f);
while (parent)
{
transform = parent->getLocalTransform() * transform;
parent = parent->m_parent.lock();
}
m_localPosition = glm::vec3(glm::inverse(transform) * glm::vec4(_position, 1.f));
}
else
{
m_localPosition = _position;
}
return *this;
}
Transform & Transform::setRotation(const glm::quat & _rotation)
{
std::shared_ptr<Transform> parent = m_parent.lock();
if (parent)
{
glm::quat rotation;
while (parent)
{
rotation = glm::inverse(parent->m_localRotation) * rotation;
parent = parent->m_parent.lock();
}
m_localRotation = rotation * _rotation;
}
else
{
m_localRotation = _rotation;
}
return *this;
}
Transform & Transform::setLocalPosition(const glm::vec3 & _position)
{
m_localPosition = _position;
return *this;
}
Transform & Transform::setLocalRotation(const glm::quat & _rotation)
{
m_localRotation = _rotation;
return *this;
}
Transform & Transform::setLocalScale(const glm::vec3 & _scale)
{
m_localScale = _scale;
return *this;
}
void Transform::OnAwake()
{
Component::OnAwake();
m_localPosition = glm::vec3(0.f);
m_localRotation = glm::quat();
m_localScale = glm::vec3(1.f);
m_parent.reset();
m_children.clear();
}
void Transform::OnDestroy()
{
Component::OnDestroy();
setParent(nullptr);
DestroyChildren();
}
void Transform::DetachChildren(const std::shared_ptr<Transform> & _newParent)
{
//if it is being added to the same parent, nothing changes.
if (_newParent.get() == this) { return; }
while (!m_children.empty())
{
std::shared_ptr<Transform> child = m_children.back().lock();
child->setParent(_newParent);
}
}
void Transform::DestroyChildren()
{
while (!m_children.empty())
{
std::shared_ptr<Transform> child = m_children.back().lock();
child->setParent(nullptr);
child->Destroy();
}
}
Transform & Transform::setParent(const std::shared_ptr<Transform> & _parent)
{
std::shared_ptr<Transform> parent = m_parent.lock();
if (parent)
{
parent->RemoveChild(Transform::getShared());
}
m_parent = _parent;
if (_parent)
{
_parent->AddChild(Transform::getShared());
}
return *this;
}
void Transform::AddChild(const std::shared_ptr<Transform> & _child)
{
//exit if the child already exits.
for (size_t i = 0; i < m_children.size(); ++i)
{
if (m_children[i].lock() == _child)
{
return;
}
}
m_children.push_back(_child);
}
void Transform::RemoveChild(const std::shared_ptr<Transform> & _child)
{
for (size_t i = 0; i < m_children.size();)
{
if (m_children[i].lock() == _child)
{
m_children.erase(std::begin(m_children) + i);
}
else { ++i; }
}
}
glm::mat4 Transform::getLocalTransform() const
{
return getTransform(m_localPosition, m_localRotation, m_localScale);
}
} // engine | [
"[email protected]"
] | |
aed570da708b409de471985e9e44ad8f223df757 | bb6ebff7a7f6140903d37905c350954ff6599091 | /chrome/browser/ui/views/bookmarks/bookmark_menu_controller_views.h | 89ba38e2dad5112e9dc3ac19fd9cce075044982c | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 5,174 | h | // 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.
#ifndef CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_MENU_CONTROLLER_VIEWS_H_
#define CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_MENU_CONTROLLER_VIEWS_H_
#include <set>
#include "base/compiler_specific.h"
#include "components/bookmarks/browser/base_bookmark_model_observer.h"
#include "components/bookmarks/browser/bookmark_node_data.h"
#include "ui/views/controls/menu/menu_delegate.h"
class BookmarkBarView;
class BookmarkMenuControllerObserver;
class BookmarkMenuDelegate;
class BookmarkNode;
class Browser;
namespace content {
class PageNavigator;
}
namespace ui {
class OSExchangeData;
}
namespace views {
class MenuButton;
class MenuItemView;
class MenuRunner;
class Widget;
}
// BookmarkMenuController is responsible for showing a menu of bookmarks,
// each item in the menu represents a bookmark.
// BookmarkMenuController deletes itself as necessary, although the menu can
// be explicitly hidden by way of the Cancel method.
class BookmarkMenuController : public BaseBookmarkModelObserver,
public views::MenuDelegate {
public:
// Creates a BookmarkMenuController showing the children of |node| starting
// at |start_child_index|.
BookmarkMenuController(Browser* browser,
content::PageNavigator* page_navigator,
views::Widget* parent,
const BookmarkNode* node,
int start_child_index);
void RunMenuAt(BookmarkBarView* bookmark_bar, bool for_drop);
void clear_bookmark_bar() {
bookmark_bar_ = NULL;
}
// Hides the menu.
void Cancel();
// Returns the node the menu is showing for.
const BookmarkNode* node() const { return node_; }
// Returns the menu.
views::MenuItemView* menu() const;
// Returns the context menu, or NULL if the context menu isn't showing.
views::MenuItemView* context_menu() const;
// Sets the page navigator.
void SetPageNavigator(content::PageNavigator* navigator);
void set_observer(BookmarkMenuControllerObserver* observer) {
observer_ = observer;
}
// views::MenuDelegate:
virtual base::string16 GetTooltipText(int id,
const gfx::Point& p) const OVERRIDE;
virtual bool IsTriggerableEvent(views::MenuItemView* view,
const ui::Event& e) OVERRIDE;
virtual void ExecuteCommand(int id, int mouse_event_flags) OVERRIDE;
virtual bool ShouldExecuteCommandWithoutClosingMenu(
int id,
const ui::Event& e) OVERRIDE;
virtual bool GetDropFormats(
views::MenuItemView* menu,
int* formats,
std::set<ui::OSExchangeData::CustomFormat>* custom_formats) OVERRIDE;
virtual bool AreDropTypesRequired(views::MenuItemView* menu) OVERRIDE;
virtual bool CanDrop(views::MenuItemView* menu,
const ui::OSExchangeData& data) OVERRIDE;
virtual int GetDropOperation(views::MenuItemView* item,
const ui::DropTargetEvent& event,
DropPosition* position) OVERRIDE;
virtual int OnPerformDrop(views::MenuItemView* menu,
DropPosition position,
const ui::DropTargetEvent& event) OVERRIDE;
virtual bool ShowContextMenu(views::MenuItemView* source,
int id,
const gfx::Point& p,
ui::MenuSourceType source_type) OVERRIDE;
virtual void DropMenuClosed(views::MenuItemView* menu) OVERRIDE;
virtual bool CanDrag(views::MenuItemView* menu) OVERRIDE;
virtual void WriteDragData(views::MenuItemView* sender,
ui::OSExchangeData* data) OVERRIDE;
virtual int GetDragOperations(views::MenuItemView* sender) OVERRIDE;
virtual views::MenuItemView* GetSiblingMenu(
views::MenuItemView* menu,
const gfx::Point& screen_point,
views::MenuAnchorPosition* anchor,
bool* has_mnemonics,
views::MenuButton** button) OVERRIDE;
virtual int GetMaxWidthForMenu(views::MenuItemView* view) OVERRIDE;
// BaseBookmarkModelObserver:
virtual void BookmarkModelChanged() OVERRIDE;
private:
// BookmarkMenuController deletes itself as necessary.
virtual ~BookmarkMenuController();
scoped_ptr<views::MenuRunner> menu_runner_;
scoped_ptr<BookmarkMenuDelegate> menu_delegate_;
// The node we're showing the contents of.
const BookmarkNode* node_;
// Data for the drop.
BookmarkNodeData drop_data_;
// The observer, may be null.
BookmarkMenuControllerObserver* observer_;
// Is the menu being shown for a drop?
bool for_drop_;
// The bookmark bar. This is only non-null if we're showing a menu item for a
// folder on the bookmark bar and not for drop, or if the BookmarkBarView has
// been destroyed before the menu.
BookmarkBarView* bookmark_bar_;
DISALLOW_COPY_AND_ASSIGN(BookmarkMenuController);
};
#endif // CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_MENU_CONTROLLER_VIEWS_H_
| [
"[email protected]"
] | |
e191b24ab8ff99b502f47b04db5610c806e22c45 | 861c6b196ec440027bebc410f2e03a21fc5948a6 | /fmi/fmi tests/11.test/removingEdges.cpp | e463ec0c8ac1c75fcaa7424f794bf545184f3c79 | [] | no_license | VPetrova00/Data-structures-and-algorithms | 54b324a80d90aa5d66bc5234e9ac01a57e33a675 | 33c8a2e1209d1fa8ec2528b6db59008cd11200bb | refs/heads/master | 2023-03-07T18:41:49.376180 | 2021-02-19T14:52:40 | 2021-02-19T14:52:40 | 321,169,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | cpp | #include <iostream>
#include <vector>
#include <list>
using namespace std;
int maxEdgesToRemove(int src, const vector<list<int>> &adjList, vector<int> &count) {
count[src] = 1;
int total = 0;
for (auto &c: adjList[src]) {
if (count[c] == 0) {
total += maxEdgesToRemove(c, adjList, count);
count[src] += count[c];
if (count[c] % 2 == 0) {
total++;
}
}
}
return total;
}
int main() {
int V, E;
cin >> V >> E;
vector<list<int> > adjList(V, list<int>());
for (int i = 0; i < E; ++i) {
int from, to;
cin >> from >> to;
from--;
to--;
adjList[from].push_back(to);
adjList[to].push_back(from);
}
vector<int> count(V, 0);
cout << maxEdgesToRemove(0, adjList, count) << endl;
return 0;
} | [
"[email protected]"
] | |
6cabde81050a5b31d8102afe436fc2711d780e02 | 447cfa0acc4a565a2ed7515bce5e12056e7583d9 | /PC_Tracker/APU.SDL.OLD.DONT.TOUCH/gme_vspc/shared/Midi.h | f21d8e3abcfc0c886d7f333007832c07d6aaf324 | [] | no_license | bepisTM/SNES-Tracker | 0608d4a32cd081183a01481b7768021b2576c286 | b98ebf5618d2acbfc6f60519868802092ff76410 | refs/heads/master | 2021-05-04T23:17:42.114218 | 2016-04-09T03:44:13 | 2016-04-09T03:44:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | h | #pragma once
#include <map>
#include "RtMidi.h"
#include "App_Settings_Context.h"
#include "jdkmidi/world.h"
#include "jdkmidi/midi.h"
#include "jdkmidi/msg.h"
#include "jdkmidi/sysex.h"
#include "jdkmidi/parser.h"
struct Midi : public App_Settings_Context
{
Midi();
~Midi();
void PrintSysEx( FILE *f, jdkmidi::MIDISystemExclusive *ex );
void PrintMsg( FILE *f, jdkmidi::MIDIMessage *m );
void internal_callback(double &deltatime, std::vector< unsigned char > **message);
/* RtMidi Stuffz */
std::map<int, std::string> apiMap;
std::vector< RtMidi::Api > apis;
std::vector<std::string> available_devices;
RtMidiIn in;
bool is_available=true;
//RtMidiOut *midiout = 0;
Uint8 last_note_on=0;
// jdkmidi stuffz
jdkmidi::MIDIParser parser;
jdkmidi::MIDIMessage msg;
}; | [
"[email protected]"
] | |
69bc8982dc953001230d41d664c38758bb6d3f2a | b6b6f8834f97d128de6a7fcc7319bdf5b8826ebe | /tugboat_control/src/ShipControl_Generic.cpp | 006a815eb390d9a231dca8f3f35138f1d27520be | [] | no_license | Sondrenm/Master-git | d3f027731a7138127dd0fb50c5f52d64863b5aba | 5bfda935b8824649f75b5bf5daef2879bc623d2c | refs/heads/master | 2021-01-18T20:24:40.493091 | 2017-07-24T19:26:17 | 2017-07-24T19:26:17 | 80,836,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,466 | cpp | /* Description:
START_UNIQUE
This is an example algorithm for shipControl, which simply arranges tugboat(s)
along one side of the ship, and tries to maintain contact.
STOP_UNIQUE */
#include "ros/ros.h"
#include "tugboat_control/BoatPose.h"
#include "tugboat_control/Waypoint.h"
#include "tugboat_control/PushingForce.h"
#include "tugboat_control/TugSetpoints.h"
#include "std_msgs/Bool.h"
#include "std_msgs/UInt8MultiArray.h"
#include "std_msgs/UInt8.h"
#include "tugboat_control/addOneTug.h"
#include "tugboat_control/removeOneTug.h"
#include "/usr/local/include/PID_cpp/pid.h"
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <vector>
#define SHIP_ID 0 //Should be 0! 4 for testing purposes ony
#define ACCEPTABLE_DIST_ERROR 0.5 //0.5 m from ship means tug has lost contact
int numCtrlTugs = 0;
std_msgs::UInt8MultiArray ctrlTugIDs;
std::vector<tugboat_control::BoatPose> tugPoses; //In ship coordinates (x is along ship)
tugboat_control::BoatPose shipPose;
tugboat_control::Waypoint shipWaypoint;
std_msgs::UInt8MultiArray discardTugs;
void shipPoseCallback(const tugboat_control::BoatPose::ConstPtr& pose_in)
{
shipPose = *pose_in;
}
tugboat_control::BoatPose worldToShipCoordinates(tugboat_control::BoatPose poseIn)
{ //Transforms from world coordinates to ship coordinates
tugboat_control::BoatPose poseOut;
poseOut.ID = poseIn.ID;
poseOut.o = PIDnormalizeAngle( poseIn.o - shipPose.o );
double xTemp = poseIn.x - shipPose.x;
double yTemp = poseIn.y - shipPose.y;
double sinO = sin(poseOut.o);
double cosO = cos(poseOut.o);
poseOut.x = xTemp * cosO - yTemp * sinO;
poseOut.y = xTemp * sinO + yTemp * cosO;
return poseOut;
}
void tugPoseCallback(const tugboat_control::BoatPose::ConstPtr& pose_in)
{
for (int tug = 0; tug < numCtrlTugs; ++tug)
{
if(pose_in->ID == ctrlTugIDs.data[tug]){
tugPoses[tug] = worldToShipCoordinates(*pose_in);
std::cout << "Found tugboat at: x=" << tugPoses[tug].x << "\t y=" << tugPoses[tug].y << " in ship coordinates\n";
if(sqrt( pow(tugPoses[tug].x, 2) + pow(tugPoses[tug].y, 2) ) > ACCEPTABLE_DIST_ERROR)
{ //Tugboat lost touch with ship - send back to waypoint manager
discardTugs.data.push_back(ctrlTugIDs.data[tug]);
ctrlTugIDs.data.erase(ctrlTugIDs.data.begin() + tug);
std::cout << "Tugboat " << (int)ctrlTugIDs.data[tug] << " strayed too far from ship. Assumed lost.\n";
tugPoses.erase(tugPoses.begin() + tug);
numCtrlTugs--;
}
return;
}
}
}
void waypCallback(const tugboat_control::Waypoint::ConstPtr& wayp_in)
{
shipWaypoint = *wayp_in;
}
void ctrlTugsCallback(const std_msgs::UInt8MultiArray::ConstPtr& tugsIn)
{
std::vector<tugboat_control::BoatPose> newPoses;
ctrlTugIDs = *tugsIn;
for (int ID = 0; ID < ctrlTugIDs.data.size(); ++ID)
{
for (int pose = 0; pose < tugPoses.size(); ++pose)
{
if(tugPoses[pose].ID == ctrlTugIDs.data[ID])
{
newPoses.push_back(tugPoses[pose]);
break;
}
}
if(newPoses.size() <= ID)
{ //No element added above, because no Pose is in record
std::cout << "Adding tugboat " << (int)ctrlTugIDs.data[ID] << " to Ship Control\n";
tugboat_control::BoatPose blankPose;
blankPose.ID = ctrlTugIDs.data[ID];
blankPose.x = 0;
blankPose.y = 0;
blankPose.o = 0;
newPoses.push_back(blankPose);
}
}
tugPoses = newPoses;
numCtrlTugs = ctrlTugIDs.data.size();
}
bool addOneTug(tugboat_control::addOneTug::Request &req, tugboat_control::addOneTug::Response &res)
{ //If one extra tugboat is needed - where does it go?
//Pose given in ship coordinates
//START_UNIQUE
//Tugboats are lined up along starboard side, perpendicular to the ship
res.Pose.x = 0.2 * numCtrlTugs;
res.Pose.y = 0.2;
res.Pose.o = 1.57;
//END_UNIQUE
std::cout << "Requested tugboat at: x=" << res.Pose.x << "\t y=" << res.Pose.y << "\n";
return true;
}
bool removeOneTug(tugboat_control::removeOneTug::Request &req, tugboat_control::removeOneTug::Response &res)
{ //If there are too many tugboats, one is removed
if(numCtrlTugs > 0){
//START_UNIQUE
res.ID = ctrlTugIDs.data[numCtrlTugs]; //This algorithm simply selects the last tugboat
//END_UNIQUE
std::cout << "Removing tugboat " << (int)res.ID << " from Ship Control\n";
for (int tug = 0; tug < numCtrlTugs; ++tug)
{ //Remove the selected tugboat from lists
if(res.ID == ctrlTugIDs.data[tug]){
ctrlTugIDs.data.erase(ctrlTugIDs.data.begin() + tug);
tugPoses.erase(tugPoses.begin() + tug);
}
break;
}
numCtrlTugs--;
return true;
}
else
{
return false;
}
}
void control(ros::Publisher *pub)
{ //This is where the magic happens
//START_UNIQUE
tugboat_control::TugSetpoints ctrl;
for (int tug = 0; tug < numCtrlTugs; ++tug)
{
//get thrust from somewhere
ctrl.ID = ctrlTugIDs.data[tug];
ctrl.o = PIDnormalizeAngle(1.57 + shipPose.o);
ctrl.force = 2; //TODO: Calibrate load cell, find threshold, and update this number
pub->publish(ctrl);
}//END_UNIQUE
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "generic_control");
ros::NodeHandle n;
ros::ServiceServer remove_service = n.advertiseService("removeOneTug", removeOneTug);
ros::ServiceServer add_service = n.advertiseService("addOneTug", addOneTug);
ros::Subscriber wayp_sub = n.subscribe("shipWaypoint", 1, waypCallback);
ros::Subscriber shipPose_sub = n.subscribe("shipPose", 1, shipPoseCallback);
ros::Subscriber tugPose_sub = n.subscribe("pose", 100, tugPoseCallback);
ros::Subscriber ctrlTugs_sub = n.subscribe("ctrlTugs", 100, ctrlTugsCallback);
ros::Publisher ctrl_pub = n.advertise<tugboat_control::TugSetpoints>("control", 100);
ros::Publisher stress_pub = n.advertise<std_msgs::Bool>("distress", 100);
ros::Publisher discard_pub = n.advertise<std_msgs::UInt8>("ctrlClear", 100);
ros::Rate loop_rate(10);
std::cout << "Ship Control node initialized successfully\n";
while (ros::ok())
{
if(numCtrlTugs > 0)
{
control(&ctrl_pub);
}
else {
std_msgs::Bool msg;
msg.data = true;
stress_pub.publish(msg);
std::cout << "No tugs attached to ship!\n";
}
while( discardTugs.data.size() > 0)
{
std_msgs::UInt8 msg;
msg.data = discardTugs.data[0];
discard_pub.publish(msg);
discardTugs.data.erase(discardTugs.data.begin());
}
ros::spinOnce();
loop_rate.sleep();
}
return 0;
} | [
"[email protected]"
] | |
237c5c39cba126a076db44e06e9023a9146951ee | 31c54cdda94bec3b77431b8f3fa5f77389a41ab0 | /ThirdParty/Stasm/source/print.cpp | 226ed5e1bd501c15e9d7053ee136a408f61d7213 | [] | no_license | rootkit/FaceScoreEval | b16b6b1b01b23bc1d38f19e19af593a9e8df80c7 | 1beaa8344641291f932e409dd14ee4d4b9129ae8 | refs/heads/master | 2020-04-02T10:01:24.418258 | 2018-10-21T11:50:25 | 2018-10-21T11:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,188 | cpp | // print.cpp: printing and logging utilities for the Stasm library
//
// Copyright (C) 2005-2013, Stephen Milborrow
#include "stasm.h"
#include <sys/stat.h>
namespace stasm
{
bool print_g; // true to allow output to stdout (but error msgs always printed)
bool trace_g; // true to trace Stasm internal operation
static FILE* logfile_g; // lprintfs go to this log file as well as stdout
//-----------------------------------------------------------------------------
// Open the log file. After this, when you call lprintf, you print to the log
// file (as well as to stdout). This inits the global variable logfile_g.
void OpenLogFile( // also inits the global variable logfile_g
const char* path) // in: log file path, default is "stasm.log"
{
if (!logfile_g)
{
if (print_g)
printf("Generating %s\n", path);
logfile_g = fopen(path, "wb");
if (!logfile_g)
Err("Cannot open \"%s\"", path);
// check that we can write to the log file
if (fputs("log file\n", logfile_g) < 0)
Err("Cannot write to \"%s\"", path);
rewind(logfile_g); // rewind so above test msg is not in the log file
}
}
// Like printf but only prints if print_g flag is set.
// Also prints to the log file if it is open (regardless of print_g).
void lprintf(const char* format, ...) // args like printf
{
char s[SBIG];
va_list args;
va_start(args, format);
VSPRINTF(s, format, args);
va_end(args);
if (print_g)
{
printf("%s", s);
fflush(stdout); // flush so if there is a crash we can see what happened
}
if (logfile_g)
{
// we don't check fputs here, to prevent recursive calls and msgs
fputs(s, logfile_g);
fflush(logfile_g);
}
}
// Like printf but prints to the log file only (and not to stdout).
// Used for detailed stuff that we don't usually want to see.
void logprintf(const char* format, ...) // args like printf
{
if (logfile_g)
{
char s[SBIG];
va_list args;
va_start(args, format);
VSPRINTF(s, format, args);
va_end(args);
// we don't check fputs here, to prevent recursive calls and msgs
fputs(s, logfile_g);
fflush(logfile_g);
}
}
// Like lprintf but always prints even if print_g is false.
void lprintf_always(const char* format, ...)
{
char s[SBIG];
va_list args;
va_start(args, format);
VSPRINTF(s, format, args);
va_end(args);
printf("%s", s);
fflush(stdout); // flush so if there is a crash we can see what happened
if (logfile_g)
{
// we don't check fputs here, to prevent recursive calls and msgs
fputs(s, logfile_g);
fflush(logfile_g);
}
}
// Like puts but prints to the log file as well if it is open,
// and does not append a newline.
void lputs(const char* s)
{
printf("%s", s);
fflush(stdout); // flush so if there is a crash we can see what happened
logprintf("%s", s);
}
// Print message only once on the screen, and only 100 times to the log file.
// This is used when similar messages could be printed many times and it
// suffices to let the user know just once. By convention the message is
// printed followed by "..." so the user knows that just the first message
// was printed. The user can look in the log file for further messages if
// necessary (but we print only 100 times to the log file --- else all the
// log prints make tasm slow).
void PrintOnce(
int& printed, // io: zero=print, nonzero=no print
const char* format, ...) // in: args like printf
{
char s[SBIG];
va_list args;
va_start(args, format);
VSPRINTF(s, format, args);
va_end(args);
if (printed == 0 && print_g)
{
printed = 1;
printf("%s", s);
fflush(stdout); // flush so if there is a crash we can see what happened
}
if (printed < 100 && logfile_g)
{
fputs(s, logfile_g);
fflush(logfile_g);
printed++;
if (printed == 100)
logprintf("no more prints of the above message (printed == 100)\n");
}
}
} // namespace stasm
| [
"[email protected]"
] | |
07178f8d0b2d4c8fdc2dd235663c24415661610f | ce83be4cb4bef438137b1d942ddd84e8f8c76a79 | /src/Tonality/DSPUtils.cpp | e10e6c16cc0f40d0f7adab95ccf9c847ed6f8702 | [
"Unlicense"
] | permissive | warrengalyen/Tonality | 7fb6f069b4c00efa3d02a4bb0df073a2823b3578 | 4e2721e1fc801cedc91ab902873c0ecdf50442cf | refs/heads/master | 2020-03-30T11:42:11.290931 | 2018-10-07T04:19:12 | 2018-12-27T20:09:55 | 151,188,251 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,882 | cpp | #include "DSPUtils.h"
namespace Tonality
{
// --------------- Time/Frequency Analysis --------------
// Discrete Fourier Transform
void DFT(int length, float *realTimeIn, float *imagTimeIn, float *realFreqOut, float *imagFreqOut)
{
int k, i;
float sr, si, p;
memset(realFreqOut, 0, sizeof(float) * length);
memset(imagFreqOut, 0, sizeof(float) * length);
for (k = 0; k < length; k++)
for (i = 0; i < length; i++)
{
p = (2.0f * PI * (float)(k * i)) / length;
sr = cosf(p);
si = -sinf(p);
realFreqOut[k] += (realTimeIn[i] * sr) - (imagTimeIn[i] * si);
imagFreqOut[k] += (realTimeIn[i] * si) + (imagTimeIn[i] * sr);
}
}
// Inverse Discrete Fourier Transform
void InverseDFT(int length, float *realFreqIn, float *imagFreqIn, float *realTimeOut, float *imagTimeOut)
{
int k, i;
float sr, si, p;
memset(realTimeOut, 0, sizeof(float) * length);
memset(imagTimeOut, 0, sizeof(float) * length);
for (k = 0; k < length; k++)
{
for (i = 0; i < length; i++)
{
p = (2.0f * PI * (float)(k * i)) / length;
sr = cosf(p);
si = -sinf(p);
realTimeOut[k] += (realFreqIn[i] * sr) + (imagFreqIn[i] * si);
imagTimeOut[k] += (realFreqIn[i] * si) - (imagFreqIn[i] * sr);
}
realTimeOut[k] /= (float)length;
imagTimeOut[k] /= (float)length;
}
}
// Real Cepstrum
void RealCepstrum(int length, float *signalIn, float *realCepstrumOut)
{
float *realTime, *imagTime, *realFreq, *imagFreq;
int i;
realTime = new float[length];
imagTime = new float[length];
realFreq = new float[length];
imagFreq = new float[length];
// Compose Complex FFT Input
for (i = 0; i < length; i++)
{
realTime[i] = signalIn[i];
imagTime[i] = 0.0f;
}
// Perform DFT
DFT(length, realTime, imagTime, realFreq, imagFreq);
// Calculate Log Of Absolute Value
for (i = 0; i < length; i++)
{
realFreq[i] = logf(cabs(realFreq[i], imagFreq[i]));
imagFreq[i] = 0.0f;
}
// Perform Inverse FFT
InverseDFT(length, realFreq, imagFreq, realTime, imagTime);
// Output Real Part Of FFT
for (i = 0; i < length; i++)
realCepstrumOut[i] = realTime[i];
delete realTime;
delete imagTime;
delete realFreq;
delete imagFreq;
}
// Compute Minimum Phase Reconstruction Of Signal
void MinimumPhase(int length, float *realCepstrum, float *minimumPhase)
{
int i, nd2;
float *realTime, *imagTime, *realFreq, *imagFreq;
nd2 = length / 2;
realTime = new float[length];
imagTime = new float[length];
realFreq = new float[length];
imagFreq = new float[length];
if ((length % 2) == 1)
{
realTime[0] = realCepstrum[0];
for (i = 1; i < nd2; i++)
realTime[i] = 2.0f * realCepstrum[i];
for (i = nd2; i < length; i++)
realTime[i] = 0.0f;
}
else
{
realTime[0] = realCepstrum[0];
for (i = 1; i < nd2; i++)
realTime[i] = 2.0f * realCepstrum[i];
realTime[nd2] = realCepstrum[nd2];
for (i = nd2 + 1; i < length; i++)
realTime[i] = 0.0f;
}
for (i = 0; i < length; i++)
imagTime[i] = 0.0f;
DFT(length, realTime, imagTime, realFreq, imagFreq);
for (i = 0; i < length; i++)
cexp(realFreq[i], imagFreq[i], &realFreq[i], &imagFreq[i]);
InverseDFT(length, realFreq, imagFreq, realTime, imagTime);
for (i = 0; i < length; i++)
minimumPhase[i] = realTime[i];
delete realTime;
delete imagTime;
delete realFreq;
delete imagFreq;
}
// ---------------- minBLEP Generation --------------------
// Generate MinBLEP And Return It In An Array Of Floating Point Values
/*
This can be used to create a new minimum phase bandlimited step function
to store for later use as a lookup table.
Note that BLEPOscillator.cpp already has a runtime constant version of a BLEP
for use with the BLEP-based oscillators.
*/
float *GenerateMinBLEP(int zeroCrossings, int overSampling)
{
int i, n, m;
float r, a, b;
float *buffer1, *buffer2, *minBLEP;
// use power-of-two for DFT/Cepstrum for potential future
// speed boost
n = (zeroCrossings * 2 * overSampling) + 1;
m = n - 1;
buffer1 = new float[m];
buffer2 = new float[m];
// Generate Sinc
a = (float)-zeroCrossings;
b = (float)zeroCrossings;
for (i = 0; i < m; i++)
{
r = ((float)i) / ((float)m);
buffer1[i] = sinc(a + (r * (b - a)));
}
GenerateBlackmanWindow(m, buffer2);
for (i = 0; i < m; i++)
{
buffer1[i] *= buffer2[i];
}
// Minimum Phase Reconstruction
RealCepstrum(m, buffer1, buffer2);
MinimumPhase(m, buffer2, buffer1);
// Integrate Into MinBLEP
minBLEP = new float[n];
a = 0.0f;
for (i = 0; i < m; i++)
{
a += buffer1[i];
minBLEP[i] = a;
}
// copy next-to-last sample
minBLEP[m] = minBLEP[m - 1];
// Normalize
a = minBLEP[m];
a = 1.0f / a;
for (i = 0; i < n; i++)
{
minBLEP[i] *= a;
}
delete buffer1;
delete buffer2;
return minBLEP;
}
} | [
"[email protected]"
] | |
04bb62827bb75418be8e061341ad25d4921802e4 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2652486_0/C++/tigabunnie/c.cpp | 4ad3d1a8a60783bd11fc8681016a5ef5c346a714 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,549 | cpp | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int main(int argc, char **argv) {
if (argc!=3) {
printf("provide input and output file names as command line parameters\n");
}
FILE *fp_in, *fp_out;
if ((fp_in=fopen(argv[1],"r"))==NULL) { printf("can't open file %s\n", argv[1]); exit(1); }
if ((fp_out=fopen(argv[2],"w"))==NULL) { printf("can't open file %s\n", argv[2]); exit(1); }
int num_cases;
fscanf(fp_in, "%d\n", &num_cases);
int R, N, M, K;
int i, j, k, digit, power;
int prod[7];
char div[8][8];
int answer[1000];
int answer_size, num;
for (int test_case=1; test_case<=num_cases; test_case++) {
fscanf(fp_in, "%d %d %d %d\n", &R, &N, &M, &K);
fprintf(fp_out, "Case #%d:\n", test_case);
for (i=0; i<R; i++) {
for (j=0; j<K; j++) fscanf(fp_in, "%d", &(prod[j]));
for (digit=2; digit<=5; digit++) {
num = digit;
for (power=1; power<8; power++) {
div[power][digit] = 0;
for (k=0; k<K; k++) if ((prod[k] % num)==0) {
div[power][digit] = 1;
break;
}
num *= digit;
}
}
answer_size = 0;
for (digit=5; digit>=2; digit--) {
for (power=1; power<8; power++) {
if (div[power][digit]) answer[answer_size++] = digit;
}
}
for (digit=5; digit>=3; digit--) if (div[1][digit]) break;
while (answer_size < N) {
answer[answer_size++] = digit;
}
for (j=0; j<N; j++) fprintf(fp_out, "%d", answer[j]);
fprintf(fp_out, "\n");
}
}
fclose(fp_in);
fclose(fp_out);
return 0;
}
| [
"[email protected]"
] | |
df02df782aeec558dd01d5fdf89ab29759639abb | 4c378a1be91f9574cffb428ea1a493dbe7306773 | /mars exploration.cpp | 4232d01af48ccd0b52df2fc9ea90660c64aab392 | [] | no_license | nishantprajapati123/competitive-coding | 81c09976833ff49d079e4edd0c5254203d0552d7 | 8cbac4be5cd36c3626af4676a8385a638f98654e | refs/heads/master | 2021-07-07T14:02:21.646254 | 2020-08-26T07:36:28 | 2020-08-26T07:36:28 | 160,255,056 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | #include<bits/stdc++.h>
using namespace std;
int marsExploration(string s)
{
int alter=0,k=0;
string signal="SOS";
if(s.length()%3==0)
{
// cout<<signal.length();
for(int i=0;i<s.length();i++)
{
if(s[i]!=signal[k++]) alter++;
if(k>=signal.length()) k=0;
}
}
return alter;
}
int main()
{
string s;
getline(cin,s);
cout<<marsExploration(s);
}
| [
"[email protected]"
] | |
62f66d464a55d158c4e0748ea24c871f775d26f0 | c1671bd042b11704cc7d8c545d023e718ae99a09 | /eMu - GameServer Sapphire S0/GameServer/Tips.cpp | 76f829ae24598c69d4ab3ba037a10efdc7797bd7 | [] | no_license | Sogues/mu1.1 | e9a31864b2ebc2517f5aeba1ead735d3fedfcfba | 58de7aeee6ca26be861b0f0a81cf0cbf5ad8db11 | refs/heads/master | 2022-04-08T13:32:57.142927 | 2020-03-29T15:13:46 | 2020-03-29T15:13:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,417 | cpp | #include "StdAfx.h"
#include "TNotice.h"
CTips gTips;
void CTips::Load()
{
this->iEnabled = GetPrivateProfileInt("Tips", "IsEnabled", NULL, TIPS_FILE);
this->iSections = GetPrivateProfileInt("Tips", "IsSections", NULL, TIPS_FILE);
this->iInterval = GetPrivateProfileInt("Tips", "IsInterval", NULL, TIPS_FILE) * 60000;
// ---
char szBuffer[50] = {0};
// ---
ZeroMemory(this->m_Data, sizeof(this->m_Data));
// ---
for(int i = 1; i <= this->iSections; i++)
{
wsprintf(szBuffer, "Section%d", i);
// ---
GetPrivateProfileString(szBuffer, "String", NULL, this->m_Data[i].szMessage, 150, TIPS_FILE);
this->m_Data[i].iColor = GetPrivateProfileInt(szBuffer, "Color", NULL, TIPS_FILE);
}
// ---
_beginthread(this->Init, NULL, NULL);
// ---
LogAdd(LOG_GOLD, "[TIPS FILE] Carregado !");
}
void CTips::CheckProcent(char * szMsg)
{
for(int i = 0; i <= strlen(szMsg); i++)
{
if(szMsg[i] == '%')
{
for(int x = strlen(szMsg); x >= i; x--)
{
szMsg[x + 1] = szMsg[x];
}
// ---
i++;
}
}
}
void CTips::Init(LPVOID lpParam)
{
while(gTips.iEnabled)
{
for(int i = 1; i <= gTips.iSections; i++)
{
Sleep(gTips.iInterval);
// ---
gTips.CheckProcent(gTips.m_Data[i].szMessage);
// ---
gToolKit.SendMsg(gTips.m_Data[i].iColor, gTips.m_Data[i].szMessage);
}
}
// ---
_endthread();
} | [
"[email protected]"
] | |
7d2afd61ff86019f9ad99ea1e3829846a2fb0aef | eb8c7a2102b1c91fa9d5d43dbed58a7a1854142a | /src/ut/timer.cpp | 6f1041818c64e1237b64c1bb4ab5751b1156d706 | [
"BSD-3-Clause"
] | permissive | cuhk-eda/split-extract | 00e3610564a5ccb362a773e935c3f0bf44e08415 | 1841214919a87277596395d33d363a7048fecb54 | refs/heads/main | 2023-03-01T00:00:52.710162 | 2021-01-30T23:12:56 | 2021-01-30T23:12:56 | 312,288,253 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,138 | cpp | #include "timer.h"
using namespace utils;
std::vector<Timer> Timer::_timers;
unsigned Timer::start(){
for(unsigned i=0; i<_timers.size(); i++){
if(!_timers[i].active()){
_timers[i].active(true);
_timers[i]._time = std::chrono::steady_clock::now();
return i;
}
}
_timers.push_back(Timer());
_timers.back()._time = std::chrono::steady_clock::now();
_timers.back().active(true);
return _timers.size() - 1;
}
double Timer::time(unsigned id){
if(!_timers[id].active()){
return 0.0;
}
auto now = std::chrono::steady_clock::now();
return std::chrono::duration<double>(now - _timers[id]._time).count();
}
double Timer::reset(unsigned id){
if(!_timers[id].active()){
return 0.0;
}
auto now = std::chrono::steady_clock::now();
auto old = _timers[id]._time;
_timers[id]._time = now;
return std::chrono::duration<double>(now - old).count();
}
double Timer::stop(unsigned id){
if(!_timers[id].active()){
return 0.0;
}
double diff = time(id);
_timers[id].active(false);
return diff;
}
| [
"[email protected]"
] | |
1f59af12aa1b0cd548d0e55b41f899fac8ed39a4 | b9ee68d627e37a028331a4aa321c732e6981eb69 | /AbstractVM/src/Exception/OperandException.cpp | 8ac0bdfdb545afdf5bf3661eaae5ab4ccd94d72b | [] | no_license | cpaille/Assembleur | 8b09a6b5192cc731ded19da2dc2242cfa1190f89 | 730832608962f9b1f8f693030cf76e4d4ecee2d7 | refs/heads/master | 2020-04-15T16:33:36.741562 | 2013-02-15T15:45:57 | 2013-02-15T15:45:57 | 7,080,482 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 213 | cpp |
#include "OperandException.hh"
OperandException::OperandException(std::string message) throw()
: AbstractVMException(std::string("Operand : ") + message) {
}
OperandException::~OperandException() throw() {
}
| [
"[email protected]"
] | |
51b2d2ac497106cc6eb93d7a48c7bfe44f3e8937 | ecfbedf1b6c1970f3026be3da7f824a28bf37855 | /main.cpp | 9d4529c12987b89e3ab3d04d4cdd9f18f32a718d | [] | no_license | AustinBower/HotelProject | 4b04460e70a5de8bb1d0bfce32272dc00e7d74be | ad5539377ef2bb1a499d5623e119d104cbbd3f55 | refs/heads/master | 2021-01-01T19:34:38.628283 | 2015-05-07T04:28:14 | 2015-05-07T04:28:14 | 34,330,214 | 0 | 1 | null | 2015-04-28T14:51:06 | 2015-04-21T13:56:19 | C++ | UTF-8 | C++ | false | false | 233 | cpp | #include "loginscreen.h"
#include <QApplication>
int main(int argc, char *argv[])
{
//set up the app and create a login screen and show it
QApplication a(argc, argv);
LoginScreen w;
w.show();
return a.exec();
}
| [
"[email protected]"
] | |
fe333860e846ca0f3245acfdf31f1076cc77b458 | 0581c409c61898e48a5cbeb0916f25640e7845e3 | /src/test/test_collision.cc | fff7bad1e7f1b1394ba432b06a0b970f6fa92a72 | [
"MIT"
] | permissive | markus456/navigator | d2348ef1c7981e9b2bc5527ce347a521448e6966 | e6950bf39e23b599143ae4db54b17bd6d46fabbf | refs/heads/main | 2023-05-30T06:33:22.416682 | 2021-05-23T09:05:56 | 2021-05-23T09:05:56 | 355,319,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cc | #include "../objects.hh"
#include <vector>
#include <iostream>
struct TestObject : public Object
{
public:
TestObject()
: Object({
{0, 0},
{0, 10},
{10, 10},
{10, 0},
})
{
}
void tick()
{
}
void state_changed(Object::ChangeType type)
{
}
};
int main(int argc, char **argv)
{
TestObject n1, n2;
n1.set_position({0, 0});
n2.set_position({5, 5});
std::cout << "Collision 1: " << (n1.collision(n2) ? "Yes" : "No") << std::endl;
n2.set_position({0, 2.05});
n2.set_rotation(45);
std::cout << "Collision 2: " << (n1.collision(n2) ? "Yes" : "No") << std::endl;
n2.set_position({0, 20});
n2.set_rotation(0);
std::cout << "Collision 3: " << (n1.collision(n2) ? "Yes" : "No") << std::endl;
std::string line;
std::cin >> line;
return 0;
}
| [
"[email protected]"
] | |
5bb172e530e7ec97dd2b9c584292b41487cc0b32 | 7f82053dad041ab00cc28d760e19f4c71878fec6 | /Stacks.cpp | 2aed2f0489a2bfaab3c072c8a40adfdcb351f3e4 | [] | no_license | TewariUtkarsh/CPP-Data-Structure | 803eb26a62aafe8d9712c1db07accf88f3867403 | 1c282c47081c0254dc485144198b3c625232f2a5 | refs/heads/master | 2023-03-27T13:39:05.512638 | 2021-03-22T17:56:02 | 2021-03-22T17:56:02 | 345,292,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,989 | cpp | #include<iostream>
using namespace std;
struct stack // Implementing Stacks using structure
{
int size;
int top;
int *arr;
};
typedef struct stack Stack;
int isEmpty(Stack *s)
{
/* This Function checks if the struct stack pointer is empty or not */
if(s->top==-1)
{
return 1;
}
return 0;
}
int isFull(Stack *s)
{
/* This Function checks if the struct stack pointer is full or not */
if(s->top == (s->size) - 1)
{
return 1;
}
return 0;
}
void push(Stack*s)
{
/* This Function is used to Push an Element to the Stack */
if(isFull(s))
{
cout<<"\nStack Overflow.\n";
}
else
{
cout<<"\nEnter the Element to be pushed: ";
++(s->top);
cin>>s->arr[s->top];
cout<<"\n"<<s->arr[s->top]<<" Pushed to the Stack Successfully!!!\n";
}
}
void pop(Stack*s)
{
/* This Element is used to remove/delete/pop an Element from the Stack (LIFO) */
if(isEmpty(s))
{
cout<<"\nStack Underflow.\n";
}
else
{
int val=s->arr[s->top];
--(s->top);
cout<<"\n"<<val<<" Popped from the Stack Successfully\n";
}
}
void peek(Stack*s)
{
/* This Function is used to Display the Element at a desired index */
int val,ans;
cout<<"\nEnter the Position for Peeking: ";
cin>>val;
ans=s->top-val+1;
if(ans<0)
cout<<"\nInvalid Position.\n";
else
{
cout<<"\nElement at Position "<<val<<" is "<<s->arr[ans];
}
}
int StackTop(Stack*s)
{
/* This Function returns the top element of the Stack */
return s->arr[s->top];
}
int StackBottom(Stack*s)
{
/* This Function returns the Bottom Element of the Stack */
return s->arr[0];
}
void display(Stack*s)
{
/* This Function is used display the Stack */
cout<<"\nElements in the Stack are: ";
for(int j=s->top;j>=0;--j)
{
cout<<s->arr[j]<<" ";
}
}
int main()
{
Stack *s=new Stack;
s->top = -1;
cout << "Enter the size of the Stack: ";
cin >> s->size;
s->arr = new int(s->size);
int c,i=1;
// Menu Driven:
while(i){
cout<<"\nSelect from the following: \n1. Push Element\n2. Pop Element\n3. Peek through the Stack\n4. Display Stack Top Element\n5. Display Stack Bottom Element\n6. Display the Stack\n7. Exit the program\n\nEnter your Choice: ";
cin>>c;
switch(c)
{
case 1:
push(s);
break;
case 2:
pop(s);
break;
case 3:
peek(s);
break;
case 4:
cout<<"Stack Top Element: "<<StackTop(s);
break;
case 5:
cout<<"Stack Bottom Element: "<<StackBottom(s);
break;
case 6:
display(s);
break;
case 7:
cout<<"\nThank You for using the Program.\n";
exit(0);
break;
default:
cout<<"\nInvalid Choice.\n";
break;
}
}
return 0;
} | [
"[email protected]"
] | |
c10b1947822e1a463b924dd65539c6af2801eab7 | 992c0e7eb5c370ba2a6581a32fe15975bb1a33fa | /eğitim ve mini projeler/mini projeler/build-proje_bitmis_hali-Desktop_Qt_5_9_7_GCC_64bit-Debug/moc_baglanti.cpp | 817a674a777a7ce113a84c30f451901272b1107c | [
"Apache-2.0"
] | permissive | yakupc55/c--linux-havadurumu | db38c02e5e94c2582ed03282b37488610121c0fc | 5c30d6a744445e758771eb140dddb9409777c901 | refs/heads/master | 2020-04-27T01:22:22.331852 | 2019-03-10T11:47:32 | 2019-03-10T11:47:32 | 173,963,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,592 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'baglanti.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.7)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../proje_bitmis_hali/baglanti.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'baglanti.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.7. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_baglanti_t {
QByteArrayData data[1];
char stringdata0[9];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_baglanti_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_baglanti_t qt_meta_stringdata_baglanti = {
{
QT_MOC_LITERAL(0, 0, 8) // "baglanti"
},
"baglanti"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_baglanti[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void baglanti::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject baglanti::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_baglanti.data,
qt_meta_data_baglanti, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *baglanti::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *baglanti::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_baglanti.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int baglanti::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
a729f8ad30de59b6c0bb80ef67d93b7a2417b487 | b7671e7c80f7529911a6fd15a3830f469fe435f3 | /src/common/common/constructs/PlayerControl.hpp | d4b79709266e2af4d92d914d58592f871e7e76e3 | [
"MIT"
] | permissive | QualityHammer/CrossPlat | cf1ca50b4ae09ef2ec999be6ed7aaff2c11b5a20 | 60ea4e9849253e3753fa0becf6c3cf68c67d4b36 | refs/heads/master | 2023-01-13T20:38:51.659183 | 2020-04-22T02:37:44 | 2020-04-22T02:37:44 | 253,580,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | hpp | #pragma once
#include "Types.hpp"
namespace Common {
// Represents a client's player movement
// during a frame.
struct PlayerControl {
// Movement in X direction
i8 moveX;
// Movement in Y direction
i8 moveY;
// Amount to turn
float turn;
u8 bytes() const { return sizeof(i8) * 2 + sizeof(float); }
};
}
| [
"[email protected]"
] | |
264d438de9038c185cae5e6b3ac0fc9041e812e6 | ac97248eb2cfd22125dc0384b0c2379731c958ff | /Codechef/WPC1501 IIT Kanpur/1.cpp | 7794898ce87453109c41bb7317eff207ca755020 | [] | no_license | vampcoder/Online-Programmes | 40d5d8d2955b975e43e61669bfc83f48a2efc5e7 | 2b00deb5ad59cbff07819012a84ce86751e3859a | refs/heads/master | 2020-04-12T01:21:27.778215 | 2017-03-30T11:49:46 | 2017-03-30T11:49:46 | 48,844,940 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,436 | cpp | #include<cstring>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include <cfloat>
#include<vector>
#include<cmath>
#ifndef ONLINE_JUDGE // ifndef checks whether this macro is defined earlier or not
#define gc getchar //for local PC
#else
#define gc getchar_unlocked //for online judge environments
#endif
#define ll long long int
using namespace std;
long long int read_int()
{
register char c=gc();
while(c<'0'||c>'9')
c=gc(); //ignore aint characters tiint the first digit
long long int ret=0;
while(c>='0' && c<='9') //tiint we get a stream of digits.As soon as we get something else,we stop
{
ret=ret*10+(c-48);//construct the number
c=gc();
}
return ret;
}
int calculate(long long int a, long long int b){
int p = ceil(log2(a)/log2(b));
long long int x = pow(b, p);
//cout<< p << " " << x << endl;
int count = 0;
for(int i = 0; i < p; i++){
if(a >= x){
count += a/x;
//cout << a << " "<< x << endl;
a = a%x;
}
if(x > a){
x /= b;
}
}
if(a < b){
count+= a;
}
return count;
}
int main()
{
long long int t, n, k;
t = read_int();
while(t--){
n = read_int();
k = read_int();
if(k == 1){
printf("%lld\n", n);
}else{
printf("%d\n", calculate(n, k));
}
}
}
| [
"[email protected]"
] | |
bb7632fc47aca7a2d0b20147ad2574ae04db33df | 035cb6036a2c06961135525622acbf9eab80598b | /Solvers/Stress/FTimer.h | a73129424bc5ed702ba299846962ab61ab3db672 | [] | no_license | vicvget/StressSolver | dfa28bbae8197b8c89f92d20d8f7bc4dc12e6b7f | d89c790000ab492f9831f7832ebcc89c8e44d434 | refs/heads/master | 2021-07-15T19:16:00.906310 | 2017-04-21T11:26:48 | 2017-04-21T11:26:48 | 91,075,300 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,825 | h | #pragma once
//#define NOTIMER
//#undef _MSC_VER
//struct timeval
//{
// long tv_sec;
// long tv_usec;
//};
//
//void gettimeofday(timeval*, void*)
//{
//
//}
// include OS specific timing library
#ifdef _MSC_VER
// Windows
#include <Windows.h>
#else
// Linux
#include <ctime>
#endif
#include <vector>
#include <iomanip>
#include <iostream>
#include <omp.h>
class PerformanceCounter
{
private:
#ifdef _MSC_VER
LARGE_INTEGER _freq;
LARGE_INTEGER _current;
LARGE_INTEGER _total;
#else
// lower resolution but never wraps around:
clock_t _current;
long _total;
#endif
public:
PerformanceCounter()
{
#ifdef _MSC_VER
QueryPerformanceFrequency(&_freq);
_total.QuadPart = 0LL;
#endif
}
void Start()
{
#ifdef _MSC_VER
QueryPerformanceCounter(&_current);
#else
_total = 0;
#endif
}
void Stop()
{
#ifdef _MSC_VER
LARGE_INTEGER current_time;
QueryPerformanceCounter(¤t_time);
_total.QuadPart += (current_time.QuadPart - _current.QuadPart);
#else
_total += clock() - _current;
#endif
}
double Get(bool isStop = false)
{
if (isStop) Stop();
double current_time;
#ifdef _MSC_VER
current_time = (double)(_total.QuadPart) / _freq.QuadPart;
#else
current_time = (double)_total / CLOCKS_PER_SEC;
#endif
return current_time;
}
double Print(const char* tag, bool isStop = false)
{
double current_time = Get(isStop);
std::cout << std::setw(15) << tag << std::setprecision(15) << current_time << std::endl;
return current_time;
}
};
class PerformanceOmpCounter
{
double _current;
double _total;
public:
PerformanceOmpCounter()
{
_total = 0;
}
void Start()
{
_current = omp_get_wtime();
}
double Get(bool isStop = false)
{
if (isStop) Stop();
double current_time = (double)_total;
return current_time;
}
void Stop()
{
_total += omp_get_wtime() -_current;
}
double Print(const char* tag, bool isStop = false)
{
double current_time = Get(isStop);
std::cout << std::setw(15) << tag << std::setprecision(15) << current_time << std::endl;
return current_time;
}
};
class FTimer
{
std::vector<PerformanceOmpCounter> _counters;
public:
FTimer(){};
void Add()
{
_counters.push_back(PerformanceOmpCounter());
}
void Allocate(unsigned int num)
{
_counters.resize(num);
}
double Get(unsigned int id)
{
return id > _counters.size() ? _counters[id].Get() : -1;
}
void Start(unsigned int id)
{
if (id < _counters.size())
_counters[id].Start();
}
void Stop(unsigned int id)
{
if (id < _counters.size())
_counters[id].Stop();
}
double Print(unsigned int id, const char* tag)
{
return id < _counters.size() ? _counters[id].Print(tag) : 0.;
}
}; | [
"getmansky@95891348-1de2-4420-a55f-93115de88a4c"
] | getmansky@95891348-1de2-4420-a55f-93115de88a4c |
f22f7bf5c94025f587c46f869d7e94144f978548 | 538f0970eac607392b205e9b2b8f2acf6a8efc24 | /subprojects/harfbuzz/src/hb-ot-tag-table.hh | d8fcd2fdb46eb178e64b19107631dfecc278abea | [
"OFL-1.1",
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unicode",
"MIT",
"Unlicense",
"GPL-2.0-only",
"Apache-2.0",
"MPL-1.0",
"Zlib",
"Libpng",
"LicenseRef-scancode-unknown-license-reference",
"MIT-Modern-Variant",
"LicenseRef-scancode-other-permissive"
] | permissive | bruvzg/godot_tl | 416f27f019c1ae3c34893115fde960b6339993f8 | ca2fc4151bd8141241151dd6e29768608600473a | refs/heads/master | 2022-01-23T07:46:08.850194 | 2022-01-13T13:05:02 | 2022-01-13T13:05:02 | 163,456,298 | 30 | 7 | Unlicense | 2020-07-14T18:31:21 | 2018-12-28T23:00:10 | C++ | UTF-8 | C++ | false | false | 97,988 | hh | /* == Start of generated table == */
/*
* The following table is generated by running:
*
* ./gen-tag-table.py languagetags language-subtag-registry
*
* on files with these headers:
*
* <meta name="updated_at" content="2018-11-18 05:25 AM" />
* File-Date: 2019-04-03
*/
#ifndef HB_OT_TAG_TABLE_HH
#define HB_OT_TAG_TABLE_HH
static const LangTag ot_languages[] = {
{"aa", HB_TAG('A','F','R',' ')}, /* Afar */
{"aae", HB_TAG('S','Q','I',' ')}, /* Arbëreshë Albanian -> Albanian */
{"aao", HB_TAG('A','R','A',' ')}, /* Algerian Saharan Arabic -> Arabic */
{"aat", HB_TAG('S','Q','I',' ')}, /* Arvanitika Albanian -> Albanian */
{"ab", HB_TAG('A','B','K',' ')}, /* Abkhazian */
{"abh", HB_TAG('A','R','A',' ')}, /* Tajiki Arabic -> Arabic */
{"abq", HB_TAG('A','B','A',' ')}, /* Abaza */
{"abv", HB_TAG('A','R','A',' ')}, /* Baharna Arabic -> Arabic */
{"acf", HB_TAG('F','A','N',' ')}, /* Saint Lucian Creole French -> French Antillean */
/*{"ach", HB_TAG('A','C','H',' ')},*/ /* Acoli -> Acholi */
{"acm", HB_TAG('A','R','A',' ')}, /* Mesopotamian Arabic -> Arabic */
{"acq", HB_TAG('A','R','A',' ')}, /* Ta'izzi-Adeni Arabic -> Arabic */
/*{"acr", HB_TAG('A','C','R',' ')},*/ /* Achi */
{"acw", HB_TAG('A','R','A',' ')}, /* Hijazi Arabic -> Arabic */
{"acx", HB_TAG('A','R','A',' ')}, /* Omani Arabic -> Arabic */
{"acy", HB_TAG('A','R','A',' ')}, /* Cypriot Arabic -> Arabic */
{"ada", HB_TAG('D','N','G',' ')}, /* Adangme -> Dangme */
{"adf", HB_TAG('A','R','A',' ')}, /* Dhofari Arabic -> Arabic */
{"adp", HB_TAG('D','Z','N',' ')}, /* Adap (retired code) -> Dzongkha */
/*{"ady", HB_TAG('A','D','Y',' ')},*/ /* Adyghe */
{"aeb", HB_TAG('A','R','A',' ')}, /* Tunisian Arabic -> Arabic */
{"aec", HB_TAG('A','R','A',' ')}, /* Saidi Arabic -> Arabic */
{"af", HB_TAG('A','F','K',' ')}, /* Afrikaans */
{"afb", HB_TAG('A','R','A',' ')}, /* Gulf Arabic -> Arabic */
{"ahg", HB_TAG('A','G','W',' ')}, /* Qimant -> Agaw */
{"aht", HB_TAG('A','T','H',' ')}, /* Ahtena -> Athapaskan */
{"aii", HB_TAG('S','W','A',' ')}, /* Assyrian Neo-Aramaic -> Swadaya Aramaic */
{"aii", HB_TAG('S','Y','R',' ')}, /* Assyrian Neo-Aramaic -> Syriac */
/*{"aio", HB_TAG('A','I','O',' ')},*/ /* Aiton */
{"aiw", HB_TAG('A','R','I',' ')}, /* Aari */
{"ajp", HB_TAG('A','R','A',' ')}, /* South Levantine Arabic -> Arabic */
{"ak", HB_TAG('A','K','A',' ')}, /* Akan [macrolanguage] */
{"ak", HB_TAG('T','W','I',' ')}, /* Akan [macrolanguage] -> Twi */
{"aln", HB_TAG('S','Q','I',' ')}, /* Gheg Albanian -> Albanian */
{"als", HB_TAG('S','Q','I',' ')}, /* Tosk Albanian -> Albanian */
/*{"alt", HB_TAG('A','L','T',' ')},*/ /* Southern Altai -> Altai */
{"am", HB_TAG('A','M','H',' ')}, /* Amharic */
{"amf", HB_TAG('H','B','N',' ')}, /* Hamer-Banna -> Hammer-Banna */
{"amw", HB_TAG('S','Y','R',' ')}, /* Western Neo-Aramaic -> Syriac */
{"an", HB_TAG('A','R','G',' ')}, /* Aragonese */
/*{"ang", HB_TAG('A','N','G',' ')},*/ /* Old English (ca. 450-1100) -> Anglo-Saxon */
{"apc", HB_TAG('A','R','A',' ')}, /* North Levantine Arabic -> Arabic */
{"apd", HB_TAG('A','R','A',' ')}, /* Sudanese Arabic -> Arabic */
{"apj", HB_TAG('A','T','H',' ')}, /* Jicarilla Apache -> Athapaskan */
{"apk", HB_TAG('A','T','H',' ')}, /* Kiowa Apache -> Athapaskan */
{"apl", HB_TAG('A','T','H',' ')}, /* Lipan Apache -> Athapaskan */
{"apm", HB_TAG('A','T','H',' ')}, /* Mescalero-Chiricahua Apache -> Athapaskan */
{"apw", HB_TAG('A','T','H',' ')}, /* Western Apache -> Athapaskan */
{"ar", HB_TAG('A','R','A',' ')}, /* Arabic [macrolanguage] */
{"arb", HB_TAG('A','R','A',' ')}, /* Standard Arabic -> Arabic */
{"arn", HB_TAG('M','A','P',' ')}, /* Mapudungun */
{"arq", HB_TAG('A','R','A',' ')}, /* Algerian Arabic -> Arabic */
{"ars", HB_TAG('A','R','A',' ')}, /* Najdi Arabic -> Arabic */
{"ary", HB_TAG('M','O','R',' ')}, /* Moroccan Arabic -> Moroccan */
{"arz", HB_TAG('A','R','A',' ')}, /* Egyptian Arabic -> Arabic */
{"as", HB_TAG('A','S','M',' ')}, /* Assamese */
/*{"ast", HB_TAG('A','S','T',' ')},*/ /* Asturian */
/*{"ath", HB_TAG('A','T','H',' ')},*/ /* Athapascan [family] -> Athapaskan */
{"atj", HB_TAG('R','C','R',' ')}, /* Atikamekw -> R-Cree */
{"atv", HB_TAG('A','L','T',' ')}, /* Northern Altai -> Altai */
{"auz", HB_TAG('A','R','A',' ')}, /* Uzbeki Arabic -> Arabic */
{"av", HB_TAG('A','V','R',' ')}, /* Avaric -> Avar */
{"avl", HB_TAG('A','R','A',' ')}, /* Eastern Egyptian Bedawi Arabic -> Arabic */
/*{"awa", HB_TAG('A','W','A',' ')},*/ /* Awadhi */
{"ay", HB_TAG('A','Y','M',' ')}, /* Aymara [macrolanguage] */
{"ayc", HB_TAG('A','Y','M',' ')}, /* Southern Aymara -> Aymara */
{"ayh", HB_TAG('A','R','A',' ')}, /* Hadrami Arabic -> Arabic */
{"ayl", HB_TAG('A','R','A',' ')}, /* Libyan Arabic -> Arabic */
{"ayn", HB_TAG('A','R','A',' ')}, /* Sanaani Arabic -> Arabic */
{"ayp", HB_TAG('A','R','A',' ')}, /* North Mesopotamian Arabic -> Arabic */
{"ayr", HB_TAG('A','Y','M',' ')}, /* Central Aymara -> Aymara */
{"az", HB_TAG('A','Z','E',' ')}, /* Azerbaijani [macrolanguage] */
/*{"azb", HB_TAG('A','Z','B',' ')},*/ /* South Azerbaijani -> Torki */
{"azj", HB_TAG('A','Z','E',' ')}, /* North Azerbaijani -> Azerbaijani */
{"ba", HB_TAG('B','S','H',' ')}, /* Bashkir */
{"bad", HB_TAG('B','A','D','0')}, /* Banda [family] */
{"bai", HB_TAG('B','M','L',' ')}, /* Bamileke [family] */
{"bal", HB_TAG('B','L','I',' ')}, /* Baluchi [macrolanguage] */
/*{"ban", HB_TAG('B','A','N',' ')},*/ /* Balinese */
/*{"bar", HB_TAG('B','A','R',' ')},*/ /* Bavarian */
/*{"bbc", HB_TAG('B','B','C',' ')},*/ /* Batak Toba */
{"bbz", HB_TAG('A','R','A',' ')}, /* Babalia Creole Arabic -> Arabic */
{"bcc", HB_TAG('B','L','I',' ')}, /* Southern Balochi -> Baluchi */
{"bci", HB_TAG('B','A','U',' ')}, /* Baoulé -> Baulé */
{"bcl", HB_TAG('B','I','K',' ')}, /* Central Bikol -> Bikol */
{"bcq", HB_TAG('B','C','H',' ')}, /* Bench */
{"bcr", HB_TAG('A','T','H',' ')}, /* Babine -> Athapaskan */
/*{"bdy", HB_TAG('B','D','Y',' ')},*/ /* Bandjalang */
{"be", HB_TAG('B','E','L',' ')}, /* Belarusian -> Belarussian */
{"bea", HB_TAG('A','T','H',' ')}, /* Beaver -> Athapaskan */
{"beb", HB_TAG('B','T','I',' ')}, /* Bebele -> Beti */
/*{"bem", HB_TAG('B','E','M',' ')},*/ /* Bemba (Zambia) */
{"ber", HB_TAG('B','B','R',' ')}, /* Berber [family] */
{"bfq", HB_TAG('B','A','D',' ')}, /* Badaga */
{"bft", HB_TAG('B','L','T',' ')}, /* Balti */
{"bfu", HB_TAG('L','A','H',' ')}, /* Gahri -> Lahuli */
{"bfy", HB_TAG('B','A','G',' ')}, /* Bagheli -> Baghelkhandi */
{"bg", HB_TAG('B','G','R',' ')}, /* Bulgarian */
/*{"bgc", HB_TAG('B','G','C',' ')},*/ /* Haryanvi */
{"bgn", HB_TAG('B','L','I',' ')}, /* Western Balochi -> Baluchi */
{"bgp", HB_TAG('B','L','I',' ')}, /* Eastern Balochi -> Baluchi */
/*{"bgq", HB_TAG('B','G','Q',' ')},*/ /* Bagri */
{"bgr", HB_TAG('Q','I','N',' ')}, /* Bawm Chin -> Chin */
{"bhb", HB_TAG('B','H','I',' ')}, /* Bhili */
/*{"bhi", HB_TAG('B','H','I',' ')},*/ /* Bhilali -> Bhili */
{"bhk", HB_TAG('B','I','K',' ')}, /* Albay Bicolano (retired code) -> Bikol */
/*{"bho", HB_TAG('B','H','O',' ')},*/ /* Bhojpuri */
{"bhr", HB_TAG('M','L','G',' ')}, /* Bara Malagasy -> Malagasy */
{"bi", HB_TAG('B','I','S',' ')}, /* Bislama */
/*{"bik", HB_TAG('B','I','K',' ')},*/ /* Bikol [macrolanguage] */
{"bin", HB_TAG('E','D','O',' ')}, /* Edo */
/*{"bjj", HB_TAG('B','J','J',' ')},*/ /* Kanauji */
{"bjn", HB_TAG('M','L','Y',' ')}, /* Banjar -> Malay */
{"bjq", HB_TAG('M','L','G',' ')}, /* Southern Betsimisaraka Malagasy (retired code) -> Malagasy */
{"bjt", HB_TAG('B','L','N',' ')}, /* Balanta-Ganja -> Balante */
{"bla", HB_TAG('B','K','F',' ')}, /* Siksika -> Blackfoot */
{"ble", HB_TAG('B','L','N',' ')}, /* Balanta-Kentohe -> Balante */
/*{"blk", HB_TAG('B','L','K',' ')},*/ /* Pa’o Karen */
{"bln", HB_TAG('B','I','K',' ')}, /* Southern Catanduanes Bikol -> Bikol */
{"bm", HB_TAG('B','M','B',' ')}, /* Bambara (Bamanankan) */
{"bmm", HB_TAG('M','L','G',' ')}, /* Northern Betsimisaraka Malagasy -> Malagasy */
{"bn", HB_TAG('B','E','N',' ')}, /* Bengali */
{"bo", HB_TAG('T','I','B',' ')}, /* Tibetan */
/*{"bpy", HB_TAG('B','P','Y',' ')},*/ /* Bishnupriya -> Bishnupriya Manipuri */
{"bqi", HB_TAG('L','R','C',' ')}, /* Bakhtiari -> Luri */
{"br", HB_TAG('B','R','E',' ')}, /* Breton */
{"bra", HB_TAG('B','R','I',' ')}, /* Braj -> Braj Bhasha */
/*{"brh", HB_TAG('B','R','H',' ')},*/ /* Brahui */
/*{"brx", HB_TAG('B','R','X',' ')},*/ /* Bodo (India) */
{"bs", HB_TAG('B','O','S',' ')}, /* Bosnian */
/*{"bsk", HB_TAG('B','S','K',' ')},*/ /* Burushaski */
{"btb", HB_TAG('B','T','I',' ')}, /* Beti (Cameroon) (retired code) */
{"btj", HB_TAG('M','L','Y',' ')}, /* Bacanese Malay -> Malay */
{"bto", HB_TAG('B','I','K',' ')}, /* Rinconada Bikol -> Bikol */
/*{"bts", HB_TAG('B','T','S',' ')},*/ /* Batak Simalungun */
/*{"bug", HB_TAG('B','U','G',' ')},*/ /* Buginese -> Bugis */
{"bum", HB_TAG('B','T','I',' ')}, /* Bulu (Cameroon) -> Beti */
{"bve", HB_TAG('M','L','Y',' ')}, /* Berau Malay -> Malay */
{"bvu", HB_TAG('M','L','Y',' ')}, /* Bukit Malay -> Malay */
{"bxk", HB_TAG('L','U','H',' ')}, /* Bukusu -> Luyia */
{"bxp", HB_TAG('B','T','I',' ')}, /* Bebil -> Beti */
{"bxr", HB_TAG('R','B','U',' ')}, /* Russia Buriat -> Russian Buriat */
{"byn", HB_TAG('B','I','L',' ')}, /* Bilin -> Bilen */
/*{"byv", HB_TAG('B','Y','V',' ')},*/ /* Medumba */
{"bzc", HB_TAG('M','L','G',' ')}, /* Southern Betsimisaraka Malagasy -> Malagasy */
{"ca", HB_TAG('C','A','T',' ')}, /* Catalan */
{"caf", HB_TAG('C','R','R',' ')}, /* Southern Carrier -> Carrier */
{"caf", HB_TAG('A','T','H',' ')}, /* Southern Carrier -> Athapaskan */
/*{"cak", HB_TAG('C','A','K',' ')},*/ /* Kaqchikel */
/*{"cbk", HB_TAG('C','B','K',' ')},*/ /* Chavacano -> Zamboanga Chavacano */
{"cbl", HB_TAG('Q','I','N',' ')}, /* Bualkhaw Chin -> Chin */
{"cco", HB_TAG('C','C','H','N')}, /* Comaltepec Chinantec -> Chinantec */
{"ccq", HB_TAG('A','R','K',' ')}, /* Chaungtha (retired code) -> Rakhine */
{"cdo", HB_TAG('Z','H','S',' ')}, /* Min Dong Chinese -> Chinese Simplified */
{"ce", HB_TAG('C','H','E',' ')}, /* Chechen */
/*{"ceb", HB_TAG('C','E','B',' ')},*/ /* Cebuano */
{"cfm", HB_TAG('H','A','L',' ')}, /* Halam (Falam Chin) */
/*{"cgg", HB_TAG('C','G','G',' ')},*/ /* Chiga */
{"ch", HB_TAG('C','H','A',' ')}, /* Chamorro */
{"chj", HB_TAG('C','C','H','N')}, /* Ojitlán Chinantec -> Chinantec */
{"chk", HB_TAG('C','H','K','0')}, /* Chuukese */
/*{"cho", HB_TAG('C','H','O',' ')},*/ /* Choctaw */
{"chp", HB_TAG('C','H','P',' ')}, /* Chipewyan */
{"chp", HB_TAG('S','A','Y',' ')}, /* Chipewyan -> Sayisi */
{"chp", HB_TAG('A','T','H',' ')}, /* Chipewyan -> Athapaskan */
{"chq", HB_TAG('C','C','H','N')}, /* Quiotepec Chinantec -> Chinantec */
/*{"chr", HB_TAG('C','H','R',' ')},*/ /* Cherokee */
/*{"chy", HB_TAG('C','H','Y',' ')},*/ /* Cheyenne */
{"chz", HB_TAG('C','C','H','N')}, /* Ozumacín Chinantec -> Chinantec */
{"ciw", HB_TAG('O','J','B',' ')}, /* Chippewa -> Ojibway */
/*{"cja", HB_TAG('C','J','A',' ')},*/ /* Western Cham */
/*{"cjm", HB_TAG('C','J','M',' ')},*/ /* Eastern Cham */
{"cjy", HB_TAG('Z','H','S',' ')}, /* Jinyu Chinese -> Chinese Simplified */
{"cka", HB_TAG('Q','I','N',' ')}, /* Khumi Awa Chin (retired code) -> Chin */
{"ckb", HB_TAG('K','U','R',' ')}, /* Central Kurdish -> Kurdish */
{"ckt", HB_TAG('C','H','K',' ')}, /* Chukot -> Chukchi */
{"clc", HB_TAG('A','T','H',' ')}, /* Chilcotin -> Athapaskan */
{"cld", HB_TAG('S','Y','R',' ')}, /* Chaldean Neo-Aramaic -> Syriac */
{"cle", HB_TAG('C','C','H','N')}, /* Lealao Chinantec -> Chinantec */
{"cmn", HB_TAG('Z','H','S',' ')}, /* Mandarin Chinese -> Chinese Simplified */
{"cmr", HB_TAG('Q','I','N',' ')}, /* Mro-Khimi Chin -> Chin */
{"cnb", HB_TAG('Q','I','N',' ')}, /* Chinbon Chin -> Chin */
{"cnh", HB_TAG('Q','I','N',' ')}, /* Hakha Chin -> Chin */
{"cnk", HB_TAG('Q','I','N',' ')}, /* Khumi Chin -> Chin */
{"cnl", HB_TAG('C','C','H','N')}, /* Lalana Chinantec -> Chinantec */
{"cnt", HB_TAG('C','C','H','N')}, /* Tepetotutla Chinantec -> Chinantec */
{"cnw", HB_TAG('Q','I','N',' ')}, /* Ngawn Chin -> Chin */
{"co", HB_TAG('C','O','S',' ')}, /* Corsican */
{"coa", HB_TAG('M','L','Y',' ')}, /* Cocos Islands Malay -> Malay */
/*{"cop", HB_TAG('C','O','P',' ')},*/ /* Coptic */
{"coq", HB_TAG('A','T','H',' ')}, /* Coquille -> Athapaskan */
{"cpa", HB_TAG('C','C','H','N')}, /* Palantla Chinantec -> Chinantec */
{"cpe", HB_TAG('C','P','P',' ')}, /* English-based creoles and pidgins [family] -> Creoles */
{"cpf", HB_TAG('C','P','P',' ')}, /* French-based creoles and pidgins [family] -> Creoles */
/*{"cpp", HB_TAG('C','P','P',' ')},*/ /* Portuguese-based creoles and pidgins [family] -> Creoles */
{"cpx", HB_TAG('Z','H','S',' ')}, /* Pu-Xian Chinese -> Chinese Simplified */
{"cqd", HB_TAG('H','M','N',' ')}, /* Chuanqiandian Cluster Miao -> Hmong */
{"cqu", HB_TAG('Q','U','H',' ')}, /* Chilean Quechua (retired code) -> Quechua (Bolivia) */
{"cr", HB_TAG('C','R','E',' ')}, /* Cree [macrolanguage] */
{"cr", HB_TAG('Y','C','R',' ')}, /* Cree [macrolanguage] -> Y-Cree */
{"crh", HB_TAG('C','R','T',' ')}, /* Crimean Tatar */
{"crj", HB_TAG('E','C','R',' ')}, /* Southern East Cree -> Eastern Cree */
{"crk", HB_TAG('W','C','R',' ')}, /* Plains Cree -> West-Cree */
{"crl", HB_TAG('E','C','R',' ')}, /* Northern East Cree -> Eastern Cree */
{"crm", HB_TAG('M','C','R',' ')}, /* Moose Cree */
{"crm", HB_TAG('L','C','R',' ')}, /* Moose Cree -> L-Cree */
{"crp", HB_TAG('C','P','P',' ')}, /* Creoles and pidgins [family] -> Creoles */
{"crx", HB_TAG('C','R','R',' ')}, /* Carrier */
{"crx", HB_TAG('A','T','H',' ')}, /* Carrier -> Athapaskan */
{"cs", HB_TAG('C','S','Y',' ')}, /* Czech */
{"csa", HB_TAG('C','C','H','N')}, /* Chiltepec Chinantec -> Chinantec */
/*{"csb", HB_TAG('C','S','B',' ')},*/ /* Kashubian */
{"csh", HB_TAG('Q','I','N',' ')}, /* Asho Chin -> Chin */
{"cso", HB_TAG('C','C','H','N')}, /* Sochiapam Chinantec -> Chinantec */
{"csw", HB_TAG('N','C','R',' ')}, /* Swampy Cree -> N-Cree */
{"csw", HB_TAG('N','H','C',' ')}, /* Swampy Cree -> Norway House Cree */
{"csy", HB_TAG('Q','I','N',' ')}, /* Siyin Chin -> Chin */
{"ctc", HB_TAG('A','T','H',' ')}, /* Chetco -> Athapaskan */
{"ctd", HB_TAG('Q','I','N',' ')}, /* Tedim Chin -> Chin */
{"cte", HB_TAG('C','C','H','N')}, /* Tepinapa Chinantec -> Chinantec */
/*{"ctg", HB_TAG('C','T','G',' ')},*/ /* Chittagonian */
{"ctl", HB_TAG('C','C','H','N')}, /* Tlacoatzintepec Chinantec -> Chinantec */
{"cts", HB_TAG('B','I','K',' ')}, /* Northern Catanduanes Bikol -> Bikol */
{"cu", HB_TAG('C','S','L',' ')}, /* Church Slavonic */
{"cuc", HB_TAG('C','C','H','N')}, /* Usila Chinantec -> Chinantec */
/*{"cuk", HB_TAG('C','U','K',' ')},*/ /* San Blas Kuna */
{"cv", HB_TAG('C','H','U',' ')}, /* Chuvash */
{"cvn", HB_TAG('C','C','H','N')}, /* Valle Nacional Chinantec -> Chinantec */
{"cwd", HB_TAG('D','C','R',' ')}, /* Woods Cree */
{"cwd", HB_TAG('T','C','R',' ')}, /* Woods Cree -> TH-Cree */
{"cy", HB_TAG('W','E','L',' ')}, /* Welsh */
{"czh", HB_TAG('Z','H','S',' ')}, /* Huizhou Chinese -> Chinese Simplified */
{"czo", HB_TAG('Z','H','S',' ')}, /* Min Zhong Chinese -> Chinese Simplified */
{"czt", HB_TAG('Q','I','N',' ')}, /* Zotung Chin -> Chin */
{"da", HB_TAG('D','A','N',' ')}, /* Danish */
{"dao", HB_TAG('Q','I','N',' ')}, /* Daai Chin -> Chin */
{"dap", HB_TAG('N','I','S',' ')}, /* Nisi (India) (retired code) */
/*{"dar", HB_TAG('D','A','R',' ')},*/ /* Dargwa */
/*{"dax", HB_TAG('D','A','X',' ')},*/ /* Dayi */
{"de", HB_TAG('D','E','U',' ')}, /* German */
{"den", HB_TAG('S','L','A',' ')}, /* Slave (Athapascan) [macrolanguage] -> Slavey */
{"den", HB_TAG('A','T','H',' ')}, /* Slave (Athapascan) [macrolanguage] -> Athapaskan */
/*{"dgo", HB_TAG('D','G','O',' ')},*/ /* Dogri */
{"dgr", HB_TAG('A','T','H',' ')}, /* Dogrib -> Athapaskan */
{"dhd", HB_TAG('M','A','W',' ')}, /* Dhundari -> Marwari */
/*{"dhg", HB_TAG('D','H','G',' ')},*/ /* Dhangu */
{"dib", HB_TAG('D','N','K',' ')}, /* South Central Dinka -> Dinka */
{"dik", HB_TAG('D','N','K',' ')}, /* Southwestern Dinka -> Dinka */
{"din", HB_TAG('D','N','K',' ')}, /* Dinka [macrolanguage] */
{"dip", HB_TAG('D','N','K',' ')}, /* Northeastern Dinka -> Dinka */
/*{"diq", HB_TAG('D','I','Q',' ')},*/ /* Dimli */
{"diw", HB_TAG('D','N','K',' ')}, /* Northwestern Dinka -> Dinka */
{"dje", HB_TAG('D','J','R',' ')}, /* Zarma */
{"djr", HB_TAG('D','J','R','0')}, /* Djambarrpuyngu */
{"dks", HB_TAG('D','N','K',' ')}, /* Southeastern Dinka -> Dinka */
{"dng", HB_TAG('D','U','N',' ')}, /* Dungan */
/*{"dnj", HB_TAG('D','N','J',' ')},*/ /* Dan */
{"doi", HB_TAG('D','G','R',' ')}, /* Dogri [macrolanguage] */
{"drh", HB_TAG('M','N','G',' ')}, /* Darkhat (retired code) -> Mongolian */
{"drw", HB_TAG('D','R','I',' ')}, /* Darwazi (retired code) -> Dari */
{"dsb", HB_TAG('L','S','B',' ')}, /* Lower Sorbian */
{"dty", HB_TAG('N','E','P',' ')}, /* Dotyali -> Nepali */
/*{"duj", HB_TAG('D','U','J',' ')},*/ /* Dhuwal (retired code) */
{"dup", HB_TAG('M','L','Y',' ')}, /* Duano -> Malay */
{"dv", HB_TAG('D','I','V',' ')}, /* Divehi (Dhivehi, Maldivian) */
{"dv", HB_TAG('D','H','V',' ')}, /* Divehi (Dhivehi, Maldivian) (deprecated) */
{"dwu", HB_TAG('D','U','J',' ')}, /* Dhuwal */
{"dwy", HB_TAG('D','U','J',' ')}, /* Dhuwaya -> Dhuwal */
{"dyu", HB_TAG('J','U','L',' ')}, /* Dyula -> Jula */
{"dz", HB_TAG('D','Z','N',' ')}, /* Dzongkha */
{"ee", HB_TAG('E','W','E',' ')}, /* Ewe */
/*{"efi", HB_TAG('E','F','I',' ')},*/ /* Efik */
{"ekk", HB_TAG('E','T','I',' ')}, /* Standard Estonian -> Estonian */
{"el", HB_TAG('E','L','L',' ')}, /* Modern Greek (1453-) -> Greek */
{"emk", HB_TAG('E','M','K',' ')}, /* Eastern Maninkakan */
{"emk", HB_TAG('M','N','K',' ')}, /* Eastern Maninkakan -> Maninka */
{"en", HB_TAG('E','N','G',' ')}, /* English */
{"enb", HB_TAG('K','A','L',' ')}, /* Markweeta -> Kalenjin */
{"enf", HB_TAG('F','N','E',' ')}, /* Forest Enets -> Forest Nenets */
{"enh", HB_TAG('T','N','E',' ')}, /* Tundra Enets -> Tundra Nenets */
{"eo", HB_TAG('N','T','O',' ')}, /* Esperanto */
{"es", HB_TAG('E','S','P',' ')}, /* Spanish */
{"esg", HB_TAG('G','O','N',' ')}, /* Aheri Gondi -> Gondi */
{"esi", HB_TAG('I','P','K',' ')}, /* North Alaskan Inupiatun -> Inupiat */
{"esk", HB_TAG('I','P','K',' ')}, /* Northwest Alaska Inupiatun -> Inupiat */
/*{"esu", HB_TAG('E','S','U',' ')},*/ /* Central Yupik */
{"et", HB_TAG('E','T','I',' ')}, /* Estonian [macrolanguage] */
{"eto", HB_TAG('B','T','I',' ')}, /* Eton (Cameroon) -> Beti */
{"eu", HB_TAG('E','U','Q',' ')}, /* Basque */
{"eve", HB_TAG('E','V','N',' ')}, /* Even */
{"evn", HB_TAG('E','V','K',' ')}, /* Evenki */
{"ewo", HB_TAG('B','T','I',' ')}, /* Ewondo -> Beti */
{"eyo", HB_TAG('K','A','L',' ')}, /* Keiyo -> Kalenjin */
{"fa", HB_TAG('F','A','R',' ')}, /* Persian [macrolanguage] */
{"fan", HB_TAG('F','A','N','0')}, /* Fang (Equatorial Guinea) */
/*{"fat", HB_TAG('F','A','T',' ')},*/ /* Fanti */
{"fbl", HB_TAG('B','I','K',' ')}, /* West Albay Bikol -> Bikol */
{"ff", HB_TAG('F','U','L',' ')}, /* Fulah [macrolanguage] */
{"ffm", HB_TAG('F','U','L',' ')}, /* Maasina Fulfulde -> Fulah */
{"fi", HB_TAG('F','I','N',' ')}, /* Finnish */
{"fil", HB_TAG('P','I','L',' ')}, /* Filipino */
{"fj", HB_TAG('F','J','I',' ')}, /* Fijian */
{"flm", HB_TAG('H','A','L',' ')}, /* Halam (Falam Chin) (retired code) */
{"flm", HB_TAG('Q','I','N',' ')}, /* Falam Chin (retired code) -> Chin */
/*{"fmp", HB_TAG('F','M','P',' ')},*/ /* Fe’fe’ */
{"fo", HB_TAG('F','O','S',' ')}, /* Faroese */
/*{"fon", HB_TAG('F','O','N',' ')},*/ /* Fon */
{"fr", HB_TAG('F','R','A',' ')}, /* French */
/*{"frc", HB_TAG('F','R','C',' ')},*/ /* Cajun French */
/*{"frp", HB_TAG('F','R','P',' ')},*/ /* Arpitan */
{"fub", HB_TAG('F','U','L',' ')}, /* Adamawa Fulfulde -> Fulah */
{"fuc", HB_TAG('F','U','L',' ')}, /* Pulaar -> Fulah */
{"fue", HB_TAG('F','U','L',' ')}, /* Borgu Fulfulde -> Fulah */
{"fuf", HB_TAG('F','T','A',' ')}, /* Pular -> Futa */
{"fuh", HB_TAG('F','U','L',' ')}, /* Western Niger Fulfulde -> Fulah */
{"fui", HB_TAG('F','U','L',' ')}, /* Bagirmi Fulfulde -> Fulah */
{"fuq", HB_TAG('F','U','L',' ')}, /* Central-Eastern Niger Fulfulde -> Fulah */
{"fur", HB_TAG('F','R','L',' ')}, /* Friulian */
/*{"fuv", HB_TAG('F','U','V',' ')},*/ /* Nigerian Fulfulde */
{"fy", HB_TAG('F','R','I',' ')}, /* Western Frisian -> Frisian */
{"ga", HB_TAG('I','R','I',' ')}, /* Irish */
{"gaa", HB_TAG('G','A','D',' ')}, /* Ga */
/*{"gag", HB_TAG('G','A','G',' ')},*/ /* Gagauz */
{"gan", HB_TAG('Z','H','S',' ')}, /* Gan Chinese -> Chinese Simplified */
{"gax", HB_TAG('O','R','O',' ')}, /* Borana-Arsi-Guji Oromo -> Oromo */
{"gaz", HB_TAG('O','R','O',' ')}, /* West Central Oromo -> Oromo */
{"gbm", HB_TAG('G','A','W',' ')}, /* Garhwali */
{"gce", HB_TAG('A','T','H',' ')}, /* Galice -> Athapaskan */
{"gd", HB_TAG('G','A','E',' ')}, /* Scottish Gaelic (Gaelic) */
{"gda", HB_TAG('R','A','J',' ')}, /* Gade Lohar -> Rajasthani */
/*{"gez", HB_TAG('G','E','Z',' ')},*/ /* Geez */
{"ggo", HB_TAG('G','O','N',' ')}, /* Southern Gondi (retired code) -> Gondi */
/*{"gih", HB_TAG('G','I','H',' ')},*/ /* Githabul */
{"gil", HB_TAG('G','I','L','0')}, /* Kiribati (Gilbertese) */
{"gju", HB_TAG('R','A','J',' ')}, /* Gujari -> Rajasthani */
/*{"gkp", HB_TAG('G','K','P',' ')},*/ /* Guinea Kpelle -> Kpelle (Guinea) */
{"gl", HB_TAG('G','A','L',' ')}, /* Galician */
{"gld", HB_TAG('N','A','N',' ')}, /* Nanai */
/*{"glk", HB_TAG('G','L','K',' ')},*/ /* Gilaki */
{"gn", HB_TAG('G','U','A',' ')}, /* Guarani [macrolanguage] */
/*{"gnn", HB_TAG('G','N','N',' ')},*/ /* Gumatj */
{"gno", HB_TAG('G','O','N',' ')}, /* Northern Gondi -> Gondi */
{"gnw", HB_TAG('G','U','A',' ')}, /* Western Bolivian Guaraní -> Guarani */
/*{"gog", HB_TAG('G','O','G',' ')},*/ /* Gogo */
{"gom", HB_TAG('K','O','K',' ')}, /* Goan Konkani -> Konkani */
/*{"gon", HB_TAG('G','O','N',' ')},*/ /* Gondi [macrolanguage] */
{"grt", HB_TAG('G','R','O',' ')}, /* Garo */
{"gru", HB_TAG('S','O','G',' ')}, /* Kistane -> Sodo Gurage */
{"gsw", HB_TAG('A','L','S',' ')}, /* Alsatian */
{"gu", HB_TAG('G','U','J',' ')}, /* Gujarati */
/*{"guc", HB_TAG('G','U','C',' ')},*/ /* Wayuu */
/*{"guf", HB_TAG('G','U','F',' ')},*/ /* Gupapuyngu */
{"gug", HB_TAG('G','U','A',' ')}, /* Paraguayan Guaraní -> Guarani */
{"gui", HB_TAG('G','U','A',' ')}, /* Eastern Bolivian Guaraní -> Guarani */
{"guk", HB_TAG('G','M','Z',' ')}, /* Gumuz */
{"guk", HB_TAG('G','U','K',' ')}, /* Gumuz (SIL fonts) */
{"gun", HB_TAG('G','U','A',' ')}, /* Mbyá Guaraní -> Guarani */
/*{"guz", HB_TAG('G','U','Z',' ')},*/ /* Gusii */
{"gv", HB_TAG('M','N','X',' ')}, /* Manx */
{"gwi", HB_TAG('A','T','H',' ')}, /* Gwichʼin -> Athapaskan */
{"ha", HB_TAG('H','A','U',' ')}, /* Hausa */
{"haa", HB_TAG('A','T','H',' ')}, /* Han -> Athapaskan */
{"hae", HB_TAG('O','R','O',' ')}, /* Eastern Oromo -> Oromo */
{"hak", HB_TAG('Z','H','S',' ')}, /* Hakka Chinese -> Chinese Simplified */
{"har", HB_TAG('H','R','I',' ')}, /* Harari */
/*{"haw", HB_TAG('H','A','W',' ')},*/ /* Hawaiian */
/*{"hay", HB_TAG('H','A','Y',' ')},*/ /* Haya */
/*{"haz", HB_TAG('H','A','Z',' ')},*/ /* Hazaragi */
{"he", HB_TAG('I','W','R',' ')}, /* Hebrew */
{"hea", HB_TAG('H','M','N',' ')}, /* Northern Qiandong Miao -> Hmong */
{"hi", HB_TAG('H','I','N',' ')}, /* Hindi */
/*{"hil", HB_TAG('H','I','L',' ')},*/ /* Hiligaynon */
{"hji", HB_TAG('M','L','Y',' ')}, /* Haji -> Malay */
{"hlt", HB_TAG('Q','I','N',' ')}, /* Matu Chin -> Chin */
{"hma", HB_TAG('H','M','N',' ')}, /* Southern Mashan Hmong -> Hmong */
{"hmc", HB_TAG('H','M','N',' ')}, /* Central Huishui Hmong -> Hmong */
{"hmd", HB_TAG('H','M','N',' ')}, /* Large Flowery Miao -> Hmong */
{"hme", HB_TAG('H','M','N',' ')}, /* Eastern Huishui Hmong -> Hmong */
{"hmg", HB_TAG('H','M','N',' ')}, /* Southwestern Guiyang Hmong -> Hmong */
{"hmh", HB_TAG('H','M','N',' ')}, /* Southwestern Huishui Hmong -> Hmong */
{"hmi", HB_TAG('H','M','N',' ')}, /* Northern Huishui Hmong -> Hmong */
{"hmj", HB_TAG('H','M','N',' ')}, /* Ge -> Hmong */
{"hml", HB_TAG('H','M','N',' ')}, /* Luopohe Hmong -> Hmong */
{"hmm", HB_TAG('H','M','N',' ')}, /* Central Mashan Hmong -> Hmong */
/*{"hmn", HB_TAG('H','M','N',' ')},*/ /* Hmong [macrolanguage] */
{"hmp", HB_TAG('H','M','N',' ')}, /* Northern Mashan Hmong -> Hmong */
{"hmq", HB_TAG('H','M','N',' ')}, /* Eastern Qiandong Miao -> Hmong */
{"hms", HB_TAG('H','M','N',' ')}, /* Southern Qiandong Miao -> Hmong */
{"hmw", HB_TAG('H','M','N',' ')}, /* Western Mashan Hmong -> Hmong */
{"hmy", HB_TAG('H','M','N',' ')}, /* Southern Guiyang Hmong -> Hmong */
{"hmz", HB_TAG('H','M','N',' ')}, /* Hmong Shua -> Hmong */
/*{"hnd", HB_TAG('H','N','D',' ')},*/ /* Southern Hindko -> Hindko */
{"hne", HB_TAG('C','H','H',' ')}, /* Chhattisgarhi -> Chattisgarhi */
{"hnj", HB_TAG('H','M','N',' ')}, /* Hmong Njua -> Hmong */
{"hno", HB_TAG('H','N','D',' ')}, /* Northern Hindko -> Hindko */
{"ho", HB_TAG('H','M','O',' ')}, /* Hiri Motu */
{"hoc", HB_TAG('H','O',' ',' ')}, /* Ho */
{"hoi", HB_TAG('A','T','H',' ')}, /* Holikachuk -> Athapaskan */
{"hoj", HB_TAG('H','A','R',' ')}, /* Hadothi -> Harauti */
{"hr", HB_TAG('H','R','V',' ')}, /* Croatian */
{"hrm", HB_TAG('H','M','N',' ')}, /* Horned Miao -> Hmong */
{"hsb", HB_TAG('U','S','B',' ')}, /* Upper Sorbian */
{"hsn", HB_TAG('Z','H','S',' ')}, /* Xiang Chinese -> Chinese Simplified */
{"ht", HB_TAG('H','A','I',' ')}, /* Haitian (Haitian Creole) */
{"hu", HB_TAG('H','U','N',' ')}, /* Hungarian */
{"huj", HB_TAG('H','M','N',' ')}, /* Northern Guiyang Hmong -> Hmong */
{"hup", HB_TAG('A','T','H',' ')}, /* Hupa -> Athapaskan */
{"hy", HB_TAG('H','Y','E','0')}, /* Armenian -> Armenian East */
{"hy", HB_TAG('H','Y','E',' ')}, /* Armenian */
{"hyw", HB_TAG('H','Y','E',' ')}, /* Western Armenian -> Armenian */
{"hz", HB_TAG('H','E','R',' ')}, /* Herero */
{"ia", HB_TAG('I','N','A',' ')}, /* Interlingua (International Auxiliary Language Association) */
/*{"iba", HB_TAG('I','B','A',' ')},*/ /* Iban */
/*{"ibb", HB_TAG('I','B','B',' ')},*/ /* Ibibio */
{"id", HB_TAG('I','N','D',' ')}, /* Indonesian */
{"ida", HB_TAG('L','U','H',' ')}, /* Idakho-Isukha-Tiriki -> Luyia */
{"ie", HB_TAG('I','L','E',' ')}, /* Interlingue */
{"ig", HB_TAG('I','B','O',' ')}, /* Igbo */
{"igb", HB_TAG('E','B','I',' ')}, /* Ebira */
{"ii", HB_TAG('Y','I','M',' ')}, /* Sichuan Yi -> Yi Modern */
{"ijc", HB_TAG('I','J','O',' ')}, /* Izon -> Ijo */
/*{"ijo", HB_TAG('I','J','O',' ')},*/ /* Ijo [family] */
{"ik", HB_TAG('I','P','K',' ')}, /* Inupiaq [macrolanguage] -> Inupiat */
{"ike", HB_TAG('I','N','U',' ')}, /* Eastern Canadian Inuktitut -> Inuktitut */
{"ikt", HB_TAG('I','N','U',' ')}, /* Inuinnaqtun -> Inuktitut */
/*{"ilo", HB_TAG('I','L','O',' ')},*/ /* Iloko -> Ilokano */
{"in", HB_TAG('I','N','D',' ')}, /* Indonesian (retired code) */
{"ing", HB_TAG('A','T','H',' ')}, /* Degexit'an -> Athapaskan */
{"inh", HB_TAG('I','N','G',' ')}, /* Ingush */
{"io", HB_TAG('I','D','O',' ')}, /* Ido */
{"is", HB_TAG('I','S','L',' ')}, /* Icelandic */
{"it", HB_TAG('I','T','A',' ')}, /* Italian */
{"iu", HB_TAG('I','N','U',' ')}, /* Inuktitut [macrolanguage] */
{"iw", HB_TAG('I','W','R',' ')}, /* Hebrew (retired code) */
{"ja", HB_TAG('J','A','N',' ')}, /* Japanese */
{"jak", HB_TAG('M','L','Y',' ')}, /* Jakun -> Malay */
/*{"jam", HB_TAG('J','A','M',' ')},*/ /* Jamaican Creole English -> Jamaican Creole */
{"jax", HB_TAG('M','L','Y',' ')}, /* Jambi Malay -> Malay */
/*{"jbo", HB_TAG('J','B','O',' ')},*/ /* Lojban */
/*{"jct", HB_TAG('J','C','T',' ')},*/ /* Krymchak */
{"ji", HB_TAG('J','I','I',' ')}, /* Yiddish (retired code) */
{"jv", HB_TAG('J','A','V',' ')}, /* Javanese */
{"jw", HB_TAG('J','A','V',' ')}, /* Javanese (retired code) */
{"ka", HB_TAG('K','A','T',' ')}, /* Georgian */
{"kaa", HB_TAG('K','R','K',' ')}, /* Kara-Kalpak -> Karakalpak */
{"kab", HB_TAG('K','A','B','0')}, /* Kabyle */
{"kam", HB_TAG('K','M','B',' ')}, /* Kamba (Kenya) */
{"kar", HB_TAG('K','R','N',' ')}, /* Karen [family] */
{"kbd", HB_TAG('K','A','B',' ')}, /* Kabardian */
{"kby", HB_TAG('K','N','R',' ')}, /* Manga Kanuri -> Kanuri */
{"kca", HB_TAG('K','H','K',' ')}, /* Khanty -> Khanty-Kazim */
{"kca", HB_TAG('K','H','S',' ')}, /* Khanty -> Khanty-Shurishkar */
{"kca", HB_TAG('K','H','V',' ')}, /* Khanty -> Khanty-Vakhi */
/*{"kde", HB_TAG('K','D','E',' ')},*/ /* Makonde */
{"kdr", HB_TAG('K','R','M',' ')}, /* Karaim */
{"kdt", HB_TAG('K','U','Y',' ')}, /* Kuy */
/*{"kea", HB_TAG('K','E','A',' ')},*/ /* Kabuverdianu (Crioulo) */
/*{"kek", HB_TAG('K','E','K',' ')},*/ /* Kekchi */
{"kex", HB_TAG('K','K','N',' ')}, /* Kukna -> Kokni */
{"kfa", HB_TAG('K','O','D',' ')}, /* Kodava -> Kodagu */
{"kfr", HB_TAG('K','A','C',' ')}, /* Kachhi -> Kachchi */
{"kfx", HB_TAG('K','U','L',' ')}, /* Kullu Pahari -> Kulvi */
{"kfy", HB_TAG('K','M','N',' ')}, /* Kumaoni */
{"kg", HB_TAG('K','O','N','0')}, /* Kongo [macrolanguage] */
{"kha", HB_TAG('K','S','I',' ')}, /* Khasi */
{"khb", HB_TAG('X','B','D',' ')}, /* Lü */
{"khk", HB_TAG('M','N','G',' ')}, /* Halh Mongolian -> Mongolian */
{"kht", HB_TAG('K','H','N',' ')}, /* Khamti -> Khamti Shan (Microsoft fonts) */
{"kht", HB_TAG('K','H','T',' ')}, /* Khamti -> Khamti Shan (OpenType spec and SIL fonts) */
/*{"khw", HB_TAG('K','H','W',' ')},*/ /* Khowar */
{"ki", HB_TAG('K','I','K',' ')}, /* Kikuyu (Gikuyu) */
/*{"kiu", HB_TAG('K','I','U',' ')},*/ /* Kirmanjki */
{"kj", HB_TAG('K','U','A',' ')}, /* Kuanyama */
/*{"kjd", HB_TAG('K','J','D',' ')},*/ /* Southern Kiwai */
{"kjh", HB_TAG('K','H','A',' ')}, /* Khakas -> Khakass */
/*{"kjp", HB_TAG('K','J','P',' ')},*/ /* Pwo Eastern Karen -> Eastern Pwo Karen */
/*{"kjz", HB_TAG('K','J','Z',' ')},*/ /* Bumthangkha */
{"kk", HB_TAG('K','A','Z',' ')}, /* Kazakh */
{"kkz", HB_TAG('A','T','H',' ')}, /* Kaska -> Athapaskan */
{"kl", HB_TAG('G','R','N',' ')}, /* Greenlandic */
{"kln", HB_TAG('K','A','L',' ')}, /* Kalenjin [macrolanguage] */
{"km", HB_TAG('K','H','M',' ')}, /* Khmer */
{"kmb", HB_TAG('M','B','N',' ')}, /* Kimbundu -> Mbundu */
{"kmr", HB_TAG('K','U','R',' ')}, /* Northern Kurdish -> Kurdish */
{"kmw", HB_TAG('K','M','O',' ')}, /* Komo (Democratic Republic of Congo) */
/*{"kmz", HB_TAG('K','M','Z',' ')},*/ /* Khorasani Turkish -> Khorasani Turkic */
{"kn", HB_TAG('K','A','N',' ')}, /* Kannada */
{"knc", HB_TAG('K','N','R',' ')}, /* Central Kanuri -> Kanuri */
{"kng", HB_TAG('K','O','N','0')}, /* Koongo -> Kongo */
{"knn", HB_TAG('K','O','K',' ')}, /* Konkani */
{"ko", HB_TAG('K','O','R',' ')}, /* Korean */
{"koi", HB_TAG('K','O','P',' ')}, /* Komi-Permyak */
/*{"kok", HB_TAG('K','O','K',' ')},*/ /* Konkani [macrolanguage] */
/*{"kos", HB_TAG('K','O','S',' ')},*/ /* Kosraean */
{"koy", HB_TAG('A','T','H',' ')}, /* Koyukon -> Athapaskan */
{"kpe", HB_TAG('K','P','L',' ')}, /* Kpelle [macrolanguage] */
{"kpv", HB_TAG('K','O','Z',' ')}, /* Komi-Zyrian */
{"kpy", HB_TAG('K','Y','K',' ')}, /* Koryak */
{"kqs", HB_TAG('K','I','S',' ')}, /* Northern Kissi -> Kisii */
{"kqy", HB_TAG('K','R','T',' ')}, /* Koorete */
{"kr", HB_TAG('K','N','R',' ')}, /* Kanuri [macrolanguage] */
{"krc", HB_TAG('K','A','R',' ')}, /* Karachay-Balkar -> Karachay */
{"krc", HB_TAG('B','A','L',' ')}, /* Karachay-Balkar -> Balkar */
/*{"kri", HB_TAG('K','R','I',' ')},*/ /* Krio */
/*{"krl", HB_TAG('K','R','L',' ')},*/ /* Karelian */
{"krt", HB_TAG('K','N','R',' ')}, /* Tumari Kanuri -> Kanuri */
{"kru", HB_TAG('K','U','U',' ')}, /* Kurukh */
{"ks", HB_TAG('K','S','H',' ')}, /* Kashmiri */
{"ksh", HB_TAG('K','S','H','0')}, /* Kölsch -> Ripuarian */
{"kss", HB_TAG('K','I','S',' ')}, /* Southern Kisi -> Kisii */
/*{"ksw", HB_TAG('K','S','W',' ')},*/ /* S’gaw Karen */
{"ktb", HB_TAG('K','E','B',' ')}, /* Kambaata -> Kebena */
{"ktu", HB_TAG('K','O','N',' ')}, /* Kituba (Democratic Republic of Congo) -> Kikongo */
{"ktw", HB_TAG('A','T','H',' ')}, /* Kato -> Athapaskan */
{"ku", HB_TAG('K','U','R',' ')}, /* Kurdish [macrolanguage] */
/*{"kum", HB_TAG('K','U','M',' ')},*/ /* Kumyk */
{"kuu", HB_TAG('A','T','H',' ')}, /* Upper Kuskokwim -> Athapaskan */
{"kv", HB_TAG('K','O','M',' ')}, /* Komi [macrolanguage] */
{"kvb", HB_TAG('M','L','Y',' ')}, /* Kubu -> Malay */
{"kvr", HB_TAG('M','L','Y',' ')}, /* Kerinci -> Malay */
{"kw", HB_TAG('C','O','R',' ')}, /* Cornish */
{"kwy", HB_TAG('K','O','N','0')}, /* San Salvador Kongo -> Kongo */
{"kxc", HB_TAG('K','M','S',' ')}, /* Konso -> Komso */
{"kxd", HB_TAG('M','L','Y',' ')}, /* Brunei -> Malay */
{"kxu", HB_TAG('K','U','I',' ')}, /* Kui (India) */
{"ky", HB_TAG('K','I','R',' ')}, /* Kirghiz (Kyrgyz) */
/*{"kyu", HB_TAG('K','Y','U',' ')},*/ /* Western Kayah */
{"la", HB_TAG('L','A','T',' ')}, /* Latin */
{"lad", HB_TAG('J','U','D',' ')}, /* Ladino */
{"lb", HB_TAG('L','T','Z',' ')}, /* Luxembourgish */
{"lbe", HB_TAG('L','A','K',' ')}, /* Lak */
{"lbj", HB_TAG('L','D','K',' ')}, /* Ladakhi */
{"lbl", HB_TAG('B','I','K',' ')}, /* Libon Bikol -> Bikol */
{"lce", HB_TAG('M','L','Y',' ')}, /* Loncong -> Malay */
{"lcf", HB_TAG('M','L','Y',' ')}, /* Lubu -> Malay */
{"ldi", HB_TAG('K','O','N','0')}, /* Laari -> Kongo */
/*{"lez", HB_TAG('L','E','Z',' ')},*/ /* Lezghian -> Lezgi */
{"lg", HB_TAG('L','U','G',' ')}, /* Ganda */
{"li", HB_TAG('L','I','M',' ')}, /* Limburgish */
{"lif", HB_TAG('L','M','B',' ')}, /* Limbu */
/*{"lij", HB_TAG('L','I','J',' ')},*/ /* Ligurian */
/*{"lis", HB_TAG('L','I','S',' ')},*/ /* Lisu */
{"liw", HB_TAG('M','L','Y',' ')}, /* Col -> Malay */
/*{"ljp", HB_TAG('L','J','P',' ')},*/ /* Lampung Api -> Lampung */
{"lkb", HB_TAG('L','U','H',' ')}, /* Kabras -> Luyia */
/*{"lki", HB_TAG('L','K','I',' ')},*/ /* Laki */
{"lko", HB_TAG('L','U','H',' ')}, /* Khayo -> Luyia */
{"lks", HB_TAG('L','U','H',' ')}, /* Kisa -> Luyia */
{"lld", HB_TAG('L','A','D',' ')}, /* Ladin */
{"lmn", HB_TAG('L','A','M',' ')}, /* Lambadi -> Lambani */
/*{"lmo", HB_TAG('L','M','O',' ')},*/ /* Lombard */
{"ln", HB_TAG('L','I','N',' ')}, /* Lingala */
{"lo", HB_TAG('L','A','O',' ')}, /* Lao */
/*{"lom", HB_TAG('L','O','M',' ')},*/ /* Loma (Liberia) */
/*{"lrc", HB_TAG('L','R','C',' ')},*/ /* Northern Luri -> Luri */
{"lri", HB_TAG('L','U','H',' ')}, /* Marachi -> Luyia */
{"lrm", HB_TAG('L','U','H',' ')}, /* Marama -> Luyia */
{"lsm", HB_TAG('L','U','H',' ')}, /* Saamia -> Luyia */
{"lt", HB_TAG('L','T','H',' ')}, /* Lithuanian */
{"ltg", HB_TAG('L','V','I',' ')}, /* Latgalian -> Latvian */
{"lto", HB_TAG('L','U','H',' ')}, /* Tsotso -> Luyia */
{"lts", HB_TAG('L','U','H',' ')}, /* Tachoni -> Luyia */
{"lu", HB_TAG('L','U','B',' ')}, /* Luba-Katanga */
/*{"lua", HB_TAG('L','U','A',' ')},*/ /* Luba-Lulua */
/*{"luo", HB_TAG('L','U','O',' ')},*/ /* Luo (Kenya and Tanzania) */
{"lus", HB_TAG('M','I','Z',' ')}, /* Lushai -> Mizo */
{"luy", HB_TAG('L','U','H',' ')}, /* Luyia [macrolanguage] */
{"luz", HB_TAG('L','R','C',' ')}, /* Southern Luri -> Luri */
{"lv", HB_TAG('L','V','I',' ')}, /* Latvian [macrolanguage] */
{"lvs", HB_TAG('L','V','I',' ')}, /* Standard Latvian -> Latvian */
{"lwg", HB_TAG('L','U','H',' ')}, /* Wanga -> Luyia */
{"lzh", HB_TAG('Z','H','T',' ')}, /* Literary Chinese -> Chinese Traditional */
{"lzz", HB_TAG('L','A','Z',' ')}, /* Laz */
/*{"mad", HB_TAG('M','A','D',' ')},*/ /* Madurese -> Madura */
/*{"mag", HB_TAG('M','A','G',' ')},*/ /* Magahi */
{"mai", HB_TAG('M','T','H',' ')}, /* Maithili */
{"mak", HB_TAG('M','K','R',' ')}, /* Makasar */
/*{"mam", HB_TAG('M','A','M',' ')},*/ /* Mam */
{"man", HB_TAG('M','N','K',' ')}, /* Mandingo [macrolanguage] -> Maninka */
{"max", HB_TAG('M','L','Y',' ')}, /* North Moluccan Malay -> Malay */
/*{"mbo", HB_TAG('M','B','O',' ')},*/ /* Mbo (Cameroon) */
{"mct", HB_TAG('B','T','I',' ')}, /* Mengisa -> Beti */
{"mdf", HB_TAG('M','O','K',' ')}, /* Moksha */
/*{"mdr", HB_TAG('M','D','R',' ')},*/ /* Mandar */
{"mdy", HB_TAG('M','L','E',' ')}, /* Male (Ethiopia) */
{"men", HB_TAG('M','D','E',' ')}, /* Mende (Sierra Leone) */
{"meo", HB_TAG('M','L','Y',' ')}, /* Kedah Malay -> Malay */
/*{"mer", HB_TAG('M','E','R',' ')},*/ /* Meru */
/*{"mfa", HB_TAG('M','F','A',' ')},*/ /* Pattani Malay */
{"mfb", HB_TAG('M','L','Y',' ')}, /* Bangka -> Malay */
/*{"mfe", HB_TAG('M','F','E',' ')},*/ /* Morisyen */
{"mg", HB_TAG('M','L','G',' ')}, /* Malagasy [macrolanguage] */
{"mh", HB_TAG('M','A','H',' ')}, /* Marshallese */
{"mhr", HB_TAG('L','M','A',' ')}, /* Eastern Mari -> Low Mari */
{"mhv", HB_TAG('A','R','K',' ')}, /* Arakanese (retired code) -> Rakhine */
{"mi", HB_TAG('M','R','I',' ')}, /* Maori */
/*{"min", HB_TAG('M','I','N',' ')},*/ /* Minangkabau */
{"mk", HB_TAG('M','K','D',' ')}, /* Macedonian */
{"mku", HB_TAG('M','N','K',' ')}, /* Konyanka Maninka -> Maninka */
/*{"mkw", HB_TAG('M','K','W',' ')},*/ /* Kituba (Congo) */
{"ml", HB_TAG('M','A','L',' ')}, /* Malayalam -> Malayalam Traditional */
{"ml", HB_TAG('M','L','R',' ')}, /* Malayalam -> Malayalam Reformed */
{"mlq", HB_TAG('M','L','N',' ')}, /* Western Maninkakan -> Malinke */
{"mlq", HB_TAG('M','N','K',' ')}, /* Western Maninkakan -> Maninka */
{"mmr", HB_TAG('H','M','N',' ')}, /* Western Xiangxi Miao -> Hmong */
{"mn", HB_TAG('M','N','G',' ')}, /* Mongolian [macrolanguage] */
{"mnc", HB_TAG('M','C','H',' ')}, /* Manchu */
/*{"mni", HB_TAG('M','N','I',' ')},*/ /* Manipuri */
{"mnk", HB_TAG('M','N','D',' ')}, /* Mandinka */
{"mnk", HB_TAG('M','N','K',' ')}, /* Mandinka -> Maninka */
{"mnp", HB_TAG('Z','H','S',' ')}, /* Min Bei Chinese -> Chinese Simplified */
{"mns", HB_TAG('M','A','N',' ')}, /* Mansi */
{"mnw", HB_TAG('M','O','N',' ')}, /* Mon */
{"mo", HB_TAG('M','O','L',' ')}, /* Moldavian (retired code) */
/*{"moh", HB_TAG('M','O','H',' ')},*/ /* Mohawk */
/*{"mos", HB_TAG('M','O','S',' ')},*/ /* Mossi */
{"mpe", HB_TAG('M','A','J',' ')}, /* Majang */
{"mqg", HB_TAG('M','L','Y',' ')}, /* Kota Bangun Kutai Malay -> Malay */
{"mr", HB_TAG('M','A','R',' ')}, /* Marathi */
{"mrh", HB_TAG('Q','I','N',' ')}, /* Mara Chin -> Chin */
{"mrj", HB_TAG('H','M','A',' ')}, /* Western Mari -> High Mari */
{"ms", HB_TAG('M','L','Y',' ')}, /* Malay [macrolanguage] */
{"msc", HB_TAG('M','N','K',' ')}, /* Sankaran Maninka -> Maninka */
{"msh", HB_TAG('M','L','G',' ')}, /* Masikoro Malagasy -> Malagasy */
{"msi", HB_TAG('M','L','Y',' ')}, /* Sabah Malay -> Malay */
{"mt", HB_TAG('M','T','S',' ')}, /* Maltese */
{"mtr", HB_TAG('M','A','W',' ')}, /* Mewari -> Marwari */
{"mui", HB_TAG('M','L','Y',' ')}, /* Musi -> Malay */
{"mup", HB_TAG('R','A','J',' ')}, /* Malvi -> Rajasthani */
{"muq", HB_TAG('H','M','N',' ')}, /* Eastern Xiangxi Miao -> Hmong */
/*{"mus", HB_TAG('M','U','S',' ')},*/ /* Creek -> Muscogee */
{"mvb", HB_TAG('A','T','H',' ')}, /* Mattole -> Athapaskan */
{"mve", HB_TAG('M','A','W',' ')}, /* Marwari (Pakistan) */
{"mvf", HB_TAG('M','N','G',' ')}, /* Peripheral Mongolian -> Mongolian */
{"mwk", HB_TAG('M','N','K',' ')}, /* Kita Maninkakan -> Maninka */
/*{"mwl", HB_TAG('M','W','L',' ')},*/ /* Mirandese */
{"mwr", HB_TAG('M','A','W',' ')}, /* Marwari [macrolanguage] */
/*{"mww", HB_TAG('M','W','W',' ')},*/ /* Hmong Daw */
{"my", HB_TAG('B','R','M',' ')}, /* Burmese */
{"mym", HB_TAG('M','E','N',' ')}, /* Me’en */
/*{"myn", HB_TAG('M','Y','N',' ')},*/ /* Mayan [family] */
{"myq", HB_TAG('M','N','K',' ')}, /* Forest Maninka (retired code) -> Maninka */
{"myv", HB_TAG('E','R','Z',' ')}, /* Erzya */
/*{"mzn", HB_TAG('M','Z','N',' ')},*/ /* Mazanderani */
{"na", HB_TAG('N','A','U',' ')}, /* Nauru -> Nauruan */
/*{"nag", HB_TAG('N','A','G',' ')},*/ /* Naga Pidgin -> Naga-Assamese */
/*{"nah", HB_TAG('N','A','H',' ')},*/ /* Nahuatl [family] */
{"nan", HB_TAG('Z','H','S',' ')}, /* Min Nan Chinese -> Chinese Simplified */
/*{"nap", HB_TAG('N','A','P',' ')},*/ /* Neapolitan */
{"nb", HB_TAG('N','O','R',' ')}, /* Norwegian Bokmål -> Norwegian */
{"nd", HB_TAG('N','D','B',' ')}, /* North Ndebele -> Ndebele */
/*{"ndc", HB_TAG('N','D','C',' ')},*/ /* Ndau */
/*{"nds", HB_TAG('N','D','S',' ')},*/ /* Low Saxon */
{"ne", HB_TAG('N','E','P',' ')}, /* Nepali [macrolanguage] */
/*{"new", HB_TAG('N','E','W',' ')},*/ /* Newari */
{"ng", HB_TAG('N','D','G',' ')}, /* Ndonga */
/*{"nga", HB_TAG('N','G','A',' ')},*/ /* Ngbaka */
{"ngl", HB_TAG('L','M','W',' ')}, /* Lomwe */
{"ngo", HB_TAG('S','X','T',' ')}, /* Ngoni -> Sutu */
{"nhd", HB_TAG('G','U','A',' ')}, /* Chiripá -> Guarani */
{"niq", HB_TAG('K','A','L',' ')}, /* Nandi -> Kalenjin */
/*{"niu", HB_TAG('N','I','U',' ')},*/ /* Niuean */
{"niv", HB_TAG('G','I','L',' ')}, /* Gilyak */
{"njz", HB_TAG('N','I','S',' ')}, /* Nyishi -> Nisi */
{"nl", HB_TAG('N','L','D',' ')}, /* Dutch */
{"nle", HB_TAG('L','U','H',' ')}, /* East Nyala -> Luyia */
{"nn", HB_TAG('N','Y','N',' ')}, /* Norwegian Nynorsk (Nynorsk, Norwegian) */
{"no", HB_TAG('N','O','R',' ')}, /* Norwegian [macrolanguage] */
{"nod", HB_TAG('N','T','A',' ')}, /* Northern Thai -> Northern Tai */
/*{"noe", HB_TAG('N','O','E',' ')},*/ /* Nimadi */
/*{"nog", HB_TAG('N','O','G',' ')},*/ /* Nogai */
/*{"nov", HB_TAG('N','O','V',' ')},*/ /* Novial */
{"npi", HB_TAG('N','E','P',' ')}, /* Nepali */
{"nqo", HB_TAG('N','K','O',' ')}, /* N’Ko */
{"nr", HB_TAG('N','D','B',' ')}, /* South Ndebele -> Ndebele */
{"nsk", HB_TAG('N','A','S',' ')}, /* Naskapi */
/*{"nso", HB_TAG('N','S','O',' ')},*/ /* Pedi -> Sotho, Northern */
{"nv", HB_TAG('N','A','V',' ')}, /* Navajo */
{"nv", HB_TAG('A','T','H',' ')}, /* Navajo -> Athapaskan */
{"ny", HB_TAG('C','H','I',' ')}, /* Chichewa (Chewa, Nyanja) */
{"nyd", HB_TAG('L','U','H',' ')}, /* Nyore -> Luyia */
/*{"nym", HB_TAG('N','Y','M',' ')},*/ /* Nyamwezi */
{"nyn", HB_TAG('N','K','L',' ')}, /* Nyankole */
/*{"nza", HB_TAG('N','Z','A',' ')},*/ /* Tigon Mbembe -> Mbembe Tigon */
{"oc", HB_TAG('O','C','I',' ')}, /* Occitan (post 1500) */
{"oj", HB_TAG('O','J','B',' ')}, /* Ojibwa [macrolanguage] -> Ojibway */
/*{"ojb", HB_TAG('O','J','B',' ')},*/ /* Northwestern Ojibwa -> Ojibway */
{"ojc", HB_TAG('O','J','B',' ')}, /* Central Ojibwa -> Ojibway */
{"ojg", HB_TAG('O','J','B',' ')}, /* Eastern Ojibwa -> Ojibway */
{"ojs", HB_TAG('O','C','R',' ')}, /* Severn Ojibwa -> Oji-Cree */
{"ojw", HB_TAG('O','J','B',' ')}, /* Western Ojibwa -> Ojibway */
{"oki", HB_TAG('K','A','L',' ')}, /* Okiek -> Kalenjin */
{"okm", HB_TAG('K','O','H',' ')}, /* Middle Korean (10th-16th cent.) -> Korean Old Hangul */
{"om", HB_TAG('O','R','O',' ')}, /* Oromo [macrolanguage] */
{"or", HB_TAG('O','R','I',' ')}, /* Odia (formerly Oriya) [macrolanguage] */
{"orc", HB_TAG('O','R','O',' ')}, /* Orma -> Oromo */
{"orn", HB_TAG('M','L','Y',' ')}, /* Orang Kanaq -> Malay */
{"ors", HB_TAG('M','L','Y',' ')}, /* Orang Seletar -> Malay */
{"ory", HB_TAG('O','R','I',' ')}, /* Odia (formerly Oriya) */
{"os", HB_TAG('O','S','S',' ')}, /* Ossetian */
{"otw", HB_TAG('O','J','B',' ')}, /* Ottawa -> Ojibway */
{"pa", HB_TAG('P','A','N',' ')}, /* Punjabi */
/*{"pag", HB_TAG('P','A','G',' ')},*/ /* Pangasinan */
/*{"pam", HB_TAG('P','A','M',' ')},*/ /* Pampanga -> Pampangan */
{"pap", HB_TAG('P','A','P','0')}, /* Papiamento -> Papiamentu */
/*{"pau", HB_TAG('P','A','U',' ')},*/ /* Palauan */
{"pbt", HB_TAG('P','A','S',' ')}, /* Southern Pashto -> Pashto */
{"pbu", HB_TAG('P','A','S',' ')}, /* Northern Pashto -> Pashto */
/*{"pcc", HB_TAG('P','C','C',' ')},*/ /* Bouyei */
/*{"pcd", HB_TAG('P','C','D',' ')},*/ /* Picard */
{"pce", HB_TAG('P','L','G',' ')}, /* Ruching Palaung -> Palaung */
{"pck", HB_TAG('Q','I','N',' ')}, /* Paite Chin -> Chin */
/*{"pdc", HB_TAG('P','D','C',' ')},*/ /* Pennsylvania German */
{"pel", HB_TAG('M','L','Y',' ')}, /* Pekal -> Malay */
{"pes", HB_TAG('F','A','R',' ')}, /* Iranian Persian -> Persian */
{"pga", HB_TAG('A','R','A',' ')}, /* Sudanese Creole Arabic -> Arabic */
/*{"phk", HB_TAG('P','H','K',' ')},*/ /* Phake */
{"pi", HB_TAG('P','A','L',' ')}, /* Pali */
/*{"pih", HB_TAG('P','I','H',' ')},*/ /* Pitcairn-Norfolk -> Norfolk */
{"pko", HB_TAG('K','A','L',' ')}, /* Pökoot -> Kalenjin */
{"pl", HB_TAG('P','L','K',' ')}, /* Polish */
{"pll", HB_TAG('P','L','G',' ')}, /* Shwe Palaung -> Palaung */
{"plp", HB_TAG('P','A','P',' ')}, /* Palpa */
{"plt", HB_TAG('M','L','G',' ')}, /* Plateau Malagasy -> Malagasy */
/*{"pms", HB_TAG('P','M','S',' ')},*/ /* Piemontese */
/*{"pnb", HB_TAG('P','N','B',' ')},*/ /* Western Panjabi */
/*{"poh", HB_TAG('P','O','H',' ')},*/ /* Poqomchi' -> Pocomchi */
/*{"pon", HB_TAG('P','O','N',' ')},*/ /* Pohnpeian */
{"ppa", HB_TAG('B','A','G',' ')}, /* Pao (retired code) -> Baghelkhandi */
/*{"pro", HB_TAG('P','R','O',' ')},*/ /* Old Provençal (to 1500) -> Provençal / Old Provençal */
{"prs", HB_TAG('D','R','I',' ')}, /* Dari */
{"ps", HB_TAG('P','A','S',' ')}, /* Pashto [macrolanguage] */
{"pse", HB_TAG('M','L','Y',' ')}, /* Central Malay -> Malay */
{"pst", HB_TAG('P','A','S',' ')}, /* Central Pashto -> Pashto */
{"pt", HB_TAG('P','T','G',' ')}, /* Portuguese */
/*{"pwo", HB_TAG('P','W','O',' ')},*/ /* Pwo Western Karen -> Western Pwo Karen */
{"qu", HB_TAG('Q','U','Z',' ')}, /* Quechua [macrolanguage] */
{"qub", HB_TAG('Q','W','H',' ')}, /* Huallaga Huánuco Quechua -> Quechua (Peru) */
/*{"quc", HB_TAG('Q','U','C',' ')},*/ /* K’iche’ */
{"qud", HB_TAG('Q','V','I',' ')}, /* Calderón Highland Quichua -> Quechua (Ecuador) */
{"quf", HB_TAG('Q','U','Z',' ')}, /* Lambayeque Quechua -> Quechua */
{"qug", HB_TAG('Q','V','I',' ')}, /* Chimborazo Highland Quichua -> Quechua (Ecuador) */
/*{"quh", HB_TAG('Q','U','H',' ')},*/ /* South Bolivian Quechua -> Quechua (Bolivia) */
{"quk", HB_TAG('Q','U','Z',' ')}, /* Chachapoyas Quechua -> Quechua */
{"qul", HB_TAG('Q','U','Z',' ')}, /* North Bolivian Quechua -> Quechua */
{"qup", HB_TAG('Q','V','I',' ')}, /* Southern Pastaza Quechua -> Quechua (Ecuador) */
{"qur", HB_TAG('Q','W','H',' ')}, /* Yanahuanca Pasco Quechua -> Quechua (Peru) */
{"qus", HB_TAG('Q','U','H',' ')}, /* Santiago del Estero Quichua -> Quechua (Bolivia) */
{"quw", HB_TAG('Q','V','I',' ')}, /* Tena Lowland Quichua -> Quechua (Ecuador) */
{"qux", HB_TAG('Q','W','H',' ')}, /* Yauyos Quechua -> Quechua (Peru) */
{"quy", HB_TAG('Q','U','Z',' ')}, /* Ayacucho Quechua -> Quechua */
/*{"quz", HB_TAG('Q','U','Z',' ')},*/ /* Cusco Quechua -> Quechua */
{"qva", HB_TAG('Q','W','H',' ')}, /* Ambo-Pasco Quechua -> Quechua (Peru) */
{"qvc", HB_TAG('Q','U','Z',' ')}, /* Cajamarca Quechua -> Quechua */
{"qve", HB_TAG('Q','U','Z',' ')}, /* Eastern Apurímac Quechua -> Quechua */
{"qvh", HB_TAG('Q','W','H',' ')}, /* Huamalíes-Dos de Mayo Huánuco Quechua -> Quechua (Peru) */
/*{"qvi", HB_TAG('Q','V','I',' ')},*/ /* Imbabura Highland Quichua -> Quechua (Ecuador) */
{"qvj", HB_TAG('Q','V','I',' ')}, /* Loja Highland Quichua -> Quechua (Ecuador) */
{"qvl", HB_TAG('Q','W','H',' ')}, /* Cajatambo North Lima Quechua -> Quechua (Peru) */
{"qvm", HB_TAG('Q','W','H',' ')}, /* Margos-Yarowilca-Lauricocha Quechua -> Quechua (Peru) */
{"qvn", HB_TAG('Q','W','H',' ')}, /* North Junín Quechua -> Quechua (Peru) */
{"qvo", HB_TAG('Q','V','I',' ')}, /* Napo Lowland Quechua -> Quechua (Ecuador) */
{"qvp", HB_TAG('Q','W','H',' ')}, /* Pacaraos Quechua -> Quechua (Peru) */
{"qvs", HB_TAG('Q','U','Z',' ')}, /* San Martín Quechua -> Quechua */
{"qvw", HB_TAG('Q','W','H',' ')}, /* Huaylla Wanca Quechua -> Quechua (Peru) */
{"qvz", HB_TAG('Q','V','I',' ')}, /* Northern Pastaza Quichua -> Quechua (Ecuador) */
{"qwa", HB_TAG('Q','W','H',' ')}, /* Corongo Ancash Quechua -> Quechua (Peru) */
{"qwc", HB_TAG('Q','U','Z',' ')}, /* Classical Quechua -> Quechua */
/*{"qwh", HB_TAG('Q','W','H',' ')},*/ /* Huaylas Ancash Quechua -> Quechua (Peru) */
{"qws", HB_TAG('Q','W','H',' ')}, /* Sihuas Ancash Quechua -> Quechua (Peru) */
{"qxa", HB_TAG('Q','W','H',' ')}, /* Chiquián Ancash Quechua -> Quechua (Peru) */
{"qxc", HB_TAG('Q','W','H',' ')}, /* Chincha Quechua -> Quechua (Peru) */
{"qxh", HB_TAG('Q','W','H',' ')}, /* Panao Huánuco Quechua -> Quechua (Peru) */
{"qxl", HB_TAG('Q','V','I',' ')}, /* Salasaca Highland Quichua -> Quechua (Ecuador) */
{"qxn", HB_TAG('Q','W','H',' ')}, /* Northern Conchucos Ancash Quechua -> Quechua (Peru) */
{"qxo", HB_TAG('Q','W','H',' ')}, /* Southern Conchucos Ancash Quechua -> Quechua (Peru) */
{"qxp", HB_TAG('Q','U','Z',' ')}, /* Puno Quechua -> Quechua */
{"qxr", HB_TAG('Q','V','I',' ')}, /* Cañar Highland Quichua -> Quechua (Ecuador) */
{"qxt", HB_TAG('Q','W','H',' ')}, /* Santa Ana de Tusi Pasco Quechua -> Quechua (Peru) */
{"qxu", HB_TAG('Q','U','Z',' ')}, /* Arequipa-La Unión Quechua -> Quechua */
{"qxw", HB_TAG('Q','W','H',' ')}, /* Jauja Wanca Quechua -> Quechua (Peru) */
{"rag", HB_TAG('L','U','H',' ')}, /* Logooli -> Luyia */
/*{"raj", HB_TAG('R','A','J',' ')},*/ /* Rajasthani [macrolanguage] */
/*{"rar", HB_TAG('R','A','R',' ')},*/ /* Rarotongan */
{"rbb", HB_TAG('P','L','G',' ')}, /* Rumai Palaung -> Palaung */
{"rbl", HB_TAG('B','I','K',' ')}, /* Miraya Bikol -> Bikol */
/*{"rej", HB_TAG('R','E','J',' ')},*/ /* Rejang */
/*{"ria", HB_TAG('R','I','A',' ')},*/ /* Riang (India) */
/*{"rif", HB_TAG('R','I','F',' ')},*/ /* Tarifit */
/*{"rit", HB_TAG('R','I','T',' ')},*/ /* Ritarungo */
{"rki", HB_TAG('A','R','K',' ')}, /* Rakhine */
/*{"rkw", HB_TAG('R','K','W',' ')},*/ /* Arakwal */
{"rm", HB_TAG('R','M','S',' ')}, /* Romansh */
{"rmc", HB_TAG('R','O','Y',' ')}, /* Carpathian Romani -> Romany */
{"rmf", HB_TAG('R','O','Y',' ')}, /* Kalo Finnish Romani -> Romany */
{"rml", HB_TAG('R','O','Y',' ')}, /* Baltic Romani -> Romany */
{"rmn", HB_TAG('R','O','Y',' ')}, /* Balkan Romani -> Romany */
{"rmo", HB_TAG('R','O','Y',' ')}, /* Sinte Romani -> Romany */
{"rmw", HB_TAG('R','O','Y',' ')}, /* Welsh Romani -> Romany */
/*{"rmy", HB_TAG('R','M','Y',' ')},*/ /* Vlax Romani */
{"rmz", HB_TAG('A','R','K',' ')}, /* Marma -> Rakhine */
{"rn", HB_TAG('R','U','N',' ')}, /* Rundi */
{"rnl", HB_TAG('H','A','L',' ')}, /* Ranglong -> Halam (Falam Chin) */
{"ro", HB_TAG('R','O','M',' ')}, /* Romanian */
{"rom", HB_TAG('R','O','Y',' ')}, /* Romany [macrolanguage] */
/*{"rtm", HB_TAG('R','T','M',' ')},*/ /* Rotuman */
{"ru", HB_TAG('R','U','S',' ')}, /* Russian */
{"rue", HB_TAG('R','S','Y',' ')}, /* Rusyn */
/*{"rup", HB_TAG('R','U','P',' ')},*/ /* Aromanian */
{"rw", HB_TAG('R','U','A',' ')}, /* Kinyarwanda */
{"rwr", HB_TAG('M','A','W',' ')}, /* Marwari (India) */
{"sa", HB_TAG('S','A','N',' ')}, /* Sanskrit */
{"sah", HB_TAG('Y','A','K',' ')}, /* Yakut -> Sakha */
{"sam", HB_TAG('P','A','A',' ')}, /* Samaritan Aramaic -> Palestinian Aramaic */
/*{"sas", HB_TAG('S','A','S',' ')},*/ /* Sasak */
/*{"sat", HB_TAG('S','A','T',' ')},*/ /* Santali */
{"sc", HB_TAG('S','R','D',' ')}, /* Sardinian [macrolanguage] */
{"sck", HB_TAG('S','A','D',' ')}, /* Sadri */
/*{"scn", HB_TAG('S','C','N',' ')},*/ /* Sicilian */
/*{"sco", HB_TAG('S','C','O',' ')},*/ /* Scots */
{"scs", HB_TAG('S','C','S',' ')}, /* North Slavey */
{"scs", HB_TAG('S','L','A',' ')}, /* North Slavey -> Slavey */
{"scs", HB_TAG('A','T','H',' ')}, /* North Slavey -> Athapaskan */
{"sd", HB_TAG('S','N','D',' ')}, /* Sindhi */
{"sdc", HB_TAG('S','R','D',' ')}, /* Sassarese Sardinian -> Sardinian */
{"sdh", HB_TAG('K','U','R',' ')}, /* Southern Kurdish -> Kurdish */
{"sdn", HB_TAG('S','R','D',' ')}, /* Gallurese Sardinian -> Sardinian */
{"se", HB_TAG('N','S','M',' ')}, /* Northern Sami */
{"seh", HB_TAG('S','N','A',' ')}, /* Sena */
{"sek", HB_TAG('A','T','H',' ')}, /* Sekani -> Athapaskan */
/*{"sel", HB_TAG('S','E','L',' ')},*/ /* Selkup */
{"sez", HB_TAG('Q','I','N',' ')}, /* Senthang Chin -> Chin */
{"sfm", HB_TAG('H','M','N',' ')}, /* Small Flowery Miao -> Hmong */
{"sg", HB_TAG('S','G','O',' ')}, /* Sango */
/*{"sga", HB_TAG('S','G','A',' ')},*/ /* Old Irish (to 900) */
{"sgc", HB_TAG('K','A','L',' ')}, /* Kipsigis -> Kalenjin */
/*{"sgs", HB_TAG('S','G','S',' ')},*/ /* Samogitian */
{"sgw", HB_TAG('C','H','G',' ')}, /* Sebat Bet Gurage -> Chaha Gurage */
{"sgw", HB_TAG('S','G','W',' ')}, /* Sebat Bet Gurage -> Chaha Gurage (SIL fonts) */
/*{"shi", HB_TAG('S','H','I',' ')},*/ /* Tachelhit */
/*{"shn", HB_TAG('S','H','N',' ')},*/ /* Shan */
{"shu", HB_TAG('A','R','A',' ')}, /* Chadian Arabic -> Arabic */
{"si", HB_TAG('S','N','H',' ')}, /* Sinhala (Sinhalese) */
/*{"sid", HB_TAG('S','I','D',' ')},*/ /* Sidamo */
{"sjd", HB_TAG('K','S','M',' ')}, /* Kildin Sami */
{"sjo", HB_TAG('S','I','B',' ')}, /* Xibe -> Sibe */
{"sk", HB_TAG('S','K','Y',' ')}, /* Slovak */
{"skg", HB_TAG('M','L','G',' ')}, /* Sakalava Malagasy -> Malagasy */
{"skr", HB_TAG('S','R','K',' ')}, /* Saraiki */
{"sl", HB_TAG('S','L','V',' ')}, /* Slovenian */
{"sm", HB_TAG('S','M','O',' ')}, /* Samoan */
{"sma", HB_TAG('S','S','M',' ')}, /* Southern Sami */
{"smj", HB_TAG('L','S','M',' ')}, /* Lule Sami */
{"smn", HB_TAG('I','S','M',' ')}, /* Inari Sami */
{"sms", HB_TAG('S','K','S',' ')}, /* Skolt Sami */
{"sn", HB_TAG('S','N','A','0')}, /* Shona */
/*{"snk", HB_TAG('S','N','K',' ')},*/ /* Soninke */
{"so", HB_TAG('S','M','L',' ')}, /* Somali */
/*{"sop", HB_TAG('S','O','P',' ')},*/ /* Songe */
{"spv", HB_TAG('O','R','I',' ')}, /* Sambalpuri -> Odia (formerly Oriya) */
{"spy", HB_TAG('K','A','L',' ')}, /* Sabaot -> Kalenjin */
{"sq", HB_TAG('S','Q','I',' ')}, /* Albanian [macrolanguage] */
{"sr", HB_TAG('S','R','B',' ')}, /* Serbian */
{"src", HB_TAG('S','R','D',' ')}, /* Logudorese Sardinian -> Sardinian */
{"sro", HB_TAG('S','R','D',' ')}, /* Campidanese Sardinian -> Sardinian */
/*{"srr", HB_TAG('S','R','R',' ')},*/ /* Serer */
{"srs", HB_TAG('A','T','H',' ')}, /* Sarsi -> Athapaskan */
{"ss", HB_TAG('S','W','Z',' ')}, /* Swati */
{"ssh", HB_TAG('A','R','A',' ')}, /* Shihhi Arabic -> Arabic */
{"st", HB_TAG('S','O','T',' ')}, /* Southern Sotho -> Sotho, Southern */
/*{"stq", HB_TAG('S','T','Q',' ')},*/ /* Saterfriesisch -> Saterland Frisian */
{"stv", HB_TAG('S','I','G',' ')}, /* Silt'e -> Silte Gurage */
{"su", HB_TAG('S','U','N',' ')}, /* Sundanese */
/*{"suk", HB_TAG('S','U','K',' ')},*/ /* Sukuma */
{"suq", HB_TAG('S','U','R',' ')}, /* Suri */
{"sv", HB_TAG('S','V','E',' ')}, /* Swedish */
/*{"sva", HB_TAG('S','V','A',' ')},*/ /* Svan */
{"sw", HB_TAG('S','W','K',' ')}, /* Swahili [macrolanguage] */
{"swb", HB_TAG('C','M','R',' ')}, /* Maore Comorian -> Comorian */
{"swc", HB_TAG('S','W','K',' ')}, /* Congo Swahili -> Swahili */
{"swh", HB_TAG('S','W','K',' ')}, /* Swahili */
{"swv", HB_TAG('M','A','W',' ')}, /* Shekhawati -> Marwari */
/*{"sxu", HB_TAG('S','X','U',' ')},*/ /* Upper Saxon */
{"syc", HB_TAG('S','Y','R',' ')}, /* Classical Syriac -> Syriac */
/*{"syl", HB_TAG('S','Y','L',' ')},*/ /* Sylheti */
/*{"syr", HB_TAG('S','Y','R',' ')},*/ /* Syriac [macrolanguage] */
/*{"szl", HB_TAG('S','Z','L',' ')},*/ /* Silesian */
{"ta", HB_TAG('T','A','M',' ')}, /* Tamil */
{"taa", HB_TAG('A','T','H',' ')}, /* Lower Tanana -> Athapaskan */
/*{"tab", HB_TAG('T','A','B',' ')},*/ /* Tabassaran -> Tabasaran */
{"taq", HB_TAG('T','M','H',' ')}, /* Tamasheq -> Tamashek */
{"tau", HB_TAG('A','T','H',' ')}, /* Upper Tanana -> Athapaskan */
{"tcb", HB_TAG('A','T','H',' ')}, /* Tanacross -> Athapaskan */
{"tce", HB_TAG('A','T','H',' ')}, /* Southern Tutchone -> Athapaskan */
{"tcp", HB_TAG('Q','I','N',' ')}, /* Tawr Chin -> Chin */
{"tcy", HB_TAG('T','U','L',' ')}, /* Tulu -> Tumbuka */
{"tcz", HB_TAG('Q','I','N',' ')}, /* Thado Chin -> Chin */
/*{"tdd", HB_TAG('T','D','D',' ')},*/ /* Tai Nüa -> Dehong Dai */
{"tdx", HB_TAG('M','L','G',' ')}, /* Tandroy-Mahafaly Malagasy -> Malagasy */
{"te", HB_TAG('T','E','L',' ')}, /* Telugu */
{"tec", HB_TAG('K','A','L',' ')}, /* Terik -> Kalenjin */
{"tem", HB_TAG('T','M','N',' ')}, /* Timne -> Temne */
/*{"tet", HB_TAG('T','E','T',' ')},*/ /* Tetum */
{"tfn", HB_TAG('A','T','H',' ')}, /* Tanaina -> Athapaskan */
{"tg", HB_TAG('T','A','J',' ')}, /* Tajik -> Tajiki */
{"tgj", HB_TAG('N','I','S',' ')}, /* Tagin -> Nisi */
{"tgx", HB_TAG('A','T','H',' ')}, /* Tagish -> Athapaskan */
{"th", HB_TAG('T','H','A',' ')}, /* Thai */
{"tht", HB_TAG('A','T','H',' ')}, /* Tahltan -> Athapaskan */
{"thv", HB_TAG('T','M','H',' ')}, /* Tahaggart Tamahaq -> Tamashek */
{"thz", HB_TAG('T','M','H',' ')}, /* Tayart Tamajeq -> Tamashek */
{"ti", HB_TAG('T','G','Y',' ')}, /* Tigrinya */
{"tig", HB_TAG('T','G','R',' ')}, /* Tigre */
/*{"tiv", HB_TAG('T','I','V',' ')},*/ /* Tiv */
{"tk", HB_TAG('T','K','M',' ')}, /* Turkmen */
{"tkg", HB_TAG('M','L','G',' ')}, /* Tesaka Malagasy -> Malagasy */
{"tl", HB_TAG('T','G','L',' ')}, /* Tagalog */
/*{"tmh", HB_TAG('T','M','H',' ')},*/ /* Tamashek [macrolanguage] */
{"tmw", HB_TAG('M','L','Y',' ')}, /* Temuan -> Malay */
{"tn", HB_TAG('T','N','A',' ')}, /* Tswana */
{"tnf", HB_TAG('D','R','I',' ')}, /* Tangshewi (retired code) -> Dari */
{"to", HB_TAG('T','G','N',' ')}, /* Tonga (Tonga Islands) -> Tongan */
{"tod", HB_TAG('T','O','D','0')}, /* Toma */
{"toi", HB_TAG('T','N','G',' ')}, /* Tonga (Zambia) */
{"tol", HB_TAG('A','T','H',' ')}, /* Tolowa -> Athapaskan */
/*{"tpi", HB_TAG('T','P','I',' ')},*/ /* Tok Pisin */
{"tr", HB_TAG('T','R','K',' ')}, /* Turkish */
{"tru", HB_TAG('T','U','A',' ')}, /* Turoyo -> Turoyo Aramaic */
{"tru", HB_TAG('S','Y','R',' ')}, /* Turoyo -> Syriac */
{"ts", HB_TAG('T','S','G',' ')}, /* Tsonga */
/*{"tsj", HB_TAG('T','S','J',' ')},*/ /* Tshangla */
{"tt", HB_TAG('T','A','T',' ')}, /* Tatar */
{"ttm", HB_TAG('A','T','H',' ')}, /* Northern Tutchone -> Athapaskan */
{"ttq", HB_TAG('T','M','H',' ')}, /* Tawallammat Tamajaq -> Tamashek */
/*{"tum", HB_TAG('T','U','M',' ')},*/ /* Tumbuka -> Tulu */
{"tuu", HB_TAG('A','T','H',' ')}, /* Tututni -> Athapaskan */
{"tuy", HB_TAG('K','A','L',' ')}, /* Tugen -> Kalenjin */
/*{"tvl", HB_TAG('T','V','L',' ')},*/ /* Tuvalu */
{"tw", HB_TAG('T','W','I',' ')}, /* Twi */
{"tw", HB_TAG('A','K','A',' ')}, /* Twi -> Akan */
{"txc", HB_TAG('A','T','H',' ')}, /* Tsetsaut -> Athapaskan */
{"txy", HB_TAG('M','L','G',' ')}, /* Tanosy Malagasy -> Malagasy */
{"ty", HB_TAG('T','H','T',' ')}, /* Tahitian */
{"tyv", HB_TAG('T','U','V',' ')}, /* Tuvinian -> Tuvin */
/*{"tyz", HB_TAG('T','Y','Z',' ')},*/ /* Tày */
/*{"tzm", HB_TAG('T','Z','M',' ')},*/ /* Central Atlas Tamazight -> Tamazight */
/*{"tzo", HB_TAG('T','Z','O',' ')},*/ /* Tzotzil */
{"ubl", HB_TAG('B','I','K',' ')}, /* Buhi'non Bikol -> Bikol */
/*{"udm", HB_TAG('U','D','M',' ')},*/ /* Udmurt */
{"ug", HB_TAG('U','Y','G',' ')}, /* Uyghur */
{"uk", HB_TAG('U','K','R',' ')}, /* Ukrainian */
/*{"umb", HB_TAG('U','M','B',' ')},*/ /* Umbundu */
{"unr", HB_TAG('M','U','N',' ')}, /* Mundari */
{"ur", HB_TAG('U','R','D',' ')}, /* Urdu */
{"urk", HB_TAG('M','L','Y',' ')}, /* Urak Lawoi' -> Malay */
{"uz", HB_TAG('U','Z','B',' ')}, /* Uzbek [macrolanguage] */
{"uzn", HB_TAG('U','Z','B',' ')}, /* Northern Uzbek -> Uzbek */
{"uzs", HB_TAG('U','Z','B',' ')}, /* Southern Uzbek -> Uzbek */
{"ve", HB_TAG('V','E','N',' ')}, /* Venda */
/*{"vec", HB_TAG('V','E','C',' ')},*/ /* Venetian */
{"vi", HB_TAG('V','I','T',' ')}, /* Vietnamese */
{"vkk", HB_TAG('M','L','Y',' ')}, /* Kaur -> Malay */
{"vkt", HB_TAG('M','L','Y',' ')}, /* Tenggarong Kutai Malay -> Malay */
{"vls", HB_TAG('F','L','E',' ')}, /* Vlaams -> Dutch (Flemish) */
{"vmw", HB_TAG('M','A','K',' ')}, /* Makhuwa */
{"vo", HB_TAG('V','O','L',' ')}, /* Volapük */
/*{"vro", HB_TAG('V','R','O',' ')},*/ /* Võro */
{"wa", HB_TAG('W','L','N',' ')}, /* Walloon */
/*{"war", HB_TAG('W','A','R',' ')},*/ /* Waray (Philippines) -> Waray-Waray */
{"wbm", HB_TAG('W','A',' ',' ')}, /* Wa */
{"wbr", HB_TAG('W','A','G',' ')}, /* Wagdi */
{"wlc", HB_TAG('C','M','R',' ')}, /* Mwali Comorian -> Comorian */
{"wle", HB_TAG('S','I','G',' ')}, /* Wolane -> Silte Gurage */
{"wlk", HB_TAG('A','T','H',' ')}, /* Wailaki -> Athapaskan */
{"wni", HB_TAG('C','M','R',' ')}, /* Ndzwani Comorian -> Comorian */
{"wo", HB_TAG('W','L','F',' ')}, /* Wolof */
{"wry", HB_TAG('M','A','W',' ')}, /* Merwari -> Marwari */
{"wsg", HB_TAG('G','O','N',' ')}, /* Adilabad Gondi -> Gondi */
/*{"wtm", HB_TAG('W','T','M',' ')},*/ /* Mewati */
{"wuu", HB_TAG('Z','H','S',' ')}, /* Wu Chinese -> Chinese Simplified */
{"xal", HB_TAG('K','L','M',' ')}, /* Kalmyk */
{"xal", HB_TAG('T','O','D',' ')}, /* Kalmyk -> Todo */
{"xan", HB_TAG('S','E','K',' ')}, /* Xamtanga -> Sekota */
{"xh", HB_TAG('X','H','S',' ')}, /* Xhosa */
/*{"xjb", HB_TAG('X','J','B',' ')},*/ /* Minjungbal -> Minjangbal */
/*{"xkf", HB_TAG('X','K','F',' ')},*/ /* Khengkha */
{"xmm", HB_TAG('M','L','Y',' ')}, /* Manado Malay -> Malay */
{"xmv", HB_TAG('M','L','G',' ')}, /* Antankarana Malagasy -> Malagasy */
{"xmw", HB_TAG('M','L','G',' ')}, /* Tsimihety Malagasy -> Malagasy */
{"xnr", HB_TAG('D','G','R',' ')}, /* Kangri -> Dogri */
/*{"xog", HB_TAG('X','O','G',' ')},*/ /* Soga */
/*{"xpe", HB_TAG('X','P','E',' ')},*/ /* Liberia Kpelle -> Kpelle (Liberia) */
{"xsl", HB_TAG('S','S','L',' ')}, /* South Slavey */
{"xsl", HB_TAG('S','L','A',' ')}, /* South Slavey -> Slavey */
{"xsl", HB_TAG('A','T','H',' ')}, /* South Slavey -> Athapaskan */
{"xst", HB_TAG('S','I','G',' ')}, /* Silt'e (retired code) -> Silte Gurage */
{"xwo", HB_TAG('T','O','D',' ')}, /* Written Oirat -> Todo */
/*{"yao", HB_TAG('Y','A','O',' ')},*/ /* Yao */
/*{"yap", HB_TAG('Y','A','P',' ')},*/ /* Yapese */
{"ybd", HB_TAG('A','R','K',' ')}, /* Yangbye (retired code) -> Rakhine */
{"ydd", HB_TAG('J','I','I',' ')}, /* Eastern Yiddish -> Yiddish */
{"yi", HB_TAG('J','I','I',' ')}, /* Yiddish [macrolanguage] */
{"yih", HB_TAG('J','I','I',' ')}, /* Western Yiddish -> Yiddish */
{"yo", HB_TAG('Y','B','A',' ')}, /* Yoruba */
{"yos", HB_TAG('Q','I','N',' ')}, /* Yos (retired code) -> Chin */
{"yrk", HB_TAG('T','N','E',' ')}, /* Nenets -> Tundra Nenets */
{"yrk", HB_TAG('F','N','E',' ')}, /* Nenets -> Forest Nenets */
{"yue", HB_TAG('Z','H','H',' ')}, /* Yue Chinese -> Chinese, Hong Kong SAR */
{"za", HB_TAG('Z','H','A',' ')}, /* Zhuang [macrolanguage] */
{"zch", HB_TAG('Z','H','A',' ')}, /* Central Hongshuihe Zhuang -> Zhuang */
{"zdj", HB_TAG('C','M','R',' ')}, /* Ngazidja Comorian -> Comorian */
/*{"zea", HB_TAG('Z','E','A',' ')},*/ /* Zeeuws -> Zealandic */
{"zeh", HB_TAG('Z','H','A',' ')}, /* Eastern Hongshuihe Zhuang -> Zhuang */
{"zgb", HB_TAG('Z','H','A',' ')}, /* Guibei Zhuang -> Zhuang */
/*{"zgh", HB_TAG('Z','G','H',' ')},*/ /* Standard Moroccan Tamazight */
{"zgm", HB_TAG('Z','H','A',' ')}, /* Minz Zhuang -> Zhuang */
{"zgn", HB_TAG('Z','H','A',' ')}, /* Guibian Zhuang -> Zhuang */
{"zh", HB_TAG('Z','H','S',' ')}, /* Chinese [macrolanguage] -> Chinese Simplified */
{"zhd", HB_TAG('Z','H','A',' ')}, /* Dai Zhuang -> Zhuang */
{"zhn", HB_TAG('Z','H','A',' ')}, /* Nong Zhuang -> Zhuang */
{"zlj", HB_TAG('Z','H','A',' ')}, /* Liujiang Zhuang -> Zhuang */
{"zlm", HB_TAG('M','L','Y',' ')}, /* Malay */
{"zln", HB_TAG('Z','H','A',' ')}, /* Lianshan Zhuang -> Zhuang */
{"zlq", HB_TAG('Z','H','A',' ')}, /* Liuqian Zhuang -> Zhuang */
{"zmi", HB_TAG('M','L','Y',' ')}, /* Negeri Sembilan Malay -> Malay */
{"zne", HB_TAG('Z','N','D',' ')}, /* Zande */
{"zom", HB_TAG('Q','I','N',' ')}, /* Zou -> Chin */
{"zqe", HB_TAG('Z','H','A',' ')}, /* Qiubei Zhuang -> Zhuang */
{"zsm", HB_TAG('M','L','Y',' ')}, /* Standard Malay -> Malay */
{"zu", HB_TAG('Z','U','L',' ')}, /* Zulu */
{"zum", HB_TAG('L','R','C',' ')}, /* Kumzari -> Luri */
{"zyb", HB_TAG('Z','H','A',' ')}, /* Yongbei Zhuang -> Zhuang */
{"zyg", HB_TAG('Z','H','A',' ')}, /* Yang Zhuang -> Zhuang */
{"zyj", HB_TAG('Z','H','A',' ')}, /* Youjiang Zhuang -> Zhuang */
{"zyn", HB_TAG('Z','H','A',' ')}, /* Yongnan Zhuang -> Zhuang */
/*{"zza", HB_TAG('Z','Z','A',' ')},*/ /* Zazaki [macrolanguage] */
{"zzj", HB_TAG('Z','H','A',' ')}, /* Zuojiang Zhuang -> Zhuang */
};
/**
* hb_ot_tags_from_complex_language:
* @lang_str: a BCP 47 language tag to convert.
* @limit: a pointer to the end of the substring of @lang_str to consider for
* conversion.
* @count: maximum number of language tags to retrieve (IN) and actual number of
* language tags retrieved (OUT). If no tags are retrieved, it is not modified.
* @tags: array of size at least @language_count to store the language tag
* results
*
* Converts a multi-subtag BCP 47 language tag to language tags.
*
* Return value: Whether any language systems were retrieved.
**/
static bool
hb_ot_tags_from_complex_language (const char *lang_str,
const char *limit,
unsigned int *count /* IN/OUT */,
hb_tag_t *tags /* OUT */)
{
if (subtag_matches (lang_str, limit, "-fonnapa"))
{
/* Undetermined; North American Phonetic Alphabet */
tags[0] = HB_TAG('A','P','P','H'); /* Phonetic transcription—Americanist conventions */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-polyton"))
{
/* Modern Greek (1453-); Polytonic Greek */
tags[0] = HB_TAG('P','G','R',' '); /* Polytonic Greek */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-provenc"))
{
/* Occitan (post 1500); Provençal */
tags[0] = HB_TAG('P','R','O',' '); /* Provençal / Old Provençal */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-fonipa"))
{
/* Undetermined; International Phonetic Alphabet */
tags[0] = HB_TAG('I','P','P','H'); /* Phonetic transcription—IPA conventions */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-geok"))
{
/* Undetermined; Khutsuri (Asomtavruli and Nuskhuri) */
tags[0] = HB_TAG('K','G','E',' '); /* Khutsuri Georgian */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-syre"))
{
/* Undetermined; Syriac (Estrangelo variant) */
tags[0] = HB_TAG('S','Y','R','E'); /* Syriac, Estrangela script-variant (equivalent to ISO 15924 'Syre') */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-syrj"))
{
/* Undetermined; Syriac (Western variant) */
tags[0] = HB_TAG('S','Y','R','J'); /* Syriac, Western script-variant (equivalent to ISO 15924 'Syrj') */
*count = 1;
return true;
}
if (subtag_matches (lang_str, limit, "-syrn"))
{
/* Undetermined; Syriac (Eastern variant) */
tags[0] = HB_TAG('S','Y','R','N'); /* Syriac, Eastern script-variant (equivalent to ISO 15924 'Syrn') */
*count = 1;
return true;
}
switch (lang_str[0])
{
case 'a':
if (0 == strcmp (&lang_str[1], "rt-lojban"))
{
/* Lojban */
tags[0] = HB_TAG('J','B','O',' '); /* Lojban */
*count = 1;
return true;
}
break;
case 'c':
if (lang_matches (&lang_str[1], "do-hant-hk"))
{
/* Min Dong Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "do-hant-mo"))
{
/* Min Dong Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "jy-hant-hk"))
{
/* Jinyu Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "jy-hant-mo"))
{
/* Jinyu Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "mn-hant-hk"))
{
/* Mandarin Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "mn-hant-mo"))
{
/* Mandarin Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "px-hant-hk"))
{
/* Pu-Xian Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "px-hant-mo"))
{
/* Pu-Xian Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zh-hant-hk"))
{
/* Huizhou Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zh-hant-mo"))
{
/* Huizhou Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zo-hant-hk"))
{
/* Min Zhong Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zo-hant-mo"))
{
/* Min Zhong Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "do-hans"))
{
/* Min Dong Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "do-hant"))
{
/* Min Dong Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "jy-hans"))
{
/* Jinyu Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "jy-hant"))
{
/* Jinyu Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "mn-hans"))
{
/* Mandarin Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "mn-hant"))
{
/* Mandarin Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "px-hans"))
{
/* Pu-Xian Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "px-hant"))
{
/* Pu-Xian Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zh-hans"))
{
/* Huizhou Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zh-hant"))
{
/* Huizhou Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zo-hans"))
{
/* Min Zhong Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "zo-hant"))
{
/* Min Zhong Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "do-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Min Dong Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "do-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Min Dong Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "do-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Min Dong Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "jy-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Jinyu Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "jy-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Jinyu Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "jy-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Jinyu Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "mn-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Mandarin Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "mn-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Mandarin Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "mn-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Mandarin Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "px-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Pu-Xian Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "px-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Pu-Xian Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "px-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Pu-Xian Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "zh-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Huizhou Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "zh-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Huizhou Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "zh-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Huizhou Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "zo-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Min Zhong Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "zo-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Min Zhong Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "zo-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Min Zhong Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
break;
case 'g':
if (lang_matches (&lang_str[1], "an-hant-hk"))
{
/* Gan Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "an-hant-mo"))
{
/* Gan Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "an-hans"))
{
/* Gan Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "an-hant"))
{
/* Gan Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "a-latg"))
{
/* Irish */
tags[0] = HB_TAG('I','R','T',' '); /* Irish Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "an-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Gan Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "an-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Gan Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "an-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Gan Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
break;
case 'h':
if (lang_matches (&lang_str[1], "ak-hant-hk"))
{
/* Hakka Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "ak-hant-mo"))
{
/* Hakka Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "sn-hant-hk"))
{
/* Xiang Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "sn-hant-mo"))
{
/* Xiang Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "ak-hans"))
{
/* Hakka Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "ak-hant"))
{
/* Hakka Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "sn-hans"))
{
/* Xiang Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "sn-hant"))
{
/* Xiang Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "ak-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Hakka Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "ak-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Hakka Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "ak-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Hakka Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "sn-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Xiang Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "sn-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Xiang Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "sn-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Xiang Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
break;
case 'i':
if (0 == strcmp (&lang_str[1], "-navajo"))
{
/* Navajo */
unsigned int i;
hb_tag_t possible_tags[] = {
HB_TAG('N','A','V',' '), /* Navajo */
HB_TAG('A','T','H',' '), /* Athapaskan */
};
for (i = 0; i < 2 && i < *count; i++)
tags[i] = possible_tags[i];
*count = i;
return true;
}
if (0 == strcmp (&lang_str[1], "-hak"))
{
/* Hakka */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (0 == strcmp (&lang_str[1], "-lux"))
{
/* Luxembourgish */
tags[0] = HB_TAG('L','T','Z',' '); /* Luxembourgish */
*count = 1;
return true;
}
break;
case 'l':
if (lang_matches (&lang_str[1], "zh-hans"))
{
/* Literary Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
break;
case 'm':
if (lang_matches (&lang_str[1], "np-hant-hk"))
{
/* Min Bei Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "np-hant-mo"))
{
/* Min Bei Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "np-hans"))
{
/* Min Bei Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "np-hant"))
{
/* Min Bei Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "np-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Min Bei Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "np-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Min Bei Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "np-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Min Bei Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
break;
case 'n':
if (lang_matches (&lang_str[1], "an-hant-hk"))
{
/* Min Nan Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "an-hant-mo"))
{
/* Min Nan Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "an-hans"))
{
/* Min Nan Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "an-hant"))
{
/* Min Nan Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "an-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Min Nan Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "an-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Min Nan Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "an-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Min Nan Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strcmp (&lang_str[1], "o-bok"))
{
/* Norwegian Bokmal */
tags[0] = HB_TAG('N','O','R',' '); /* Norwegian */
*count = 1;
return true;
}
if (0 == strcmp (&lang_str[1], "o-nyn"))
{
/* Norwegian Nynorsk */
tags[0] = HB_TAG('N','Y','N',' '); /* Norwegian Nynorsk (Nynorsk, Norwegian) */
*count = 1;
return true;
}
break;
case 'r':
if (0 == strncmp (&lang_str[1], "o-", 2)
&& subtag_matches (lang_str, limit, "-md"))
{
/* Romanian; Moldova */
tags[0] = HB_TAG('M','O','L',' '); /* Moldavian */
*count = 1;
return true;
}
break;
case 'w':
if (lang_matches (&lang_str[1], "uu-hant-hk"))
{
/* Wu Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "uu-hant-mo"))
{
/* Wu Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "uu-hans"))
{
/* Wu Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "uu-hant"))
{
/* Wu Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "uu-", 3)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Wu Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "uu-", 3)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Wu Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "uu-", 3)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Wu Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
break;
case 'y':
if (lang_matches (&lang_str[1], "ue-hans"))
{
/* Yue Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
break;
case 'z':
if (lang_matches (&lang_str[1], "h-hant-hk"))
{
/* Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "h-hant-mo"))
{
/* Chinese */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strcmp (&lang_str[1], "h-min-nan"))
{
/* Minnan, Hokkien, Amoy, Taiwanese, Southern Min, Southern Fujian, Hoklo, Southern Fukien, Ho-lo */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "h-hans"))
{
/* Chinese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (lang_matches (&lang_str[1], "h-hant"))
{
/* Chinese */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
if (0 == strcmp (&lang_str[1], "h-min"))
{
/* Min, Fuzhou, Hokkien, Amoy, or Taiwanese */
tags[0] = HB_TAG('Z','H','S',' '); /* Chinese Simplified */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "h-", 2)
&& subtag_matches (lang_str, limit, "-hk"))
{
/* Chinese; Hong Kong */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "h-", 2)
&& subtag_matches (lang_str, limit, "-mo"))
{
/* Chinese; Macao */
tags[0] = HB_TAG('Z','H','H',' '); /* Chinese, Hong Kong SAR */
*count = 1;
return true;
}
if (0 == strncmp (&lang_str[1], "h-", 2)
&& subtag_matches (lang_str, limit, "-tw"))
{
/* Chinese; Taiwan, Province of China */
tags[0] = HB_TAG('Z','H','T',' '); /* Chinese Traditional */
*count = 1;
return true;
}
break;
}
return false;
}
/**
* hb_ot_ambiguous_tag_to_language
* @tag: A language tag.
*
* Converts @tag to a BCP 47 language tag if it is ambiguous (it corresponds to
* many language tags) and the best tag is not the alphabetically first, or if
* the best tag consists of multiple subtags, or if the best tag does not appear
* in #ot_languages.
*
* Return value: The #hb_language_t corresponding to the BCP 47 language tag,
* or #HB_LANGUAGE_INVALID if @tag is not ambiguous.
**/
static hb_language_t
hb_ot_ambiguous_tag_to_language (hb_tag_t tag)
{
switch (tag)
{
case HB_TAG('A','L','T',' '): /* Altai */
return hb_language_from_string ("alt", -1); /* Southern Altai */
case HB_TAG('A','P','P','H'): /* Phonetic transcription—Americanist conventions */
return hb_language_from_string ("und-fonnapa", -1); /* Undetermined; North American Phonetic Alphabet */
case HB_TAG('A','R','A',' '): /* Arabic */
return hb_language_from_string ("ar", -1); /* Arabic */
case HB_TAG('A','R','K',' '): /* Rakhine */
return hb_language_from_string ("rki", -1); /* Rakhine */
case HB_TAG('A','T','H',' '): /* Athapaskan */
return hb_language_from_string ("ath", -1); /* Athapascan */
case HB_TAG('B','I','K',' '): /* Bikol */
return hb_language_from_string ("bik", -1); /* Bikol */
case HB_TAG('C','P','P',' '): /* Creoles */
return hb_language_from_string ("crp", -1); /* Creoles and pidgins */
case HB_TAG('C','R','R',' '): /* Carrier */
return hb_language_from_string ("crx", -1); /* Carrier */
case HB_TAG('D','N','K',' '): /* Dinka */
return hb_language_from_string ("din", -1); /* Dinka */
case HB_TAG('D','R','I',' '): /* Dari */
return hb_language_from_string ("prs", -1); /* Dari */
case HB_TAG('D','Z','N',' '): /* Dzongkha */
return hb_language_from_string ("dz", -1); /* Dzongkha */
case HB_TAG('E','T','I',' '): /* Estonian */
return hb_language_from_string ("et", -1); /* Estonian */
case HB_TAG('G','O','N',' '): /* Gondi */
return hb_language_from_string ("gon", -1); /* Gondi */
case HB_TAG('H','M','N',' '): /* Hmong */
return hb_language_from_string ("hmn", -1); /* Hmong */
case HB_TAG('H','N','D',' '): /* Hindko */
return hb_language_from_string ("hnd", -1); /* Southern Hindko */
case HB_TAG('I','J','O',' '): /* Ijo */
return hb_language_from_string ("ijo", -1); /* Ijo */
case HB_TAG('I','N','U',' '): /* Inuktitut */
return hb_language_from_string ("iu", -1); /* Inuktitut */
case HB_TAG('I','P','K',' '): /* Inupiat */
return hb_language_from_string ("ik", -1); /* Inupiaq */
case HB_TAG('I','P','P','H'): /* Phonetic transcription—IPA conventions */
return hb_language_from_string ("und-fonipa", -1); /* Undetermined; International Phonetic Alphabet */
case HB_TAG('I','R','T',' '): /* Irish Traditional */
return hb_language_from_string ("ga-Latg", -1); /* Irish; Latin (Gaelic variant) */
case HB_TAG('J','I','I',' '): /* Yiddish */
return hb_language_from_string ("yi", -1); /* Yiddish */
case HB_TAG('K','A','L',' '): /* Kalenjin */
return hb_language_from_string ("kln", -1); /* Kalenjin */
case HB_TAG('K','G','E',' '): /* Khutsuri Georgian */
return hb_language_from_string ("und-Geok", -1); /* Undetermined; Khutsuri (Asomtavruli and Nuskhuri) */
case HB_TAG('K','N','R',' '): /* Kanuri */
return hb_language_from_string ("kr", -1); /* Kanuri */
case HB_TAG('K','O','K',' '): /* Konkani */
return hb_language_from_string ("kok", -1); /* Konkani */
case HB_TAG('K','U','R',' '): /* Kurdish */
return hb_language_from_string ("ku", -1); /* Kurdish */
case HB_TAG('L','U','H',' '): /* Luyia */
return hb_language_from_string ("luy", -1); /* Luyia */
case HB_TAG('L','V','I',' '): /* Latvian */
return hb_language_from_string ("lv", -1); /* Latvian */
case HB_TAG('M','A','W',' '): /* Marwari */
return hb_language_from_string ("mwr", -1); /* Marwari */
case HB_TAG('M','L','G',' '): /* Malagasy */
return hb_language_from_string ("mg", -1); /* Malagasy */
case HB_TAG('M','L','Y',' '): /* Malay */
return hb_language_from_string ("ms", -1); /* Malay */
case HB_TAG('M','N','G',' '): /* Mongolian */
return hb_language_from_string ("mn", -1); /* Mongolian */
case HB_TAG('M','O','L',' '): /* Moldavian */
return hb_language_from_string ("ro-MD", -1); /* Romanian; Moldova */
case HB_TAG('N','E','P',' '): /* Nepali */
return hb_language_from_string ("ne", -1); /* Nepali */
case HB_TAG('N','I','S',' '): /* Nisi */
return hb_language_from_string ("njz", -1); /* Nyishi */
case HB_TAG('N','O','R',' '): /* Norwegian */
return hb_language_from_string ("no", -1); /* Norwegian */
case HB_TAG('O','J','B',' '): /* Ojibway */
return hb_language_from_string ("oj", -1); /* Ojibwa */
case HB_TAG('O','R','O',' '): /* Oromo */
return hb_language_from_string ("om", -1); /* Oromo */
case HB_TAG('P','A','S',' '): /* Pashto */
return hb_language_from_string ("ps", -1); /* Pashto */
case HB_TAG('P','G','R',' '): /* Polytonic Greek */
return hb_language_from_string ("el-polyton", -1); /* Modern Greek (1453-); Polytonic Greek */
case HB_TAG('P','R','O',' '): /* Provençal / Old Provençal */
return hb_language_from_string ("pro", -1); /* Old Provençal (to 1500) */
case HB_TAG('Q','U','H',' '): /* Quechua (Bolivia) */
return hb_language_from_string ("quh", -1); /* South Bolivian Quechua */
case HB_TAG('Q','V','I',' '): /* Quechua (Ecuador) */
return hb_language_from_string ("qvi", -1); /* Imbabura Highland Quichua */
case HB_TAG('Q','W','H',' '): /* Quechua (Peru) */
return hb_language_from_string ("qwh", -1); /* Huaylas Ancash Quechua */
case HB_TAG('R','A','J',' '): /* Rajasthani */
return hb_language_from_string ("raj", -1); /* Rajasthani */
case HB_TAG('R','O','Y',' '): /* Romany */
return hb_language_from_string ("rom", -1); /* Romany */
case HB_TAG('S','Q','I',' '): /* Albanian */
return hb_language_from_string ("sq", -1); /* Albanian */
case HB_TAG('S','Y','R',' '): /* Syriac */
return hb_language_from_string ("syr", -1); /* Syriac */
case HB_TAG('S','Y','R','E'): /* Syriac, Estrangela script-variant (equivalent to ISO 15924 'Syre') */
return hb_language_from_string ("und-Syre", -1); /* Undetermined; Syriac (Estrangelo variant) */
case HB_TAG('S','Y','R','J'): /* Syriac, Western script-variant (equivalent to ISO 15924 'Syrj') */
return hb_language_from_string ("und-Syrj", -1); /* Undetermined; Syriac (Western variant) */
case HB_TAG('S','Y','R','N'): /* Syriac, Eastern script-variant (equivalent to ISO 15924 'Syrn') */
return hb_language_from_string ("und-Syrn", -1); /* Undetermined; Syriac (Eastern variant) */
case HB_TAG('T','M','H',' '): /* Tamashek */
return hb_language_from_string ("tmh", -1); /* Tamashek */
case HB_TAG('T','N','E',' '): /* Tundra Nenets */
return hb_language_from_string ("yrk", -1); /* Nenets */
case HB_TAG('Z','H','H',' '): /* Chinese, Hong Kong SAR */
return hb_language_from_string ("zh-HK", -1); /* Chinese; Hong Kong */
case HB_TAG('Z','H','S',' '): /* Chinese Simplified */
return hb_language_from_string ("zh-Hans", -1); /* Chinese; Han (Simplified variant) */
case HB_TAG('Z','H','T',' '): /* Chinese Traditional */
return hb_language_from_string ("zh-Hant", -1); /* Chinese; Han (Traditional variant) */
default:
return HB_LANGUAGE_INVALID;
}
}
#endif /* HB_OT_TAG_TABLE_HH */
/* == End of generated table == */
| [
"[email protected]"
] | |
74cd5c1704a00cdfd39035539172e9aedac5003a | de832c497474fd4196bfe9a11eaee3c527f8d35a | /Unrest-iOS/SlideShow.cpp | 89d1924122e17460e711be129a56782fd3d2d50a | [
"MIT"
] | permissive | q4a/unrest | 779be2f39c0933f83871b00e7b6519d8ceba8201 | d89f20e95fbcdef37a47ab1454b2479522a0e43f | refs/heads/master | 2023-03-17T19:51:51.251457 | 2020-08-04T05:41:35 | 2020-08-04T05:41:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | cpp | #include "stdafx.h"
#include "SlideShow.h"
namespace pyrodactyl
{
namespace ui
{
SlideShow gHelpScreen;
}
}
using namespace pyrodactyl::ui;
using namespace pyrodactyl::image;
using namespace pyrodactyl::input;
void SlideShow::Load(rapidxml::xml_node<char> *node)
{
if (NodeValid(node))
{
if (NodeValid("pos", node))
pos.Load(node->first_node("pos"));
if (NodeValid("bg", node))
bg.Load(node->first_node("bg"));
if (NodeValid("prev", node))
{
prev.Load(node->first_node("prev"));
prev.hotkey.Set(IU_PREV);
}
if (NodeValid("next", node))
{
next.Load(node->first_node("next"));
next.hotkey.Set(IU_NEXT);
}
path.clear();
for (auto n = node->first_node("slide"); n != NULL; n = n->next_sibling("slide"))
{
std::string p;
LoadStr(p, "path", n);
path.push_back(p);
}
index = 0;
LoadBool(usekeyboard, "keyboard", node, false);
}
}
void SlideShow::Draw()
{
bg.Draw();
img.Draw(pos.x, pos.y);
if (index > 0)
prev.Draw();
if (index < path.size() - 1)
next.Draw();
}
void SlideShow::HandleEvents(const SDL_Event &Event)
{
using namespace pyrodactyl::input;
if (index > 0)
if (prev.HandleEvents(Event) == BUAC_LCLICK || (usekeyboard && gInput.Equals(IU_LEFT, Event) == SDL_PRESSED))
{
index--;
Refresh();
}
if (index < path.size() - 1)
if (next.HandleEvents(Event) == BUAC_LCLICK || (usekeyboard && gInput.Equals(IU_RIGHT, Event) == SDL_PRESSED))
{
index++;
Refresh();
}
}
void SlideShow::Refresh()
{
img.Delete();
if (index >= 0 && index < path.size())
img.Load(path.at(index));
}
void SlideShow::SetUI()
{
pos.SetUI();
bg.SetUI();
prev.SetUI();
next.SetUI();
} | [
"[email protected]"
] | |
e66ebb47cadff40315f68ac1a0dc084ac3569dd5 | c983a7d121aab6765033b92a05b902f6dc210c5b | /src/scheduling/powerawarebackfilling.h | cb4b365b58e9283e115d7f48d02bc9c69f1b5869 | [] | no_license | AlvioSim/kentosim | d77ba87a1f6d3effe8790a30124ca8e0471f9955 | faf73a743438052d5d429af30119b8a4f8d5f66f | refs/heads/master | 2016-09-02T04:09:23.509625 | 2015-01-08T13:55:26 | 2015-01-08T13:55:26 | 28,967,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | h | #ifndef SIMULATORPOWERAWAREBACKFILLING_H
#define SIMULATORPOWERAWAREBACKFILLING_H
#include <scheduling/easyschedulingpolicy.h>
#include <scheduling/virtualanalogicalrtable.h>
namespace Simulator {
/**
* @author Francesc Guim,C6-E201,93 401 16 50, <[email protected]>*/
/**
* This function implements the EASYSchedulingPolicy , but takes into account the collisions between the jobs when they are allocated.
* @see For more information see the virtualanalogicalrtable class.
*/
class PowerAwareBackfilling : public EASYSchedulingPolicy{
public:
PowerAwareBackfilling();
PowerAwareBackfilling(ArchitectureConfiguration* theValue,Log* log,double globaltime,Backfilling_variant_t backfillingType);
virtual ~PowerAwareBackfilling();
/* iherited functions from the EASY SchedulingPolicy class - we only will modify those functions that take part in the decision
of where to submitt the job */
virtual void setJobList(map< int, Job * >* theValue); //this is redifined due to we need to set the list of jobs to the reservation table.
virtual void jobRemoveFromRT(Job* job); //this is redifined due to the job may be killed depending on the penalty of its real runtime
void setThresshold ( double theValue );
double getthresshold() const;
bool canSatisfyThresholdRestriction(Job* job,double thresshold);
void setAlternativeThreshold ( double theValue );
double getalternativeThreshold() const;
protected:
virtual AnalogicalJobAllocation* findAllocation(Job* job, double starttime,double runtime);
virtual void allocateJob(Job* job, AnalogicalJobAllocation* allocation);
virtual void releaseJobResources(Job* job); //releases the jobs consumed resources and updates the paraver stuff
void updateTerminationEvents(Job* scheduler); //this function checks that all the starts times and end simulation times for each of the jobs in the system are coherent with their penalized runtime , the events start and end are only generated by those jobs already scheduled.
void freeAllocation(AnalogicalJobAllocation* allocationForCheckingReq); //this is related memory management , free all the memory used by the allocation
double thresshold; /**< This indicates the maximum threaschold allowed when finding out the allocation with the findLessConsumeThreshold Experiment */
double alternativeThreshold; /**< Indicates the alternative threshold that can be used when the base threshold of the less consume threshold can not be satisfied.*/
};
}
#endif
| [
"[email protected]"
] | |
5d7d7492a8ed4249d212b485e7b316ba5c26303b | 2a5db4d9e51d29445f72d1ffd3f98609523b082d | /media-driver/media_driver/apogeios/src/domain/encode/avc_hme.h | f3f81be402019ded4f9fb2021ad005406cc8fec4 | [
"BSD-3-Clause",
"MIT"
] | permissive | mintaka33/media | 19f26239aee1d889860867a536024ffc137c2776 | 4ab1435ef3b3269ff9c0fa71072c3f81275a4b9d | refs/heads/master | 2021-05-11T04:01:48.314310 | 2018-02-02T03:43:36 | 2018-02-02T03:43:36 | 117,930,190 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,593 | h | /*===================== begin_copyright_notice ==================================
INTEL CONFIDENTIAL
Copyright 2017
Intel Corporation All Rights Reserved.
The source code contained or described herein and all documents related to the
source code ("Material") are owned by Intel Corporation or its suppliers or
licensors. Title to the Material remains with Intel Corporation or its suppliers
and licensors. The Material contains trade secrets and proprietary and confidential
information of Intel or its suppliers and licensors. The Material is protected by
worldwide copyright and trade secret laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded, posted,
transmitted, distributed, or disclosed in any way without Intel's prior express
written permission.
No license under any patent, copyright, trade secret or other intellectual
property right is granted to or conferred upon you by disclosure or delivery
of the Materials, either expressly, by implication, inducement, estoppel
or otherwise. Any license under such intellectual property rights must be
express and approved by Intel in writing.
======================= end_copyright_notice ==================================*/
//!
//! \file avc_hme.h
//! \brief avc hme kernel packet class definition
//! \details
//!
#pragma once
#include "common.h"
#include "packet_kernel.h"
namespace Apogeios
{
class AvcHmePacket : public KernelPacket
{
public:
AvcHmePacket();
virtual ~AvcHmePacket();
private:
};
}
| [
"[email protected]"
] | |
fb62c80970e81f724d89010423ee5469450da102 | 6ff7f8cc5b053682be9b84b3588f45c2aa6f4225 | /ThirdParty/Microsoft/Visual Studio 8/VC/PlatformSDK/Include/ocmm.h | 94308703096ad6e38ae1c5e7445cdc04fb44695b | [
"MIT"
] | permissive | webdev1001/dotnetinstaller | da72f9b763c7ccf0c9cfcefe5e4716b36063981c | f9b4acfb175432975720be80bccc9b2ff3cf2e88 | refs/heads/master | 2020-07-13T11:13:07.691761 | 2015-09-09T06:28:13 | 2015-09-09T06:28:13 | 44,548,252 | 2 | 0 | null | 2015-10-19T16:28:09 | 2015-10-19T16:28:09 | null | UTF-8 | C++ | false | false | 28,716 | h |
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 6.00.0366 */
/* Compiler settings for ocmm.idl:
Oicf, W1, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 440
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __ocmm_h__
#define __ocmm_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __ITimerService_FWD_DEFINED__
#define __ITimerService_FWD_DEFINED__
typedef interface ITimerService ITimerService;
#endif /* __ITimerService_FWD_DEFINED__ */
#ifndef __ITimer_FWD_DEFINED__
#define __ITimer_FWD_DEFINED__
typedef interface ITimer ITimer;
#endif /* __ITimer_FWD_DEFINED__ */
#ifndef __ITimerSink_FWD_DEFINED__
#define __ITimerSink_FWD_DEFINED__
typedef interface ITimerSink ITimerSink;
#endif /* __ITimerSink_FWD_DEFINED__ */
#ifndef __IMapMIMEToCLSID_FWD_DEFINED__
#define __IMapMIMEToCLSID_FWD_DEFINED__
typedef interface IMapMIMEToCLSID IMapMIMEToCLSID;
#endif /* __IMapMIMEToCLSID_FWD_DEFINED__ */
#ifndef __IImageDecodeFilter_FWD_DEFINED__
#define __IImageDecodeFilter_FWD_DEFINED__
typedef interface IImageDecodeFilter IImageDecodeFilter;
#endif /* __IImageDecodeFilter_FWD_DEFINED__ */
#ifndef __IImageDecodeEventSink_FWD_DEFINED__
#define __IImageDecodeEventSink_FWD_DEFINED__
typedef interface IImageDecodeEventSink IImageDecodeEventSink;
#endif /* __IImageDecodeEventSink_FWD_DEFINED__ */
/* header files for imported files */
#include "oaidl.h"
#include "oleidl.h"
#ifdef __cplusplus
extern "C"{
#endif
void * __RPC_USER MIDL_user_allocate(size_t);
void __RPC_USER MIDL_user_free( void * );
/* interface __MIDL_itf_ocmm_0000 */
/* [local] */
#define SURFACE_LOCK_EXCLUSIVE 0x01
#define SURFACE_LOCK_ALLOW_DISCARD 0x02
#define SURFACE_LOCK_WAIT 0x04
#define E_SURFACE_NOSURFACE 0x8000C000L
#define E_SURFACE_UNKNOWN_FORMAT 0x8000C001L
#define E_SURFACE_NOTMYPOINTER 0x8000C002L
#define E_SURFACE_DISCARDED 0x8000C003L
#define E_SURFACE_NODC 0x8000C004L
#define E_SURFACE_NOTMYDC 0x8000C005L
#define S_SURFACE_DISCARDED 0x0000C003L
typedef GUID BFID;
#ifndef RGBQUAD_DEFINED
#define RGBQUAD_DEFINED
typedef struct tagRGBQUAD RGBQUAD;
#endif
EXTERN_C const GUID BFID_MONOCHROME;
EXTERN_C const GUID BFID_RGB_4;
EXTERN_C const GUID BFID_RGB_8;
EXTERN_C const GUID BFID_RGB_555;
EXTERN_C const GUID BFID_RGB_565;
EXTERN_C const GUID BFID_RGB_24;
EXTERN_C const GUID BFID_RGB_32;
EXTERN_C const GUID BFID_RGBA_32;
EXTERN_C const GUID BFID_GRAY_8;
EXTERN_C const GUID BFID_GRAY_16;
#define SID_SDirectDraw3 IID_IDirectDraw3
#define COLOR_NO_TRANSPARENT 0xFFFFFFFF
#define IMGDECODE_EVENT_PROGRESS 0x01
#define IMGDECODE_EVENT_PALETTE 0x02
#define IMGDECODE_EVENT_BEGINBITS 0x04
#define IMGDECODE_EVENT_BITSCOMPLETE 0x08
#define IMGDECODE_EVENT_USEDDRAW 0x10
#define IMGDECODE_HINT_TOPDOWN 0x01
#define IMGDECODE_HINT_BOTTOMUP 0x02
#define IMGDECODE_HINT_FULLWIDTH 0x04
#define MAPMIME_DEFAULT 0
#define MAPMIME_CLSID 1
#define MAPMIME_DISABLE 2
#define MAPMIME_DEFAULT_ALWAYS 3
#define BFID_INDEXED_RGB_8 BFID_RGB_8
#define BFID_INDEXED_RGB_4 BFID_RGB_4
#define BFID_INDEXED_RGB_1 BFID_MONOCHROME
EXTERN_C const GUID CLSID_IImageDecodeFilter;
EXTERN_C const GUID NAMEDTIMER_DRAW;
extern RPC_IF_HANDLE __MIDL_itf_ocmm_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_ocmm_0000_v0_0_s_ifspec;
#ifndef __ITimerService_INTERFACE_DEFINED__
#define __ITimerService_INTERFACE_DEFINED__
/* interface ITimerService */
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITimerService;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("3050f35f-98b5-11cf-bb82-00aa00bdce0b")
ITimerService : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE CreateTimer(
/* [in] */ ITimer *pReferenceTimer,
/* [out] */ ITimer **ppNewTimer) = 0;
virtual HRESULT STDMETHODCALLTYPE GetNamedTimer(
/* [in] */ REFGUID rguidName,
/* [out] */ ITimer **ppTimer) = 0;
virtual HRESULT STDMETHODCALLTYPE SetNamedTimerReference(
/* [in] */ REFGUID rguidName,
/* [in] */ ITimer *pReferenceTimer) = 0;
};
#else /* C style interface */
typedef struct ITimerServiceVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ITimerService * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ITimerService * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ITimerService * This);
HRESULT ( STDMETHODCALLTYPE *CreateTimer )(
ITimerService * This,
/* [in] */ ITimer *pReferenceTimer,
/* [out] */ ITimer **ppNewTimer);
HRESULT ( STDMETHODCALLTYPE *GetNamedTimer )(
ITimerService * This,
/* [in] */ REFGUID rguidName,
/* [out] */ ITimer **ppTimer);
HRESULT ( STDMETHODCALLTYPE *SetNamedTimerReference )(
ITimerService * This,
/* [in] */ REFGUID rguidName,
/* [in] */ ITimer *pReferenceTimer);
END_INTERFACE
} ITimerServiceVtbl;
interface ITimerService
{
CONST_VTBL struct ITimerServiceVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITimerService_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITimerService_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITimerService_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITimerService_CreateTimer(This,pReferenceTimer,ppNewTimer) \
(This)->lpVtbl -> CreateTimer(This,pReferenceTimer,ppNewTimer)
#define ITimerService_GetNamedTimer(This,rguidName,ppTimer) \
(This)->lpVtbl -> GetNamedTimer(This,rguidName,ppTimer)
#define ITimerService_SetNamedTimerReference(This,rguidName,pReferenceTimer) \
(This)->lpVtbl -> SetNamedTimerReference(This,rguidName,pReferenceTimer)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ITimerService_CreateTimer_Proxy(
ITimerService * This,
/* [in] */ ITimer *pReferenceTimer,
/* [out] */ ITimer **ppNewTimer);
void __RPC_STUB ITimerService_CreateTimer_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITimerService_GetNamedTimer_Proxy(
ITimerService * This,
/* [in] */ REFGUID rguidName,
/* [out] */ ITimer **ppTimer);
void __RPC_STUB ITimerService_GetNamedTimer_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITimerService_SetNamedTimerReference_Proxy(
ITimerService * This,
/* [in] */ REFGUID rguidName,
/* [in] */ ITimer *pReferenceTimer);
void __RPC_STUB ITimerService_SetNamedTimerReference_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITimerService_INTERFACE_DEFINED__ */
#ifndef __ITimer_INTERFACE_DEFINED__
#define __ITimer_INTERFACE_DEFINED__
/* interface ITimer */
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITimer;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("3050f360-98b5-11cf-bb82-00aa00bdce0b")
ITimer : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Advise(
/* [in] */ VARIANT vtimeMin,
/* [in] */ VARIANT vtimeMax,
/* [in] */ VARIANT vtimeInterval,
/* [in] */ DWORD dwFlags,
/* [in] */ ITimerSink *pTimerSink,
/* [out] */ DWORD *pdwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE Unadvise(
/* [in] */ DWORD dwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE Freeze(
/* [in] */ BOOL fFreeze) = 0;
virtual HRESULT STDMETHODCALLTYPE GetTime(
/* [out] */ VARIANT *pvtime) = 0;
};
#else /* C style interface */
typedef struct ITimerVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ITimer * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ITimer * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ITimer * This);
HRESULT ( STDMETHODCALLTYPE *Advise )(
ITimer * This,
/* [in] */ VARIANT vtimeMin,
/* [in] */ VARIANT vtimeMax,
/* [in] */ VARIANT vtimeInterval,
/* [in] */ DWORD dwFlags,
/* [in] */ ITimerSink *pTimerSink,
/* [out] */ DWORD *pdwCookie);
HRESULT ( STDMETHODCALLTYPE *Unadvise )(
ITimer * This,
/* [in] */ DWORD dwCookie);
HRESULT ( STDMETHODCALLTYPE *Freeze )(
ITimer * This,
/* [in] */ BOOL fFreeze);
HRESULT ( STDMETHODCALLTYPE *GetTime )(
ITimer * This,
/* [out] */ VARIANT *pvtime);
END_INTERFACE
} ITimerVtbl;
interface ITimer
{
CONST_VTBL struct ITimerVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITimer_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITimer_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITimer_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITimer_Advise(This,vtimeMin,vtimeMax,vtimeInterval,dwFlags,pTimerSink,pdwCookie) \
(This)->lpVtbl -> Advise(This,vtimeMin,vtimeMax,vtimeInterval,dwFlags,pTimerSink,pdwCookie)
#define ITimer_Unadvise(This,dwCookie) \
(This)->lpVtbl -> Unadvise(This,dwCookie)
#define ITimer_Freeze(This,fFreeze) \
(This)->lpVtbl -> Freeze(This,fFreeze)
#define ITimer_GetTime(This,pvtime) \
(This)->lpVtbl -> GetTime(This,pvtime)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ITimer_Advise_Proxy(
ITimer * This,
/* [in] */ VARIANT vtimeMin,
/* [in] */ VARIANT vtimeMax,
/* [in] */ VARIANT vtimeInterval,
/* [in] */ DWORD dwFlags,
/* [in] */ ITimerSink *pTimerSink,
/* [out] */ DWORD *pdwCookie);
void __RPC_STUB ITimer_Advise_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITimer_Unadvise_Proxy(
ITimer * This,
/* [in] */ DWORD dwCookie);
void __RPC_STUB ITimer_Unadvise_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITimer_Freeze_Proxy(
ITimer * This,
/* [in] */ BOOL fFreeze);
void __RPC_STUB ITimer_Freeze_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITimer_GetTime_Proxy(
ITimer * This,
/* [out] */ VARIANT *pvtime);
void __RPC_STUB ITimer_GetTime_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITimer_INTERFACE_DEFINED__ */
#ifndef __ITimerSink_INTERFACE_DEFINED__
#define __ITimerSink_INTERFACE_DEFINED__
/* interface ITimerSink */
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITimerSink;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("3050f361-98b5-11cf-bb82-00aa00bdce0b")
ITimerSink : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE OnTimer(
/* [in] */ VARIANT vtimeAdvise) = 0;
};
#else /* C style interface */
typedef struct ITimerSinkVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ITimerSink * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ITimerSink * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ITimerSink * This);
HRESULT ( STDMETHODCALLTYPE *OnTimer )(
ITimerSink * This,
/* [in] */ VARIANT vtimeAdvise);
END_INTERFACE
} ITimerSinkVtbl;
interface ITimerSink
{
CONST_VTBL struct ITimerSinkVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITimerSink_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITimerSink_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITimerSink_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITimerSink_OnTimer(This,vtimeAdvise) \
(This)->lpVtbl -> OnTimer(This,vtimeAdvise)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ITimerSink_OnTimer_Proxy(
ITimerSink * This,
/* [in] */ VARIANT vtimeAdvise);
void __RPC_STUB ITimerSink_OnTimer_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITimerSink_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_ocmm_0142 */
/* [local] */
#define SID_STimerService IID_ITimerService
extern RPC_IF_HANDLE __MIDL_itf_ocmm_0142_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_ocmm_0142_v0_0_s_ifspec;
#ifndef __IMapMIMEToCLSID_INTERFACE_DEFINED__
#define __IMapMIMEToCLSID_INTERFACE_DEFINED__
/* interface IMapMIMEToCLSID */
/* [unique][uuid][object] */
EXTERN_C const IID IID_IMapMIMEToCLSID;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("D9E89500-30FA-11d0-B724-00AA006C1A01")
IMapMIMEToCLSID : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE EnableDefaultMappings(
BOOL bEnable) = 0;
virtual HRESULT STDMETHODCALLTYPE MapMIMEToCLSID(
LPCOLESTR pszMIMEType,
CLSID *pCLSID) = 0;
virtual HRESULT STDMETHODCALLTYPE SetMapping(
LPCOLESTR pszMIMEType,
DWORD dwMapMode,
REFCLSID clsid) = 0;
};
#else /* C style interface */
typedef struct IMapMIMEToCLSIDVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
IMapMIMEToCLSID * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
IMapMIMEToCLSID * This);
ULONG ( STDMETHODCALLTYPE *Release )(
IMapMIMEToCLSID * This);
HRESULT ( STDMETHODCALLTYPE *EnableDefaultMappings )(
IMapMIMEToCLSID * This,
BOOL bEnable);
HRESULT ( STDMETHODCALLTYPE *MapMIMEToCLSID )(
IMapMIMEToCLSID * This,
LPCOLESTR pszMIMEType,
CLSID *pCLSID);
HRESULT ( STDMETHODCALLTYPE *SetMapping )(
IMapMIMEToCLSID * This,
LPCOLESTR pszMIMEType,
DWORD dwMapMode,
REFCLSID clsid);
END_INTERFACE
} IMapMIMEToCLSIDVtbl;
interface IMapMIMEToCLSID
{
CONST_VTBL struct IMapMIMEToCLSIDVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IMapMIMEToCLSID_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IMapMIMEToCLSID_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IMapMIMEToCLSID_Release(This) \
(This)->lpVtbl -> Release(This)
#define IMapMIMEToCLSID_EnableDefaultMappings(This,bEnable) \
(This)->lpVtbl -> EnableDefaultMappings(This,bEnable)
#define IMapMIMEToCLSID_MapMIMEToCLSID(This,pszMIMEType,pCLSID) \
(This)->lpVtbl -> MapMIMEToCLSID(This,pszMIMEType,pCLSID)
#define IMapMIMEToCLSID_SetMapping(This,pszMIMEType,dwMapMode,clsid) \
(This)->lpVtbl -> SetMapping(This,pszMIMEType,dwMapMode,clsid)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IMapMIMEToCLSID_EnableDefaultMappings_Proxy(
IMapMIMEToCLSID * This,
BOOL bEnable);
void __RPC_STUB IMapMIMEToCLSID_EnableDefaultMappings_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMapMIMEToCLSID_MapMIMEToCLSID_Proxy(
IMapMIMEToCLSID * This,
LPCOLESTR pszMIMEType,
CLSID *pCLSID);
void __RPC_STUB IMapMIMEToCLSID_MapMIMEToCLSID_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMapMIMEToCLSID_SetMapping_Proxy(
IMapMIMEToCLSID * This,
LPCOLESTR pszMIMEType,
DWORD dwMapMode,
REFCLSID clsid);
void __RPC_STUB IMapMIMEToCLSID_SetMapping_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IMapMIMEToCLSID_INTERFACE_DEFINED__ */
#ifndef __IImageDecodeFilter_INTERFACE_DEFINED__
#define __IImageDecodeFilter_INTERFACE_DEFINED__
/* interface IImageDecodeFilter */
/* [unique][uuid][object] */
EXTERN_C const IID IID_IImageDecodeFilter;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("A3CCEDF3-2DE2-11D0-86F4-00A0C913F750")
IImageDecodeFilter : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Initialize(
IImageDecodeEventSink *pEventSink) = 0;
virtual HRESULT STDMETHODCALLTYPE Process(
IStream *pStream) = 0;
virtual HRESULT STDMETHODCALLTYPE Terminate(
HRESULT hrStatus) = 0;
};
#else /* C style interface */
typedef struct IImageDecodeFilterVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
IImageDecodeFilter * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
IImageDecodeFilter * This);
ULONG ( STDMETHODCALLTYPE *Release )(
IImageDecodeFilter * This);
HRESULT ( STDMETHODCALLTYPE *Initialize )(
IImageDecodeFilter * This,
IImageDecodeEventSink *pEventSink);
HRESULT ( STDMETHODCALLTYPE *Process )(
IImageDecodeFilter * This,
IStream *pStream);
HRESULT ( STDMETHODCALLTYPE *Terminate )(
IImageDecodeFilter * This,
HRESULT hrStatus);
END_INTERFACE
} IImageDecodeFilterVtbl;
interface IImageDecodeFilter
{
CONST_VTBL struct IImageDecodeFilterVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IImageDecodeFilter_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IImageDecodeFilter_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IImageDecodeFilter_Release(This) \
(This)->lpVtbl -> Release(This)
#define IImageDecodeFilter_Initialize(This,pEventSink) \
(This)->lpVtbl -> Initialize(This,pEventSink)
#define IImageDecodeFilter_Process(This,pStream) \
(This)->lpVtbl -> Process(This,pStream)
#define IImageDecodeFilter_Terminate(This,hrStatus) \
(This)->lpVtbl -> Terminate(This,hrStatus)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IImageDecodeFilter_Initialize_Proxy(
IImageDecodeFilter * This,
IImageDecodeEventSink *pEventSink);
void __RPC_STUB IImageDecodeFilter_Initialize_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeFilter_Process_Proxy(
IImageDecodeFilter * This,
IStream *pStream);
void __RPC_STUB IImageDecodeFilter_Process_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeFilter_Terminate_Proxy(
IImageDecodeFilter * This,
HRESULT hrStatus);
void __RPC_STUB IImageDecodeFilter_Terminate_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IImageDecodeFilter_INTERFACE_DEFINED__ */
#ifndef __IImageDecodeEventSink_INTERFACE_DEFINED__
#define __IImageDecodeEventSink_INTERFACE_DEFINED__
/* interface IImageDecodeEventSink */
/* [unique][uuid][object] */
EXTERN_C const IID IID_IImageDecodeEventSink;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("BAA342A0-2DED-11d0-86F4-00A0C913F750")
IImageDecodeEventSink : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetSurface(
/* [in] */ LONG nWidth,
/* [in] */ LONG nHeight,
/* [in] */ REFGUID bfid,
/* [in] */ ULONG nPasses,
/* [in] */ DWORD dwHints,
/* [out] */ IUnknown **ppSurface) = 0;
virtual HRESULT STDMETHODCALLTYPE OnBeginDecode(
/* [out] */ DWORD *pdwEvents,
/* [out] */ ULONG *pnFormats,
/* [size_is][size_is][out] */ BFID **ppFormats) = 0;
virtual HRESULT STDMETHODCALLTYPE OnBitsComplete( void) = 0;
virtual HRESULT STDMETHODCALLTYPE OnDecodeComplete(
/* [in] */ HRESULT hrStatus) = 0;
virtual HRESULT STDMETHODCALLTYPE OnPalette( void) = 0;
virtual HRESULT STDMETHODCALLTYPE OnProgress(
/* [in] */ RECT *pBounds,
/* [in] */ BOOL bComplete) = 0;
};
#else /* C style interface */
typedef struct IImageDecodeEventSinkVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
IImageDecodeEventSink * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
IImageDecodeEventSink * This);
ULONG ( STDMETHODCALLTYPE *Release )(
IImageDecodeEventSink * This);
HRESULT ( STDMETHODCALLTYPE *GetSurface )(
IImageDecodeEventSink * This,
/* [in] */ LONG nWidth,
/* [in] */ LONG nHeight,
/* [in] */ REFGUID bfid,
/* [in] */ ULONG nPasses,
/* [in] */ DWORD dwHints,
/* [out] */ IUnknown **ppSurface);
HRESULT ( STDMETHODCALLTYPE *OnBeginDecode )(
IImageDecodeEventSink * This,
/* [out] */ DWORD *pdwEvents,
/* [out] */ ULONG *pnFormats,
/* [size_is][size_is][out] */ BFID **ppFormats);
HRESULT ( STDMETHODCALLTYPE *OnBitsComplete )(
IImageDecodeEventSink * This);
HRESULT ( STDMETHODCALLTYPE *OnDecodeComplete )(
IImageDecodeEventSink * This,
/* [in] */ HRESULT hrStatus);
HRESULT ( STDMETHODCALLTYPE *OnPalette )(
IImageDecodeEventSink * This);
HRESULT ( STDMETHODCALLTYPE *OnProgress )(
IImageDecodeEventSink * This,
/* [in] */ RECT *pBounds,
/* [in] */ BOOL bComplete);
END_INTERFACE
} IImageDecodeEventSinkVtbl;
interface IImageDecodeEventSink
{
CONST_VTBL struct IImageDecodeEventSinkVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IImageDecodeEventSink_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IImageDecodeEventSink_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IImageDecodeEventSink_Release(This) \
(This)->lpVtbl -> Release(This)
#define IImageDecodeEventSink_GetSurface(This,nWidth,nHeight,bfid,nPasses,dwHints,ppSurface) \
(This)->lpVtbl -> GetSurface(This,nWidth,nHeight,bfid,nPasses,dwHints,ppSurface)
#define IImageDecodeEventSink_OnBeginDecode(This,pdwEvents,pnFormats,ppFormats) \
(This)->lpVtbl -> OnBeginDecode(This,pdwEvents,pnFormats,ppFormats)
#define IImageDecodeEventSink_OnBitsComplete(This) \
(This)->lpVtbl -> OnBitsComplete(This)
#define IImageDecodeEventSink_OnDecodeComplete(This,hrStatus) \
(This)->lpVtbl -> OnDecodeComplete(This,hrStatus)
#define IImageDecodeEventSink_OnPalette(This) \
(This)->lpVtbl -> OnPalette(This)
#define IImageDecodeEventSink_OnProgress(This,pBounds,bComplete) \
(This)->lpVtbl -> OnProgress(This,pBounds,bComplete)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IImageDecodeEventSink_GetSurface_Proxy(
IImageDecodeEventSink * This,
/* [in] */ LONG nWidth,
/* [in] */ LONG nHeight,
/* [in] */ REFGUID bfid,
/* [in] */ ULONG nPasses,
/* [in] */ DWORD dwHints,
/* [out] */ IUnknown **ppSurface);
void __RPC_STUB IImageDecodeEventSink_GetSurface_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeEventSink_OnBeginDecode_Proxy(
IImageDecodeEventSink * This,
/* [out] */ DWORD *pdwEvents,
/* [out] */ ULONG *pnFormats,
/* [size_is][size_is][out] */ BFID **ppFormats);
void __RPC_STUB IImageDecodeEventSink_OnBeginDecode_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeEventSink_OnBitsComplete_Proxy(
IImageDecodeEventSink * This);
void __RPC_STUB IImageDecodeEventSink_OnBitsComplete_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeEventSink_OnDecodeComplete_Proxy(
IImageDecodeEventSink * This,
/* [in] */ HRESULT hrStatus);
void __RPC_STUB IImageDecodeEventSink_OnDecodeComplete_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeEventSink_OnPalette_Proxy(
IImageDecodeEventSink * This);
void __RPC_STUB IImageDecodeEventSink_OnPalette_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IImageDecodeEventSink_OnProgress_Proxy(
IImageDecodeEventSink * This,
/* [in] */ RECT *pBounds,
/* [in] */ BOOL bComplete);
void __RPC_STUB IImageDecodeEventSink_OnProgress_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IImageDecodeEventSink_INTERFACE_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
unsigned long __RPC_USER VARIANT_UserSize( unsigned long *, unsigned long , VARIANT * );
unsigned char * __RPC_USER VARIANT_UserMarshal( unsigned long *, unsigned char *, VARIANT * );
unsigned char * __RPC_USER VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * );
void __RPC_USER VARIANT_UserFree( unsigned long *, VARIANT * );
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| [
"[email protected]"
] | |
ac3ae7ca80e4160770ff722342e029a89ed5105b | f713b9c4a2fe3e59b95372a6b1563ca01f3f9acf | /components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.cc | f836172cf98bb1b1b3edd6c7a75e70c322edc593 | [
"BSD-3-Clause"
] | permissive | chenjunpu/chromium | 1888afb75726771a07c68c75003733db0e0f8967 | 812abd15e33ab7dd8179bca0cf783d03d361cb9a | refs/heads/master | 2023-02-24T03:53:47.066144 | 2018-07-26T02:18:36 | 2018-07-26T02:18:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,002 | cc | // 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 "components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.h"
#include <utility>
#include "base/logging.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/sync/model_impl/client_tag_based_model_type_processor.h"
namespace autofill {
namespace {
// Address to this variable used as the user data key.
static int kAutofillWalletMetadataSyncBridgeUserDataKey = 0;
} // namespace
// static
void AutofillWalletMetadataSyncBridge::CreateForWebDataServiceAndBackend(
const std::string& app_locale,
AutofillWebDataBackend* web_data_backend,
AutofillWebDataService* web_data_service) {
web_data_service->GetDBUserData()->SetUserData(
&kAutofillWalletMetadataSyncBridgeUserDataKey,
std::make_unique<AutofillWalletMetadataSyncBridge>(
std::make_unique<syncer::ClientTagBasedModelTypeProcessor>(
syncer::AUTOFILL_WALLET_DATA,
/*dump_stack=*/base::RepeatingClosure())));
}
// static
syncer::ModelTypeSyncBridge*
AutofillWalletMetadataSyncBridge::FromWebDataService(
AutofillWebDataService* web_data_service) {
return static_cast<AutofillWalletMetadataSyncBridge*>(
web_data_service->GetDBUserData()->GetUserData(
&kAutofillWalletMetadataSyncBridgeUserDataKey));
}
AutofillWalletMetadataSyncBridge::AutofillWalletMetadataSyncBridge(
std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor)
: ModelTypeSyncBridge(std::move(change_processor)) {}
AutofillWalletMetadataSyncBridge::~AutofillWalletMetadataSyncBridge() {}
std::unique_ptr<syncer::MetadataChangeList>
AutofillWalletMetadataSyncBridge::CreateMetadataChangeList() {
NOTIMPLEMENTED();
return nullptr;
}
base::Optional<syncer::ModelError>
AutofillWalletMetadataSyncBridge::MergeSyncData(
std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
syncer::EntityChangeList entity_data) {
NOTIMPLEMENTED();
return base::nullopt;
}
base::Optional<syncer::ModelError>
AutofillWalletMetadataSyncBridge::ApplySyncChanges(
std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
syncer::EntityChangeList entity_data) {
NOTIMPLEMENTED();
return base::nullopt;
}
void AutofillWalletMetadataSyncBridge::GetData(StorageKeyList storage_keys,
DataCallback callback) {
NOTIMPLEMENTED();
}
void AutofillWalletMetadataSyncBridge::GetAllDataForDebugging(
DataCallback callback) {
NOTIMPLEMENTED();
}
std::string AutofillWalletMetadataSyncBridge::GetClientTag(
const syncer::EntityData& entity_data) {
NOTIMPLEMENTED();
return "";
}
std::string AutofillWalletMetadataSyncBridge::GetStorageKey(
const syncer::EntityData& entity_data) {
NOTIMPLEMENTED();
return "";
}
} // namespace autofill
| [
"[email protected]"
] | |
0b87266c5437274ec4747b26935307c8e7193bd3 | 6ed471f36e5188f77dc61cca24daa41496a6d4a0 | /SDK/WeapMachinedPistol_Scoped_parameters.h | 2c81c7fa94afcd1a70e554f775571ac7a8ca7e74 | [] | no_license | zH4x-SDK/zARKSotF-SDK | 77bfaf9b4b9b6a41951ee18db88f826dd720c367 | 714730f4bb79c07d065181caf360d168761223f6 | refs/heads/main | 2023-07-16T22:33:15.140456 | 2021-08-27T13:40:06 | 2021-08-27T13:40:06 | 400,521,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | h | #pragma once
#include "../SDK.h"
// Name: ARKSotF, Version: 178.8.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function WeapMachinedPistol_Scoped.WeapMachinedPistol_Scoped_C.UserConstructionScript
struct AWeapMachinedPistol_Scoped_C_UserConstructionScript_Params
{
};
// Function WeapMachinedPistol_Scoped.WeapMachinedPistol_Scoped_C.ExecuteUbergraph_WeapMachinedPistol_Scoped
struct AWeapMachinedPistol_Scoped_C_ExecuteUbergraph_WeapMachinedPistol_Scoped_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
ac2b79e8765de93d564743822ce1b535b1c12d8b | dc191b30e3b833a5a2eff5526877ed9a6a816af7 | /common/object/position/Vector3.h | 4aead46ea5d9119f344086eb3975138fba8cee03 | [] | no_license | Ellie42/SillyGame | 5008cd4507a64a731e8191bcf679344c430ca33f | 5d9bb4c3a0e204cbffb9a7c277af8c2422e6b0ac | refs/heads/master | 2021-05-14T07:19:14.113288 | 2018-01-10T08:54:38 | 2018-01-10T08:54:38 | 116,260,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,254 | h | //
// Created by Sophie Gauthier on 03/01/2018.
//
#ifndef SILLYGAME2_VECTOR3_H
#define SILLYGAME2_VECTOR3_H
#include <glm/glm.hpp>
template<typename T = float>
class Vector3
{
public:
T x = (T) 0;
T y = (T) 0;
T z = (T) 0;
Vector3() = default;
Vector3(T t_x, T t_y, T t_z)
{
x = t_x;
y = t_y;
z = t_z;
}
operator glm::tvec3<T>()
{
return glm::tvec3<T>(x, y, z);
};
Vector3<T>& operator*(double t_num)
{
x = x * t_num;
y = y * t_num;
z = z * t_num;
return *this;
}
Vector3<T>& operator+=(const Vector3<>& t_vec)
{
x = x + t_vec.x;
y = y + t_vec.y;
z = z + t_vec.z;
return *this;
}
Vector3<T>& operator-=(const Vector3<>& t_vec)
{
x = x - t_vec.x;
y = y - t_vec.y;
z = z - t_vec.z;
return *this;
}
Vector3<T> operator-(){
x = -x;
y = -y;
z = -z;
return *this;
}
};
inline Vector3<> operator+(Vector3<> lhs, const Vector3<>& rhs)
{
lhs += rhs;
return lhs;
}
inline Vector3<> operator-(Vector3<> lhs, const Vector3<>& rhs)
{
lhs -= rhs;
return lhs;
}
#endif //SILLYGAME2_VECTOR3_H
| [
"[email protected]"
] | |
4bbb4067b1dec39f5e930940841ff9b0a377408a | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.007/C4H8CHO4-2 | 014ce0fae3cb65a9fef5f00790775918c009ce23 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.007";
object C4H8CHO4-2;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 2.52085e-31;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
ac3b451c4ceeed1cbbb90b94d3386f4a0b05c10e | daf8abfcbbbff0dfe0425608af291f4be0a6bea7 | /chromium/src/content/browser/frame_host/render_widget_host_view_guest.cc | 3c4e008d1562ae01f15939aba65cc74b9e91de76 | [
"BSD-3-Clause"
] | permissive | mvines/cef | 68389e7b0cfe0caf5cd61c80055b01382d34000d | a3faf18e55dc258ce7783c39c7ed22d7cecd4e74 | refs/heads/master | 2022-10-24T17:06:15.960761 | 2017-01-13T19:01:58 | 2017-01-13T19:06:55 | 78,868,621 | 0 | 1 | null | 2022-10-22T09:12:09 | 2017-01-13T17:05:59 | null | UTF-8 | C++ | false | false | 25,884 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/frame_host/render_widget_host_view_guest.h"
#include <utility>
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "build/build_config.h"
#include "cc/surfaces/surface.h"
#include "cc/surfaces/surface_factory.h"
#include "cc/surfaces/surface_manager.h"
#include "cc/surfaces/surface_sequence.h"
#include "content/browser/browser_plugin/browser_plugin_guest.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/renderer_host/input/input_router.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
#include "content/common/browser_plugin/browser_plugin_messages.h"
#include "content/common/content_switches_internal.h"
#include "content/common/frame_messages.h"
#include "content/common/input/web_touch_event_traits.h"
#include "content/common/site_isolation_policy.h"
#include "content/common/view_messages.h"
#include "content/public/common/content_switches.h"
#include "gpu/ipc/common/gpu_messages.h"
#include "skia/ext/platform_canvas.h"
#if defined(OS_MACOSX)
#import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
#endif
#if defined(USE_AURA)
#include "content/browser/renderer_host/ui_events_helper.h"
#endif
namespace content {
namespace {
class ScopedInputScaleDisabler {
public:
ScopedInputScaleDisabler(RenderWidgetHostImpl* host, float scale_factor)
: host_(host), scale_factor_(scale_factor) {
if (IsUseZoomForDSFEnabled())
host_->input_router()->SetDeviceScaleFactor(1.0f);
}
~ScopedInputScaleDisabler() {
if (IsUseZoomForDSFEnabled())
host_->input_router()->SetDeviceScaleFactor(scale_factor_);
}
private:
RenderWidgetHostImpl* host_;
float scale_factor_;
DISALLOW_COPY_AND_ASSIGN(ScopedInputScaleDisabler);
};
} // namespace
// static
RenderWidgetHostViewGuest* RenderWidgetHostViewGuest::Create(
RenderWidgetHost* widget,
BrowserPluginGuest* guest,
base::WeakPtr<RenderWidgetHostViewBase> platform_view) {
RenderWidgetHostViewGuest* view =
new RenderWidgetHostViewGuest(widget, guest, platform_view);
view->Init();
return view;
}
RenderWidgetHostViewGuest::RenderWidgetHostViewGuest(
RenderWidgetHost* widget_host,
BrowserPluginGuest* guest,
base::WeakPtr<RenderWidgetHostViewBase> platform_view)
: RenderWidgetHostViewChildFrame(widget_host),
// |guest| is NULL during test.
guest_(guest ? guest->AsWeakPtr() : base::WeakPtr<BrowserPluginGuest>()),
platform_view_(platform_view) {
gfx::NativeView view = GetNativeView();
if (view)
UpdateScreenInfo(view);
}
RenderWidgetHostViewGuest::~RenderWidgetHostViewGuest() {}
bool RenderWidgetHostViewGuest::OnMessageReceivedFromEmbedder(
const IPC::Message& message,
RenderWidgetHostImpl* embedder) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(RenderWidgetHostViewGuest, message,
embedder)
IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_HandleInputEvent,
OnHandleInputEvent)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void RenderWidgetHostViewGuest::Show() {
// If the WebContents associated with us showed an interstitial page in the
// beginning, the teardown path might call WasShown() while |host_| is in
// the process of destruction. Avoid calling WasShown below in this case.
// TODO(lazyboy): We shouldn't be showing interstitial pages in guests in the
// first place: http://crbug.com/273089.
//
// |guest_| is NULL during test.
if ((guest_ && guest_->is_in_destruction()) || !host_->is_hidden())
return;
// Make sure the size of this view matches the size of the WebContentsView.
// The two sizes may fall out of sync if we switch RenderWidgetHostViews,
// resize, and then switch page, as is the case with interstitial pages.
// NOTE: |guest_| is NULL in unit tests.
if (guest_) {
SetSize(guest_->web_contents()->GetViewBounds().size());
// Since we were last shown, our renderer may have had a different surface
// set (e.g. showing an interstitial), so we resend our current surface to
// the renderer.
if (local_frame_id_.is_valid()) {
cc::SurfaceSequence sequence =
cc::SurfaceSequence(frame_sink_id_, next_surface_sequence_++);
cc::SurfaceId surface_id(frame_sink_id_, local_frame_id_);
GetSurfaceManager()
->GetSurfaceForId(surface_id)
->AddDestructionDependency(sequence);
guest_->SetChildFrameSurface(surface_id, current_surface_size_,
current_surface_scale_factor_, sequence);
}
}
host_->WasShown(ui::LatencyInfo());
}
void RenderWidgetHostViewGuest::Hide() {
// |guest_| is NULL during test.
if ((guest_ && guest_->is_in_destruction()) || host_->is_hidden())
return;
host_->WasHidden();
}
void RenderWidgetHostViewGuest::SetSize(const gfx::Size& size) {
size_ = size;
host_->WasResized();
}
void RenderWidgetHostViewGuest::SetBounds(const gfx::Rect& rect) {
SetSize(rect.size());
}
void RenderWidgetHostViewGuest::Focus() {
// InterstitialPageImpl focuses views directly, so we place focus logic here.
// InterstitialPages are not WebContents, and so BrowserPluginGuest does not
// have direct access to the interstitial page's RenderWidgetHost.
if (guest_)
guest_->SetFocus(host_, true, blink::WebFocusTypeNone);
}
bool RenderWidgetHostViewGuest::HasFocus() const {
if (!guest_)
return false;
return guest_->focused();
}
#if defined(USE_AURA)
void RenderWidgetHostViewGuest::ProcessAckedTouchEvent(
const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
// TODO(tdresser): Since all ProcessAckedTouchEvent() uses is the event id,
// don't pass the full event object here. https://crbug.com/550581.
GetOwnerRenderWidgetHostView()->ProcessAckedTouchEvent(touch, ack_result);
}
#endif
void RenderWidgetHostViewGuest::ProcessMouseEvent(
const blink::WebMouseEvent& event,
const ui::LatencyInfo& latency) {
if (event.type == blink::WebInputEvent::MouseDown) {
DCHECK(guest_->GetOwnerRenderWidgetHostView());
RenderWidgetHost* embedder =
guest_->GetOwnerRenderWidgetHostView()->GetRenderWidgetHost();
if (!embedder->GetView()->HasFocus())
embedder->GetView()->Focus();
// With direct routing, the embedder would not know to focus the guest on
// click. Sends a synthetic event for the focusing side effect.
// TODO(wjmaclean): When we remove BrowserPlugin, delete this code.
// http://crbug.com/533069
MaybeSendSyntheticTapGesture(
blink::WebFloatPoint(event.x, event.y),
blink::WebFloatPoint(event.globalX, event.globalY));
}
host_->ForwardMouseEventWithLatencyInfo(event, latency);
}
void RenderWidgetHostViewGuest::ProcessTouchEvent(
const blink::WebTouchEvent& event,
const ui::LatencyInfo& latency) {
if (event.type == blink::WebInputEvent::TouchStart) {
DCHECK(guest_->GetOwnerRenderWidgetHostView());
RenderWidgetHost* embedder =
guest_->GetOwnerRenderWidgetHostView()->GetRenderWidgetHost();
if (!embedder->GetView()->HasFocus())
embedder->GetView()->Focus();
// With direct routing, the embedder would not know to focus the guest on
// touch. Sends a synthetic event for the focusing side effect.
// TODO(wjmaclean): When we remove BrowserPlugin, delete this code.
// http://crbug.com/533069
MaybeSendSyntheticTapGesture(event.touches[0].position,
event.touches[0].screenPosition);
}
host_->ForwardTouchEventWithLatencyInfo(event, latency);
}
gfx::Rect RenderWidgetHostViewGuest::GetViewBounds() const {
if (!guest_)
return gfx::Rect();
RenderWidgetHostViewBase* rwhv = GetOwnerRenderWidgetHostView();
gfx::Rect embedder_bounds;
if (rwhv)
embedder_bounds = rwhv->GetViewBounds();
return gfx::Rect(
guest_->GetScreenCoordinates(embedder_bounds.origin()), size_);
}
gfx::Rect RenderWidgetHostViewGuest::GetBoundsInRootWindow() {
return GetViewBounds();
}
void RenderWidgetHostViewGuest::RenderProcessGone(
base::TerminationStatus status,
int error_code) {
// The |platform_view_| gets destroyed before we get here if this view
// is for an InterstitialPage.
if (platform_view_)
platform_view_->RenderProcessGone(status, error_code);
RenderWidgetHostViewChildFrame::RenderProcessGone(status, error_code);
}
void RenderWidgetHostViewGuest::Destroy() {
RenderWidgetHostViewChildFrame::Destroy();
if (platform_view_) // The platform view might have been destroyed already.
platform_view_->Destroy();
}
gfx::Size RenderWidgetHostViewGuest::GetPhysicalBackingSize() const {
RenderWidgetHostViewBase* rwhv = GetOwnerRenderWidgetHostView();
if (rwhv)
return rwhv->GetPhysicalBackingSize();
// We obtain the reference to native view from the owner RenderWidgetHostView.
// If the guest is embedded inside a cross-process frame, it is possible to
// reach here after the frame is detached in which case there will be no owner
// view.
return gfx::Size();
}
base::string16 RenderWidgetHostViewGuest::GetSelectedText() {
return platform_view_->GetSelectedText();
}
void RenderWidgetHostViewGuest::SetNeedsBeginFrames(
bool needs_begin_frames) {
if (platform_view_)
platform_view_->SetNeedsBeginFrames(needs_begin_frames);
}
void RenderWidgetHostViewGuest::SetTooltipText(
const base::string16& tooltip_text) {
if (guest_)
guest_->SetTooltipText(tooltip_text);
}
void RenderWidgetHostViewGuest::OnSwapCompositorFrame(
uint32_t compositor_frame_sink_id,
cc::CompositorFrame frame) {
TRACE_EVENT0("content", "RenderWidgetHostViewGuest::OnSwapCompositorFrame");
last_scroll_offset_ = frame.metadata.root_scroll_offset;
cc::RenderPass* root_pass =
frame.delegated_frame_data->render_pass_list.back().get();
gfx::Size frame_size = root_pass->output_rect.size();
float scale_factor = frame.metadata.device_scale_factor;
// Check whether we need to recreate the cc::Surface, which means the child
// frame renderer has changed its output surface, or size, or scale factor.
if (compositor_frame_sink_id != last_compositor_frame_sink_id_ ||
frame_size != current_surface_size_ ||
scale_factor != current_surface_scale_factor_ ||
(guest_ && guest_->has_attached_since_surface_set())) {
ClearCompositorSurfaceIfNecessary();
// If the renderer changed its frame sink, reset the surface factory to
// avoid returning stale resources.
if (compositor_frame_sink_id != last_compositor_frame_sink_id_)
surface_factory_->Reset();
last_compositor_frame_sink_id_ = compositor_frame_sink_id;
current_surface_size_ = frame_size;
current_surface_scale_factor_ = scale_factor;
}
if (!local_frame_id_.is_valid()) {
local_frame_id_ = id_allocator_->GenerateId();
surface_factory_->Create(local_frame_id_);
cc::SurfaceSequence sequence =
cc::SurfaceSequence(frame_sink_id_, next_surface_sequence_++);
// The renderer process will satisfy this dependency when it creates a
// SurfaceLayer.
cc::SurfaceManager* manager = GetSurfaceManager();
cc::SurfaceId surface_id(frame_sink_id_, local_frame_id_);
manager->GetSurfaceForId(surface_id)->AddDestructionDependency(sequence);
// TODO(wjmaclean): I'm not sure what it means to create a surface id
// without setting it on the child, though since we will in this case be
// guaranteed to call ClearCompositorSurfaceIfNecessary() below, I suspect
// skipping SetChildFrameSurface() here is irrelevant.
if (guest_ && !guest_->is_in_destruction()) {
guest_->SetChildFrameSurface(surface_id, frame_size, scale_factor,
sequence);
}
}
cc::SurfaceFactory::DrawCallback ack_callback = base::Bind(
&RenderWidgetHostViewChildFrame::SurfaceDrawn,
RenderWidgetHostViewChildFrame::AsWeakPtr(), compositor_frame_sink_id);
ack_pending_count_++;
// If this value grows very large, something is going wrong.
DCHECK(ack_pending_count_ < 1000);
surface_factory_->SubmitCompositorFrame(local_frame_id_, std::move(frame),
ack_callback);
ProcessFrameSwappedCallbacks();
// If after detaching we are sent a frame, we should finish processing it, and
// then we should clear the surface so that we are not holding resources we
// no longer need.
if (!guest_ || !guest_->attached())
ClearCompositorSurfaceIfNecessary();
}
bool RenderWidgetHostViewGuest::OnMessageReceived(const IPC::Message& msg) {
if (!platform_view_) {
// In theory, we can get here if there's a delay between Destroy()
// being called and when our destructor is invoked.
return false;
}
return platform_view_->OnMessageReceived(msg);
}
void RenderWidgetHostViewGuest::InitAsChild(
gfx::NativeView parent_view) {
platform_view_->InitAsChild(parent_view);
}
void RenderWidgetHostViewGuest::InitAsPopup(
RenderWidgetHostView* parent_host_view, const gfx::Rect& bounds) {
// This should never get called.
NOTREACHED();
}
void RenderWidgetHostViewGuest::InitAsFullscreen(
RenderWidgetHostView* reference_host_view) {
// This should never get called.
NOTREACHED();
}
gfx::NativeView RenderWidgetHostViewGuest::GetNativeView() const {
if (!guest_)
return gfx::NativeView();
RenderWidgetHostView* rwhv = guest_->GetOwnerRenderWidgetHostView();
if (!rwhv)
return gfx::NativeView();
return rwhv->GetNativeView();
}
gfx::NativeViewAccessible RenderWidgetHostViewGuest::GetNativeViewAccessible() {
if (!guest_)
return gfx::NativeViewAccessible();
RenderWidgetHostView* rwhv = guest_->GetOwnerRenderWidgetHostView();
if (!rwhv)
return gfx::NativeViewAccessible();
return rwhv->GetNativeViewAccessible();
}
void RenderWidgetHostViewGuest::UpdateCursor(const WebCursor& cursor) {
// InterstitialPages are not WebContents so we cannot intercept
// ViewHostMsg_SetCursor for interstitial pages in BrowserPluginGuest.
// All guest RenderViewHosts have RenderWidgetHostViewGuests however,
// and so we will always hit this code path.
if (!guest_)
return;
if (SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
RenderWidgetHostViewBase* rwhvb = GetOwnerRenderWidgetHostView();
if (rwhvb)
rwhvb->UpdateCursor(cursor);
} else {
guest_->SendMessageToEmbedder(base::MakeUnique<BrowserPluginMsg_SetCursor>(
guest_->browser_plugin_instance_id(), cursor));
}
}
void RenderWidgetHostViewGuest::SetIsLoading(bool is_loading) {
platform_view_->SetIsLoading(is_loading);
}
void RenderWidgetHostViewGuest::TextInputStateChanged(
const TextInputState& params) {
if (!guest_)
return;
RenderWidgetHostViewBase* rwhv = GetOwnerRenderWidgetHostView();
if (!rwhv)
return;
// Forward the information to embedding RWHV.
rwhv->TextInputStateChanged(params);
}
void RenderWidgetHostViewGuest::ImeCancelComposition() {
if (!guest_)
return;
RenderWidgetHostViewBase* rwhv = GetOwnerRenderWidgetHostView();
if (!rwhv)
return;
// Forward the information to embedding RWHV.
rwhv->ImeCancelComposition();
}
#if defined(OS_MACOSX) || defined(USE_AURA)
void RenderWidgetHostViewGuest::ImeCompositionRangeChanged(
const gfx::Range& range,
const std::vector<gfx::Rect>& character_bounds) {
if (!guest_)
return;
RenderWidgetHostViewBase* rwhv = GetOwnerRenderWidgetHostView();
if (!rwhv)
return;
std::vector<gfx::Rect> guest_character_bounds;
for (size_t i = 0; i < character_bounds.size(); ++i) {
guest_character_bounds.push_back(gfx::Rect(
guest_->GetScreenCoordinates(character_bounds[i].origin()),
character_bounds[i].size()));
}
// Forward the information to embedding RWHV.
rwhv->ImeCompositionRangeChanged(range, guest_character_bounds);
}
#endif
void RenderWidgetHostViewGuest::SelectionChanged(const base::string16& text,
size_t offset,
const gfx::Range& range) {
platform_view_->SelectionChanged(text, offset, range);
}
void RenderWidgetHostViewGuest::SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params& params) {
if (!guest_)
return;
RenderWidgetHostViewBase* rwhv = GetOwnerRenderWidgetHostView();
if (!rwhv)
return;
ViewHostMsg_SelectionBounds_Params guest_params(params);
guest_params.anchor_rect.set_origin(
guest_->GetScreenCoordinates(params.anchor_rect.origin()));
guest_params.focus_rect.set_origin(
guest_->GetScreenCoordinates(params.focus_rect.origin()));
rwhv->SelectionBoundsChanged(guest_params);
}
bool RenderWidgetHostViewGuest::LockMouse() {
return platform_view_->LockMouse();
}
void RenderWidgetHostViewGuest::UnlockMouse() {
return platform_view_->UnlockMouse();
}
#if defined(OS_MACOSX)
void RenderWidgetHostViewGuest::SetActive(bool active) {
platform_view_->SetActive(active);
}
void RenderWidgetHostViewGuest::ShowDefinitionForSelection() {
if (!guest_)
return;
gfx::Point origin;
gfx::Rect guest_bounds = GetViewBounds();
RenderWidgetHostView* rwhv = guest_->GetOwnerRenderWidgetHostView();
gfx::Rect embedder_bounds;
if (rwhv)
embedder_bounds = rwhv->GetViewBounds();
gfx::Vector2d guest_offset = gfx::Vector2d(
// Horizontal offset of guest from embedder.
guest_bounds.x() - embedder_bounds.x(),
// Vertical offset from guest's top to embedder's bottom edge.
embedder_bounds.bottom() - guest_bounds.y());
RenderWidgetHostViewMacDictionaryHelper helper(platform_view_.get());
helper.SetTargetView(rwhv);
helper.set_offset(guest_offset);
helper.ShowDefinitionForSelection();
}
bool RenderWidgetHostViewGuest::SupportsSpeech() const {
return platform_view_->SupportsSpeech();
}
void RenderWidgetHostViewGuest::SpeakSelection() {
platform_view_->SpeakSelection();
}
bool RenderWidgetHostViewGuest::IsSpeaking() const {
return platform_view_->IsSpeaking();
}
void RenderWidgetHostViewGuest::StopSpeaking() {
platform_view_->StopSpeaking();
}
#endif // defined(OS_MACOSX)
void RenderWidgetHostViewGuest::LockCompositingSurface() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGuest::UnlockCompositingSurface() {
NOTIMPLEMENTED();
}
RenderWidgetHostViewBase*
RenderWidgetHostViewGuest::GetOwnerRenderWidgetHostView() const {
return static_cast<RenderWidgetHostViewBase*>(
guest_->GetOwnerRenderWidgetHostView());
}
// TODO(wjmaclean): When we remove BrowserPlugin, delete this code.
// http://crbug.com/533069
void RenderWidgetHostViewGuest::MaybeSendSyntheticTapGesture(
const blink::WebFloatPoint& position,
const blink::WebFloatPoint& screenPosition) const {
if (!HasFocus()) {
// We need to a account for the position of the guest view within the
// embedder, as well as the fact that the embedder's host will add its
// offset in screen coordinates before sending the event (with the latter
// component just serving to confuse the renderer, hence why it should be
// removed).
gfx::Vector2d offset =
GetViewBounds().origin() -
GetOwnerRenderWidgetHostView()->GetBoundsInRootWindow().origin();
blink::WebGestureEvent gesture_tap_event;
gesture_tap_event.sourceDevice = blink::WebGestureDeviceTouchscreen;
gesture_tap_event.type = blink::WebGestureEvent::GestureTapDown;
gesture_tap_event.x = position.x + offset.x();
gesture_tap_event.y = position.y + offset.y();
gesture_tap_event.globalX = screenPosition.x;
gesture_tap_event.globalY = screenPosition.y;
GetOwnerRenderWidgetHostView()->ProcessGestureEvent(
gesture_tap_event, ui::LatencyInfo(ui::SourceEventType::TOUCH));
gesture_tap_event.type = blink::WebGestureEvent::GestureTapCancel;
GetOwnerRenderWidgetHostView()->ProcessGestureEvent(
gesture_tap_event, ui::LatencyInfo(ui::SourceEventType::TOUCH));
}
}
void RenderWidgetHostViewGuest::WheelEventAck(
const blink::WebMouseWheelEvent& event,
InputEventAckState ack_result) {
if (ack_result == INPUT_EVENT_ACK_STATE_NOT_CONSUMED ||
ack_result == INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS) {
guest_->ResendEventToEmbedder(event);
}
}
void RenderWidgetHostViewGuest::GestureEventAck(
const blink::WebGestureEvent& event,
InputEventAckState ack_result) {
bool not_consumed = ack_result == INPUT_EVENT_ACK_STATE_NOT_CONSUMED ||
ack_result == INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
// GestureScrollBegin/End are always consumed by the guest, so we only
// forward GestureScrollUpdate.
if (event.type == blink::WebInputEvent::GestureScrollUpdate && not_consumed)
guest_->ResendEventToEmbedder(event);
}
bool RenderWidgetHostViewGuest::IsRenderWidgetHostViewGuest() {
return true;
}
void RenderWidgetHostViewGuest::OnHandleInputEvent(
RenderWidgetHostImpl* embedder,
int browser_plugin_instance_id,
const blink::WebInputEvent* event) {
// WebMouseWheelEvents go into a queue, and may not be forwarded to the
// renderer until after this method goes out of scope. Therefore we need to
// explicitly remove the additional device scale factor from the coordinates
// before allowing the event to be queued.
if (IsUseZoomForDSFEnabled() &&
event->type == blink::WebInputEvent::MouseWheel) {
blink::WebMouseWheelEvent rescaled_event =
*static_cast<const blink::WebMouseWheelEvent*>(event);
rescaled_event.x /= current_device_scale_factor();
rescaled_event.y /= current_device_scale_factor();
rescaled_event.deltaX /= current_device_scale_factor();
rescaled_event.deltaY /= current_device_scale_factor();
rescaled_event.wheelTicksX /= current_device_scale_factor();
rescaled_event.wheelTicksY /= current_device_scale_factor();
ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
host_->ForwardWheelEventWithLatencyInfo(rescaled_event, latency_info);
return;
}
ScopedInputScaleDisabler disable(host_, current_device_scale_factor());
if (blink::WebInputEvent::isMouseEventType(event->type)) {
// The mouse events for BrowserPlugin are modified by all
// the CSS transforms applied on the <object> and embedder. As a result of
// this, the coordinates passed on to the guest renderer are potentially
// incorrect to determine the position of the context menu(they are not the
// actual X, Y of the window). As a hack, we report the last location of a
// right mouse up to the BrowserPluginGuest to inform it of the next
// potential location for context menu (BUG=470087).
// TODO(ekaramad): Find a better and more fundamental solution. Could the
// ContextMenuParams be based on global X, Y?
const blink::WebMouseEvent& mouse_event =
static_cast<const blink::WebMouseEvent&>(*event);
// A MouseDown on the ButtonRight could suggest a ContextMenu.
if (guest_ && mouse_event.type == blink::WebInputEvent::MouseDown &&
mouse_event.button == blink::WebPointerProperties::Button::Right)
guest_->SetContextMenuPosition(
gfx::Point(mouse_event.globalX - GetViewBounds().x(),
mouse_event.globalY - GetViewBounds().y()));
host_->ForwardMouseEvent(mouse_event);
return;
}
if (event->type == blink::WebInputEvent::MouseWheel) {
ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
host_->ForwardWheelEventWithLatencyInfo(
*static_cast<const blink::WebMouseWheelEvent*>(event), latency_info);
return;
}
if (blink::WebInputEvent::isKeyboardEventType(event->type)) {
if (!embedder->GetLastKeyboardEvent())
return;
NativeWebKeyboardEvent keyboard_event(*embedder->GetLastKeyboardEvent());
host_->ForwardKeyboardEvent(keyboard_event);
return;
}
if (blink::WebInputEvent::isTouchEventType(event->type)) {
if (event->type == blink::WebInputEvent::TouchStart &&
!embedder->GetView()->HasFocus()) {
embedder->GetView()->Focus();
}
ui::LatencyInfo latency_info(ui::SourceEventType::TOUCH);
host_->ForwardTouchEventWithLatencyInfo(
*static_cast<const blink::WebTouchEvent*>(event), latency_info);
return;
}
if (blink::WebInputEvent::isGestureEventType(event->type)) {
const blink::WebGestureEvent& gesture_event =
*static_cast<const blink::WebGestureEvent*>(event);
// We don't forward inertial GestureScrollUpdates to the guest anymore
// since it now receives GestureFlingStart and will have its own fling
// curve generating GestureScrollUpdate events for it.
// TODO(wjmaclean): Should we try to avoid creating a fling curve in the
// embedder renderer in this case? BrowserPlugin can return 'true' for
// handleInputEvent() on a GestureFlingStart, and we could use this as
// a signal to let the guest handle the fling, though we'd need to be
// sure other plugins would behave appropriately (i.e. return 'false').
if (gesture_event.type == blink::WebInputEvent::GestureScrollUpdate &&
gesture_event.data.scrollUpdate.inertialPhase ==
blink::WebGestureEvent::MomentumPhase) {
return;
}
host_->ForwardGestureEvent(gesture_event);
return;
}
}
} // namespace content
| [
"[email protected]"
] | |
aa90ac0f274c49c674d5221e71173655973b26c0 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_467_collectd-4.5.1.cpp | 0e6ac3b10ba534a4bdfb1d74c47ada72e496e5e2 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | static void serial_submit (const char *type_instance,
counter_t rx, counter_t tx)
{
value_t values[2];
value_list_t vl = VALUE_LIST_INIT;
values[0].counter = rx;
values[1].counter = tx;
vl.values = values;
vl.values_len = 2;
vl.time = time (NULL);
sstrncpy (vl.host, hostname_g, sizeof (vl.host));
sstrncpy (vl.plugin, "serial", sizeof (vl.plugin));
sstrncpy (vl.type, "serial_octets", sizeof (vl.type));
sstrncpy (vl.type_instance, type_instance,
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
} | [
"[email protected]"
] | |
b9450f33e103176b897a8d4902f6dcf19b492327 | 0d0e78c6262417fb1dff53901c6087b29fe260a0 | /kms/src/v20190118/model/ReEncryptResponse.cpp | 693bc1079f23f6dd09267f5da0a5def8ad5017a7 | [
"Apache-2.0"
] | permissive | li5ch/tencentcloud-sdk-cpp | ae35ffb0c36773fd28e1b1a58d11755682ade2ee | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | refs/heads/master | 2022-12-04T15:33:08.729850 | 2020-07-20T00:52:24 | 2020-07-20T00:52:24 | 281,135,686 | 1 | 0 | Apache-2.0 | 2020-07-20T14:14:47 | 2020-07-20T14:14:46 | null | UTF-8 | C++ | false | false | 4,712 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/kms/v20190118/model/ReEncryptResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Kms::V20190118::Model;
using namespace rapidjson;
using namespace std;
ReEncryptResponse::ReEncryptResponse() :
m_ciphertextBlobHasBeenSet(false),
m_keyIdHasBeenSet(false),
m_sourceKeyIdHasBeenSet(false),
m_reEncryptedHasBeenSet(false)
{
}
CoreInternalOutcome ReEncryptResponse::Deserialize(const string &payload)
{
Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Error("response `Response` is null or not object"));
}
Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("CiphertextBlob") && !rsp["CiphertextBlob"].IsNull())
{
if (!rsp["CiphertextBlob"].IsString())
{
return CoreInternalOutcome(Error("response `CiphertextBlob` IsString=false incorrectly").SetRequestId(requestId));
}
m_ciphertextBlob = string(rsp["CiphertextBlob"].GetString());
m_ciphertextBlobHasBeenSet = true;
}
if (rsp.HasMember("KeyId") && !rsp["KeyId"].IsNull())
{
if (!rsp["KeyId"].IsString())
{
return CoreInternalOutcome(Error("response `KeyId` IsString=false incorrectly").SetRequestId(requestId));
}
m_keyId = string(rsp["KeyId"].GetString());
m_keyIdHasBeenSet = true;
}
if (rsp.HasMember("SourceKeyId") && !rsp["SourceKeyId"].IsNull())
{
if (!rsp["SourceKeyId"].IsString())
{
return CoreInternalOutcome(Error("response `SourceKeyId` IsString=false incorrectly").SetRequestId(requestId));
}
m_sourceKeyId = string(rsp["SourceKeyId"].GetString());
m_sourceKeyIdHasBeenSet = true;
}
if (rsp.HasMember("ReEncrypted") && !rsp["ReEncrypted"].IsNull())
{
if (!rsp["ReEncrypted"].IsBool())
{
return CoreInternalOutcome(Error("response `ReEncrypted` IsBool=false incorrectly").SetRequestId(requestId));
}
m_reEncrypted = rsp["ReEncrypted"].GetBool();
m_reEncryptedHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string ReEncryptResponse::GetCiphertextBlob() const
{
return m_ciphertextBlob;
}
bool ReEncryptResponse::CiphertextBlobHasBeenSet() const
{
return m_ciphertextBlobHasBeenSet;
}
string ReEncryptResponse::GetKeyId() const
{
return m_keyId;
}
bool ReEncryptResponse::KeyIdHasBeenSet() const
{
return m_keyIdHasBeenSet;
}
string ReEncryptResponse::GetSourceKeyId() const
{
return m_sourceKeyId;
}
bool ReEncryptResponse::SourceKeyIdHasBeenSet() const
{
return m_sourceKeyIdHasBeenSet;
}
bool ReEncryptResponse::GetReEncrypted() const
{
return m_reEncrypted;
}
bool ReEncryptResponse::ReEncryptedHasBeenSet() const
{
return m_reEncryptedHasBeenSet;
}
| [
"[email protected]"
] | |
c71212a31fca43d1e38cbf73176e55658c8850ee | 6b660cb96baa003de9e18e332b048c0f1fa67ab9 | /External/SDK/BP_PromptActor_EmissaryEncounteredAIShip_OOS_parameters.h | 0562fc95d76f68386a1fa0ae1608429573fba427 | [] | no_license | zanzo420/zSoT-SDK | 1edbff62b3e12695ecf3969537a6d2631a0ff36f | 5e581eb0400061f6e5f93b3affd95001f62d4f7c | refs/heads/main | 2022-07-30T03:35:51.225374 | 2021-07-07T01:07:20 | 2021-07-07T01:07:20 | 383,634,601 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | h | #pragma once
// Name: SoT, Version: 2.2.0.2
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_PromptActor_EmissaryEncounteredAIShip_OOS.BP_PromptActor_EmissaryEncounteredAIShip_OOS_C.UserConstructionScript
struct ABP_PromptActor_EmissaryEncounteredAIShip_OOS_C_UserConstructionScript_Params
{
};
// Function BP_PromptActor_EmissaryEncounteredAIShip_OOS.BP_PromptActor_EmissaryEncounteredAIShip_OOS_C.ReceiveBeginPlay
struct ABP_PromptActor_EmissaryEncounteredAIShip_OOS_C_ReceiveBeginPlay_Params
{
};
// Function BP_PromptActor_EmissaryEncounteredAIShip_OOS.BP_PromptActor_EmissaryEncounteredAIShip_OOS_C.ReceiveEndPlay
struct ABP_PromptActor_EmissaryEncounteredAIShip_OOS_C_ReceiveEndPlay_Params
{
TEnumAsByte<Engine_EEndPlayReason> EndPlayReason; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_PromptActor_EmissaryEncounteredAIShip_OOS.BP_PromptActor_EmissaryEncounteredAIShip_OOS_C.ExecuteUbergraph_BP_PromptActor_EmissaryEncounteredAIShip_OOS
struct ABP_PromptActor_EmissaryEncounteredAIShip_OOS_C_ExecuteUbergraph_BP_PromptActor_EmissaryEncounteredAIShip_OOS_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
5ec3950617d83fddc49dbf0b3f3b2d1d2b807bcc | dbc2f341a9e9e0200f9a59e8b05a5cad0301e3ec | /script.h | a8e2ef9c4e5fdbcafbd51e1a18111a10a6007f90 | [] | no_license | JonSalazar/serialization | 3523e20abd521f2d7f36c0b88befbb76e9657db9 | e91f41505598ee37cec3cdbaa771f2f68fcd4368 | refs/heads/master | 2020-04-24T18:00:48.528153 | 2019-03-07T03:47:35 | 2019-03-07T03:47:35 | 172,166,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,917 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SCRIPT_SCRIPT_H
#define BITCOIN_SCRIPT_SCRIPT_H
#include "common.h"
#include "prevector.h"
#include "serialize.h"
#include <assert.h>
#include <climits>
#include <limits>
#include <stdexcept>
#include <stdint.h>
#include <string.h>
#include <string>
#include <vector>
// Maximum number of bytes pushable to the stack
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520;
// Maximum number of non-push operations per script
static const int MAX_OPS_PER_SCRIPT = 201;
// Maximum number of public keys per multisig
static const int MAX_PUBKEYS_PER_MULTISIG = 20;
// Maximum script length in bytes
static const int MAX_SCRIPT_SIZE = 10000;
// Maximum number of values on script interpreter stack
static const int MAX_STACK_SIZE = 1000;
// Threshold for nLockTime: below this value it is interpreted as block number,
// otherwise as UNIX timestamp.
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
template <typename T>
std::vector<unsigned char> ToByteVector(const T& in)
{
return std::vector<unsigned char>(in.begin(), in.end());
}
/** Script opcodes */
enum opcodetype
{
// push value
OP_0 = 0x00,
OP_FALSE = OP_0,
OP_PUSHDATA1 = 0x4c,
OP_PUSHDATA2 = 0x4d,
OP_PUSHDATA4 = 0x4e,
OP_1NEGATE = 0x4f,
OP_RESERVED = 0x50,
OP_1 = 0x51,
OP_TRUE=OP_1,
OP_2 = 0x52,
OP_3 = 0x53,
OP_4 = 0x54,
OP_5 = 0x55,
OP_6 = 0x56,
OP_7 = 0x57,
OP_8 = 0x58,
OP_9 = 0x59,
OP_10 = 0x5a,
OP_11 = 0x5b,
OP_12 = 0x5c,
OP_13 = 0x5d,
OP_14 = 0x5e,
OP_15 = 0x5f,
OP_16 = 0x60,
// control
OP_NOP = 0x61,
OP_VER = 0x62,
OP_IF = 0x63,
OP_NOTIF = 0x64,
OP_VERIF = 0x65,
OP_VERNOTIF = 0x66,
OP_ELSE = 0x67,
OP_ENDIF = 0x68,
OP_VERIFY = 0x69,
OP_RETURN = 0x6a,
// stack ops
OP_TOALTSTACK = 0x6b,
OP_FROMALTSTACK = 0x6c,
OP_2DROP = 0x6d,
OP_2DUP = 0x6e,
OP_3DUP = 0x6f,
OP_2OVER = 0x70,
OP_2ROT = 0x71,
OP_2SWAP = 0x72,
OP_IFDUP = 0x73,
OP_DEPTH = 0x74,
OP_DROP = 0x75,
OP_DUP = 0x76,
OP_NIP = 0x77,
OP_OVER = 0x78,
OP_PICK = 0x79,
OP_ROLL = 0x7a,
OP_ROT = 0x7b,
OP_SWAP = 0x7c,
OP_TUCK = 0x7d,
// splice ops
OP_CAT = 0x7e,
OP_SUBSTR = 0x7f,
OP_LEFT = 0x80,
OP_RIGHT = 0x81,
OP_SIZE = 0x82,
// bit logic
OP_INVERT = 0x83,
OP_AND = 0x84,
OP_OR = 0x85,
OP_XOR = 0x86,
OP_EQUAL = 0x87,
OP_EQUALVERIFY = 0x88,
OP_RESERVED1 = 0x89,
OP_RESERVED2 = 0x8a,
// numeric
OP_1ADD = 0x8b,
OP_1SUB = 0x8c,
OP_2MUL = 0x8d,
OP_2DIV = 0x8e,
OP_NEGATE = 0x8f,
OP_ABS = 0x90,
OP_NOT = 0x91,
OP_0NOTEQUAL = 0x92,
OP_ADD = 0x93,
OP_SUB = 0x94,
OP_MUL = 0x95,
OP_DIV = 0x96,
OP_MOD = 0x97,
OP_LSHIFT = 0x98,
OP_RSHIFT = 0x99,
OP_BOOLAND = 0x9a,
OP_BOOLOR = 0x9b,
OP_NUMEQUAL = 0x9c,
OP_NUMEQUALVERIFY = 0x9d,
OP_NUMNOTEQUAL = 0x9e,
OP_LESSTHAN = 0x9f,
OP_GREATERTHAN = 0xa0,
OP_LESSTHANOREQUAL = 0xa1,
OP_GREATERTHANOREQUAL = 0xa2,
OP_MIN = 0xa3,
OP_MAX = 0xa4,
OP_WITHIN = 0xa5,
// crypto
OP_RIPEMD160 = 0xa6,
OP_SHA1 = 0xa7,
OP_SHA256 = 0xa8,
OP_HASH160 = 0xa9,
OP_HASH256 = 0xaa,
OP_CODESEPARATOR = 0xab,
OP_CHECKSIG = 0xac,
OP_CHECKSIGVERIFY = 0xad,
OP_CHECKMULTISIG = 0xae,
OP_CHECKMULTISIGVERIFY = 0xaf,
// expansion
OP_NOP1 = 0xb0,
OP_CHECKLOCKTIMEVERIFY = 0xb1,
OP_NOP2 = OP_CHECKLOCKTIMEVERIFY,
OP_CHECKSEQUENCEVERIFY = 0xb2,
OP_NOP3 = OP_CHECKSEQUENCEVERIFY,
OP_NOP4 = 0xb3,
OP_NOP5 = 0xb4,
OP_NOP6 = 0xb5,
OP_NOP7 = 0xb6,
OP_NOP8 = 0xb7,
OP_NOP9 = 0xb8,
OP_NOP10 = 0xb9,
// template matching params
OP_SMALLINTEGER = 0xfa,
OP_PUBKEYS = 0xfb,
OP_PUBKEYHASH = 0xfd,
OP_PUBKEY = 0xfe,
OP_INVALIDOPCODE = 0xff,
};
// Maximum value that an opcode can be
static const unsigned int MAX_OPCODE = OP_NOP10;
const char* GetOpName(opcodetype opcode);
class scriptnum_error : public std::runtime_error
{
public:
explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
};
class CScriptNum
{
/**
* Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
* The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
* but results may overflow (and are valid as long as they are not used in a subsequent
* numeric operation). CScriptNum enforces those semantics by storing results as
* an int64 and allowing out-of-range values to be returned as a vector of bytes but
* throwing an exception if arithmetic is done or the result is interpreted as an integer.
*/
public:
explicit CScriptNum(const int64_t& n)
{
m_value = n;
}
static const size_t nDefaultMaxNumSize = 4;
explicit CScriptNum(const std::vector<unsigned char>& vch, bool fRequireMinimal,
const size_t nMaxNumSize = nDefaultMaxNumSize)
{
if (vch.size() > nMaxNumSize) {
throw scriptnum_error("script number overflow");
}
if (fRequireMinimal && vch.size() > 0) {
// Check that the number is encoded with the minimum possible
// number of bytes.
//
// If the most-significant-byte - excluding the sign bit - is zero
// then we're not minimal. Note how this test also rejects the
// negative-zero encoding, 0x80.
if ((vch.back() & 0x7f) == 0) {
// One exception: if there's more than one byte and the most
// significant bit of the second-most-significant-byte is set
// it would conflict with the sign bit. An example of this case
// is +-255, which encode to 0xff00 and 0xff80 respectively.
// (big-endian).
if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) {
throw scriptnum_error("non-minimally encoded script number");
}
}
}
m_value = set_vch(vch);
}
inline bool operator==(const int64_t& rhs) const { return m_value == rhs; }
inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; }
inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; }
inline bool operator< (const int64_t& rhs) const { return m_value < rhs; }
inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); }
inline bool operator!=(const CScriptNum& rhs) const { return operator!=(rhs.m_value); }
inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); }
inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); }
inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); }
inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); }
inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
inline CScriptNum operator&( const int64_t& rhs) const { return CScriptNum(m_value & rhs);}
inline CScriptNum operator&( const CScriptNum& rhs) const { return operator&(rhs.m_value); }
inline CScriptNum& operator&=( const CScriptNum& rhs) { return operator&=(rhs.m_value); }
inline CScriptNum operator-() const
{
assert(m_value != std::numeric_limits<int64_t>::min());
return CScriptNum(-m_value);
}
inline CScriptNum& operator=( const int64_t& rhs)
{
m_value = rhs;
return *this;
}
inline CScriptNum& operator+=( const int64_t& rhs)
{
assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
(rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
m_value += rhs;
return *this;
}
inline CScriptNum& operator-=( const int64_t& rhs)
{
assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
(rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
m_value -= rhs;
return *this;
}
inline CScriptNum& operator&=( const int64_t& rhs)
{
m_value &= rhs;
return *this;
}
int getint() const
{
if (m_value > std::numeric_limits<int>::max())
return std::numeric_limits<int>::max();
else if (m_value < std::numeric_limits<int>::min())
return std::numeric_limits<int>::min();
return m_value;
}
std::vector<unsigned char> getvch() const
{
return serialize(m_value);
}
static std::vector<unsigned char> serialize(const int64_t& value)
{
if(value == 0)
return std::vector<unsigned char>();
std::vector<unsigned char> result;
const bool neg = value < 0;
uint64_t absvalue = neg ? -value : value;
while(absvalue)
{
result.push_back(absvalue & 0xff);
absvalue >>= 8;
}
// - If the most significant byte is >= 0x80 and the value is positive, push a
// new zero-byte to make the significant byte < 0x80 again.
// - If the most significant byte is >= 0x80 and the value is negative, push a
// new 0x80 byte that will be popped off when converting to an integral.
// - If the most significant byte is < 0x80 and the value is negative, add
// 0x80 to it, since it will be subtracted and interpreted as a negative when
// converting to an integral.
if (result.back() & 0x80)
result.push_back(neg ? 0x80 : 0);
else if (neg)
result.back() |= 0x80;
return result;
}
private:
static int64_t set_vch(const std::vector<unsigned char>& vch)
{
if (vch.empty())
return 0;
int64_t result = 0;
for (size_t i = 0; i != vch.size(); ++i)
result |= static_cast<int64_t>(vch[i]) << 8*i;
// If the input vector's most significant byte is 0x80, remove it from
// the result's msb and return a negative.
if (vch.back() & 0x80)
return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
return result;
}
int64_t m_value;
};
/**
* We use a prevector for the script to reduce the considerable memory overhead
* of vectors in cases where they normally contain a small number of small elements.
* Tests in October 2015 showed use of this reduced dbcache memory usage by 23%
* and made an initial sync 13% faster.
*/
typedef prevector<28, unsigned char> CScriptBase;
bool GetScriptOp(CScriptBase::const_iterator& pc, CScriptBase::const_iterator end, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet);
/** Serialized script, used inside transaction inputs and outputs */
class CScript : public CScriptBase
{
protected:
CScript& push_int64(int64_t n)
{
if (n == -1 || (n >= 1 && n <= 16))
{
push_back(n + (OP_1 - 1));
}
else if (n == 0)
{
push_back(OP_0);
}
else
{
*this << CScriptNum::serialize(n);
}
return *this;
}
public:
CScript() { }
CScript(const_iterator pbegin, const_iterator pend) : CScriptBase(pbegin, pend) { }
CScript(std::vector<unsigned char>::const_iterator pbegin, std::vector<unsigned char>::const_iterator pend) : CScriptBase(pbegin, pend) { }
CScript(const unsigned char* pbegin, const unsigned char* pend) : CScriptBase(pbegin, pend) { }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITEAS(CScriptBase, *this);
}
CScript& operator+=(const CScript& b)
{
reserve(size() + b.size());
insert(end(), b.begin(), b.end());
return *this;
}
friend CScript operator+(const CScript& a, const CScript& b)
{
CScript ret = a;
ret += b;
return ret;
}
CScript(int64_t b) { operator<<(b); }
explicit CScript(opcodetype b) { operator<<(b); }
explicit CScript(const CScriptNum& b) { operator<<(b); }
explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
CScript& operator<<(int64_t b) { return push_int64(b); }
CScript& operator<<(opcodetype opcode)
{
if (opcode < 0 || opcode > 0xff)
throw std::runtime_error("CScript::operator<<(): invalid opcode");
insert(end(), (unsigned char)opcode);
return *this;
}
CScript& operator<<(const CScriptNum& b)
{
*this << b.getvch();
return *this;
}
CScript& operator<<(const std::vector<unsigned char>& b)
{
if (b.size() < OP_PUSHDATA1)
{
insert(end(), (unsigned char)b.size());
}
else if (b.size() <= 0xff)
{
insert(end(), OP_PUSHDATA1);
insert(end(), (unsigned char)b.size());
}
else if (b.size() <= 0xffff)
{
insert(end(), OP_PUSHDATA2);
uint8_t _data[2];
WriteLE16(_data, b.size());
insert(end(), _data, _data + sizeof(_data));
}
else
{
insert(end(), OP_PUSHDATA4);
uint8_t _data[4];
WriteLE32(_data, b.size());
insert(end(), _data, _data + sizeof(_data));
}
insert(end(), b.begin(), b.end());
return *this;
}
CScript& operator<<(const CScript& b)
{
// I'm not sure if this should push the script or concatenate scripts.
// If there's ever a use for pushing a script onto a script, delete this member fn
assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
return *this;
}
bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
{
return GetScriptOp(pc, end(), opcodeRet, &vchRet);
}
bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
{
return GetScriptOp(pc, end(), opcodeRet, nullptr);
}
/** Encode/decode small integers: */
static int DecodeOP_N(opcodetype opcode)
{
if (opcode == OP_0)
return 0;
assert(opcode >= OP_1 && opcode <= OP_16);
return (int)opcode - (int)(OP_1 - 1);
}
static opcodetype EncodeOP_N(int n)
{
assert(n >= 0 && n <= 16);
if (n == 0)
return OP_0;
return (opcodetype)(OP_1+n-1);
}
int FindAndDelete(const CScript& b) const;
/**
* Pre-version-0.6, XSN always counted CHECKMULTISIGs
* as 20 sigops. With pay-to-script-hash, that changed:
* CHECKMULTISIGs serialized in scriptSigs are
* counted more accurately, assuming they are of the form
* ... OP_N CHECKMULTISIG ...
*/
unsigned int GetSigOpCount(bool fAccurate) const;
/**
* Accurately count sigOps, including sigOps in
* pay-to-script-hash transactions:
*/
unsigned int GetSigOpCount(const CScript& scriptSig) const;
bool IsPayToScriptHash() const;
bool IsPayToPublicKeyHash() const;
bool IsPayToWitnessScriptHash() const;
bool IsWitnessProgram(int& version, std::vector<unsigned char>& program) const;
/** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
bool IsPushOnly(const_iterator pc) const;
bool IsPushOnly() const;
/** Check if the script contains valid OP_CODES */
bool HasValidOps() const;
/**
* Returns whether the script is guaranteed to fail at execution,
* regardless of the initial stack. This allows outputs to be pruned
* instantly when entering the UTXO set.
*/
bool IsUnspendable() const
{
return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);
}
std::string ToString() const;
void clear()
{
// The default prevector::clear() does not release memory
CScriptBase::clear();
shrink_to_fit();
}
};
struct CScriptWitness
{
// Note that this encodes the data elements being pushed, rather than
// encoding them as a CScript that pushes them.
std::vector<std::vector<unsigned char> > stack;
// Some compilers complain without a default constructor
CScriptWitness() { }
bool IsNull() const { return stack.empty(); }
void SetNull() { stack.clear(); stack.shrink_to_fit(); }
std::string ToString() const;
};
class CReserveScript
{
public:
CScript reserveScript;
virtual void KeepScript() {}
CReserveScript() {}
virtual ~CReserveScript() {}
};
#endif // BITCOIN_SCRIPT_SCRIPT_H
| [
"[email protected]"
] | |
20265d559de3fe82f05f27d1e040ca5bb7c1fbc4 | 8b965913e982a4edfe72640202ca9fdbdcb02563 | /regex/sregex_iterator2.cpp | e25bd2203ff11465a8e13fac606fc34def9b389c | [] | no_license | artisdom/cpp_snippets | f13e5f737f4b3f149e07b5f1e9e011c3d440887a | b38ddb956281817076854791f07399ec6823b23f | refs/heads/master | 2020-02-26T14:38:58.448756 | 2018-01-14T01:50:52 | 2018-01-14T01:50:52 | 64,611,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include <iostream>
#include <iterator>
#include <string>
#include <regex>
using namespace std;
int main(int argc, char *argv[])
{
string s = "KEYPAD_NUMERIC_ONLY = 0,";
regex enum_regex("/(\w+)\s*(?:=\s*(\d+)|)\s*,?\s*(?:(?:\n|$)|\/\/.*?(?:\n|$)|)/");
auto words_begin = std::sregex_iterator(s.begin(), s.end(), enum_regex);
auto words_end = std::sregex_iterator();
//const int N = 6;
//std::cout << "Words longer than " << N << " characters:\n";
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
//if (match_str.size() > N) {
cout << " " << match_str << '\n';
//}
}
return 0;
}
| [
"[email protected]"
] | |
03335d030e485a9c3a7d05c63fc27bea69533d67 | 1f032ac06a2fc792859a57099e04d2b9bc43f387 | /85/a9/7d/9c/b866accf461de5e1d40642d784cbbc66fd93187bc4f9d1a2c442ec85b5b0587b6cd4a0f928172b4e2a0eb5392e6e8ccedab4decef51b87168e7ce2c4/sw.cpp | d8b9155c0c333ab1675ab02ac3d2b48555b38766 | [] | no_license | SoftwareNetwork/specifications | 9d6d97c136d2b03af45669bad2bcb00fda9d2e26 | ba960f416e4728a43aa3e41af16a7bdd82006ec3 | refs/heads/master | 2023-08-16T13:17:25.996674 | 2023-08-15T10:45:47 | 2023-08-15T10:45:47 | 145,738,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 343 | cpp | void build(Solution &s)
{
auto &t = s.addTarget<StaticLibrary>("lemire.simdjson", "0.9.1");
t += Git("https://github.com/lemire/simdjson", "v{v}");
t += cpp17;
if (t.getCompilerType() == CompilerType::MSVC ||
t.getCompilerType() == CompilerType::ClangCl)
{
t.CompileOptions.push_back("-arch:AVX2");
}
}
| [
"[email protected]"
] | |
5a93c224e0129af5f6f36136d9d0036ffa65ee12 | a0fc1c274ab8b126b866a295055a6ebcd263edd4 | /simpleperf/InplaceSamplerClient.cpp | 536b70c9da9fbe2d53bbb6e226feaeb4f0673daf | [
"Apache-2.0"
] | permissive | SuperiorOS/android_system_extras | 88627dced915ba595038f7b2bacecde73f87b614 | 25615a747ce345392661b32f86dc9bbb829805df | refs/heads/ten | 2023-07-12T16:30:05.981897 | 2019-10-30T04:34:21 | 2019-10-30T04:34:21 | 149,216,797 | 0 | 1 | null | 2021-07-10T15:16:29 | 2018-09-18T02:26:13 | HTML | UTF-8 | C++ | false | false | 6,275 | cpp | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InplaceSamplerClient.h"
#include <algorithm>
#include "environment.h"
#include "inplace_sampler_lib.h"
#include "utils.h"
static constexpr uint64_t EVENT_ID_FOR_INPLACE_SAMPLER = ULONG_MAX;
std::unique_ptr<InplaceSamplerClient> InplaceSamplerClient::Create(const perf_event_attr& attr,
pid_t pid,
const std::set<pid_t>& tids) {
if (pid == -1) {
LOG(ERROR) << "inplace-sampler can't monitor system wide events.";
return nullptr;
}
std::unique_ptr<InplaceSamplerClient> sampler(new InplaceSamplerClient(attr, pid, tids));
if (!sampler->ConnectServer()) {
return nullptr;
}
return sampler;
}
InplaceSamplerClient::InplaceSamplerClient(const perf_event_attr& attr, pid_t pid,
const std::set<pid_t>& tids)
: attr_(attr), pid_(pid), tids_(tids), got_start_profiling_reply_msg_(false) {
if (attr_.freq) {
sample_freq_ = attr_.sample_freq;
} else {
sample_freq_ = std::max(1u, static_cast<uint32_t>(1000000000 / attr_.sample_period));
}
}
uint64_t InplaceSamplerClient::Id() const {
return EVENT_ID_FOR_INPLACE_SAMPLER;
}
bool InplaceSamplerClient::ConnectServer() {
std::string server_path = "inplace_sampler_server_" + std::to_string(pid_);
// Try to connect server in 1s.
uint64_t timeout = GetSystemClock() + 10000000000ull;
while (GetSystemClock() < timeout) {
conn_ = UnixSocketConnection::Connect(server_path, true);
if (conn_ != nullptr) {
return true;
}
usleep(10);
}
LOG(ERROR) << "Can't find inplace_sampler_server for process " << pid_;
return false;
}
bool InplaceSamplerClient::StartPolling(IOEventLoop& loop,
const std::function<bool(Record*)>& record_callback,
const std::function<bool()>& close_callback) {
record_callback_ = record_callback;
CHECK(conn_ != nullptr);
auto read_callback = [&](const UnixSocketMessage& msg) {
return HandleMessage(msg);
};
if (!conn_->PrepareForIO(loop, read_callback, close_callback)) {
return false;
}
if (!SendStartProfilingMessage()) {
return false;
}
// If the inplace sampler doesn't reply in 3 seconds, report the error.
timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
auto check_reply_callback = [this]() {
if (!got_start_profiling_reply_msg_) {
LOG(ERROR) << "can't receive START_PROFILING_REPLY from process " << pid_;
return false;
}
return true;
};
return loop.AddPeriodicEvent(tv, check_reply_callback);
}
bool InplaceSamplerClient::SendStartProfilingMessage() {
std::string options;
options += "freq=" + std::to_string(sample_freq_);
if (attr_.sample_type & PERF_SAMPLE_CALLCHAIN) {
options += " dump_callchain=1";
}
if (!tids_.empty()) {
options += " tids=";
bool first = true;
for (auto& tid : tids_) {
if (first) {
first = false;
} else {
options.push_back(',');
}
options += std::to_string(tid);
}
}
size_t size = sizeof(UnixSocketMessage) + options.size() + 1;
std::unique_ptr<char[]> data(new char[size]);
UnixSocketMessage* msg = reinterpret_cast<UnixSocketMessage*>(data.get());
msg->len = size;
msg->type = START_PROFILING;
strcpy(msg->data, options.c_str());
return conn_->SendMessage(*msg, true);
}
bool InplaceSamplerClient::StopProfiling(IOEventLoop& loop,
const std::function<bool()>& close_callback) {
auto read_callback = [&](const UnixSocketMessage& msg) {
return HandleMessage(msg);
};
if (!conn_->PrepareForIO(loop, read_callback, close_callback)) {
return false;
}
// Notify inplace sampler to send buffered data and close the connection.
UnixSocketMessage msg;
msg.len = sizeof(UnixSocketMessage);
msg.type = END_PROFILING;
return conn_->SendMessage(msg, true);
}
bool InplaceSamplerClient::HandleMessage(const UnixSocketMessage& msg) {
const char* p = msg.data;
if (msg.type == START_PROFILING_REPLY) {
got_start_profiling_reply_msg_ = true;
if (strcmp(p, "ok") != 0) {
LOG(ERROR) << "receive reply from inplace_sampler_server of " << pid_ << ": " << p;
return false;
}
} else if (msg.type == THREAD_INFO) {
uint64_t time;
uint32_t tid;
MoveFromBinaryFormat(time, p);
MoveFromBinaryFormat(tid, p);
CommRecord r(attr_, pid_, tid, p, Id(), time);
if (!record_callback_(&r)) {
return false;
}
} else if (msg.type == MAP_INFO) {
uint64_t time;
uint64_t start;
uint64_t len;
uint64_t pgoff;
MoveFromBinaryFormat(time, p);
MoveFromBinaryFormat(start, p);
MoveFromBinaryFormat(len, p);
MoveFromBinaryFormat(pgoff, p);
MmapRecord r(attr_, false, pid_, pid_, start, len, pgoff, p, Id(), time);
if (!record_callback_(&r)) {
return false;
}
} else if (msg.type == SAMPLE_INFO) {
uint64_t time;
uint32_t tid;
uint32_t period;
uint32_t ip_nr;
MoveFromBinaryFormat(time, p);
MoveFromBinaryFormat(tid, p);
MoveFromBinaryFormat(period, p);
MoveFromBinaryFormat(ip_nr, p);
std::vector<uint64_t> ips(ip_nr);
MoveFromBinaryFormat(ips.data(), ip_nr, p);
// Don't know which cpu tid is running on, use cpu 0.
SampleRecord r(attr_, Id(), ips[0], pid_, tid, time, 0, period, ips, {}, 0);
if (!record_callback_(&r)) {
return false;
}
} else {
LOG(ERROR) << "Unexpected msg type: " << msg.type;
return false;
}
return true;
}
| [
"[email protected]"
] | |
6dbc1d067094e4d179322aa954c66f73988df406 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE404_Improper_Resource_Shutdown/CWE404_Improper_Resource_Shutdown__w32CreateFile_close_82_bad.cpp | 21f2d1f95ab01343a9e9833d7f1bd8fd700ea171 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,075 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE404_Improper_Resource_Shutdown__w32CreateFile_close_82_bad.cpp
Label Definition File: CWE404_Improper_Resource_Shutdown__w32CreateFile.label.xml
Template File: source-sinks-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 404 Improper Resource Shutdown or Release
* BadSource: Open a file using CreateFile()
* Sinks: close
* GoodSink: Close the file using CloseHandle()
* BadSink : Close the file using close()
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE404_Improper_Resource_Shutdown__w32CreateFile_close_82.h"
namespace CWE404_Improper_Resource_Shutdown__w32CreateFile_close_82
{
void CWE404_Improper_Resource_Shutdown__w32CreateFile_close_82_bad::action(HANDLE data)
{
if (data != INVALID_HANDLE_VALUE)
{
/* FLAW: Attempt to close the file using close() instead of CloseHandle() */
_close((int)data);
}
}
}
#endif /* OMITBAD */
| [
"[email protected]"
] | |
aa07b049e9c7ffdf2ab051b52dbe197b0945286a | e245dbf26d9d3f86ff0a7d3b8f9bdd8b54b073ec | /sky/engine/public/platform/WebHTTPBody.h | 96dc608a19a4828ec023a6c5b0d6430fa82cd6c8 | [
"BSD-3-Clause"
] | permissive | domenic/mojo | f665395c6895bc70054db26de0287ea904427b84 | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | refs/heads/master | 2023-07-23T01:35:26.439034 | 2014-11-19T01:11:18 | 2014-11-19T01:11:18 | 26,838,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,595 | h | /*
* Copyright (C) 2009 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:
*
* * 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.
*/
#ifndef WebHTTPBody_h
#define WebHTTPBody_h
#include "WebData.h"
#include "WebNonCopyable.h"
#include "WebString.h"
#include "WebURL.h"
#if INSIDE_BLINK
namespace WTF { template <typename T> class PassRefPtr; }
#endif
namespace blink {
class FormData;
class WebHTTPBodyPrivate;
class WebHTTPBody {
public:
struct Element {
enum Type { TypeData } type;
WebData data;
};
~WebHTTPBody() { reset(); }
WebHTTPBody() : m_private(0) { }
WebHTTPBody(const WebHTTPBody& b) : m_private(0) { assign(b); }
WebHTTPBody& operator=(const WebHTTPBody& b)
{
assign(b);
return *this;
}
BLINK_PLATFORM_EXPORT void initialize();
BLINK_PLATFORM_EXPORT void reset();
BLINK_PLATFORM_EXPORT void assign(const WebHTTPBody&);
bool isNull() const { return !m_private; }
// Returns the number of elements comprising the http body.
BLINK_PLATFORM_EXPORT size_t elementCount() const;
// Sets the values of the element at the given index. Returns false if
// index is out of bounds.
BLINK_PLATFORM_EXPORT bool elementAt(size_t index, Element&) const;
// Append to the list of elements.
BLINK_PLATFORM_EXPORT void appendData(const WebData&);
// Identifies a particular form submission instance. A value of 0 is
// used to indicate an unspecified identifier.
BLINK_PLATFORM_EXPORT long long identifier() const;
BLINK_PLATFORM_EXPORT void setIdentifier(long long);
BLINK_PLATFORM_EXPORT bool containsPasswordData() const;
BLINK_PLATFORM_EXPORT void setContainsPasswordData(bool);
#if INSIDE_BLINK
BLINK_PLATFORM_EXPORT WebHTTPBody(const WTF::PassRefPtr<FormData>&);
BLINK_PLATFORM_EXPORT WebHTTPBody& operator=(const WTF::PassRefPtr<FormData>&);
BLINK_PLATFORM_EXPORT operator WTF::PassRefPtr<FormData>() const;
#endif
private:
BLINK_PLATFORM_EXPORT void assign(WebHTTPBodyPrivate*);
BLINK_PLATFORM_EXPORT void ensureMutable();
WebHTTPBodyPrivate* m_private;
};
} // namespace blink
#endif
| [
"[email protected]"
] | |
edb225c184dd9a95affc15c178757ac4f826a18c | 63d311e5c0c196e9242b7c2fc167f1df579a2a0d | /Neural/Neural Net/NeuralNet.h | 61582966ef60011908f1a11b3f971394d3604035 | [] | no_license | jeremy-marvel/CRPI | 647919378f158bad87208ae27679e430926bdfaa | 162f8960f752c5a9fd790af94e13bac4507bbd12 | refs/heads/master | 2021-12-26T12:53:43.159972 | 2021-12-14T19:41:22 | 2021-12-14T19:41:22 | 206,053,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,715 | h | ///////////////////////////////////////////////////////////////////////////////
//
// Original System: Collaborative Robot Programming Interface
// Subsystem: NeuralNet
// Workfile: NeuralNet.h
// Revision: 1.0 - 6 February, 2008
// 1.1 - 5 August, 2008 : Added accessor functions of the
// network's state.
// 2.0 - 27 January, 2009 : Added black-box NN simulator
// 3.0 - 23 March, 2009 : Separated simulators from
// FeedForward class header file
// Author: J. Marvel
//
// Description
// ===========
// Neural network declarations for Feed-Forward networks.
// Currently, can only use numerical neuron types
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEURALNET_H
#define NEURALNET_H
#include "NetCommon.h"
#include "../../portable.h"
#include <vector>
using namespace std;
namespace NeuralNet
{
//! @ingroup NeuralNet
//!
//! @brief Standard feed-forward neural network with back propagation with
//! one hidden layer.
//!
template <class T> class LIBRARY_API FeedForward
{
public:
//! @brief Default constructor
//!
//! @param inFeat The number of input features for the network
//! @param interFeat The number of hidden-layer neurons
//! @param outFeat The number of output-layer neurons
//! @param initWeight TODO
//! @param initEta The initial learning rate during back propagation
//!
FeedForward (int inFeat,
int interFeat,
int outFeat,
double initWeight = 1.0,
double initEta = 0.001);
//! @brief Default destructor
//!
~FeedForward ();
//! @brief Initialize the dE/dw values for learning
//!
//! @note: Must be called following network creation and input insertion
//!
void initialize ();
//! @brief Run the neural net for a specified number of iterations
//!
//! @param iter The number of training iterations to run
//! @param prune Whether or not to prune the top 10% worst performers from the
//! training set
//!
//! @return The resulting RMS error
//!
double trainNetwork (int iter, bool prune = false);
//! @brief Run the test set through the neural network and write a .m file
//! to display the resulting outputs of the training and test sets
//! for comparison
//!
//! @param k The output neuron being queried
//!
void runTests (int k);
//! @brief Run the test set through the neural network and write an output file
//! specifying the top performers
//!
//! @param top Specify how many of the top performers to return
//! @param k The output neuron being queried
//!
void runTestsBest (int top, int k);
//! @brief Attempt to find the optimum input vector that results in the
//! best output for a specified output-layer node
//!
//! @param minVals The minimum values for the input vector
//! @param maxVals The maximum values for the input vector
//! @param best The best input sequence according to the trained NN
//! @param outWatch The output layer index over which the method optimizes
//! @param maximize Whether or not the performance metric is maximization
//!
//! @return The optimized output node output
//!
double autoOptimize (vector<double>& minVals,
vector<double>& maxVals,
vector<double>& best,
int outWatch,
bool maximize = true);
//! @brief TODO
//!
//! @param trainPath TODO
//! @param testPath
//!
//! @return TODO
//!
int parseInputFile (const char *trainPath = NULL,
const char *testPath = NULL);
//! @brief Read a NN weight description file from disk
//!
//! @param netPath The location of the description file to be read
//!
//! @return True if the file was successfully read, False otherwise
//!
bool readNetworkFile (const char *netPath);
//! @brief Write a NN weight description file from disk
//!
//! @param netPath The location of the description file to be written
//!
//! @return True if the file was successfully written, False otherwise
//!
bool writeNetworkFile (const char *netPath);
//! @brief Add a training sample to the network's collection
//!
//! @param in The raw input feature values for the training sample
//! @param out The raw output feature values for the training sample
//!
void addTrainingSet (double *in, double *out);
//! @brief TODO
//!
void clearTrainingSets ();
//! @brief Reduce the applicable training set population
//!
//! @param method The method for generating the neighborhood subset, based
//! on the enumerated types found in NetCommon.h
//! @param size The size of the neighborhood subset to create
//!
void adjustNeighborhood (int method, unsigned int size = 0);
//! @brief Add a testing sample to the network's collection
//!
//! @param in The raw input feature values for the testing sample
//!
void addTestingSet (double *in);
//! @brief Scale an input vector to the range of values observed in the
//! training set, and convert to a usable format
//!
//! @param rawVec The raw (unscaled) input vector
//! @param scaledVec The input vector scaled to the range observed in the
//! training set
//!
void scaleInput (vector<double> &rawVec, double *scaledVec);
//! @brief Get the minimum and maximum value vectors for both the intputs and
//! outputs that were fed into the training system
//!
//! @param minInVals The per-element minimum values given as inputs
//! @param maxInVals The per-element maximum values given as inputs
//!
void getRawRange (vector<double>& minInVals,
vector<double>& maxInVals);
//! @brief TODO
//!
//! @param inputVec TODO
//!
void setInputs (double *inputVec); // stimulate network with an input vec
// must do this before compute_outputs()
//! @brief Compute the outputs for all neurons in the network
//!
//! Note: No error detection: assumes inputs have been allocated &
//! populated properly
//!
void computeOutputs ();
//! @brief Report the value for the specified output node
//!
//! @param index The output node index being queried
//!
//! @return The value of the output node, or -1 if node does not exist
//!
double getOutput (unsigned int index);
//! @brief TODO
//!
//! @return The value of ETotal_
//!
double getTotalError ();
//! @brief TODO
//!
//! @return TODO
//!
double getRMSError ();
//! @brief TODO
//!
//! @return TODO
//!
int getNumInputs ();
//! @brief TODO
//!
//! @return TODO
//!
int getNumOutputs ();
//! @brief Get the number of training epochs the network has undergone
//!
//! @return The number of times adjustWeights() has been called
//!
int getNumEpochs ();
//! @brief Get the number of training patterns added to the collection
//!
//! @return The number of training patterns added
//!
int getNumTrainingPatterns();
//! @brief Access the scaled training input patterns
//!
//! @param pattern The training pattern vector to be inquiried
//! @param input The training pattern element to be retrieved
//!
//! @return The scaled input parameter
//!
double getTrainingInput (unsigned int pattern, unsigned int input);
//! @brief TODO
//!
//! @param pattern TODO
//! @param input TODO
//!
//! @return TODO
//!
double getRawTrainingInput (unsigned int pattern, unsigned int input);
//! @brief Access the scaled training ouput patterns
//!
//! @param pattern The training pattern vector to be inquiried
//! @param output The training pattern element to be retrieved
//!
//! @return The scaled output parameter
//!
double getTrainingOutput (unsigned int pattern, unsigned int output);
//! @brief TODO
//!
//! @param pattern TODO
//! @param output TODO
//!
//! @return TODO
//!
double getRawTrainingOutput (unsigned int pattern, unsigned int output);
//! @brief TODO
//!
//! @param output TODO
//!
//! @return TODO
//!
double getMaxOutput (unsigned int output);
//! @brief TODO
//!
//! @param TODO
//!
//! @return TODO
//!
double getMinOutput (unsigned int output);
private:
//! @brief Recursive helper function for the auto-optimization method
//!
//! @param minVals The minimum values for the input vector
//! @param maxVals The maximum values for the input vector
//! @param current The current input vector being tested
//! @Param best The best input sequence according to the trained NN
//! @param element The current input vector index being sequenced
//! @param outwatch The output layer index over which the method optimizes
//! @param bestout The current best value for the specified output node
//! @param maximize Whether or not the performance metric is maximization
//!
void optiHelper (vector<double>& minVals,
vector<double>& maxVals,
vector<double>& current,
vector<double>& best,
unsigned int element,
int outWatch,
double& bestout,
bool maximize);
//! @brief TODO
//!
void adjustWeights (); // here's the main deal--learn by adjusting wts
//! @brief Scale the currently loaded training and testing values
//!
void scaleAllInputs ();
//! @brief Scale the outputs to be in the range of min(outputs) to
//! max(outputs)
//!
void scaleAllOutputs ();
//! @brief Compute do/du for each neuron (calls the derivative(u) function
//! of the respective neuron type)
//!
void computeGPrimes ();
// may use these to adjust learning factors...
// copy elements of dEdw01_ to dEdw01Old_
// and dEdw12_ to dEdw12Old_
// may test changes in sign of derivatives to determine
// how to vary learning params
//! @brief TODO
//!
void backupDerivs (); // makes a copy of all derivs to old_dEsqd_dw
//! @brief TODO
//!
//! @note May adjust learning factors up or down based on the convergence
//! behavior (ex. sign reversal of dE/dw)
//!
void updateEtas ();
//! @brief Get the vector of minimum and maximum values for the
//! collection of training input values (populates
//! inputMinVals_ and inputMaxVals_, use prior to scaling
//! inputs)
//!
void findInputMinMaxVals ();
//! @brief Get the vector of minimum and maximum values for the
//! collection of training output values (populates
//! outputMinVals_ and outputMaxVals_, use prior to scaling
//! outputs)
//!
void findOutputMinMaxVals ();
//! @brief Compute the value of the RMS error for convergence testing
//!
void computeErrors ();
//! @brief Compute the value of the RMS error for convergence testing,
//! modified to allow for selective pruning of inputs
//!
void computeErrorsWithDisable ();
//! @brief Compute the sum of squared errors for dE/dw
//!
//! @return The summed value of the squares of all dEdw##_ values
//!
double dEdwSumSqr ();
//! @brief Compute the gradient descent sensitivity of the layer-I to
//! layer-J synapses: dE/dw term
//!
void compute_dEdw01 ();
//! @brief TODO
//!
void compute_dEdw12 (); // same, for all interneuron-to-output neuron wts
//! @brief Range (-initWeight_, +initWeight_) to which the random
//! synaptic weights are set
//!
double initWeight_;
//! @brief Initial learning factor to which all other etas are reset
//! once the training begins to show signs of diverging
//!
double initEta_;
//! @brief The number of training patterns input into the system
//!
unsigned int pTrainingPatterns_;
//! @brief The number of training patterns entered into the backup system,
//! for use when we want to select subpopulations for training
//!
unsigned int pRawTrainingPatternsBackup_;
//! @brief The number of testing patterns input into the system
//!
unsigned int pTestingPatterns_;
//! @brief The number of input features for the network
//!
unsigned int inputFeatures_;
//! @brief The number of hidden-layer neurons for the J layer
//!
unsigned int interFeatures_;
//! @brief The number of output-layer neurons for the K layer
//!
unsigned int outputFeatures_;
//! @brief Matrix to hold synapse values from inputs to hidden layer
//!
//! @note Indexing is [hidden][input]
//!
double **synapses0to1_;
//! @brief Matrix to hold synapse values from hidden to output layers
//!
//! @note Indexing is [output][hidden]
//!
double **synapses1to2_;
//! @brief TODO
//!
double *hiddenInputs_;
//! @brief TODO
//!
double *hiddenOutputs_;
//! @brief TODO
//!
double *hiddenGPrimes_;
//! @brief TODO
//!
double *layer2Inputs_;
//! @brief TODO
//!
double *gPrimes_;
//! @brief Variable used to keep track of the number of training iterations
//! the network undergoes
//!
int nIters_;
//! @brief TODO
//!
T *interNeurons_;
//! @brief TODO
//!
T *outputNeurons_;
//! @brief Scaled input training data vectors
//!
vector<double *> trainingInputs_;
//! @brief Scaled output training data vectors
//!
vector<double *> trainingOutputs_;
//! @brief Scaled input testing data vectors
//!
vector<double *> testingInputs_;
//! @brief Raw (unscaled) input training data vectors
//!
vector<double *> rawTrainingInputs_;
//! @brief Raw (unscaled) output training data vectors
//!
vector<double *> rawTrainingOutputs_;
//! @brief A backup copy of all training input vectors, for use when we
//! want to select subpopulations for training
//!
vector<double *> rawTrainingInputsBackup_;
//! @brief A backup copy of all training input vectors, for use when we
//! want to select subpopulations for training
//!
vector<double *> rawTrainingOutputsBackup_;
//! @brief Raw (unscaled) input testing data vectors
//!
vector<double *> rawTestingInputs_;
//! @brief TODO
//!
vector<bool> inputActive_;
//! @brief TODO
//!
double *inputs_;
//! @brief TODO
//!
double *inputMaxVals_;
//! @brief TODO
//!
double *inputMinVals_;
//! @brief TODO
//!
double *outputs_; // same as *layer2_outputs;
//! @brief TODO
//!
double *outputMaxVals_;
//! @brief TODO
//!
double *outputMinVals_;
//! @brief TODO
//!
vector<double> EVals_;
//! @brief TODO
//!
double ETotal_;
//! @brief Computed root mean squared error value
//!
double RMSError_;
//! @brief Matrix to hold weight sensitivities, dE/dw_j,i
//!
double **dEdw01_;
//! @brief TODO
//!
double **dEdw01Old_;
//! @brief Matrix to hold weight sensitivities, dEdw_j,k
//!
double **dEdw12_;
//! @brief TODO
//!
double **dEdw12Old_;
//! @brief Matrix of learning factors for each synapse from layer
//! 1 to Layer 2
//!
double **dw01Eta_;
//! @brief Matrix of learning factors for each synapse from layer
//! 2 to layer 3
//!
double **dw12Eta_;
//! @brief Matrix of computed perturbations of input synapses
//!
double **dw01_;
//! @brief Matrix of computed perturbations of each weight
//!
double **dw02_;
//! @brief Give an initial random value to the network's synapses
//!
void initializeSynapses ();
}; // FeedForward
} // NeuralNet
#endif | [
"[email protected]"
] | |
7e5951fe3ad3aa5f6c031a2016a69877938b3f4a | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtbase/src/widgets/doc/snippets/qtreewidget-using/mainwindow.cpp | 1474cdbcfb55681088609e5098b555882056c7f6 | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
"GPL-1.0-or-later",
"GPL-3.0-only",
"BSD-3-Clause",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-generic-exception"
] | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 7,622 | cpp | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "mainwindow.h"
MainWindow::MainWindow()
{
QMenu *fileMenu = new QMenu(tr("&File"));
QAction *quitAction = fileMenu->addAction(tr("E&xit"));
quitAction->setShortcut(tr("Ctrl+Q"));
QMenu *itemsMenu = new QMenu(tr("&Items"));
insertAction = itemsMenu->addAction(tr("&Insert Item"));
removeAction = itemsMenu->addAction(tr("&Remove Item"));
removeAction->setEnabled(false);
itemsMenu->addSeparator();
ascendingAction = itemsMenu->addAction(tr("Sort in &Ascending Order"));
descendingAction = itemsMenu->addAction(tr("Sort in &Descending Order"));
autoSortAction = itemsMenu->addAction(tr("&Automatically Sort Items"));
autoSortAction->setCheckable(true);
itemsMenu->addSeparator();
QAction *findItemsAction = itemsMenu->addAction(tr("&Find Items"));
findItemsAction->setShortcut(tr("Ctrl+F"));
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(itemsMenu);
/* For convenient quoting:
//! [0]
QTreeWidget *treeWidget = new QTreeWidget(this);
//! [0]
*/
treeWidget = new QTreeWidget(this);
//! [1]
treeWidget->setColumnCount(2);
//! [1] //! [2]
QStringList headers;
headers << tr("Subject") << tr("Default");
treeWidget->setHeaderLabels(headers);
//! [2]
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
connect(ascendingAction, SIGNAL(triggered()), this, SLOT(sortAscending()));
connect(autoSortAction, SIGNAL(triggered()), this, SLOT(updateSortItems()));
connect(descendingAction, SIGNAL(triggered()), this, SLOT(sortDescending()));
connect(findItemsAction, SIGNAL(triggered()), this, SLOT(findItems()));
connect(insertAction, SIGNAL(triggered()), this, SLOT(insertItem()));
connect(removeAction, SIGNAL(triggered()), this, SLOT(removeItem()));
connect(treeWidget,
SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(updateMenus(QTreeWidgetItem*)));
setupTreeItems();
updateMenus(treeWidget->currentItem());
setCentralWidget(treeWidget);
setWindowTitle(tr("Tree Widget"));
}
void MainWindow::setupTreeItems()
{
//! [3]
QTreeWidgetItem *cities = new QTreeWidgetItem(treeWidget);
cities->setText(0, tr("Cities"));
QTreeWidgetItem *osloItem = new QTreeWidgetItem(cities);
osloItem->setText(0, tr("Oslo"));
osloItem->setText(1, tr("Yes"));
//! [3]
(new QTreeWidgetItem(cities))->setText(0, tr("Stockholm"));
(new QTreeWidgetItem(cities))->setText(0, tr("Helsinki"));
(new QTreeWidgetItem(cities))->setText(0, tr("Copenhagen"));
//! [4] //! [5]
QTreeWidgetItem *planets = new QTreeWidgetItem(treeWidget, cities);
//! [4]
planets->setText(0, tr("Planets"));
//! [5]
(new QTreeWidgetItem(planets))->setText(0, tr("Mercury"));
(new QTreeWidgetItem(planets))->setText(0, tr("Venus"));
QTreeWidgetItem *earthItem = new QTreeWidgetItem(planets);
earthItem->setText(0, tr("Earth"));
earthItem->setText(1, tr("Yes"));
(new QTreeWidgetItem(planets))->setText(0, tr("Mars"));
(new QTreeWidgetItem(planets))->setText(0, tr("Jupiter"));
(new QTreeWidgetItem(planets))->setText(0, tr("Saturn"));
(new QTreeWidgetItem(planets))->setText(0, tr("Uranus"));
(new QTreeWidgetItem(planets))->setText(0, tr("Neptune"));
(new QTreeWidgetItem(planets))->setText(0, tr("Pluto"));
}
void MainWindow::findItems()
{
QString itemText = QInputDialog::getText(this, tr("Find Items"),
tr("Text to find (including wildcards):"));
if (itemText.isEmpty())
return;
//! [6]
QTreeWidgetItem *item;
//! [6]
foreach (item, treeWidget->selectedItems())
treeWidget->setItemSelected(item, false);
//! [7]
QList<QTreeWidgetItem *> found = treeWidget->findItems(
itemText, Qt::MatchWildcard);
foreach (item, found) {
treeWidget->setItemSelected(item, true);
// Show the item->text(0) for each item.
}
//! [7]
}
void MainWindow::insertItem()
{
QTreeWidgetItem *currentItem = treeWidget->currentItem();
if (!currentItem)
return;
QString itemText = QInputDialog::getText(this, tr("Insert Item"),
tr("Input text for the new item:"));
if (itemText.isEmpty())
return;
//! [8]
QTreeWidgetItem *parent = currentItem->parent();
QTreeWidgetItem *newItem;
if (parent)
newItem = new QTreeWidgetItem(parent, treeWidget->currentItem());
else
//! [8] //! [9]
newItem = new QTreeWidgetItem(treeWidget, treeWidget->currentItem());
//! [9]
newItem->setText(0, itemText);
}
void MainWindow::removeItem()
{
QTreeWidgetItem *currentItem = treeWidget->currentItem();
if (!currentItem)
return;
//! [10]
QTreeWidgetItem *parent = currentItem->parent();
int index;
if (parent) {
index = parent->indexOfChild(treeWidget->currentItem());
delete parent->takeChild(index);
} else {
index = treeWidget->indexOfTopLevelItem(treeWidget->currentItem());
delete treeWidget->takeTopLevelItem(index);
//! [10] //! [11]
}
//! [11]
}
void MainWindow::sortAscending()
{
treeWidget->sortItems(0, Qt::AscendingOrder);
}
void MainWindow::sortDescending()
{
treeWidget->sortItems(0, Qt::DescendingOrder);
}
void MainWindow::updateMenus(QTreeWidgetItem *current)
{
insertAction->setEnabled(current != 0);
removeAction->setEnabled(current != 0);
}
void MainWindow::updateSortItems()
{
ascendingAction->setEnabled(!autoSortAction->isChecked());
descendingAction->setEnabled(!autoSortAction->isChecked());
treeWidget->setSortingEnabled(autoSortAction->isChecked());
}
| [
"[email protected]"
] | |
6aeef7de4df29389ce42ef517acd74ed73da4ba7 | 54ab0f79f5d68f4732ca7d205f72ecef99862303 | /aten/src/ATen/native/vulkan/ops/Shape.cpp | 4209a3781cd28644df0453e3e0b50c3885e6a6c2 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | csarofeen/pytorch | a9dd0f8ffa0642d72df2d5e109a8b4d9c2389cbc | e8557ec5e064608577f81e51ccfe7c36c917cb0f | refs/heads/devel | 2023-04-30T02:42:13.558738 | 2023-03-14T00:50:01 | 2023-03-14T00:50:01 | 88,071,101 | 35 | 10 | NOASSERTION | 2023-06-21T17:37:30 | 2017-04-12T16:02:31 | C++ | UTF-8 | C++ | false | false | 1,732 | cpp | #include <ATen/InferSize.h>
#include <ATen/native/vulkan/ops/Common.h>
#include <ATen/native/vulkan/ops/Utils.h>
#include <torch/library.h>
namespace at {
namespace native {
namespace vulkan {
namespace ops {
Tensor view_internal(const Tensor& self_arg, const IntArrayRef shape) {
api::Context* const context = api::context();
Tensor self = self_arg.is_vulkan() ? self_arg : self_arg.vulkan();
vTensor& v_self = convert(self);
at::DimVector inferred_size = at::infer_size_dv(shape, self.numel());
vTensor v_output{
context,
inferred_size,
self.options(),
};
api::StorageBuffer buffer(context, at::kFloat, v_self.gpu_numel(), true);
utils::pack_vtensor_to_staging(v_self, buffer.buffer());
api::PipelineBarrier pipeline_barrier{};
add_buffer_barrier(
pipeline_barrier,
buffer.buffer(),
// Previous access
api::PipelineStage::COMPUTE,
api::MemoryAccessType::WRITE,
// Next access
api::PipelineStage::COMPUTE,
api::MemoryAccessType::READ);
utils::pack_buffer_to_vtensor(buffer.buffer(), v_output, pipeline_barrier);
return convert(v_output);
}
inline Tensor view(const Tensor& self_arg, IntArrayRef shape) {
return view_internal(self_arg, shape);
}
Tensor _reshape_alias(
const Tensor& self_arg,
const IntArrayRef shape,
const IntArrayRef strides) {
return view_internal(self_arg, shape);
}
#ifdef USE_VULKAN_API
TORCH_LIBRARY_IMPL(aten, Vulkan, m) {
m.impl(TORCH_SELECTIVE_NAME("aten::view"), TORCH_FN(view));
m.impl(
TORCH_SELECTIVE_NAME("aten::_reshape_alias"), TORCH_FN(_reshape_alias));
}
#endif /* USE_VULKAN_API */
} // namespace ops
} // namespace vulkan
} // namespace native
} // namespace at
| [
"[email protected]"
] | |
c095010d785c7c710a09b79094adb5b85eee045f | 364e5cd1ce6948183e6ebb38bd8f555511b54495 | /DesignPattern/Command/CommandNormal/include/Command.h | db67f4f5984097b44cce13200b0830b6271ed86c | [] | no_license | danelumax/CPP_study | c38e37f0d2cebe4adccc65ad1064aa338913f044 | 22124f8d83d59e5b351f16983d638a821197b7ae | refs/heads/master | 2021-01-22T21:41:11.867311 | 2017-03-19T09:01:11 | 2017-03-19T09:01:11 | 85,462,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | h | /*
* Command.h
*
* Created on: Oct 31, 2016
* Author: eliwech
*/
#ifndef COMMAND_H_
#define COMMAND_H_
class Command
{
public:
virtual void execute() = 0;
};
#endif /* COMMAND_H_ */
| [
"[email protected]"
] | |
0c2fa304ad0077a6cb923ca09f2cfbab4aef3168 | 2485005ebb1b9ac79a3f9195b6bfeb7817ae7a9c | /lib/win32/cpprestsdk-static/Release/src/http/listener/http_server_api.cpp | 727e77a6f8a8bd9d47b6cac8c0355ac57e5689be | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | getbraincloud/braincloud-cpp | c2ca31e9971b1103178eedc55cd40ea98a03bbb1 | 03c2446cd512529a35fdf4d041da0ec84c785b4a | refs/heads/master | 2023-09-01T15:47:48.536831 | 2023-08-03T19:40:31 | 2023-08-03T19:40:31 | 51,466,360 | 4 | 19 | Apache-2.0 | 2023-09-14T20:39:40 | 2016-02-10T19:33:02 | C++ | UTF-8 | C++ | false | false | 5,315 | cpp | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. 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.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* http_server_api.cpp
*
* HTTP Library: exposes the entry points to the http server transport apis.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
#include "cpprest/http_server_api.h"
#ifdef _MS_WINDOWS
#include "cpprest/http_windows_server.h"
#else
#include "cpprest/http_linux_server.h"
#endif
namespace web { namespace http
{
namespace experimental {
namespace details
{
using namespace web;
using namespace utility;
using namespace web::http::experimental::listener;
pplx::extensibility::critical_section_t http_server_api::s_lock;
std::unique_ptr<http_server> http_server_api::s_server_api((http_server*)nullptr);
pplx::details::atomic_long http_server_api::s_registrations(0L);
bool http_server_api::has_listener()
{
return s_registrations > 0L;
}
void http_server_api::register_server_api(std::unique_ptr<http_server> server_api)
{
pplx::extensibility::scoped_critical_section_t lock(s_lock);
http_server_api::unsafe_register_server_api(std::move(server_api));
}
void http_server_api::unregister_server_api()
{
pplx::extensibility::scoped_critical_section_t lock(s_lock);
if (http_server_api::has_listener())
{
throw http_exception(_XPLATSTR("Server API was cleared while listeners were still attached"));
}
s_server_api.release();
}
void http_server_api::unsafe_register_server_api(std::unique_ptr<http_server> server_api)
{
// we assume that the lock has been taken here.
if (http_server_api::has_listener())
{
throw http_exception(_XPLATSTR("Current server API instance has listeners attached."));
}
s_server_api.swap(server_api);
}
pplx::task<void> http_server_api::register_listener(_In_ web::http::experimental::listener::details::http_listener_impl *listener)
{
return pplx::create_task([listener]()
{
pplx::extensibility::scoped_critical_section_t lock(s_lock);
// the server API was not initialized, register a default
if(s_server_api == nullptr)
{
#ifdef _MS_WINDOWS
std::unique_ptr<http_windows_server> server_api(new http_windows_server());
#else
std::unique_ptr<http_linux_server> server_api(new http_linux_server());
#endif
http_server_api::unsafe_register_server_api(std::move(server_api));
}
std::exception_ptr except;
try
{
// start the server if necessary
if (pplx::details::atomic_increment(s_registrations) == 1L)
{
s_server_api->start().wait();
}
// register listener
s_server_api->register_listener(listener).wait();
} catch(...)
{
except = std::current_exception();
}
// Registration failed, need to decrement registration count.
if(except != nullptr)
{
if (pplx::details::atomic_decrement(s_registrations) == 0L)
{
try
{
server_api()->stop().wait();
} catch(...)
{
// ignore this exception since we want to report the original one
}
}
std::rethrow_exception(except);
}
});
}
pplx::task<void> http_server_api::unregister_listener(_In_ web::http::experimental::listener::details::http_listener_impl *pListener)
{
return pplx::create_task([pListener]()
{
pplx::extensibility::scoped_critical_section_t lock(s_lock);
// unregister listener
std::exception_ptr except;
try
{
server_api()->unregister_listener(pListener).wait();
} catch(...)
{
except = std::current_exception();
}
// stop server if necessary
try
{
if (pplx::details::atomic_decrement(s_registrations) == 0L)
{
server_api()->stop().wait();
}
} catch(...)
{
// save the original exception from unregister listener
if(except != nullptr)
{
except = std::current_exception();
}
}
// rethrow exception if one occurred
if(except != nullptr)
{
std::rethrow_exception(except);
}
});
}
http_server *http_server_api::server_api()
{
return s_server_api.get();
}
} // namespace listener
} // namespace experimental
}} // namespace web::http
| [
"[email protected]"
] | |
71706e162186b60fe029aad8ec6ddbd44ec0c3e2 | 376b8082af96ac8870db2e91654959f2d75ad296 | /time.cpp | 02dfe7cb08f3700b9e587904803318ae7e1b354b | [] | no_license | Luterium/Deterministic-rounding-set-cover | a887df5c9f2e4512dc34e574b47968be3783299e | 98d525f1cea75a9f998210fa2df682f944a1fe63 | refs/heads/master | 2020-05-30T17:56:54.077526 | 2019-06-02T22:17:10 | 2019-06-02T22:17:10 | 189,886,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,994 | cpp | #include <iostream>
#include <sstream>
#include <fstream>
#include <ctime>
#include <Windows.h>
using namespace std;
int main(int argc, char *argv[]){
std::string auxInputName;
ifstream inputName;
inputName.open("testCases.txt");
fstream timeLog;
fstream timeLogMin;
fstream timeLogMax;
fstream timeLogAvg;
timeLog.open("timeLogDeterministicRounding.txt", std::fstream::in | std::fstream::out | std::fstream::app);
timeLogMin.open("timeLogDeterministicRoundingMin.txt", std::fstream::in | std::fstream::out | std::fstream::app);
timeLogMax.open("timeLogDeterministicRoundingMax.txt", std::fstream::in | std::fstream::out | std::fstream::app);
timeLogAvg.open("timeLogDeterministicRoundingAvg.txt", std::fstream::in | std::fstream::out | std::fstream::app);
double timeSpent;
struct timespec start, finish;
double minTime = 1000;
double maxTime = 0;
double avgTime;
while(!inputName.eof()){
std::stringstream stringBuilder;
inputName >> auxInputName;
stringBuilder << "main.exe setCoverTestCases/" << auxInputName << " Results/" << auxInputName;
std::string completeString = stringBuilder.str();
cout << endl << auxInputName << endl;
timeLog << auxInputName << endl;
avgTime = 0;
minTime = 10000;
maxTime = 0;
for(int i = 0; i < 25; i++){
clock_gettime(CLOCK_REALTIME, &start);
int retCode = system(completeString.c_str());
clock_gettime(CLOCK_REALTIME, &finish);
timeSpent = (finish.tv_sec - start.tv_sec);
timeSpent += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
cout << "Time spent: " << timeSpent << " seconds" << endl;
if(timeSpent > maxTime)
maxTime = timeSpent;
if(timeSpent < minTime)
minTime = timeSpent;
timeLog << i << ": " << timeSpent << endl;
avgTime += timeSpent;
}
timeLogMin << minTime << endl;
timeLogAvg << avgTime/25 << endl;
timeLogMax << maxTime << endl;
timeLog << "Min: " << minTime << endl << "Max:" << maxTime << endl << "Avg:" << avgTime/25 << endl << endl;
}
return 0;
} | [
"[email protected]"
] | |
fa5f69d35074e0670450a6c78af7ab6f6b3ef34d | 9870e11c26c15aec3cc13bc910e711367749a7ff | /SPOJ/sp_4.cpp | 2fefe3faf5f90c933de3df403c0da988b208fd03 | [] | no_license | liuq901/code | 56eddb81972d00f2b733121505555b7c7cbc2544 | fcbfba70338d3d10bad2a4c08f59d501761c205a | refs/heads/master | 2021-01-15T23:50:10.570996 | 2016-01-16T16:14:18 | 2016-01-16T16:14:18 | 12,918,517 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,701 | cpp | #include <cstdio>
#include <cstdlib>
#include <cctype>
#include <string>
#include <stack>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
for (int i=1;i<=t;i++)
{
char tmp[500];
string s;
scanf("%s",tmp);
s=tmp;
int l;
l=s.size();
string ans;
stack <char> a;
for (int i=0;i<l;i++)
{
if (isalpha(s[i]))
ans+=s[i];
if (s[i]=='(')
a.push(s[i]);
if (s[i]==')')
{
while (a.top()!='(')
{
ans+=a.top();
a.pop();
}
a.pop();
}
if (s[i]=='+')
a.push(s[i]);
if (s[i]=='-')
{
while (a.top()=='+')
{
ans+=a.top();
a.pop();
}
a.push(s[i]);
}
if (s[i]=='*')
{
while (a.top()=='+' || a.top()=='-')
{
ans+=a.top();
a.pop();
}
a.push(s[i]);
}
if (s[i]=='/')
{
while (a.top()=='+' || a.top()=='-' || a.top()=='*')
{
ans+=a.top();
a.pop();
}
a.push(s[i]);
}
if (s[i]=='^')
{
while (a.top()=='+' || a.top()=='-' || a.top()=='*' || a.top()=='/')
{
ans+=a.top();
a.pop();
}
a.push(s[i]);
}
}
while (!a.empty())
{
ans+=a.top();
a.pop();
}
printf("%s\n",ans.c_str());
}
system("pause");
return(0);
}
| [
"[email protected]"
] | |
bddeb9d8fd183a7a6173e3bbce2b41606d2d227f | 49f88ff91aa582e1a9d5ae5a7014f5c07eab7503 | /gen/services/network/public/mojom/cors.mojom-blink.h | 18362d23d282edacde99b9dbcbea1c0d6d6619d1 | [] | no_license | AoEiuV020/kiwibrowser-arm64 | b6c719b5f35d65906ae08503ec32f6775c9bb048 | ae7383776e0978b945e85e54242b4e3f7b930284 | refs/heads/main | 2023-06-01T21:09:33.928929 | 2021-06-22T15:56:53 | 2021-06-22T15:56:53 | 379,186,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,451 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_NETWORK_PUBLIC_MOJOM_CORS_MOJOM_BLINK_H_
#define SERVICES_NETWORK_PUBLIC_MOJOM_CORS_MOJOM_BLINK_H_
#include <stdint.h>
#include <limits>
#include <type_traits>
#include <utility>
#include "base/callback.h"
#include "base/macros.h"
#include "base/optional.h"
#include "mojo/public/cpp/bindings/mojo_buildflags.h"
#if BUILDFLAG(MOJO_TRACE_ENABLED)
#include "base/trace_event/trace_event.h"
#endif
#include "mojo/public/cpp/bindings/clone_traits.h"
#include "mojo/public/cpp/bindings/equals_traits.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
#include "mojo/public/cpp/bindings/union_traits.h"
#include "services/network/public/mojom/cors.mojom-shared.h"
#include "mojo/public/cpp/bindings/lib/wtf_clone_equals_util.h"
#include "mojo/public/cpp/bindings/lib/wtf_hash_util.h"
#include "third_party/blink/renderer/platform/mojo/revocable_interface_ptr.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr_info.h"
#include "mojo/public/cpp/bindings/associated_interface_request.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/lib/control_message_handler.h"
#include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h"
#include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
#include "third_party/blink/renderer/platform/mojo/revocable_interface_ptr.h"
#include "mojo/public/cpp/bindings/lib/native_enum_serialization.h"
#include "mojo/public/cpp/bindings/lib/native_struct_serialization.h"
#include "third_party/blink/public/platform/web_common.h"
namespace WTF {
struct network_mojom_internal_CORSPreflightPolicy_DataHashFn {
static unsigned GetHash(const ::network::mojom::CORSPreflightPolicy& value) {
using utype = std::underlying_type<::network::mojom::CORSPreflightPolicy>::type;
return DefaultHash<utype>::Hash().GetHash(static_cast<utype>(value));
}
static bool Equal(const ::network::mojom::CORSPreflightPolicy& left, const ::network::mojom::CORSPreflightPolicy& right) {
return left == right;
}
static const bool safe_to_compare_to_empty_or_deleted = true;
};
template <>
struct DefaultHash<::network::mojom::CORSPreflightPolicy> {
using Hash = network_mojom_internal_CORSPreflightPolicy_DataHashFn;
};
template <>
struct HashTraits<::network::mojom::CORSPreflightPolicy>
: public GenericHashTraits<::network::mojom::CORSPreflightPolicy> {
static_assert(true,
"-1000000 is a reserved enum value");
static_assert(true,
"-1000001 is a reserved enum value");
static const bool hasIsEmptyValueFunction = true;
static bool IsEmptyValue(const ::network::mojom::CORSPreflightPolicy& value) {
return value == static_cast<::network::mojom::CORSPreflightPolicy>(-1000000);
}
static void ConstructDeletedValue(::network::mojom::CORSPreflightPolicy& slot, bool) {
slot = static_cast<::network::mojom::CORSPreflightPolicy>(-1000001);
}
static bool IsDeletedValue(const ::network::mojom::CORSPreflightPolicy& value) {
return value == static_cast<::network::mojom::CORSPreflightPolicy>(-1000001);
}
};
} // namespace WTF
namespace WTF {
struct network_mojom_internal_CORSError_DataHashFn {
static unsigned GetHash(const ::network::mojom::CORSError& value) {
using utype = std::underlying_type<::network::mojom::CORSError>::type;
return DefaultHash<utype>::Hash().GetHash(static_cast<utype>(value));
}
static bool Equal(const ::network::mojom::CORSError& left, const ::network::mojom::CORSError& right) {
return left == right;
}
static const bool safe_to_compare_to_empty_or_deleted = true;
};
template <>
struct DefaultHash<::network::mojom::CORSError> {
using Hash = network_mojom_internal_CORSError_DataHashFn;
};
template <>
struct HashTraits<::network::mojom::CORSError>
: public GenericHashTraits<::network::mojom::CORSError> {
static_assert(true,
"-1000000 is a reserved enum value");
static_assert(true,
"-1000001 is a reserved enum value");
static const bool hasIsEmptyValueFunction = true;
static bool IsEmptyValue(const ::network::mojom::CORSError& value) {
return value == static_cast<::network::mojom::CORSError>(-1000000);
}
static void ConstructDeletedValue(::network::mojom::CORSError& slot, bool) {
slot = static_cast<::network::mojom::CORSError>(-1000001);
}
static bool IsDeletedValue(const ::network::mojom::CORSError& value) {
return value == static_cast<::network::mojom::CORSError>(-1000001);
}
};
} // namespace WTF
namespace network {
namespace mojom {
namespace blink {
using CORSPreflightPolicy = CORSPreflightPolicy; // Alias for definition in the parent namespace.
using CORSError = CORSError; // Alias for definition in the parent namespace.
} // namespace blink
} // namespace mojom
} // namespace network
namespace mojo {
} // namespace mojo
#endif // SERVICES_NETWORK_PUBLIC_MOJOM_CORS_MOJOM_BLINK_H_ | [
"[email protected]"
] | |
43a41a805f5e0b93107b170ff977c3daecac42cf | 0f6765cdbf6b59519a407e071be79f860898640f | /reader/mifarereaderemulator.cpp | fe2e8fc7a7035e12b4642112a23d34f89a73bdbb | [] | no_license | skifcorp/bossn | 0d6ee9d894c823fd9660f9c6d05f1ec6313fccb9 | 09b9d1cd6542fa5af71e8808572552d618160eee | HEAD | 2016-09-06T00:08:25.981114 | 2014-09-19T05:47:11 | 2014-09-19T05:47:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,224 | cpp | #include "mifarereaderemulator.h"
#include "mifarereader.h"
#include "func.h"
#include "settingstool.h"
using std::cout;
#include "mifarecarddata.h"
#include "cardstructs.h"
BossnFactoryRegistrator<MifareReaderEmulator> MifareReaderEmulator::registator("MifareReaderEmulator");
MifareReaderEmulator::MifareReaderEmulator(const QVariantMap& s)
{
qDebug () << "MifareReaderEmulator CREATED!";
card_class_name = get_setting<QString>("card_class_name", s);
}
MifareReaderEmulator::~MifareReaderEmulator()
{
}
QVariant MifareReaderEmulator::doOn()
{
return QVariant(true);
}
QVariant MifareReaderEmulator::doOff()
{
return QVariant(true);
}
QVariant MifareReaderEmulator::doSound(const QVariant& )
{
return QVariant(true);
}
QVariant MifareReaderEmulator::activateIdleA()
{
ActivateCardISO14443A ac;
ac.uid += "000000";
return QVariant::fromValue<ActivateCardISO14443A>(ac);
}
QVariant MifareReaderEmulator::getHostCodedKey(const QVariant& )
{
HostCodedKey coded_key;
coded_key.ack = 0;
coded_key.coded = QByteArray(6, 0);
return QVariant::fromValue<HostCodedKey>(coded_key);
}
MifareReaderEmulator::current_block_offsets MifareReaderEmulator::getCurrentBlockOffsets(int num) const
{
current_block_offsets o;
const BlocksConf& bc = CardStructs::blocks_conf();
for ( int i = 0; i<num; ++i ) {
o.start_offset += bc[i].blockSize;
}
o.finish_offset = o.start_offset + bc[num].blockSize;
return o;
}
QVariant MifareReaderEmulator::doAuth(const QVariant& )//const AuthKey & auth)
{
return QVariant(true);
}
MifareCardData MifareReaderEmulator::defaultDataForBlock(int num) const
{
checkBlockNum(num);
const StructConf & sc = CardStructs::bill_conf(card_class_name);
MifareCardData one_block;
current_block_offsets offsets = getCurrentBlockOffsets(num);
for ( auto iter = sc.members_conf.begin(); iter != sc.members_conf.end(); ++iter) {
if ( (*iter).offset >= offsets.start_offset && (*iter).offset < offsets.finish_offset ) {
//qDebug()<< "num: " << num << " foundOffset: " << (*iter).offset << " value: "<<iter->defaultValue().toString();
one_block.insert( iter->memberName, iter->defaultValue() );
}
}
return one_block;
}
QByteArray MifareReaderEmulator::cardDataToByteArray( const MifareCardData& data, int num ) const
{
const StructConf& sc = CardStructs::bill_conf(card_class_name);
const BlocksConf& bc = CardStructs::blocks_conf();
current_block_offsets offsets = getCurrentBlockOffsets(num);
QByteArray ret( bc[num].blockSize, 0 );
for (MifareCardData::const_iterator iter = data.begin(); iter != data.end(); ++iter ) {
const StructMemberConf& smc = sc.findByMember( iter.key() );
QByteArray arr = StructMemberConf::functionForWrite( smc.typeName )( *iter );
ret.replace( smc.offset - offsets.start_offset, smc.length, arr );
}
return ret;
}
void MifareReaderEmulator::checkBlockNum(int num) const
{
if ( num >= CardStructs::blocks_conf().count() ) {
qWarning() << " MifareCardEmulator: you passed block_num " << num << " but blocks_count is: " <<
CardStructs::blocks_conf().count();
qFatal("Exiting...");
}
if ( num >= CardStructs::bill_conf(card_class_name).members_conf.count() ) {
qWarning() << " MifareCardEmulator: you passed block_num " << num << " but blocks_count is: " <<
CardStructs::bill_conf(card_class_name).members_conf.count();
qFatal("Exiting...");
}
}
int MifareReaderEmulator::blockIndexByNum(uint num) const
{
const BlocksConf& bc = CardStructs::blocks_conf() ;
int counter = 0;
for ( auto iter = bc.begin(); iter != bc.end(); ++iter , ++counter) {
if (iter->blockNum == num) return counter;
}
qWarning() << "MifareReaderEmulator: cant find blockConf with blockNum == " << num;
qFatal("Exiting!"); return 0;
}
QVariant MifareReaderEmulator::readBlock(const QVariant& n)
{
int num = blockIndexByNum( n.toInt() );
checkBlockNum( num );
MifareRead ret;
ret.result = 0;
ret.result = true;
try {
MifareCardData bill = defaultDataForBlock( num );
if ( num == 0 ) { //must refactor this
bill.setMemberValue("driver", 390);
bill.setMemberValue("billNumber", 1);
bill.setMemberValue("numField", 105);
}
else if ( num == 1) {
bill.setMemberValue("bruttoWeight", 10000);
bill.setMemberValue("dateOfBrutto", QDateTime(QDate(2013, 01, 29), QTime(12, 20, 0)));
}
else if ( num == 2 ) {
bill.setMemberValue("bumFact", 1);
bill.setMemberValue("kagat", 1);
bill.setMemberValue("material", 21);
}
ret.data = cardDataToByteArray( bill, num );
}
catch ( FuncNotFoundException& e ) {
qWarning() << "func_not_found exception! name: " << e.funcName();
qFatal("exiting!");
}
return QVariant::fromValue<MifareRead>(ret);
}
QVariant MifareReaderEmulator::writeBlock(const QVariant& , const QVariant& )
{
return QVariant(true);
}
| [
"[email protected]"
] | |
592a70b7236759c9c106e579da17037099d126d7 | 541fb73b9d81c8d3f121274532921d926089fa8a | /simplexmethod/test1/miracl/curve/comflash.h | 8c45a82415bb31236dabe5f932db33a982b6f8f8 | [] | no_license | antonklimovsky/ancient-numerics | 3cdc80d8402088a32ed82838c113fd2f77a8457a | 91ccd6c399ca5e47a76de2ee3012c67f5a687c45 | refs/heads/master | 2020-04-01T18:34:03.429513 | 2018-10-26T17:16:35 | 2018-10-26T17:16:35 | 153,500,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,538 | h | /*
* Quick and dirty complex data type using flash arithmetic
* Should be extended
*/
#ifndef COMFLASH_H
#define COMFLASH_H
#include <iostream.h>
#include <flash.h>
class Complex
{
Flash x,y;
public:
Complex() {x=(Flash)0; y=(Flash)0; }
Complex(int a) {x=(Flash)a; y=(Flash)0; }
Complex(const Flash& a) {x=a; y=(Flash)0; }
Complex(const Flash& a,const Flash& b) {x=a;y=b;}
Complex(const Complex& a) {x=a.x;y=a.y;}
Complex& operator=(const Complex &);
Complex& operator+=(const Complex &);
Complex& operator-=(const Complex &);
Complex& operator*=(const Complex &);
Complex& operator/=(const Complex &);
friend Flash real(const Complex &);
friend Flash imaginary(const Complex &);
friend Complex operator-(const Complex&);
friend BOOL operator==(const Complex&,const Complex&);
friend BOOL operator!=(const Complex&,const Complex&);
friend Complex operator+(const Complex &, const Complex &);
friend Complex operator-(const Complex &, const Complex &);
friend Complex operator*(const Complex &, const Complex &);
friend Complex operator/(const Complex &, const Complex &);
friend Complex exp(const Complex &);
friend Complex log(const Complex &);
friend Complex pow(const Complex &,const Complex &);
friend Complex pow(const Complex &,int);
friend Complex nroot(const Complex&,int);
friend ostream& operator<<(ostream&,const Complex&);
~Complex() {}
};
#endif
| [
"[email protected]"
] | |
85c3829541aa2dfd07968ea7b1d47f8f76eea198 | 38321e31e29acee0dd79253424e3deca13b572e6 | /MLN-iOS/MLN/Classes/MUIKit/Component/ObjectAnimation/Source/Platform/RunLoop.h | 5218cfcc5f6ee8a61311424917440b6f5e7abefe | [
"MIT"
] | permissive | NSOiO/MLN | 9c4c8cf35151d2a7c542bd016e0eba071221e22d | ea5b6b13c705c4fdaa0528e1a5eadc0a7bf2642c | refs/heads/master | 2021-11-11T16:35:17.414059 | 2020-10-28T02:35:01 | 2020-10-28T02:35:01 | 238,377,296 | 0 | 0 | MIT | 2020-02-05T05:44:42 | 2020-02-05T05:44:41 | null | UTF-8 | C++ | false | false | 766 | h | //
// Created by momo783 on 2020/5/15.
// Copyright (c) 2020 boztrail. All rights reserved.
//
#ifndef ANIMATION_RUNLOOP_H
#define ANIMATION_RUNLOOP_H
#include "Defines.h"
#include <functional>
ANIMATOR_NAMESPACE_BEGIN
typedef std::function<void(AMTTimeInterval)> RunLoopCallback;
class RunLoop {
RunLoop();
~RunLoop();
public:
static RunLoop *ShareLoop();
ANIMATOR_INLINE AMTBool IsRunning() const {
return running;
};
AMTTimeInterval CurrentTime();
void StartLoop();
RunLoopCallback LoopCallback;
void StopLoop();
static void DestoryShareLoop();
private:
AMTBool running;
};
ANIMATOR_NAMESPACE_END
#endif //ANIMATION_RUNLOOP_H
| [
"[email protected]"
] | |
29853f570be7b3fc2069913475dce22fcf0b9ebb | f44f4de33840f31720923d1b34e0ba9f03886579 | /CandyCane.cpp | 981818aa77eb7a4eb4c9632f9da351740be32fac | [] | no_license | robotics1714/2013-Code | 00c189326504d0f1a1fd338946be9511f09588bb | ed15fdc544df60b6c346e87a426adc65cf2de9a6 | refs/heads/master | 2021-01-22T11:54:57.175613 | 2013-11-27T04:04:58 | 2013-11-27T04:04:58 | 14,736,089 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,543 | cpp | /*
* File: CandyCane.cpp
* Description: cpp for the CandyCane class
* Last Changed: 2-1-13
* Author: Mitchell S
*/
//***********************************************************
// INCLUDES
//***********************************************************
#include "WPILib.h"
#include "CandyCane.h"
//***********************************************************
// DEFINES
//***********************************************************
#define MANUAL 1
#define MOTOR_FORWARDS 1.0
#define MOTOR_BACKWARDS -1.0
#define MOTOR_STOPPED 0
// Limit switch states
#define ACTIVATED 0
#define DE_ACTIVATED 1
#define CC_RETRACT_LIMIT 18
#define CC_EXTEND_LIMIT CC_FULL_SAFETY
// Servo Hook positions
#define HOOK_POSITION 130 //90 degrees
#define HOOK_NEUTRAL 30 // 0 degrees
#define GRAB_RELEASE_OUT_DISTANCE 22500//The distance the CC will need to go out before coming back in
//***********************************************************
// CLASS METHOD DECLARATIONS
//***********************************************************
CandyCane_Class::CandyCane_Class(
UINT32 moduleNumber,
UINT32 extensionArmMotorPort, // port that the extension arm motor(lead screw) is connected to
UINT32 twistServoPort, // pwm port that the twist servo is connected to
//TODO REMOVE //UINT32 hookLimitPort, // port that the hook limit switch is connected to
UINT32 armMinLimitPort, // port that the fully extended switch is connected to
UINT32 armMaxLimitPort, // port that the fully retracted limit switch is connected to
UINT32 clawGrabSwitchPort, // port that the claw's limit switch is on
//UINT32 lightSensorPort, // port that gets the ferous sensor that detcecets the horizontal
UINT32 railPositionPort1, // port that gets the rail position when it's in between the switches
UINT32 railPositionPort2
)
{
extensionArmMotor = new Talon(moduleNumber, extensionArmMotorPort);//sidecar#,port#
twistServo = new Servo(moduleNumber, twistServoPort);
ArmUpLimit = new DigitalInput(moduleNumber, armMaxLimitPort);
ArmDownLimit = new DigitalInput(moduleNumber, armMinLimitPort);
homeSwitch = new DigitalInput(moduleNumber, clawGrabSwitchPort);//TODO
//lightSensor = new AnalogChannel(moduleNumber, lightSensorPort);
railPosition = new Encoder(moduleNumber,railPositionPort1,moduleNumber,railPositionPort2);
railPosition->Reset();
railPosition->Start();
hookTurnTimer = new Timer();
hookTurnTimer->Reset();
bringingInTower = false;
bringingInCC = false;
pushingOut = false;
candyCaneState = CC_IDLE;
twistServo->SetAngle(HOOK_NEUTRAL);
}
CandyCane_Class::~CandyCane_Class()
{
delete extensionArmMotor;
delete twistServo;
//TODO delete hookLimitSwitch;
delete ArmUpLimit;
delete ArmDownLimit;
delete homeSwitch;
//delete lightSensor;
delete railPosition;
//delete railPositionPort2;
}
void CandyCane_Class::HomeReset()
{
if(homeSwitch->Get() == PRESSED)
{
extensionArmMotor->Set(0);
railPosition->Reset();
}
}
void CandyCane_Class::StartGrab(double grabbingDistance)
{
//Don't do anything unless we're not already doing anything
if(candyCaneState == CC_IDLE)
{
candyCaneState = CC_GRAB_PUSH_OUT;
grabDistance = grabbingDistance;
}
}
//**************************************************************************************************
//
// Method Grab()
// Parameters: None
// Returns: candyCaneState
// Description: This method is the state machine process for grabbing the vertical leg of the pyramid
// It extends a hook to vertical bar, rotates the hook into position and then secures the
// robot to the vertical bar.
//
//*************************************************************************************************
int CandyCane_Class::Grab()
{
switch(candyCaneState)
{
case CC_GRAB_PUSH_OUT:
//put the servo in position
ServoNeutral();
extensionArmMotor->Set(MOTOR_FORWARDS);
candyCaneState = CC_GRAB_ROTATE_SERVO;
break;
case CC_GRAB_ROTATE_SERVO:
//Put the servo in position and stop the motor
if(railPosition->GetDistance() >= GRAB_RELEASE_OUT_DISTANCE)
{
extensionArmMotor->Set(MOTOR_STOPPED);
ServoPosition();
candyCaneState = CC_GRAB_BRING_IN;
hookTurnTimer->Reset();
hookTurnTimer->Start();
}
break;
case CC_GRAB_BRING_IN:
//bring in the cc until it gets to the grab distance
if(hookTurnTimer->Get() >= 0.25)
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
candyCaneState = CC_GRAB_END;
hookTurnTimer->Stop();
}
break;
case CC_GRAB_END:
//Turn everything off
if((railPosition->GetDistance() <= grabDistance) || (homeSwitch->Get() == PRESSED))
{
if(homeSwitch->Get() == PRESSED)
{
ResetEncoder();
}
extensionArmMotor->Set(MOTOR_STOPPED);
candyCaneState = CC_IDLE;
}
break;
default:
break;
}
return candyCaneState;
}
void CandyCane_Class::StartRelease()
{
if(candyCaneState == CC_IDLE)
{
candyCaneState = CC_RELEASE_PUSH_OUT;
}
}
//************************************************************************************
//
// Method: Release()
// Parameters: None
// Returns: candyCaneState
// Description: This function is the state machine for releasing a candy cane
// from a tower. It extends the candy cane, turns the servo, and brings in
// the candy cane.
//**************************************************************************************
int CandyCane_Class::Release()
{
switch(candyCaneState)
{
//Pushes the CC to its outer limit
case CC_RELEASE_PUSH_OUT:
extensionArmMotor->Set(MOTOR_FORWARDS);
candyCaneState = CC_RELEASE_ROTATE_SERVO;
break;
//Put the servo into the neutral position
case CC_RELEASE_ROTATE_SERVO:
if(railPosition->GetDistance() >= GRAB_RELEASE_OUT_DISTANCE)
{
ServoNeutral();
hookTurnTimer->Reset();
hookTurnTimer->Start();
candyCaneState = CC_RELEASE_BRING_IN;
}
break;
//Brings the CC into home
case CC_RELEASE_BRING_IN:
if(hookTurnTimer->Get() >= 0.25)
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
hookTurnTimer->Stop();
candyCaneState = CC_RELEASE_END;
}
break;
//Turns everything off
case CC_RELEASE_END:
if((railPosition->GetDistance() <= CC_RETRACT_LIMIT) || (homeSwitch->Get() == PRESSED))
{
if(homeSwitch->Get() == PRESSED)
{
ResetEncoder();
}
extensionArmMotor->Set(MOTOR_STOPPED);
candyCaneState = CC_IDLE;
}
break;
default:
break;
}
return candyCaneState;
}
void CandyCane_Class::StartSafety(double distance)
{
if(candyCaneState == CC_IDLE)
{
candyCaneState = CC_SAFETY_PUSH_OUT;
safetyDistance = distance;
}
}
//***********************************************************************************
//
// Method: Safety()
// Parameters: None
// Returns: candyCaneState
// Description: This function is a state machine for pushing the cc out to it's outer
// limit, and then turns the servo into position
//***********************************************************************************
int CandyCane_Class::Safety()
{
switch(candyCaneState)
{
//Brings the motor out to its limit
case CC_SAFETY_PUSH_OUT:
extensionArmMotor->Set(MOTOR_FORWARDS);
candyCaneState = CC_SAFETY_ROTATE_SERVO;
break;
case CC_SAFETY_ROTATE_SERVO:
if(railPosition->GetDistance() >= safetyDistance)
{
extensionArmMotor->Set(MOTOR_STOPPED);
ServoPosition();
candyCaneState = CC_IDLE;
}
break;
default:
break;
}
return candyCaneState;
}
void CandyCane_Class::StartLeanIn(double leaningDistance)
{
if(candyCaneState == CC_IDLE)
{
candyCaneState = CC_LEAN_IN_LEAN;
leanInDistance = leaningDistance;
}
}
//************************************************************************************
//
// Method: LeanIn()
// Parameters: None
// Returns: candyCaneState
// Description: This function brings in the cc in a more after an initial grab or
// Possibly safety
//**************************************************************************************
int CandyCane_Class::LeanIn()
{
switch(candyCaneState)
{
case CC_LEAN_IN_LEAN:
extensionArmMotor->Set(MOTOR_BACKWARDS);
ServoPosition();
candyCaneState = CC_LEAN_IN_END;
break;
case CC_LEAN_IN_END:
if((railPosition->GetDistance() <= leanInDistance)
|| (homeSwitch->Get() == PRESSED))
{
if(homeSwitch->Get() == PRESSED)
{
ResetEncoder();
}
extensionArmMotor->Set(MOTOR_STOPPED);
candyCaneState = CC_IDLE;
}
break;
default:
break;
}
return candyCaneState;
}
void CandyCane_Class::BringInTower(void)
{
//if(candyCaneDevice->)
#if MANUAL
//twistServo->SetAngle(HOOK_POSITION);
/*if(hookTurnTimer->Get() >= 1)
{*/
if(railPosition->GetDistance() >= CC_RETRACT_LIMIT )
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
}
else if(homeSwitch->Get() == PRESSED)
{
ResetEncoder();
extensionArmMotor->Set(0);
}
else
{
extensionArmMotor->Set(0);
}
//}
#else
if(bringingInTower)
{
twistServo->SetAngle(HOOK_POSITION);
if(hookTurnTimer->Get() >= 1)
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
}
if(railPosition->GetDistance() <= CC_RETRACT_LIMIT)
{
extensionArmMotor->Set(MOTOR_STOPPED);
bringingInTower = false;
}
}
#endif
/*else
{
extensionArmMotor->Set(0);
}*/
}
void CandyCane_Class::BringInCC(void)
{
#if MANUAL
if((railPosition->GetDistance() >= CC_RETRACT_LIMIT))
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
}
else if(homeSwitch->Get() == PRESSED)
{
ResetEncoder();
extensionArmMotor->Set(0);
}
else
{
extensionArmMotor->Set(0);
}
//twistServo->SetAngle(HOOK_NEUTRAL);
#else
if(bringingInCC)
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
twistServo->SetAngle(HOOK_NEUTRAL);
if(railPosition->GetDistance() <= CC_RETRACT_LIMIT)
{
extensionArmMotor->Set(MOTOR_STOPPED);
bringingInCC = false;
}
}
#endif
}
bool CandyCane_Class::PushOut(void)
{
//if(ArmMaxLimit->Get() == 1)
#if MANUAL
if(railPosition->GetDistance() <= CC_EXTEND_LIMIT)
{
extensionArmMotor->Set(MOTOR_FORWARDS);
return true;
}
else
{
extensionArmMotor->Set(0);
return false;
}
//twistServo->SetAngle(HOOK_NEUTRAL);
#else
if(pushingOut)
{
extensionArmMotor->Set(MOTOR_FORWARDS);
twistServo->SetAngle(HOOK_NEUTRAL);
if(railPosition->GetDistance() >= CC_EXTEND_LIMIT)
{
extensionArmMotor->Set(MOTOR_STOPPED);
pushingOut = false;
}
}
#endif
/*else
{
extensionArmMotor->Set(0);
}*/
}
void CandyCane_Class::ServoPosition()
{
twistServo->SetAngle(HOOK_POSITION);
}
void CandyCane_Class::ServoNeutral()
{
twistServo->SetAngle(HOOK_NEUTRAL);
}
void CandyCane_Class::StartBringInTower()
{
if(!bringingInTower && !pushingOut && !bringingInCC)
{
bringingInTower = true;
hookTurnTimer->Reset();
hookTurnTimer->Start();
}
}
void CandyCane_Class::StartBringInCC()
{
if(!bringingInTower && !pushingOut && !bringingInCC)
{
bringingInCC = true;
}
}
void CandyCane_Class::StartPushOut()
{
if(!bringingInTower && !pushingOut && !bringingInCC)
{
pushingOut = true;
}
}
bool CandyCane_Class::BringInOverride()
{
/*if(bringInOverride)
{
if(homeSwitch->Get() == RELEASED)
{
extensionArmMotor->Set(-0.25);
candyCaneState = CC_IDLE;
}
else
{
extensionArmMotor->Set(0);
bringInOverride = false;
}
}*/
//If the homeswitch is released, bring in the CC
if(homeSwitch->Get() == RELEASED)
{
extensionArmMotor->Set(MOTOR_BACKWARDS);
candyCaneState = CC_IDLE;
return true;
}
//Otherwise stop the CC and reset the encoder values
else
{
extensionArmMotor->Set(0);
ResetEncoder();
return false;
}
}
void CandyCane_Class::PushOutOverride()
{
/*if(pushOutOverride)
{
if(homeSwitch->Get() == RELEASED)
{
extensionArmMotor->Set(0.25);
candyCaneState = CC_IDLE;
}
else
{
extensionArmMotor->Set(0);
pushOutOverride = false;
}
}*/
/*if(homeSwitch->Get() == RELEASED)
{
extensionArmMotor->Set(0.25);
candyCaneState = CC_IDLE;
}
else
{
extensionArmMotor->Set(0);
}*/
extensionArmMotor->Set(MOTOR_FORWARDS);
candyCaneState = CC_IDLE;
}
void CandyCane_Class::Stop(void)
{
extensionArmMotor->Set(MOTOR_STOPPED);
candyCaneState = CC_IDLE;
bringingInTower = false;
bringingInCC = false;
pushingOut = false;
}
/*void CandyCane_Class::ClawUp(void)
{
twistServo->Set(0.2);//TODO Depreciate ClawUp(), and ClawDown()
}
void CandyCane_Class::ClawDown(void)
{
twistServo->Set(0.5);
}*/
void CandyCane_Class::ResetEncoder()
{
railPosition->Reset();
}
/*void CandyCane_Class::Grab(void)
{
*****************************************************************************************
int CandyCane_Class::getCandyCaneState(void)
{
return (candyCaneState);
}
int CandyCane_Class::getBarSensor()
{
return (barSensor->GetAverageValue());
}*/
/*int CandyCane_Class::getCaneOutSensor(void)
{
return (ArmMaxLimit->Get());
}
int CandyCane_Class::getCaneInSensor(void)
{
return (ArmMinLimit->Get());
}
int CandyCane_Class::getLightSensor(void)
{
return (lightSensor->GetVoltage());
}*/
int CandyCane_Class::getClawTop(void)
{
return ((int)ArmUpLimit->Get());
}
int CandyCane_Class::getClawBottom(void)
{
return ((int)ArmDownLimit->Get());
}
/*int CandyCane_Class::getClawPos(void)
{
return (twistServo->Get());
}*/
float CandyCane_Class::getServoPos(void)
{
return (twistServo->Get());
}
double CandyCane_Class::getRailPos(void)
{
return (railPosition->GetDistance());
}
/*int CandyCane_Class::getHomeSwitch(void)
{
return (homeSwitch->Get());
}*/
| [
"[email protected]"
] | |
a07dfa96235db46c02868b085645a97ba0e09783 | c935886a521f76fe936b3323f16be43700b71fe4 | /src/mem/protocol/DMARequestType.hh | 1a089443450284b666a1f286cafaf59a968342a3 | [] | no_license | oliverxyy/gem5-source-code-learning | 4dc9c81d08ff29b557570aeb72654f4d8a8fe47e | 6438cf07bd86942d0ed118035d398de254dac412 | refs/heads/master | 2020-04-06T06:56:18.547114 | 2016-09-06T07:22:49 | 2016-09-06T07:22:49 | 65,285,514 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | hh | /** \file DMARequestType.hh
*
* Auto generated C++ code started by /home/oliverxyy/program/gem5-stable/src/mem/slicc/symbols/Type.py:454
*/
#ifndef __DMARequestType_HH__
#define __DMARequestType_HH__
#include <iostream>
#include <string>
// Class definition
/** \enum DMARequestType
* \brief ...
*/
enum DMARequestType {
DMARequestType_FIRST,
DMARequestType_READ = DMARequestType_FIRST, /**< Memory Read */
DMARequestType_WRITE, /**< Memory Write */
DMARequestType_NULL, /**< Invalid */
DMARequestType_NUM
};
// Code to convert from a string to the enumeration
DMARequestType string_to_DMARequestType(const std::string& str);
// Code to convert state to a string
std::string DMARequestType_to_string(const DMARequestType& obj);
// Code to increment an enumeration type
DMARequestType &operator++(DMARequestType &e);
std::ostream& operator<<(std::ostream& out, const DMARequestType& obj);
#endif // __DMARequestType_HH__
| [
"[email protected]"
] | |
f726bcb414a67845f6e6a9a28a2803bb43c8eb56 | 4c457c5d8238f756b7ceedc66fba65b58831cea3 | /BAEKJOON_10844_EasyStairCount/10844_EasyStairCount_main.cpp | cc1446e0d310eea85b497b82547ff9951d5ee15f | [] | no_license | pikacsc/CodingTestPrac | f2a030d23881b8a8d086562ab2502849916819fd | 2e85c4cfd2795ab1e42d1976fa9132cabef7bfa3 | refs/heads/master | 2023-04-07T21:49:48.635654 | 2021-04-25T03:20:17 | 2021-04-25T03:20:17 | 268,752,494 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,406 | cpp | /*
https://www.acmicpc.net/problem/10844
10844
쉬운 계단 수
문제
45656이란 수를 보자.
이 수는 인접한 모든 자리수의 차이가 1이 난다. 이런 수를 계단 수라고 한다.
세준이는 수의 길이가 N인 계단 수가 몇 개 있는지 궁금해졌다.
N이 주어질 때, 길이가 N인 계단 수가 총 몇 개 있는지 구하는 프로그램을 작성하시오. (0으로 시작하는 수는 없다.)
입력
첫째 줄에 N이 주어진다. N은 1보다 크거나 같고, 100보다 작거나 같은 자연수이다.
출력
첫째 줄에 정답을 1,000,000,000으로 나눈 나머지를 출력한다.
예제 입력 1
1
예제 출력 1
9
예제 입력 2
2
예제 출력 2
17
*/
#include <iostream>
using namespace std;
int mod = 1000000000;
int dp[101][101];
int n;
int result;
int main()
{
cin >> n;
for (int i = 1; i <= 9; i++)
dp[1][i] = 1;
for (int i = 2; i <= n; i++)
{
for (int j = 0; j <= 9; j++)
{
if (j == 0)
dp[i][j] = dp[i - 1][j + 1];
else if (j == 9)
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]);
dp[i][j] %= mod;
}
}
for (int i = 0; i <= 9; i++)
{
result = (result + dp[n][i]) % mod;
}
cout << result;
return 0;
} | [
"[email protected]"
] | |
e50aecf92c926efe61cbcdd3fbfeb9a4840fec0c | be3dad0d7608e6becc1f2111127ef31a64a3738b | /CPP/373.cpp | 6204ca736868ca62822f43c2b71fbededa0308ad | [] | no_license | BaggaShivanshu/Leetcode-solutions | fa5ee1156de9cf5560d2bc11a0a1baebe16b1c39 | cab9bedebf2fd97e353977fb7939ded3d3a57c40 | refs/heads/master | 2020-09-23T22:06:40.241499 | 2019-09-30T05:12:56 | 2019-09-30T05:12:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | cpp | // Find K Pairs with Smallest Sums
class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
std::vector<std::vector<int> > ans;
if(nums1.size()<1 || nums2.size()<1)
return ans;
std::sort(nums1.begin(), nums1.end());
std::sort(nums2.begin(), nums2.end());
std::priority_queue<std::pair<int, std::pair<int, int>> , vector<std::pair<int, std::pair<int, int>>>, greater<std::pair<int, std::pair<int, int>>> >mypq; //basically it would have (sum, (i, j));
mypq.push(make_pair(nums1[0]+nums2[0],make_pair(0,0)));
std::set<std::pair<int, int> > setOfElementsInPq;
setOfElementsInPq.insert(std::pair<int, int>(0,0));
int n1= nums1.size();
int n2 = nums2.size();
for(int x = 0 ;x< min(k, n1*n2);x++)
{
std::vector<int> temp;
std::pair<int, std::pair<int, int> > topElement = mypq.top();
mypq.pop();
int sum = topElement.first;
int i = topElement.second.first;
int j = topElement.second.second;
std::cout<<k<<" "<<i<<" "<<j <<"\n";
if(j+1<nums2.size())
if(setOfElementsInPq.count(std::pair<int, int>(i,j+1))==0)
{
mypq.push(make_pair(nums1[i]+nums2[j+1],make_pair(i,j+1)));
setOfElementsInPq.insert(std::pair<int, int>(i,j+1));
}
if(i+1<nums1.size())
if(setOfElementsInPq.count(std::pair<int, int>(i+1,j))==0)
{
mypq.push(make_pair(nums1[i+1]+nums2[j],make_pair(i+1,j)));
setOfElementsInPq.insert(std::pair<int, int>(i+1,j));
}
temp.push_back(nums1[i]);
temp.push_back(nums2[j]);
ans.push_back(temp);
}
return ans;
}
}; | [
"[email protected]"
] | |
c33b9e44e554387ad05167ade24fe27dd0a994a9 | 635fc1f8a7cc3ddf147a74d11a3b92ca4caebe4f | /native/XPThumbnailDialog.h | 61e7bfd40ca902cc16b793726508862815204777 | [
"Apache-2.0"
] | permissive | consulo/windows-file-dialog | a120e39a9d62dc03a3fa38786e2daf15631e02ad | 8c58e3b758e73585848464cfe4e99e22732b4e30 | refs/heads/master | 2021-10-10T17:49:26.353651 | 2021-09-24T19:48:22 | 2021-09-24T19:48:22 | 132,003,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | h | // predefined symbols
//
// XPThumbnailDialog.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// XPThumbnailDialog
// a CFileDialg with default thumbnail mode
#define XLVM_XP_DO_NOT_PERSIST (-1)
#define XLVM_XP_UNDEFINED 0
#define XLVM_XP_ICONS 0x7029
#define XLVM_XP_LIST 0x702B
#define XLVM_XP_DETAILS 0x702C
#define XLVM_XP_THUMBNAILS 0x702D
#define XLVM_XP_TILES 0x702E
#define XLVM_VISTA_DO_NOT_PERSIST (-1)
#define XLVM_VISTA_UNDEFINED 0
#define XLVM_VISTA_DETAILS 0x704B
#define XLVM_VISTA_TILES 0x704C
#define XLVM_VISTA_EXTRA_LARGE_ICONS 0x704D
#define XLVM_VISTA_MEDIUM_ICONS 0x704E
#define XLVM_VISTA_LARGE_ICONS 0x704F
#define XLVM_VISTA_SMALL_ICONS 0x7050
#define XLVM_VISTA_LIST 0x7051
// The following 3 strings can used as filters,
// It can help CFileDialog to display only folders
class XPThumbnailDialog : public CFileDialog
{
DECLARE_DYNAMIC(XPThumbnailDialog)
public:
XPThumbnailDialog(BOOL bOpenFileDialog = TRUE, // TRUE for FileOpen, FALSE for FileSaveAs
LPCTSTR lpszDefExt = NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_EXPLORER|OFN_HIDEREADONLY,
LPCTSTR lpszFilter = NULL,
CWnd* pParentWnd = NULL);
// Attributes
public:
// Dialog Data
//{{AFX_DATA(XPThumbnailDialog)
CListBox m_wndSelectionsList;
BOOL m_bExplorer;
//}}AFX_DATA
// Operations
public:
BOOL SetListViewMode(UINT cmd);
BOOL IsXP();
BOOL IsVista();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(XPThumbnailDialog)
protected:
//}}AFX_VIRTUAL
virtual void OnFolderChange();
virtual void OnFileNameChange();
afx_msg LRESULT OnPostInit(WPARAM wp, LPARAM lp); // the REAL
// initialization
// Implementation
protected:
BOOL m_bSelectMode; // TRUE when in "Selection" mode
//{{AFX_MSG(XPThumbnailDialog)
afx_msg void OnSelectButton();
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
virtual BOOL OnInitDialog();
virtual void OnInitDone();
//}}AFX_MSG
afx_msg void OnHelp();
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
] | |
989fd28eca108739f964c93cbe6ff1d52fad24d9 | 9d94a1fce99d13f2fdb033062b1cce33a6d5b33a | /DE_BlockBreak1.01/ScoreUI.h | 42a7450b96d77429c15ce9b001f623ffe5c8e7d2 | [] | no_license | Hamoruton/BlockBreak | 6789c26959815544674d951c537ff6aff8ea1a1a | 3a334a0518167a3049271ad928f5146f18eab891 | refs/heads/master | 2022-10-09T01:50:27.759310 | 2020-06-07T01:50:29 | 2020-06-07T01:50:29 | 270,159,435 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,071 | h | #pragma once
#ifndef __SCOREUI_H_INCLUDED__
#define __SCOREUI_H_INCLUDED__
struct ID2D1RenderTarget;
struct ID2D1SolidColorBrush;
struct IDWriteTextFormat;
class CSelector;
//================================================================================
// スコアクラス
//================================================================================
class CScoreUI
{
public:
CScoreUI(ID2D1RenderTarget* pRenderTarget);
virtual ~CScoreUI();
void move();
void draw(ID2D1RenderTarget* pRenderTarget);
void SetScore(int score);
int GetScore() const;
void AddScore(int value);
int GetResultScore(int score, int life);
void SetLife(int life);
int GetLife() const;
void ScoreReset();
bool GetGameClear() const { return m_bGameClear; }
void SetGameClear(bool flag) { m_bGameClear = flag; }
protected:
ID2D1SolidColorBrush* m_pScoreBrush;
ID2D1SolidColorBrush* m_pLifeBrush;
IDWriteTextFormat* m_pTextFormat;
int m_iScore;
int m_iResultScore;
int m_iLife;
bool m_bGameClear;
};
#endif // !__SCOREUI_H_INCLUDED__ | [
"[email protected]"
] | |
416d0284e3fa4b6f92dd0b5f3926c26b355b32af | 0aa0427f3efc613489840ce6ae622e0352b07ee1 | /src/timing/calc_invitro_moves.cpp | 329c0a6a0646a81f96a0c83297f9a8fce73e84b4 | [] | no_license | cattigers/SAINT2 | 39173b0dca0705ebeb90c3853d8a337b66889069 | 884d5b22d238540b84ef1966178e90d98dc61ae7 | refs/heads/master | 2020-06-07T09:13:05.587305 | 2017-06-20T13:46:10 | 2017-06-20T13:46:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,390 | cpp | #include <cstdlib> // PG added this
#include <iostream>
#include <string>
#include <cmath>
#include "config.h"
#include "runner.h"
#include "sequence.h"
#include "extender.h"
using namespace std;
// this class can access protected members of class Extender
class Extender_Friend
{
public:
Extender_Friend(Extender *e) : m_extender(e)
{
}
void do_stuff(Sequence &seq, int non_growth_moves, bool dump)
{
m_extender->calculate_num_moves(seq);
double total_ctime = 0.0;
int total_moves = 0;
if (dump)
{
cout << "Length cotrans_moves time\n";
}
for (unsigned n = 0;n < m_extender->m_moves.size();n++)
{
if (m_extender->m_moves[n] != -1)
{
total_moves += m_extender->m_moves[n];
double cotrans_time = pow((double) n, 1.83) / 2890.0 *
m_extender->m_moves[n];
total_ctime += cotrans_time;
if (dump)
{
cout << n << " " << m_extender->m_moves[n]
<< " " << cotrans_time << "\n";
}
}
}
double invitro_move_time = pow((double) seq.length(), 1.85) / 3500.0;
double result = total_ctime / invitro_move_time;
if (dump)
{
cout << "Cotrans moves:\n" << total_moves << "\n";
cout << "Total cotrans time:\n" << total_ctime << "\n";
cout << "In vitro time for one move (length " << seq.length()
<< "):\n"
<< invitro_move_time << "\n";
cout << "Equivalent in vitro moves:\n"
<< (int) (result + 0.5) << "\n";
cout << "Including non-growth moves from config file:\n";
}
cout << (int) (result + non_growth_moves + 0.5) << "\n";
}
private:
Extender *m_extender;
};
void show_usage(const char **argv)
{
cerr << "Usage: " << argv[0] << " config_file [-d]\n\n"
<< "Calculate the equivalent number of in vitro moves for a "
"cotranslational run.\n\n"
"Use \"-d\" to dump all of the moves.\n\n";
}
int main(int argc, const char **argv)
{
if (argc != 2 && argc != 3)
{
show_usage(argv);
exit(1);
}
bool dump = false;
if (argc == 3)
{
if (argv[2][0] != '-')
{
show_usage(argv);
exit(1);
}
else
if (string(argv[2]) == "-d")
{
dump = true;
}
else
{
cerr << argv[0] << ": unknown option " << argv[2] << "\n";
exit(1);
}
}
Config config(2, argv);
Sequence seq(config);
// TO DO: check if is equential
Runner runner(config);
Extender_Friend f(runner.extender());
f.do_stuff(seq, (int) runner.move_limit(), dump);
return 0;
}
| [
"[email protected]"
] | |
7d180bfe6a6bd55426d76aacfc301f63fba1fc09 | 0d0e78c6262417fb1dff53901c6087b29fe260a0 | /ocr/include/tencentcloud/ocr/v20181119/model/QuestionBlockObj.h | 0dc721523eec3cb0a774de33644c22511bd42170 | [
"Apache-2.0"
] | permissive | li5ch/tencentcloud-sdk-cpp | ae35ffb0c36773fd28e1b1a58d11755682ade2ee | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | refs/heads/master | 2022-12-04T15:33:08.729850 | 2020-07-20T00:52:24 | 2020-07-20T00:52:24 | 281,135,686 | 1 | 0 | Apache-2.0 | 2020-07-20T14:14:47 | 2020-07-20T14:14:46 | null | UTF-8 | C++ | false | false | 2,865 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_OCR_V20181119_MODEL_QUESTIONBLOCKOBJ_H_
#define TENCENTCLOUD_OCR_V20181119_MODEL_QUESTIONBLOCKOBJ_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ocr/v20181119/model/QuestionObj.h>
namespace TencentCloud
{
namespace Ocr
{
namespace V20181119
{
namespace Model
{
/**
* 数学试题识别结构化对象
*/
class QuestionBlockObj : public AbstractModel
{
public:
QuestionBlockObj();
~QuestionBlockObj() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取数学试题识别结构化信息数组
* @return QuestionArr 数学试题识别结构化信息数组
*/
std::vector<QuestionObj> GetQuestionArr() const;
/**
* 设置数学试题识别结构化信息数组
* @param QuestionArr 数学试题识别结构化信息数组
*/
void SetQuestionArr(const std::vector<QuestionObj>& _questionArr);
/**
* 判断参数 QuestionArr 是否已赋值
* @return QuestionArr 是否已赋值
*/
bool QuestionArrHasBeenSet() const;
private:
/**
* 数学试题识别结构化信息数组
*/
std::vector<QuestionObj> m_questionArr;
bool m_questionArrHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_OCR_V20181119_MODEL_QUESTIONBLOCKOBJ_H_
| [
"[email protected]"
] | |
4368c46c1be72e830bdc7158a4f13c8a9071f8a3 | 8e9bc0b2842b050c0bf968fa574744422bfe95d5 | /geom_classes.h | 8af5a29ac554ed6098b39aeea8868e8c90bdb1fb | [] | no_license | mpiz/BaseElement | 9cd7471b4926999695dd0aba3f1c444440dc32e2 | 2e7e2d8bd8c87ab60a55c0442a5665d03adaf7de | refs/heads/master | 2021-01-17T07:18:16.958061 | 2015-06-01T13:17:18 | 2015-06-01T13:17:18 | 35,756,791 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | h | #pragma once
#include "macro.h"
#include <fstream>
#include <cmath>
#include <utility>
using namespace std;
class node {
public:
node();
node(double s_x, double s_y, double s_z);
node (double s_n[3]);
double& operator [] (int i);
node& operator = (const node pr);
bool operator < (const node pr);
bool operator > (const node pr);
friend ostream& operator << (ostream& os, node& out_n);
friend istream& operator >> (istream& is, node& inp_n);
double x, y, z;
int number;
};
class point {
public:
point();
point(double s_x, double s_y, double s_z);
point (double s_n[3]);
point(node nd);
double& operator [] (int i);
point& operator = (const point pr);
point& operator = (const node pr);
double x, y, z;
};
class vec3d {
public:
vec3d();
vec3d(double s_x, double s_y, double s_z);
vec3d(point start, point end);
vec3d(node start, node end);
double& operator [] (int i);
double operator * (const vec3d pr);
vec3d operator + (const vec3d pr);
vec3d operator - (const vec3d pr);
bool operator == (const vec3d pr);
bool operator != (const vec3d pr);
friend vec3d operator * (const double a, const vec3d vec);
vec3d operator / (const double a);
friend vec3d operator * (const matrix(3) M, vec3d vec);
vec3d cross(vec3d pr);
double norm();
point to_point();
double x, y, z;
static bool collinear(vec3d a, vec3d b);
};
class edge {
public:
edge();
edge(int sstart, int send);
bool operator == (const edge pr);
int number;
int start();
int end();
private:
pair<int, int> edge_node;
}; | [
"[email protected]"
] | |
0d027d26ec864fb03fad3a82ec4100a2f5ae6e33 | ac5a1cf680b1c523e1473fed364d8ffd71331a18 | /SkillContest3_4/SideCamera.h | 4ae205c0587fec4409a69dd549046c298ad9aaad | [] | no_license | LeeYonggi/SkillContest3_4 | 5ff6f1983b0056967c446eadb3b1f95d6b61e56d | f4e2973e4b0c741f0798607284ff9e13e4d0c89a | refs/heads/master | 2020-05-03T08:34:01.767210 | 2019-04-01T16:35:05 | 2019-04-01T16:35:05 | 178,529,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | h | #pragma once
#include "Camera.h"
class Player;
class SideCamera :
public Camera
{
public:
SideCamera(Player *_player);
virtual ~SideCamera();
private:
Player *player;
public:
virtual void Update() override;
};
| [
"[email protected]"
] | |
054d40ac8870bffcc81aabdbd3c8386ea9901da6 | 545f3d9107e918edb6fc58333f5620e3efa0d24f | /hid/lcddataformatter.h | ffa42178cd60411c68c731db6355994ff7480543 | [] | no_license | ftkalcevic/hidcomp | c0b6639670921e7891ad4ad54b0f3982181e047c | 4e4c255f29b0924afbffab4fc667ed2c5b6ba092 | refs/heads/master | 2021-01-17T12:30:13.839381 | 2019-10-05T22:02:47 | 2019-10-05T22:02:47 | 34,784,858 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,419 | h | // hidcomp/hidconfig, HID device interface for emc
// Copyright (C) 2008, Frank Tkalcevic, www.franksworkshop.com
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef _LCDDATAFORMATTER_H_
#define _LCDDATAFORMATTER_H_
#ifdef _WIN32
#pragma warning(push, 1)
#endif
#include <QString>
#include <QByteArray>
#include <QMap>
#ifdef _WIN32
#pragma warning(pop)
#pragma warning(disable:4251)
#endif
class LCDDataFormatter
{
public:
// newFormatString is a byte array because it is designed to be used with printf which requires a char *
static bool ProcessFormatString( const QString &sFormatString, QByteArray &newFormatString, QString &sDefaultString, QMap<int,QString> &lookupTable );
static QString snprintf( const char *sFmt, ... );
static QString vsnprintf( const char *sFmt, va_list args );
};
#endif
| [
"frankt@e4c7163f-7ddd-7b40-8da7-0e3d6902e64e"
] | frankt@e4c7163f-7ddd-7b40-8da7-0e3d6902e64e |
95d157bff2609030b0dd42e94ae209b388703cf7 | 1a5c10cd88e28d231fe8a9d723c6a2947e8ff54a | /frameworks/runtime-src/Classes/PluginReviewJSHelper.cpp | 4399c466df3a026c8ac7d8979909388b48c39189 | [
"MIT"
] | permissive | arloistale/NumboJumbo | f7a2fb3e89de829f65c72d79cd8c83b6e30033b1 | 308594ecd2cd75c1bc2814b067893f170ec5d8f6 | refs/heads/master | 2023-05-27T12:36:54.052170 | 2018-09-01T19:25:33 | 2018-09-01T19:25:33 | 49,230,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,780 | cpp | #include "PluginReviewJSHelper.h"
#include "PluginReview/PluginReview.h"
#include "SDKBoxJSHelper.h"
extern JSObject* jsb_sdkbox_PluginReview_prototype;
static JSContext* s_cx = nullptr;
class ReviewListenerJS : public sdkbox::ReviewListener {
private:
JSObject* _JSDelegate;
public:
void setJSDelegate(JSObject* delegate) {
_JSDelegate = delegate;
}
JSObject* getJSDelegate() {
return _JSDelegate;
}
void onDisplayAlert() {
invokeDelegate("onDisplayAlert", nullptr, 0, 0);
}
void onDeclineToRate() {
invokeDelegate("onDeclineToRate", nullptr, 0, 0);
}
void onRate() {
invokeDelegate("onRate", nullptr, 0, 0);
}
void onRemindLater() {
invokeDelegate("onRemindLater", nullptr, 0, 0);
}
private:
void invokeDelegate(const char* fName, const char* name, int intVal, int argc) {
if (!s_cx) {
return;
}
JSContext* cx = s_cx;
const char* func_name = fName;
JS::RootedObject obj(cx, _JSDelegate);
JSAutoCompartment ac(cx, obj);
#if defined(MOZJS_MAJOR_VERSION)
#if MOZJS_MAJOR_VERSION >= 33
bool hasAction;
JS::RootedValue retval(cx);
JS::RootedValue func_handle(cx);
#else
bool hasAction;
jsval retval;
JS::RootedValue func_handle(cx);
#endif
#elif defined(JS_VERSION)
JSBool hasAction;
jsval retval;
jsval func_handle;
#endif
jsval dataVal[2];
if (2 == argc) {
dataVal[0] = c_string_to_jsval(cx, name);
dataVal[1] = INT_TO_JSVAL(intVal);
} else if (1 == argc) {
dataVal[0] = c_string_to_jsval(cx, name);
}
if (JS_HasProperty(cx, obj, func_name, &hasAction) && hasAction) {
if(!JS_GetProperty(cx, obj, func_name, &func_handle)) {
return;
}
if(func_handle == JSVAL_VOID) {
return;
}
#if MOZJS_MAJOR_VERSION >= 31
if (0 == argc) {
JS_CallFunctionName(cx, obj, func_name, JS::HandleValueArray::empty(), &retval);
} else {
JS_CallFunctionName(cx, obj, func_name, JS::HandleValueArray::fromMarkedLocation(argc, dataVal), &retval);
}
#else
if (0 == argc) {
JS_CallFunctionName(cx, obj, func_name, 0, nullptr, &retval);
} else {
JS_CallFunctionName(cx, obj, func_name, argc, dataVal, &retval);
}
#endif
}
}
};
#if defined(MOZJS_MAJOR_VERSION)
#if MOZJS_MAJOR_VERSION >= 33
bool js_PluginReviewJS_PluginReview_setListener(JSContext *cx, uint32_t argc, jsval *vp)
#else
bool js_PluginReviewJS_PluginReview_setListener(JSContext *cx, uint32_t argc, jsval *vp)
#endif
#elif defined(JS_VERSION)
JSBool js_PluginReviewJS_PluginReview_setListener(JSContext *cx, uint32_t argc, jsval *vp)
#endif
{
s_cx = cx;
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
if (argc == 1) {
if (!args.get(0).isObject())
{
ok = false;
}
JSObject *tmpObj = args.get(0).toObjectOrNull();
JSB_PRECONDITION2(ok, cx, false, "js_PluginReviewJS_PluginReview_setIAPListener : Error processing arguments");
ReviewListenerJS* wrapper = new ReviewListenerJS();
wrapper->setJSDelegate(tmpObj);
sdkbox::PluginReview::setListener(wrapper);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_PluginReviewJS_PluginReview_setIAPListener : wrong number of arguments");
return false;
}
#if defined(MOZJS_MAJOR_VERSION)
#if MOZJS_MAJOR_VERSION >= 33
void register_all_PluginReviewJS_helper(JSContext* cx, JS::HandleObject global) {
JS::RootedObject pluginObj(cx);
sdkbox::getJsObjOrCreat(cx, global, "sdkbox.PluginReview", &pluginObj);
JS_DefineFunction(cx, pluginObj, "setListener", js_PluginReviewJS_PluginReview_setListener, 1, JSPROP_READONLY | JSPROP_PERMANENT);
}
#else
void register_all_PluginReviewJS_helper(JSContext* cx, JSObject* global) {
JS::RootedObject pluginObj(cx);
sdkbox::getJsObjOrCreat(cx, JS::RootedObject(cx, global), "sdkbox.PluginReview", &pluginObj);
JS_DefineFunction(cx, pluginObj, "setListener", js_PluginReviewJS_PluginReview_setListener, 1, JSPROP_READONLY | JSPROP_PERMANENT);
}
#endif
#elif defined(JS_VERSION)
void register_all_PluginReviewJS_helper(JSContext* cx, JSObject* global) {
jsval pluginVal;
JSObject* pluginObj;
pluginVal = sdkbox::getJsObjOrCreat(cx, global, "sdkbox.PluginReview", &pluginObj);
JS_DefineFunction(cx, pluginObj, "setListener", js_PluginReviewJS_PluginReview_setListener, 1, JSPROP_READONLY | JSPROP_PERMANENT);
}
#endif
| [
"[email protected]"
] | |
0ba854606b2d72e6247da3d29640ecb487dd44a0 | a6e42d81654e9dad9d201aca34e0e5187c209067 | /mainwindow.h | 121c1ce980a3b8c070dc69af88fa52e4752185ab | [] | no_license | zgqzhangguoqi/Qt_smart_elec | 400ab5b7f4bdea1a425e30809ab57bf45682f5b7 | fd681426c49e872cad52630fc0212baf5fee2fde | refs/heads/master | 2021-09-18T17:01:17.789325 | 2018-07-17T05:53:38 | 2018-07-17T05:53:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QMouseEvent>
#include<QPaintEvent>
#include<QtGui>
#include<QLabel>
#include<QDateTime>
#include<QTimer>
#include<QString>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void Paint();
int temp_data[10]={0};
int false_data[10]={28,39,12,8,39,28,19,39,30,26};
//virtual void timerEvent( QTimerEvent *event);
private:
Ui::MainWindow *ui;
QImage image;
int m_nTimerID;
protected:
/*添加自定义方法,paintEvent()
drawImage:设置显示位置
*/
void paintEvent(QPaintEvent *){
QPainter painter(this);
painter.drawImage(40,100,image);
}
private slots:
void timerUpdate(void);
void on_lcd_temp_listen();
void on_lcd_hum_listen();
void on_edit_sun_listen();
void on_radio_auto_clicked();
void on_combox_fan_set();
void on_combox_time_listen();
void on_btn_temp_clicked();
void update_cap();
};
#endif // MAINWINDOW_H
| [
"[email protected]"
] | |
1c4c2c2061192032df8c3aaa6a749c77f92d1a18 | f2a36c754a1916fb6f54e9faa3f5db0070809979 | /include/Logger.hpp | 55e945f57095538ef00df4d4b511b1b25f5a1184 | [] | no_license | ajweeks/BeamHiker | bc75d018d866a7592ea9e884bf47a82344ea0e3c | 1f57a2fd498123a0d0e6e4b12656798126407ae0 | refs/heads/master | 2020-03-26T18:00:48.581066 | 2018-09-06T15:15:04 | 2018-09-06T15:15:04 | 145,192,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | hpp | #pragma once
#include <string>
#include <stdio.h> // For va_list
#include "wtypes.h" // For HANDLE, WORD
void Print(const char* str, ...);
void PrintWarn(const char* str, ...);
void PrintError(const char* str, ...);
void Print(const char* str, va_list argList);
void GetConsoleHandle();
extern bool g_bEnableLogToConsole;
#if _WIN32
extern HANDLE g_ConsoleHandle;
const WORD CONSOLE_COLOR_DEFAULT = 0 | FOREGROUND_INTENSITY;
const WORD CONSOLE_COLOR_WARNING = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
const WORD CONSOLE_COLOR_ERROR = FOREGROUND_RED | FOREGROUND_INTENSITY;
#endif
| [
"[email protected]"
] | |
733561ebcbf05f2dd9377be0b02becd8bc11d69a | 2bda3b6ad09018f6955234c79ad07476017dcfb4 | /cl_dll/vgui_TeamFortressViewport.cpp | abefb962c3b480c6c430adfdd3c8178d368a4add | [] | no_license | mittorn/csdm | e8b49193f1c08b6290f7ef34d3a1a1e530728912 | 9c011acd1fa9145f0f8b7cd9e2e42c95902172c0 | refs/heads/master | 2021-01-10T06:38:28.643569 | 2015-12-28T22:20:30 | 2015-12-28T22:20:30 | 44,879,377 | 2 | 3 | null | 2018-11-05T07:36:40 | 2015-10-24T18:37:42 | C++ | UTF-8 | C++ | false | false | 67,782 | cpp | //=========== (C) Copyright 1996-2002 Valve, L.L.C. All rights reserved. ===========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose: Client DLL VGUI Viewport
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#include<VGUI_Cursor.h>
#include<VGUI_Frame.h>
#include<VGUI_Label.h>
#include<VGUI_Surface.h>
#include<VGUI_BorderLayout.h>
#include<VGUI_Panel.h>
#include<VGUI_ImagePanel.h>
#include<VGUI_Button.h>
#include<VGUI_ActionSignal.h>
#include<VGUI_InputSignal.h>
#include<VGUI_MenuSeparator.h>
#include<VGUI_TextPanel.h>
#include<VGUI_LoweredBorder.h>
#include<VGUI_LineBorder.h>
#include<VGUI_Scheme.h>
#include<VGUI_Font.h>
#include<VGUI_App.h>
#include<VGUI_BuildGroup.h>
#include "hud.h"
#include "cl_util.h"
#include "camera.h"
#include "kbutton.h"
#include "cvardef.h"
#include "usercmd.h"
#include "const.h"
#include "camera.h"
#include "in_defs.h"
#include "parsemsg.h"
#include "pm_shared.h"
#include "../engine/keydefs.h"
#include "demo.h"
#include "demo_api.h"
#include "vgui_int.h"
#include "vgui_TeamFortressViewport.h"
#include "vgui_ServerBrowser.h"
#include "vgui_SpectatorPanel.h"
#include "vgui_ScoreBoard.h"
#include "vgui_ProgressBar.h"
extern int g_iVisibleMouse;
class CCommandMenu;
int g_iPlayerClass;
int g_iTeamNumber;
int g_iUser1;
int g_iUser2;
int g_iUser3;
// Scoreboard positions
#define SBOARD_INDENT_X XRES(104)
#define SBOARD_INDENT_Y YRES(40)
// low-res scoreboard indents
#define SBOARD_INDENT_X_512 30
#define SBOARD_INDENT_Y_512 30
#define SBOARD_INDENT_X_400 0
#define SBOARD_INDENT_Y_400 20
void IN_ResetMouse( void );
extern CMenuPanel *CMessageWindowPanel_Create( const char *szMOTD, const char *szTitle, int iShadeFullscreen, int iRemoveMe, int x, int y, int wide, int tall );
extern float * GetClientColor( int clientIndex );
using namespace vgui;
// Team Colors
int iNumberOfTeamColors = 5;
int iTeamColors[5][3] =
{
{ 255, 170, 0 }, // HL orange (default)
{ 125, 165, 210 }, // Blue
{ 200, 90, 70 }, // Red
{ 225, 205, 45 }, // Yellow
{ 145, 215, 140 }, // Green
};
// Used for Class specific buttons
char *sTFClasses[] =
{
"",
"SCOUT",
"SNIPER",
"SOLDIER",
"DEMOMAN",
"MEDIC",
"HWGUY",
"PYRO",
"SPY",
"ENGINEER",
"CIVILIAN",
};
char *sLocalisedClasses[] =
{
"#Civilian",
"#Scout",
"#Sniper",
"#Soldier",
"#Demoman",
"#Medic",
"#HWGuy",
"#Pyro",
"#Spy",
"#Engineer",
"#Random",
"#Civilian",
};
char *sTFClassSelection[] =
{
"civilian",
"scout",
"sniper",
"soldier",
"demoman",
"medic",
"hwguy",
"pyro",
"spy",
"engineer",
"randompc",
"civilian",
};
int iBuildingCosts[] =
{
BUILD_COST_DISPENSER,
BUILD_COST_SENTRYGUN
};
// This maps class numbers to the Invalid Class bit.
// This is needed for backwards compatability in maps that were finished before
// all the classes were in TF. Hence the wacky sequence.
int sTFValidClassInts[] =
{
0,
TF_ILL_SCOUT,
TF_ILL_SNIPER,
TF_ILL_SOLDIER,
TF_ILL_DEMOMAN,
TF_ILL_MEDIC,
TF_ILL_HVYWEP,
TF_ILL_PYRO,
TF_ILL_SPY,
TF_ILL_ENGINEER,
TF_ILL_RANDOMPC,
};
// Get the name of TGA file, based on GameDir
char* GetVGUITGAName(const char *pszName)
{
int i;
char sz[256];
static char gd[256];
const char *gamedir;
if (ScreenWidth < 640)
i = 320;
else
i = 640;
sprintf(sz, pszName, i);
gamedir = gEngfuncs.pfnGetGameDirectory();
sprintf(gd, "%s/gfx/vgui/%s.tga",gamedir,sz);
return gd;
}
//================================================================
// COMMAND MENU
//================================================================
void CCommandMenu::AddButton( CommandButton *pButton )
{
if (m_iButtons >= MAX_BUTTONS)
return;
m_aButtons[m_iButtons] = pButton;
m_iButtons++;
pButton->setParent( this );
pButton->setFont( Scheme::sf_primary3 );
// give the button a default key binding
if ( m_iButtons < 10 )
{
pButton->setBoundKey( m_iButtons + '0' );
}
else if ( m_iButtons == 10 )
{
pButton->setBoundKey( '0' );
}
}
//-----------------------------------------------------------------------------
// Purpose: Tries to find a button that has a key bound to the input, and
// presses the button if found
// Input : keyNum - the character number of the input key
// Output : Returns true if the command menu should close, false otherwise
//-----------------------------------------------------------------------------
bool CCommandMenu::KeyInput( int keyNum )
{
// loop through all our buttons looking for one bound to keyNum
for ( int i = 0; i < m_iButtons; i++ )
{
if ( !m_aButtons[i]->IsNotValid() )
{
if ( m_aButtons[i]->getBoundKey() == keyNum )
{
// hit the button
if ( m_aButtons[i]->GetSubMenu() )
{
// open the sub menu
gViewPort->SetCurrentCommandMenu( m_aButtons[i]->GetSubMenu() );
return false;
}
else
{
// run the bound command
m_aButtons[i]->fireActionSignal();
return true;
}
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: clears the current menus buttons of any armed (highlighted)
// state, and all their sub buttons
//-----------------------------------------------------------------------------
void CCommandMenu::ClearButtonsOfArmedState( void )
{
for ( int i = 0; i < GetNumButtons(); i++ )
{
m_aButtons[i]->setArmed( false );
if ( m_aButtons[i]->GetSubMenu() )
{
m_aButtons[i]->GetSubMenu()->ClearButtonsOfArmedState();
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pSubMenu -
// Output : CommandButton
//-----------------------------------------------------------------------------
CommandButton *CCommandMenu::FindButtonWithSubmenu( CCommandMenu *pSubMenu )
{
for ( int i = 0; i < GetNumButtons(); i++ )
{
if ( m_aButtons[i]->GetSubMenu() == pSubMenu )
return m_aButtons[i];
}
return NULL;
}
// Recalculate the visible buttons
bool CCommandMenu::RecalculateVisibles( int iYOffset, bool bHideAll )
{
int i, iCurrentY = 0;
int iVisibleButtons = 0;
// Cycle through all the buttons in this menu, and see which will be visible
for (i = 0; i < m_iButtons; i++)
{
int iClass = m_aButtons[i]->GetPlayerClass();
if ( (iClass && iClass != g_iPlayerClass ) || ( m_aButtons[i]->IsNotValid() ) || bHideAll )
{
m_aButtons[i]->setVisible( false );
if ( m_aButtons[i]->GetSubMenu() != NULL )
{
(m_aButtons[i]->GetSubMenu())->RecalculateVisibles( 0, true );
}
}
else
{
// If it's got a submenu, force it to check visibilities
if ( m_aButtons[i]->GetSubMenu() != NULL )
{
if ( !(m_aButtons[i]->GetSubMenu())->RecalculateVisibles( 0 , false ) )
{
// The submenu had no visible buttons, so don't display this button
m_aButtons[i]->setVisible( false );
continue;
}
}
m_aButtons[i]->setVisible( true );
iVisibleButtons++;
}
}
// Set Size
setSize( _size[0], (iVisibleButtons * (m_flButtonSizeY-1)) + 1 );
if ( iYOffset )
{
m_iYOffset = iYOffset;
}
for (i = 0; i < m_iButtons; i++)
{
if ( m_aButtons[i]->isVisible() )
{
if ( m_aButtons[i]->GetSubMenu() != NULL )
(m_aButtons[i]->GetSubMenu())->RecalculateVisibles( iCurrentY + m_iYOffset, false );
// Make sure it's at the right Y position
// m_aButtons[i]->getPos( iXPos, iYPos );
if ( m_iDirection )
{
m_aButtons[i]->setPos( 0, (iVisibleButtons-1) * (m_flButtonSizeY-1) - iCurrentY );
}
else
{
m_aButtons[i]->setPos( 0, iCurrentY );
}
iCurrentY += (m_flButtonSizeY-1);
}
}
return iVisibleButtons?true:false;
}
// Make sure all submenus can fit on the screen
void CCommandMenu::RecalculatePositions( int iYOffset )
{
int iTop;
int iAdjust = 0;
m_iYOffset+= iYOffset;
if ( m_iDirection )
iTop = ScreenHeight - (m_iYOffset + _size[1] );
else
iTop = m_iYOffset;
if ( iTop < 0 )
iTop = 0;
// Calculate if this is going to fit onscreen, and shuffle it up if it won't
int iBottom = iTop + _size[1];
if ( iBottom > ScreenHeight )
{
// Move in increments of button sizes
while (iAdjust < (iBottom - ScreenHeight))
{
iAdjust += m_flButtonSizeY - 1;
}
iTop -= iAdjust;
// Make sure it doesn't move off the top of the screen (the menu's too big to fit it all)
if ( iTop < 0 )
{
iAdjust -= (0 - iTop);
iTop = 0;
}
}
setPos( _pos[0], iTop );
// We need to force all menus below this one to update their positions now, because they
// might have submenus riding off buttons in this menu that have just shifted.
for (int i = 0; i < m_iButtons; i++)
m_aButtons[i]->UpdateSubMenus( iAdjust );
}
// Make this menu and all menus above it in the chain visible
void CCommandMenu::MakeVisible( CCommandMenu *pChildMenu )
{
/*
// Push down the button leading to the child menu
for (int i = 0; i < m_iButtons; i++)
{
if ( (pChildMenu != NULL) && (m_aButtons[i]->GetSubMenu() == pChildMenu) )
{
m_aButtons[i]->setArmed( true );
}
else
{
m_aButtons[i]->setArmed( false );
}
}
*/
setVisible(true);
if (m_pParentMenu)
m_pParentMenu->MakeVisible( this );
}
//================================================================
// CreateSubMenu
CCommandMenu *TeamFortressViewport::CreateSubMenu( CommandButton *pButton, CCommandMenu *pParentMenu, int iYOffset, int iXOffset )
{
int iXPos = 0;
int iYPos = 0;
int iWide = CMENU_SIZE_X;
int iTall = 0;
int iDirection = 0;
if (pParentMenu)
{
iXPos = m_pCurrentCommandMenu->GetXOffset() + (CMENU_SIZE_X - 1) + iXOffset;
iYPos = m_pCurrentCommandMenu->GetYOffset() + iYOffset;
iDirection = pParentMenu->GetDirection();
}
CCommandMenu *pMenu = new CCommandMenu(pParentMenu, iDirection, iXPos, iYPos, iWide, iTall );
pMenu->setParent(this);
pButton->AddSubMenu( pMenu );
pButton->setFont( Scheme::sf_primary3 );
pMenu->m_flButtonSizeY = m_pCurrentCommandMenu->m_flButtonSizeY;
// Create the Submenu-open signal
InputSignal *pISignal = new CMenuHandler_PopupSubMenuInput(pButton, pMenu);
pButton->addInputSignal(pISignal);
// Put a > to show it's a submenu
CImageLabel *pLabel = new CImageLabel( "arrow", CMENU_SIZE_X - SUBMENU_SIZE_X, SUBMENU_SIZE_Y );
pLabel->setParent(pButton);
pLabel->addInputSignal(pISignal);
// Reposition
pLabel->getPos( iXPos, iYPos );
pLabel->setPos( CMENU_SIZE_X - pLabel->getImageWide(), (BUTTON_SIZE_Y - pLabel->getImageTall()) / 2 );
// Create the mouse off signal for the Label too
if (!pButton->m_bNoHighlight)
pLabel->addInputSignal( new CHandler_CommandButtonHighlight(pButton) );
return pMenu;
}
//-----------------------------------------------------------------------------
// Purpose: Makes sure the memory allocated for TeamFortressViewport is nulled out
// Input : stAllocateBlock -
// Output : void *
//-----------------------------------------------------------------------------
void *TeamFortressViewport::operator new( size_t stAllocateBlock )
{
// void *mem = Panel::operator new( stAllocateBlock );
void *mem = ::operator new( stAllocateBlock );
memset( mem, 0, stAllocateBlock );
return mem;
}
//-----------------------------------------------------------------------------
// Purpose: InputSignal handler for the main viewport
//-----------------------------------------------------------------------------
class CViewPortInputHandler : public InputSignal
{
public:
bool bPressed;
CViewPortInputHandler()
{
}
virtual void cursorMoved(int x,int y,Panel* panel) {}
virtual void cursorEntered(Panel* panel) {}
virtual void cursorExited(Panel* panel) {}
virtual void mousePressed(MouseCode code,Panel* panel)
{
if ( code != MOUSE_LEFT )
{
// send a message to close the command menu
// this needs to be a message, since a direct call screws the timing
gEngfuncs.pfnClientCmd( "ForceCloseCommandMenu\n" );
}
}
virtual void mouseReleased(MouseCode code,Panel* panel)
{
}
virtual void mouseDoublePressed(MouseCode code,Panel* panel) {}
virtual void mouseWheeled(int delta,Panel* panel) {}
virtual void keyPressed(KeyCode code,Panel* panel) {}
virtual void keyTyped(KeyCode code,Panel* panel) {}
virtual void keyReleased(KeyCode code,Panel* panel) {}
virtual void keyFocusTicked(Panel* panel) {}
};
//================================================================
TeamFortressViewport::TeamFortressViewport(int x,int y,int wide,int tall) : Panel(x,y,wide,tall), m_SchemeManager(wide,tall)
{
gViewPort = this;
m_iInitialized = false;
m_pTeamMenu = NULL;
m_pClassMenu = NULL;
m_pSpectatorPanel = NULL;
m_pCurrentMenu = NULL;
m_pCurrentCommandMenu = NULL;
Initialize();
addInputSignal( new CViewPortInputHandler );
int r, g, b, a;
Scheme* pScheme = App::getInstance()->getScheme();
// primary text color
// Get the colors
//!! two different types of scheme here, need to integrate
SchemeHandle_t hPrimaryScheme = m_SchemeManager.getSchemeHandle( "Primary Button Text" );
{
// font
pScheme->setFont( Scheme::sf_primary1, m_SchemeManager.getFont(hPrimaryScheme) );
// text color
m_SchemeManager.getFgColor( hPrimaryScheme, r, g, b, a );
pScheme->setColor(Scheme::sc_primary1, r, g, b, a ); // sc_primary1 is non-transparent orange
// background color (transparent black)
m_SchemeManager.getBgColor( hPrimaryScheme, r, g, b, a );
pScheme->setColor(Scheme::sc_primary3, r, g, b, a );
// armed foreground color
m_SchemeManager.getFgArmedColor( hPrimaryScheme, r, g, b, a );
pScheme->setColor(Scheme::sc_secondary2, r, g, b, a );
// armed background color
m_SchemeManager.getBgArmedColor( hPrimaryScheme, r, g, b, a );
pScheme->setColor(Scheme::sc_primary2, r, g, b, a );
//!! need to get this color from scheme file
// used for orange borders around buttons
m_SchemeManager.getBorderColor( hPrimaryScheme, r, g, b, a );
// pScheme->setColor(Scheme::sc_secondary1, r, g, b, a );
pScheme->setColor(Scheme::sc_secondary1, 255*0.7, 170*0.7, 0, 0);
}
// Change the second primary font (used in the scoreboard)
SchemeHandle_t hScoreboardScheme = m_SchemeManager.getSchemeHandle( "Scoreboard Text" );
{
pScheme->setFont(Scheme::sf_primary2, m_SchemeManager.getFont(hScoreboardScheme) );
}
// Change the third primary font (used in command menu)
SchemeHandle_t hCommandMenuScheme = m_SchemeManager.getSchemeHandle( "CommandMenu Text" );
{
pScheme->setFont(Scheme::sf_primary3, m_SchemeManager.getFont(hCommandMenuScheme) );
}
App::getInstance()->setScheme(pScheme);
// VGUI MENUS
CreateTeamMenu();
CreateClassMenu();
CreateSpectatorMenu();
m_pProgressBar = new CProgressBar();
m_pProgressBar->setParent( this );
m_pProgressBar->setVisible( false );
m_pScoreBoard = new CScoreBoard();
m_pScoreBoard->setParent( this );
m_pScoreBoard->setVisible( false );
// Init command menus
m_iNumMenus = 0;
m_iCurrentTeamNumber = m_iUser1 = m_iUser2 = m_iUser3 = 0;
m_StandardMenu = CreateCommandMenu("commandmenu.txt", 0, CMENU_TOP, false, CMENU_SIZE_X, BUTTON_SIZE_Y, 0 );
m_SpectatorOptionsMenu = CreateCommandMenu("spectatormenu.txt", 1, YRES(32), true, CMENU_SIZE_X, BUTTON_SIZE_Y / 2, 0 ); // above bottom bar, flat design
m_SpectatorCameraMenu = CreateCommandMenu("spectcammenu.txt", 1, YRES(32), true, XRES( 200 ), BUTTON_SIZE_Y / 2, ScreenWidth - ( XRES ( 200 ) + 15 ) ); // above bottom bar, flat design
CreateServerBrowser();
//ShowVGUIMenu( 2 );
}
//-----------------------------------------------------------------------------
// Purpose: Called everytime a new level is started. Viewport clears out it's data.
//-----------------------------------------------------------------------------
void TeamFortressViewport::Initialize( void )
{
// Force each menu to Initialize
if (m_pTeamMenu)
{
m_pTeamMenu->Initialize();
}
if (m_pClassMenu)
{
m_pClassMenu->Initialize();
}
if (m_pSpectatorPanel)
{
// Spectator menu doesn't need initializing
m_pSpectatorPanel->setVisible( false );
}
// Make sure all menus are hidden
HideVGUIMenu();
HideCommandMenu();
// Clear out some data
m_iGotAllMOTD = true;
m_iRandomPC = false;
m_flScoreBoardLastUpdated = 0;
m_flSpectatorPanelLastUpdated = 0;
// reset player info
g_iPlayerClass = 0;
g_iTeamNumber = 0;
strcpy(m_sMapName, "");
strcpy(m_szServerName, "");
for (int i = 0; i < 5; i++)
{
m_iValidClasses[i] = 0;
strcpy(m_sTeamNames[i], "");
}
App::getInstance()->setCursorOveride( App::getInstance()->getScheme()->getCursor(Scheme::SchemeCursor::scu_none) );
}
class CException;
//-----------------------------------------------------------------------------
// Purpose: Read the Command Menu structure from the txt file and create the menu.
// Returns Index of menu in m_pCommandMenus
//-----------------------------------------------------------------------------
int TeamFortressViewport::CreateCommandMenu( char * menuFile, int direction, int yOffset, bool flatDesign, float flButtonSizeX, float flButtonSizeY, int xOffset )
{
// COMMAND MENU
// Create the root of this new Command Menu
int newIndex = m_iNumMenus;
m_pCommandMenus[newIndex] = new CCommandMenu(NULL, direction, xOffset, yOffset, flButtonSizeX, 300); // This will be resized once we know how many items are in it
m_pCommandMenus[newIndex]->setParent(this);
m_pCommandMenus[newIndex]->setVisible(false);
m_pCommandMenus[newIndex]->m_flButtonSizeY = flButtonSizeY;
m_pCommandMenus[newIndex]->m_iSpectCmdMenu = direction;
m_iNumMenus++;
// Read Command Menu from the txt file
char token[1024];
char *pfile = (char*)gEngfuncs.COM_LoadFile( menuFile, 5, NULL);
if (!pfile)
{
gEngfuncs.Con_DPrintf( "Unable to open %s\n", menuFile);
SetCurrentCommandMenu( NULL );
return newIndex;
}
try
{
// First, read in the localisation strings
// Detpack strings
gHUD.m_TextMessage.LocaliseTextString( "#DetpackSet_For5Seconds", m_sDetpackStrings[0], MAX_BUTTON_SIZE );
gHUD.m_TextMessage.LocaliseTextString( "#DetpackSet_For20Seconds", m_sDetpackStrings[1], MAX_BUTTON_SIZE );
gHUD.m_TextMessage.LocaliseTextString( "#DetpackSet_For50Seconds", m_sDetpackStrings[2], MAX_BUTTON_SIZE );
// Now start parsing the menu structure
m_pCurrentCommandMenu = m_pCommandMenus[newIndex];
char szLastButtonText[32] = "file start";
pfile = gEngfuncs.COM_ParseFile(pfile, token);
while ( ( strlen ( token ) > 0 ) && ( m_iNumMenus < MAX_MENUS ) )
{
// Keep looping until we hit the end of this menu
while ( token[0] != '}' && ( strlen( token ) > 0 ) )
{
char cText[32] = "";
char cBoundKey[32] = "";
char cCustom[32] = "";
static const int cCommandLength = 128;
char cCommand[cCommandLength] = "";
char szMap[MAX_MAPNAME] = "";
int iPlayerClass = 0;
int iCustom = false;
int iTeamOnly = -1;
int iToggle = 0;
int iButtonY;
bool bGetExtraToken = true;
CommandButton *pButton = NULL;
// We should never be here without a Command Menu
if (!m_pCurrentCommandMenu)
{
gEngfuncs.Con_Printf("Error in %s file after '%s'.\n",menuFile, szLastButtonText );
m_iInitialized = false;
return newIndex;
}
// token should already be the bound key, or the custom name
strncpy( cCustom, token, 32 );
cCustom[31] = '\0';
// See if it's a custom button
if (!strcmp(cCustom, "CUSTOM") )
{
iCustom = true;
// Get the next token
pfile = gEngfuncs.COM_ParseFile(pfile, token);
}
// See if it's a map
else if (!strcmp(cCustom, "MAP") )
{
// Get the mapname
pfile = gEngfuncs.COM_ParseFile(pfile, token);
strncpy( szMap, token, MAX_MAPNAME );
szMap[MAX_MAPNAME-1] = '\0';
// Get the next token
pfile = gEngfuncs.COM_ParseFile(pfile, token);
}
else if ( !strncmp(cCustom, "TEAM", 4) ) // TEAM1, TEAM2, TEAM3, TEAM4
{
// make it a team only button
iTeamOnly = atoi( cCustom + 4 );
// Get the next token
pfile = gEngfuncs.COM_ParseFile(pfile, token);
}
else if ( !strncmp(cCustom, "TOGGLE", 6) )
{
iToggle = true;
// Get the next token
pfile = gEngfuncs.COM_ParseFile(pfile, token);
}
else
{
// See if it's a Class
for (int i = 1; i <= PC_ENGINEER; i++)
{
if ( !strcmp(token, sTFClasses[i]) )
{
// Save it off
iPlayerClass = i;
// Get the button text
pfile = gEngfuncs.COM_ParseFile(pfile, token);
break;
}
}
}
// Get the button bound key
strncpy( cBoundKey, token, 32 );
cText[31] = '\0';
// Get the button text
pfile = gEngfuncs.COM_ParseFile(pfile, token);
strncpy( cText, token, 32 );
cText[31] = '\0';
// save off the last button text we've come across (for error reporting)
strcpy( szLastButtonText, cText );
// Get the button command
pfile = gEngfuncs.COM_ParseFile(pfile, token);
strncpy( cCommand, token, cCommandLength );
cCommand[cCommandLength - 1] = '\0';
iButtonY = (BUTTON_SIZE_Y-1) * m_pCurrentCommandMenu->GetNumButtons();
// Custom button handling
if ( iCustom )
{
pButton = CreateCustomButton( cText, cCommand, iButtonY );
// Get the next token to see if we're a menu
pfile = gEngfuncs.COM_ParseFile(pfile, token);
if ( token[0] == '{' )
{
strcpy( cCommand, token );
}
else
{
bGetExtraToken = false;
}
}
else if ( szMap[0] != '\0' )
{
// create a map button
pButton = new MapButton(szMap, cText, xOffset, iButtonY, flButtonSizeX, flButtonSizeY );
}
else if ( iTeamOnly != -1)
{
// button that only shows up if the player is on team iTeamOnly
pButton = new TeamOnlyCommandButton( iTeamOnly, cText, xOffset, iButtonY, flButtonSizeX, flButtonSizeY, flatDesign );
}
else if ( iToggle && direction == 0 )
{
pButton = new ToggleCommandButton( cCommand, cText, xOffset, iButtonY, flButtonSizeX, flButtonSizeY, flatDesign );
}
else if ( direction == 1 )
{
if ( iToggle )
pButton = new SpectToggleButton( cCommand, cText, xOffset, iButtonY, flButtonSizeX, flButtonSizeY, flatDesign );
else
pButton = new SpectButton( iPlayerClass, cText, xOffset, iButtonY, flButtonSizeX, flButtonSizeY );
}
else
{
// normal button
pButton = new CommandButton( iPlayerClass, cText, xOffset, iButtonY, flButtonSizeX, flButtonSizeY, flatDesign );
}
// add the button into the command menu
if ( pButton )
{
m_pCurrentCommandMenu->AddButton( pButton );
pButton->setBoundKey( cBoundKey[0] );
pButton->setParentMenu( m_pCurrentCommandMenu );
// Override font in CommandMenu
pButton->setFont( Scheme::sf_primary3 );
}
// Find out if it's a submenu or a button we're dealing with
if ( cCommand[0] == '{' )
{
if ( m_iNumMenus >= MAX_MENUS )
{
gEngfuncs.Con_Printf( "Too many menus in %s past '%s'\n",menuFile, szLastButtonText );
}
else
{
// Create the menu
m_pCommandMenus[m_iNumMenus] = CreateSubMenu(pButton, m_pCurrentCommandMenu, iButtonY );
m_pCurrentCommandMenu = m_pCommandMenus[m_iNumMenus];
m_iNumMenus++;
}
}
else if ( !iCustom )
{
// Create the button and attach it to the current menu
if ( iToggle )
pButton->addActionSignal(new CMenuHandler_ToggleCvar(cCommand));
else
pButton->addActionSignal(new CMenuHandler_StringCommand(cCommand));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Get the next token
if ( bGetExtraToken )
{
pfile = gEngfuncs.COM_ParseFile(pfile, token);
}
}
// Move back up a menu
m_pCurrentCommandMenu = m_pCurrentCommandMenu->GetParentMenu();
pfile = gEngfuncs.COM_ParseFile(pfile, token);
}
}
catch( CException *e )
{
e;
//e->Delete();
e = NULL;
m_iInitialized = false;
return newIndex;
}
SetCurrentMenu( NULL );
SetCurrentCommandMenu( NULL );
gEngfuncs.COM_FreeFile( pfile );
m_iInitialized = true;
return newIndex;
}
//-----------------------------------------------------------------------------
// Purpose: Creates all the class choices under a spy's disguise menus, and
// maps a command to them
// Output : CCommandMenu
//-----------------------------------------------------------------------------
CCommandMenu *TeamFortressViewport::CreateDisguiseSubmenu( CommandButton *pButton, CCommandMenu *pParentMenu, const char *commandText, int iYOffset, int iXOffset )
{
// create the submenu, under which the class choices will be listed
CCommandMenu *pMenu = CreateSubMenu( pButton, pParentMenu, iYOffset, iXOffset );
m_pCommandMenus[m_iNumMenus] = pMenu;
m_iNumMenus++;
// create the class choice buttons
for ( int i = PC_SCOUT; i <= PC_ENGINEER; i++ )
{
CommandButton *pDisguiseButton = new CommandButton( CHudTextMessage::BufferedLocaliseTextString( sLocalisedClasses[i] ), 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y );
char sz[256];
sprintf(sz, "%s %d", commandText, i );
pDisguiseButton->addActionSignal(new CMenuHandler_StringCommand(sz));
pMenu->AddButton( pDisguiseButton );
}
return pMenu;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pButtonText -
// *pButtonName -
// Output : CommandButton
//-----------------------------------------------------------------------------
CommandButton *TeamFortressViewport::CreateCustomButton( char *pButtonText, char *pButtonName, int iYOffset )
{
CommandButton *pButton = NULL;
CCommandMenu *pMenu = NULL;
// ChangeTeam
if ( !strcmp( pButtonName, "!CHANGETEAM" ) )
{
// ChangeTeam Submenu
pButton = new CommandButton(pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
// Create the submenu
pMenu = CreateSubMenu(pButton, m_pCurrentCommandMenu, iYOffset );
m_pCommandMenus[m_iNumMenus] = pMenu;
m_iNumMenus++;
// ChangeTeam buttons
for (int i = 0; i < 4; i++)
{
char sz[256];
sprintf(sz, "jointeam %d", i+1);
m_pTeamButtons[i] = new TeamButton(i+1, "teamname", 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
m_pTeamButtons[i]->addActionSignal(new CMenuHandler_StringCommandWatch( sz ));
pMenu->AddButton( m_pTeamButtons[i] );
}
// Auto Assign button
m_pTeamButtons[4] = new TeamButton(5, gHUD.m_TextMessage.BufferedLocaliseTextString( "#Team_AutoAssign" ), 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
m_pTeamButtons[4]->addActionSignal(new CMenuHandler_StringCommand( "jointeam 5" ));
pMenu->AddButton( m_pTeamButtons[4] );
// Spectate button
m_pTeamButtons[5] = new SpectateButton( CHudTextMessage::BufferedLocaliseTextString( "#Menu_Spectate" ), 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y, false);
m_pTeamButtons[5]->addActionSignal(new CMenuHandler_StringCommand( "spectate" ));
pMenu->AddButton( m_pTeamButtons[5] );
}
// ChangeClass
else if ( !strcmp( pButtonName, "!CHANGECLASS" ) )
{
// Create the Change class menu
pButton = new ClassButton(-1, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y, false);
// ChangeClass Submenu
pMenu = CreateSubMenu(pButton, m_pCurrentCommandMenu, iYOffset );
m_pCommandMenus[m_iNumMenus] = pMenu;
m_iNumMenus++;
for (int i = PC_SCOUT; i <= PC_RANDOM; i++ )
{
char sz[256];
// ChangeClass buttons
CHudTextMessage::LocaliseTextString( sLocalisedClasses[i], sz, 256 );
ClassButton *pClassButton = new ClassButton( i, sz, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y, false);
sprintf(sz, "%s", sTFClassSelection[i]);
pClassButton->addActionSignal(new CMenuHandler_StringCommandClassSelect(sz));
pMenu->AddButton( pClassButton );
}
}
// Map Briefing
else if ( !strcmp( pButtonName, "!MAPBRIEFING" ) )
{
pButton = new CommandButton(pButtonText, 0, BUTTON_SIZE_Y * m_pCurrentCommandMenu->GetNumButtons(), CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_TextWindow(MENU_MAPBRIEFING));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Class Descriptions
else if ( !strcmp( pButtonName, "!CLASSDESC" ) )
{
pButton = new ClassButton(0, pButtonText, 0, BUTTON_SIZE_Y * m_pCurrentCommandMenu->GetNumButtons(), CMENU_SIZE_X, BUTTON_SIZE_Y, false);
pButton->addActionSignal(new CMenuHandler_TextWindow(MENU_CLASSHELP));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!SERVERINFO" ) )
{
pButton = new ClassButton(0, pButtonText, 0, BUTTON_SIZE_Y * m_pCurrentCommandMenu->GetNumButtons(), CMENU_SIZE_X, BUTTON_SIZE_Y, false);
pButton->addActionSignal(new CMenuHandler_TextWindow(MENU_INTRO));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Spy abilities
else if ( !strcmp( pButtonName, "!SPY" ) )
{
pButton = new DisguiseButton( 0, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y );
}
// Feign
else if ( !strcmp( pButtonName, "!FEIGN" ) )
{
pButton = new FeignButton(FALSE, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand( "feign" ));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Feign Silently
else if ( !strcmp( pButtonName, "!FEIGNSILENT" ) )
{
pButton = new FeignButton(FALSE, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand( "sfeign" ));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Stop Feigning
else if ( !strcmp( pButtonName, "!FEIGNSTOP" ) )
{
pButton = new FeignButton(TRUE, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand( "feign" ));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Disguise
else if ( !strcmp( pButtonName, "!DISGUISEENEMY" ) )
{
// Create the disguise enemy button, which active only if there are 2 teams
pButton = new DisguiseButton(DISGUISE_TEAM2, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
CreateDisguiseSubmenu( pButton, m_pCurrentCommandMenu, "disguise_enemy", iYOffset);
}
else if ( !strcmp( pButtonName, "!DISGUISEFRIENDLY" ) )
{
// Create the disguise friendly button, which active only if there are 1 or 2 teams
pButton = new DisguiseButton(DISGUISE_TEAM1 | DISGUISE_TEAM2, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
CreateDisguiseSubmenu( pButton, m_pCurrentCommandMenu, "disguise_friendly", iYOffset );
}
else if ( !strcmp( pButtonName, "!DISGUISE" ) )
{
// Create the Disguise button
pButton = new DisguiseButton( DISGUISE_TEAM3 | DISGUISE_TEAM4, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
CCommandMenu *pDisguiseMenu = CreateSubMenu( pButton, m_pCurrentCommandMenu, iYOffset );
m_pCommandMenus[m_iNumMenus] = pDisguiseMenu;
m_iNumMenus++;
// Disguise Enemy submenu buttons
for ( int i = 1; i <= 4; i++ )
{
// only show the 4th disguise button if we have 4 teams
m_pDisguiseButtons[i] = new DisguiseButton( ((i < 4) ? DISGUISE_TEAM3 : 0) | DISGUISE_TEAM4, "Disguise", 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pDisguiseMenu->AddButton( m_pDisguiseButtons[i] );
m_pDisguiseButtons[i]->setParentMenu( pDisguiseMenu );
char sz[256];
sprintf( sz, "disguise %d", i );
CreateDisguiseSubmenu( m_pDisguiseButtons[i], pDisguiseMenu, sz, iYOffset, CMENU_SIZE_X - 1 );
}
}
// Start setting a Detpack
else if ( !strcmp( pButtonName, "!DETPACKSTART" ) )
{
// Detpack Submenu
pButton = new DetpackButton(2, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
// Create the submenu
pMenu = CreateSubMenu(pButton, m_pCurrentCommandMenu, iYOffset );
m_pCommandMenus[m_iNumMenus] = pMenu;
m_iNumMenus++;
// Set detpack buttons
CommandButton *pDetButton;
pDetButton = new CommandButton(m_sDetpackStrings[0], 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pDetButton->addActionSignal(new CMenuHandler_StringCommand("detstart 5"));
pMenu->AddButton( pDetButton );
pDetButton = new CommandButton(m_sDetpackStrings[1], 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pDetButton->addActionSignal(new CMenuHandler_StringCommand("detstart 20"));
pMenu->AddButton( pDetButton );
pDetButton = new CommandButton(m_sDetpackStrings[2], 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pDetButton->addActionSignal(new CMenuHandler_StringCommand("detstart 50"));
pMenu->AddButton( pDetButton );
}
// Stop setting a Detpack
else if ( !strcmp( pButtonName, "!DETPACKSTOP" ) )
{
pButton = new DetpackButton(1, pButtonText, 0, BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand( "detstop" ));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Engineer building
else if ( !strcmp( pButtonName, "!BUILD" ) )
{
// only appears if the player is an engineer, and either they have built something or have enough metal to build
pButton = new BuildButton( BUILDSTATE_BASE, 0, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
}
else if ( !strcmp( pButtonName, "!BUILDSENTRY" ) )
{
pButton = new BuildButton( BUILDSTATE_CANBUILD, BuildButton::SENTRYGUN, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("build 2"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!BUILDDISPENSER" ) )
{
pButton = new BuildButton( BUILDSTATE_CANBUILD, BuildButton::DISPENSER, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("build 1"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!ROTATESENTRY180" ) )
{
pButton = new BuildButton( BUILDSTATE_HASBUILDING, BuildButton::SENTRYGUN, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("rotatesentry180"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!ROTATESENTRY" ) )
{
pButton = new BuildButton( BUILDSTATE_HASBUILDING, BuildButton::SENTRYGUN, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("rotatesentry"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!DISMANTLEDISPENSER" ) )
{
pButton = new BuildButton( BUILDSTATE_HASBUILDING, BuildButton::DISPENSER, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("dismantle 1"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!DISMANTLESENTRY" ) )
{
pButton = new BuildButton( BUILDSTATE_HASBUILDING, BuildButton::SENTRYGUN, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("dismantle 2"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!DETONATEDISPENSER" ) )
{
pButton = new BuildButton( BUILDSTATE_HASBUILDING, BuildButton::DISPENSER, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("detdispenser"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
else if ( !strcmp( pButtonName, "!DETONATESENTRY" ) )
{
pButton = new BuildButton( BUILDSTATE_HASBUILDING, BuildButton::SENTRYGUN, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("detsentry"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
// Stop building
else if ( !strcmp( pButtonName, "!BUILDSTOP" ) )
{
pButton = new BuildButton( BUILDSTATE_BUILDING, 0, pButtonText, 0, BUTTON_SIZE_Y * 2, CMENU_SIZE_X, BUTTON_SIZE_Y);
pButton->addActionSignal(new CMenuHandler_StringCommand("build"));
// Create an input signal that'll popup the current menu
pButton->addInputSignal( new CMenuHandler_PopupSubMenuInput(pButton, m_pCurrentCommandMenu) );
}
return pButton;
}
void TeamFortressViewport::ToggleServerBrowser()
{
if (!m_iInitialized)
return;
if ( !m_pServerBrowser )
return;
if ( m_pServerBrowser->isVisible() )
{
m_pServerBrowser->setVisible( false );
}
else
{
m_pServerBrowser->setVisible( true );
}
UpdateCursorState();
}
//=======================================================================
void TeamFortressViewport::ShowCommandMenu(int menuIndex)
{
if (!m_iInitialized)
return;
//Already have a menu open.
if ( m_pCurrentMenu )
return;
// is the command menu open?
if ( m_pCurrentCommandMenu == m_pCommandMenus[menuIndex] )
{
HideCommandMenu();
return;
}
// Not visible while in intermission
if ( gHUD.m_iIntermission )
return;
// Recalculate visible menus
UpdateCommandMenu( menuIndex );
HideVGUIMenu();
SetCurrentCommandMenu( m_pCommandMenus[menuIndex] );
m_flMenuOpenTime = gHUD.m_flTime;
UpdateCursorState();
// get command menu parameters
for ( int i = 2; i < gEngfuncs.Cmd_Argc(); i++ )
{
const char *param = gEngfuncs.Cmd_Argv( i - 1 );
if ( param )
{
if ( m_pCurrentCommandMenu->KeyInput(param[0]) )
{
// kill the menu open time, since the key input is final
HideCommandMenu();
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles the key input of "-commandmenu"
// Input :
//-----------------------------------------------------------------------------
void TeamFortressViewport::InputSignalHideCommandMenu()
{
if (!m_iInitialized)
return;
// if they've just tapped the command menu key, leave it open
if ( (m_flMenuOpenTime + 0.3) > gHUD.m_flTime )
return;
HideCommandMenu();
}
//-----------------------------------------------------------------------------
// Purpose: Hides the command menu
//-----------------------------------------------------------------------------
void TeamFortressViewport::HideCommandMenu()
{
if (!m_iInitialized)
return;
if ( m_pCommandMenus[m_StandardMenu] )
{
m_pCommandMenus[m_StandardMenu]->ClearButtonsOfArmedState();
}
if ( m_pCommandMenus[m_SpectatorOptionsMenu] )
{
m_pCommandMenus[m_SpectatorOptionsMenu]->ClearButtonsOfArmedState();
}
if ( m_pCommandMenus[m_SpectatorCameraMenu] )
{
m_pCommandMenus[m_SpectatorCameraMenu]->ClearButtonsOfArmedState();
}
m_flMenuOpenTime = 0.0f;
SetCurrentCommandMenu( NULL );
UpdateCursorState();
}
//-----------------------------------------------------------------------------
// Purpose: Bring up the scoreboard
//-----------------------------------------------------------------------------
void TeamFortressViewport::ShowScoreBoard( void )
{
if (m_pScoreBoard)
{
m_pScoreBoard->setVisible( true );
UpdateCursorState();
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns true if the scoreboard is up
//-----------------------------------------------------------------------------
bool TeamFortressViewport::IsScoreBoardVisible( void )
{
if (m_pScoreBoard)
return m_pScoreBoard->isVisible();
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Hide the scoreboard
//-----------------------------------------------------------------------------
void TeamFortressViewport::HideScoreBoard( void )
{
// Prevent removal of scoreboard during intermission
if ( gHUD.m_iIntermission )
return;
if (m_pScoreBoard)
{
m_pScoreBoard->setVisible( false );
GetClientVoiceMgr()->StopSquelchMode();
UpdateCursorState();
}
}
//-----------------------------------------------------------------------------
// Purpose: Activate's the player special ability
// called when the player hits their "special" key
//-----------------------------------------------------------------------------
void TeamFortressViewport::InputPlayerSpecial( void )
{
if (!m_iInitialized)
return;
if ( g_iPlayerClass == PC_ENGINEER || g_iPlayerClass == PC_SPY )
{
ShowCommandMenu( gViewPort->m_StandardMenu );
if ( m_pCurrentCommandMenu )
{
m_pCurrentCommandMenu->KeyInput( '7' );
}
}
else
{
// if it's any other class, just send the command down to the server
ClientCmd( "_special" );
}
}
// Set the submenu of the Command Menu
void TeamFortressViewport::SetCurrentCommandMenu( CCommandMenu *pNewMenu )
{
for (int i = 0; i < m_iNumMenus; i++)
m_pCommandMenus[i]->setVisible(false);
m_pCurrentCommandMenu = pNewMenu;
if (m_pCurrentCommandMenu)
m_pCurrentCommandMenu->MakeVisible( NULL );
}
void TeamFortressViewport::UpdateCommandMenu(int menuIndex)
{
m_pCommandMenus[menuIndex]->RecalculateVisibles( 0, false );
m_pCommandMenus[menuIndex]->RecalculatePositions( 0 );
}
void COM_FileBase ( const char *in, char *out);
void TeamFortressViewport::UpdateSpectatorPanel()
{
m_iUser1 = g_iUser1;
m_iUser2 = g_iUser2;
m_iUser3 = g_iUser3;
if (!m_pSpectatorPanel)
return;
if ( g_iUser1 && gHUD.m_pCvarDraw->value && !gHUD.m_iIntermission) // don't draw in dev_overview mode
{
char bottomText[128];
char helpString2[128];
char tempString[128];
char * name;
int player = 0;
// check if spectator combinations are still valid
gHUD.m_Spectator.CheckSettings();
if ( !m_pSpectatorPanel->isVisible() )
{
m_pSpectatorPanel->setVisible( true ); // show spectator panel, but
m_pSpectatorPanel->ShowMenu( false ); // dsiable all menus/buttons
_snprintf( tempString, sizeof( tempString ) - 1, "%c%s", HUD_PRINTCENTER, CHudTextMessage::BufferedLocaliseTextString( "#Spec_Duck" ) );
tempString[ sizeof( tempString ) - 1 ] = '\0';
gHUD.m_TextMessage.MsgFunc_TextMsg( NULL, strlen( tempString ) + 1, tempString );
}
sprintf(bottomText,"#Spec_Mode%d", g_iUser1 );
sprintf(helpString2,"#Spec_Mode%d", g_iUser1 );
if ( gEngfuncs.IsSpectateOnly() )
strcat(helpString2, " - HLTV");
// check if we're locked onto a target, show the player's name
if ( (g_iUser2 > 0) && (g_iUser2 <= gEngfuncs.GetMaxClients()) && (g_iUser1 != OBS_ROAMING) )
{
player = g_iUser2;
}
// special case in free map and inset off, don't show names
if ( (g_iUser1 == OBS_MAP_FREE) && !gHUD.m_Spectator.m_pip->value )
name = NULL;
else
name = g_PlayerInfoList[player].name;
// create player & health string
if ( player && name )
{
strcpy( bottomText, name );
}
// in first person mode colorize player names
if ( (g_iUser1 == OBS_IN_EYE) && player )
{
float * color = GetClientColor( player );
int r = color[0]*255;
int g = color[1]*255;
int b = color[2]*255;
// set team color, a bit transparent
m_pSpectatorPanel->m_BottomMainLabel->setFgColor(r,g,b,0);
}
else
{ // restore GUI color
m_pSpectatorPanel->m_BottomMainLabel->setFgColor( 143, 143, 54, 0 );
}
// add sting auto if we are in auto directed mode
if ( gHUD.m_Spectator.m_autoDirector->value )
{
char tempString[128];
sprintf(tempString, "#Spec_Auto %s", helpString2);
strcpy( helpString2, tempString );
}
m_pSpectatorPanel->m_BottomMainLabel->setText( CHudTextMessage::BufferedLocaliseTextString( bottomText ) );
// update extra info field
char szText[64];
if ( gEngfuncs.IsSpectateOnly() )
{
// in HLTV mode show number of spectators
_snprintf( szText, 63, "%s: %d", CHudTextMessage::BufferedLocaliseTextString( "#Spectators" ), gHUD.m_Spectator.m_iSpectatorNumber );
}
else
{
// otherwise show map name
char szMapName[64];
COM_FileBase( gEngfuncs.pfnGetLevelName(), szMapName );
_snprintf ( szText, 63, "%s: %s",CHudTextMessage::BufferedLocaliseTextString( "#Spec_Map" ), szMapName );
}
szText[63] = 0;
m_pSpectatorPanel->m_ExtraInfo->setText ( szText );
/*
int timer = (int)( gHUD.m_roundTimer.m_flTimeEnd - gHUD.m_flTime );
if ( timer < 0 )
timer = 0;
_snprintf ( szText, 63, "%d:%02d\n", (timer / 60), (timer % 60) );
szText[63] = 0;
m_pSpectatorPanel->m_CurrentTime->setText( szText ); */
// update spectator panel
gViewPort->m_pSpectatorPanel->Update();
}
else
{
if ( m_pSpectatorPanel->isVisible() )
{
m_pSpectatorPanel->setVisible( false );
m_pSpectatorPanel->ShowMenu( false ); // dsiable all menus/buttons
}
}
m_flSpectatorPanelLastUpdated = gHUD.m_flTime + 1.0; // update every seconds
}
//======================================================================
void TeamFortressViewport::CreateServerBrowser( void )
{
m_pServerBrowser = new ServerBrowser( 0, 0, ScreenWidth, ScreenHeight );
m_pServerBrowser->setParent(this);
m_pServerBrowser->setVisible(false);
}
//======================================================================
// Set the VGUI Menu
void TeamFortressViewport::SetCurrentMenu( CMenuPanel *pMenu )
{
m_pCurrentMenu = pMenu;
if ( m_pCurrentMenu )
{
// Don't open menus in demo playback
if ( gEngfuncs.pDemoAPI->IsPlayingback() )
return;
m_pCurrentMenu->Open();
}
}
//================================================================
// Text Window
CMenuPanel* TeamFortressViewport::CreateTextWindow( int iTextToShow )
{
char sz[256];
char *cText;
char *pfile = NULL;
static const int MAX_TITLE_LENGTH = 32;
char cTitle[MAX_TITLE_LENGTH];
if ( iTextToShow == SHOW_MOTD )
{
if (!m_szServerName || !m_szServerName[0])
strcpy( cTitle, "CSDM" );
else
strncpy( cTitle, m_szServerName, MAX_TITLE_LENGTH );
cTitle[MAX_TITLE_LENGTH-1] = 0;
cText = m_szMOTD;
}
else if ( iTextToShow == SHOW_MAPBRIEFING )
{
// Get the current mapname, and open it's map briefing text
if (m_sMapName && m_sMapName[0])
{
strcpy( sz, "maps/");
strcat( sz, m_sMapName );
strcat( sz, ".txt" );
}
else
{
const char *level = gEngfuncs.pfnGetLevelName();
if (!level)
return NULL;
strcpy( sz, level );
char *ch = strchr( sz, '.' );
*ch = '\0';
strcat( sz, ".txt" );
// pull out the map name
strcpy( m_sMapName, level );
ch = strchr( m_sMapName, '.' );
if ( ch )
{
*ch = 0;
}
ch = strchr( m_sMapName, '/' );
if ( ch )
{
// move the string back over the '/'
memmove( m_sMapName, ch+1, strlen(ch)+1 );
}
}
pfile = (char*)gEngfuncs.COM_LoadFile( sz, 5, NULL );
if (!pfile)
return NULL;
cText = pfile;
strncpy( cTitle, m_sMapName, MAX_TITLE_LENGTH );
cTitle[MAX_TITLE_LENGTH-1] = 0;
}
else if ( iTextToShow == SHOW_CLASSDESC )
{
switch ( g_iPlayerClass )
{
case PC_SCOUT: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_scout" );
CHudTextMessage::LocaliseTextString( "#Title_scout", cTitle, MAX_TITLE_LENGTH ); break;
case PC_SNIPER: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_sniper" );
CHudTextMessage::LocaliseTextString( "#Title_sniper", cTitle, MAX_TITLE_LENGTH ); break;
case PC_SOLDIER: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_soldier" );
CHudTextMessage::LocaliseTextString( "#Title_soldier", cTitle, MAX_TITLE_LENGTH ); break;
case PC_DEMOMAN: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_demoman" );
CHudTextMessage::LocaliseTextString( "#Title_demoman", cTitle, MAX_TITLE_LENGTH ); break;
case PC_MEDIC: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_medic" );
CHudTextMessage::LocaliseTextString( "#Title_medic", cTitle, MAX_TITLE_LENGTH ); break;
case PC_HVYWEAP: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_hwguy" );
CHudTextMessage::LocaliseTextString( "#Title_hwguy", cTitle, MAX_TITLE_LENGTH ); break;
case PC_PYRO: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_pyro" );
CHudTextMessage::LocaliseTextString( "#Title_pyro", cTitle, MAX_TITLE_LENGTH ); break;
case PC_SPY: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_spy" );
CHudTextMessage::LocaliseTextString( "#Title_spy", cTitle, MAX_TITLE_LENGTH ); break;
case PC_ENGINEER: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_engineer" );
CHudTextMessage::LocaliseTextString( "#Title_engineer", cTitle, MAX_TITLE_LENGTH ); break;
case PC_CIVILIAN: cText = CHudTextMessage::BufferedLocaliseTextString( "#Help_civilian" );
CHudTextMessage::LocaliseTextString( "#Title_civilian", cTitle, MAX_TITLE_LENGTH ); break;
default:
return NULL;
}
if ( g_iPlayerClass == PC_CIVILIAN )
{
sprintf(sz, "classes/long_civilian.txt");
}
else
{
sprintf(sz, "classes/long_%s.txt", sTFClassSelection[ g_iPlayerClass ]);
}
char *pfile = (char*)gEngfuncs.COM_LoadFile( sz, 5, NULL );
if (pfile)
{
cText = pfile;
}
}
else if ( iTextToShow == SHOW_SPECHELP )
{
CHudTextMessage::LocaliseTextString( "#Spec_Help_Title", cTitle, MAX_TITLE_LENGTH );
cTitle[MAX_TITLE_LENGTH-1] = 0;
char *pfile = CHudTextMessage::BufferedLocaliseTextString( "#Spec_Help_Text" );
if ( pfile )
{
cText = pfile;
}
}
// if we're in the game (ie. have selected a class), flag the menu to be only grayed in the dialog box, instead of full screen
CMenuPanel *pMOTDPanel = CMessageWindowPanel_Create( cText, cTitle, g_iPlayerClass == PC_UNDEFINED, false, 0, 0, ScreenWidth, ScreenHeight );
pMOTDPanel->setParent( this );
if ( pfile )
gEngfuncs.COM_FreeFile( pfile );
return pMOTDPanel;
}
//================================================================
// VGUI Menus
void TeamFortressViewport::ShowVGUIMenu( int iMenu )
{
CMenuPanel *pNewMenu = NULL;
// Don't open menus in demo playback
if ( gEngfuncs.pDemoAPI->IsPlayingback() )
return;
// Don't open any menus except the MOTD during intermission
// MOTD needs to be accepted because it's sent down to the client
// after map change, before intermission's turned off
if ( gHUD.m_iIntermission && iMenu != MENU_INTRO )
return;
// Don't create one if it's already in the list
if (m_pCurrentMenu)
{
CMenuPanel *pMenu = m_pCurrentMenu;
while (pMenu != NULL)
{
if (pMenu->GetMenuID() == iMenu)
return;
pMenu = pMenu->GetNextMenu();
}
}
switch ( iMenu )
{
case MENU_TEAM:
pNewMenu = ShowTeamMenu();
break;
// Map Briefing removed now that it appears in the team menu
case MENU_MAPBRIEFING:
pNewMenu = CreateTextWindow( SHOW_MAPBRIEFING );
break;
case MENU_INTRO:
pNewMenu = CreateTextWindow( SHOW_MOTD );
break;
case MENU_CLASSHELP:
pNewMenu = CreateTextWindow( SHOW_CLASSDESC );
break;
case MENU_SPECHELP:
pNewMenu = CreateTextWindow( SHOW_SPECHELP );
break;
case MENU_CLASS:
pNewMenu = ShowClassMenu();
break;
default:
break;
}
if (!pNewMenu)
return;
// Close the Command Menu if it's open
HideCommandMenu();
pNewMenu->SetMenuID( iMenu );
pNewMenu->SetActive( true );
pNewMenu->setParent(this);
// See if another menu is visible, and if so, cache this one for display once the other one's finished
if (m_pCurrentMenu)
{
if ( m_pCurrentMenu->GetMenuID() == MENU_CLASS && iMenu == MENU_TEAM )
{
CMenuPanel *temp = m_pCurrentMenu;
m_pCurrentMenu->Close();
m_pCurrentMenu = pNewMenu;
m_pCurrentMenu->SetNextMenu( temp );
m_pCurrentMenu->Open();
UpdateCursorState();
}
else
{
m_pCurrentMenu->SetNextMenu( pNewMenu );
}
}
else
{
m_pCurrentMenu = pNewMenu;
m_pCurrentMenu->Open();
UpdateCursorState();
}
}
// Removes all VGUI Menu's onscreen
void TeamFortressViewport::HideVGUIMenu()
{
while (m_pCurrentMenu)
{
HideTopMenu();
}
}
// Remove the top VGUI menu, and bring up the next one
void TeamFortressViewport::HideTopMenu()
{
if (m_pCurrentMenu)
{
// Close the top one
m_pCurrentMenu->Close();
// Bring up the next one
gViewPort->SetCurrentMenu( m_pCurrentMenu->GetNextMenu() );
}
UpdateCursorState();
}
// Return TRUE if the HUD's allowed to print text messages
bool TeamFortressViewport::AllowedToPrintText( void )
{
// Prevent text messages when fullscreen menus are up
if ( m_pCurrentMenu && g_iPlayerClass == 0 )
{
int iId = m_pCurrentMenu->GetMenuID();
if ( iId == MENU_TEAM || iId == MENU_CLASS || iId == MENU_INTRO || iId == MENU_CLASSHELP )
return FALSE;
}
return TRUE;
}
//======================================================================================
// TEAM MENU
//======================================================================================
// Bring up the Team selection Menu
CMenuPanel* TeamFortressViewport::ShowTeamMenu()
{
// Don't open menus in demo playback
if ( gEngfuncs.pDemoAPI->IsPlayingback() )
return NULL;
m_pTeamMenu->Reset();
return m_pTeamMenu;
}
void TeamFortressViewport::CreateTeamMenu()
{
// Create the panel
m_pTeamMenu = new CTeamMenuPanel(100, false, 0, 0, ScreenWidth, ScreenHeight);
m_pTeamMenu->setParent( this );
m_pTeamMenu->setVisible( false );
}
//======================================================================================
// CLASS MENU
//======================================================================================
// Bring up the Class selection Menu
CMenuPanel* TeamFortressViewport::ShowClassMenu()
{
// Don't open menus in demo playback
if ( gEngfuncs.pDemoAPI->IsPlayingback() )
return NULL;
m_pClassMenu->Reset();
return m_pClassMenu;
}
void TeamFortressViewport::CreateClassMenu()
{
// Create the panel
m_pClassMenu = new CClassMenuPanel(100, false, 0, 0, ScreenWidth, ScreenHeight);
m_pClassMenu->setParent(this);
m_pClassMenu->setVisible( false );
}
//======================================================================================
//======================================================================================
// SPECTATOR MENU
//======================================================================================
// Spectator "Menu" explaining the Spectator buttons
void TeamFortressViewport::CreateSpectatorMenu()
{
// Create the Panel
m_pSpectatorPanel = new SpectatorPanel(0, 0, ScreenWidth, ScreenHeight);
m_pSpectatorPanel->setParent(this);
m_pSpectatorPanel->setVisible(false);
m_pSpectatorPanel->Initialize();
}
//======================================================================================
// UPDATE HUD SECTIONS
//======================================================================================
// We've got an update on player info
// Recalculate any menus that use it.
void TeamFortressViewport::UpdateOnPlayerInfo()
{
if (m_pTeamMenu)
m_pTeamMenu->Update();
if (m_pClassMenu)
m_pClassMenu->Update();
}
void TeamFortressViewport::UpdateCursorState()
{
// Need cursor if any VGUI window is up
if ( m_pSpectatorPanel->m_menuVisible || m_pCurrentMenu || m_pTeamMenu->isVisible() || m_pServerBrowser->isVisible() || GetClientVoiceMgr()->IsInSquelchMode() )
{
g_iVisibleMouse = true;
App::getInstance()->setCursorOveride( App::getInstance()->getScheme()->getCursor(Scheme::SchemeCursor::scu_arrow) );
return;
}
else if ( m_pCurrentCommandMenu )
{
// commandmenu doesn't have cursor if hud_capturemouse is turned off
if ( gHUD.m_pCvarStealMouse->value != 0.0f )
{
g_iVisibleMouse = true;
App::getInstance()->setCursorOveride( App::getInstance()->getScheme()->getCursor(Scheme::SchemeCursor::scu_arrow) );
return;
}
}
// Don't reset mouse in demo playback
if ( !gEngfuncs.pDemoAPI->IsPlayingback() )
{
IN_ResetMouse();
}
g_iVisibleMouse = false;
App::getInstance()->setCursorOveride( App::getInstance()->getScheme()->getCursor(Scheme::SchemeCursor::scu_none) );
}
void TeamFortressViewport::UpdateHighlights()
{
if (m_pCurrentCommandMenu)
m_pCurrentCommandMenu->MakeVisible( NULL );
}
void TeamFortressViewport::GetAllPlayersInfo( void )
{
for ( int i = 1; i < MAX_PLAYERS; i++ )
GetPlayerInfo( i, &g_PlayerInfoList[i] );
}
void TeamFortressViewport::paintBackground()
{
// See if the command menu is visible and needs recalculating due to some external change
if ( g_iTeamNumber != m_iCurrentTeamNumber )
{
UpdateCommandMenu( m_StandardMenu );
if ( m_pClassMenu )
{
m_pClassMenu->Update();
}
m_iCurrentTeamNumber = g_iTeamNumber;
}
if ( g_iPlayerClass != m_iCurrentPlayerClass )
{
UpdateCommandMenu( m_StandardMenu );
m_iCurrentPlayerClass = g_iPlayerClass;
}
// See if the Spectator Menu needs to be update
if ( ( g_iUser1 != m_iUser1 || g_iUser2 != m_iUser2 ) ||
( m_flSpectatorPanelLastUpdated < gHUD.m_flTime ) )
{
UpdateSpectatorPanel();
}
int extents[4];
getAbsExtents(extents[0],extents[1],extents[2],extents[3]);
VGui_ViewportPaintBackground(extents);
}
//================================================================
// Input Handler for Drag N Drop panels
void CDragNDropHandler::cursorMoved(int x,int y,Panel* panel)
{
if(m_bDragging)
{
App::getInstance()->getCursorPos(x,y);
m_pPanel->setPos(m_iaDragOrgPos[0]+(x-m_iaDragStart[0]),m_iaDragOrgPos[1]+(y-m_iaDragStart[1]));
if(m_pPanel->getParent()!=null)
{
m_pPanel->getParent()->repaint();
}
}
}
void CDragNDropHandler::mousePressed(MouseCode code,Panel* panel)
{
int x,y;
App::getInstance()->getCursorPos(x,y);
m_bDragging=true;
m_iaDragStart[0]=x;
m_iaDragStart[1]=y;
m_pPanel->getPos(m_iaDragOrgPos[0],m_iaDragOrgPos[1]);
App::getInstance()->setMouseCapture(panel);
m_pPanel->setDragged(m_bDragging);
m_pPanel->requestFocus();
}
void CDragNDropHandler::mouseReleased(MouseCode code,Panel* panel)
{
m_bDragging=false;
m_pPanel->setDragged(m_bDragging);
App::getInstance()->setMouseCapture(null);
}
//================================================================
// Number Key Input
bool TeamFortressViewport::SlotInput( int iSlot )
{
// If there's a menu up, give it the input
if ( m_pCurrentMenu )
return m_pCurrentMenu->SlotInput( iSlot );
return FALSE;
}
// Direct Key Input
int TeamFortressViewport::KeyInput( int down, int keynum, const char *pszCurrentBinding )
{
// Enter gets out of Spectator Mode by bringing up the Team Menu
if (m_iUser1 && gEngfuncs.Con_IsVisible() == false )
{
if ( down && (keynum == K_ENTER || keynum == K_KP_ENTER) )
ShowVGUIMenu( MENU_TEAM );
}
// Open Text Window?
if (m_pCurrentMenu && gEngfuncs.Con_IsVisible() == false)
{
int iMenuID = m_pCurrentMenu->GetMenuID();
// Get number keys as Input for Team/Class menus
if (iMenuID == MENU_TEAM || iMenuID == MENU_CLASS)
{
// Escape gets you out of Team/Class menus if the Cancel button is visible
if ( keynum == K_ESCAPE )
{
if ( (iMenuID == MENU_TEAM && g_iTeamNumber) || (iMenuID == MENU_CLASS && g_iPlayerClass) )
{
HideTopMenu();
return 0;
}
}
for (int i = '0'; i <= '9'; i++)
{
if ( down && (keynum == i) )
{
SlotInput( i - '0' );
return 0;
}
}
}
// Grab enter keys to close TextWindows
if ( down && (keynum == K_ENTER || keynum == K_KP_ENTER || keynum == K_SPACE || keynum == K_ESCAPE) )
{
if ( iMenuID == MENU_MAPBRIEFING || iMenuID == MENU_INTRO || iMenuID == MENU_CLASSHELP )
{
HideTopMenu();
return 0;
}
}
// Grab jump key on Team Menu as autoassign
if ( pszCurrentBinding && down && !strcmp(pszCurrentBinding, "+jump") )
{
if (iMenuID == MENU_TEAM)
{
m_pTeamMenu->SlotInput(5);
return 0;
}
}
}
// if we're in a command menu, try hit one of it's buttons
if ( down && m_pCurrentCommandMenu )
{
// Escape hides the command menu
if ( keynum == K_ESCAPE )
{
HideCommandMenu();
return 0;
}
// only trap the number keys
if ( keynum >= '0' && keynum <= '9' )
{
if ( m_pCurrentCommandMenu->KeyInput(keynum) )
{
// a final command has been issued, so close the command menu
HideCommandMenu();
}
return 0;
}
}
return 1;
}
//================================================================
// Message Handlers
int TeamFortressViewport::MsgFunc_ValClass(const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
for (int i = 0; i < 5; i++)
m_iValidClasses[i] = READ_SHORT();
// Force the menu to update
UpdateCommandMenu( m_StandardMenu );
return 1;
}
int TeamFortressViewport::MsgFunc_TeamNames(const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
m_iNumberOfTeams = READ_BYTE();
for (int i = 0; i < m_iNumberOfTeams; i++)
{
int teamNum = i + 1;
gHUD.m_TextMessage.LocaliseTextString( READ_STRING(), m_sTeamNames[teamNum], MAX_TEAMNAME_SIZE );
// Set the team name buttons
if (m_pTeamButtons[i])
m_pTeamButtons[i]->setText( m_sTeamNames[teamNum] );
// range check this value...m_pDisguiseButtons[5];
if ( teamNum < 5 )
{
// Set the disguise buttons
if ( m_pDisguiseButtons[teamNum] )
m_pDisguiseButtons[teamNum]->setText( m_sTeamNames[teamNum] );
}
}
// Update the Team Menu
if (m_pTeamMenu)
m_pTeamMenu->Update();
return 1;
}
int TeamFortressViewport::MsgFunc_Feign(const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
m_iIsFeigning = READ_BYTE();
// Force the menu to update
UpdateCommandMenu( m_StandardMenu );
return 1;
}
int TeamFortressViewport::MsgFunc_Detpack(const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
m_iIsSettingDetpack = READ_BYTE();
// Force the menu to update
UpdateCommandMenu( m_StandardMenu );
return 1;
}
int TeamFortressViewport::MsgFunc_VGUIMenu(const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
int iMenu = READ_BYTE();
// Map briefing includes the name of the map (because it's sent down before the client knows what map it is)
if (iMenu == MENU_MAPBRIEFING)
{
strncpy( m_sMapName, READ_STRING(), sizeof(m_sMapName) );
m_sMapName[ sizeof(m_sMapName) - 1 ] = '\0';
}
// Bring up the menu6
ShowVGUIMenu( iMenu );
return 1;
}
int TeamFortressViewport::MsgFunc_MOTD( const char *pszName, int iSize, void *pbuf )
{
if (m_iGotAllMOTD)
m_szMOTD[0] = 0;
BEGIN_READ( pbuf, iSize );
m_iGotAllMOTD = READ_BYTE();
int roomInArray = sizeof(m_szMOTD) - strlen(m_szMOTD) - 1;
strncat( m_szMOTD, READ_STRING(), roomInArray >= 0 ? roomInArray : 0 );
m_szMOTD[ sizeof(m_szMOTD)-1 ] = '\0';
// don't show MOTD for HLTV spectators
if ( m_iGotAllMOTD && !gEngfuncs.IsSpectateOnly() )
{
ShowVGUIMenu( MENU_INTRO );
}
return 1;
}
int TeamFortressViewport::MsgFunc_BuildSt( const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
m_iBuildState = READ_BYTE();
// Force the menu to update
UpdateCommandMenu( m_StandardMenu );
return 1;
}
int TeamFortressViewport::MsgFunc_RandomPC( const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
m_iRandomPC = READ_BYTE();
return 1;
}
int TeamFortressViewport::MsgFunc_ServerName( const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
strncpy( m_szServerName, READ_STRING(), MAX_SERVERNAME_LENGTH );
return 1;
}
int TeamFortressViewport::MsgFunc_ScoreInfo( const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
short cl = READ_BYTE();
short frags = READ_SHORT();
short deaths = READ_SHORT();
short spectator = READ_SHORT();
short teamnumber = READ_SHORT();
g_PlayerExtraInfo[cl].frags = frags;
g_PlayerExtraInfo[cl].deaths = deaths;
g_IsSpectator[cl] = spectator;
g_PlayerExtraInfo[cl].teamnumber = teamnumber;
UpdateOnPlayerInfo();
return 1;
}
int TeamFortressViewport::MsgFunc_AllowSpec( const char *pszName, int iSize, void *pbuf )
{
BEGIN_READ( pbuf, iSize );
m_iAllowSpectators = READ_BYTE();
// Force the menu to update
UpdateCommandMenu( m_StandardMenu );
// If the team menu is up, update it too
if (m_pTeamMenu)
m_pTeamMenu->Update();
return 1;
}
| [
"[email protected]"
] | |
ed65ba93100cf082db46347ab2de911a11fe3171 | 1de3f3f31775d0b2fef7695933b2b3a611d6d657 | /Breakout/Source/ECS/Entities/EntityManager.cpp | 647a91676fbf6bed802273886ed3ec4fcfbce2c4 | [] | no_license | labramusic/Breakout | 4b1c32952226d220bbedba0183094d61fbc009ad | 4515e004c94d14f5b2781348bef76165730b57df | refs/heads/master | 2023-06-25T19:42:00.747727 | 2021-07-27T15:15:57 | 2021-07-27T15:15:57 | 335,380,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | cpp | #include "EntityManager.hpp"
#include <iostream>
namespace breakout
{
EntityManager::EntityManager() : nextId(1) {}
EntityManager::~EntityManager()
{
std::cout << "calling destructor of entity manager" << std::endl;
}
Entity *EntityManager::GetEntityByTag(const std::string &tag)
{
for (std::unique_ptr<Entity> &entity : entities)
{
if (entity && entity->IsActive() && entity->getTag() == tag)
return entity.get();
}
return nullptr;
}
void EntityManager::Refresh()
{
for (std::unique_ptr<Entity> &entity : entities)
{
if (entity && !entity->IsActive())
{
removeEntityComponents(*entity);
entity.reset();
}
}
}
void EntityManager::removeEntityComponents(Entity &entity)
{
for (auto it = componentsByClass.begin(); it != componentsByClass.end(); ++it) {
auto entityComponent = it->second.find(entity.getId());
if (entityComponent != it->second.end())
{
it->second.erase(entityComponent);
}
}
}
EntityID EntityManager::generateNewId()
{
if (nextId < MAX_ENTITIES)
{
return nextId++;
}
for (EntityID i = 1; i < MAX_ENTITIES; ++i)
{
if (!entities[i])
{
return i;
}
}
// no available ids
return 0;
}
Entity &EntityManager::createEntity(const std::string &tag)
{
const EntityID id = generateNewId();
Entity *entity = new Entity(id, tag);
std::unique_ptr<Entity> uPtr{ entity };
entities[id] = std::move(uPtr);
return *entity;
}
} | [
"[email protected]"
] | |
40f40e309debc5b379248bd2cf1f8db2b741dea6 | d9934fe0bb63e8f377a930ff45673e313c3aad8a | /hal/python/bindings/metavision_hal_bindings.cpp | 2b91a1926676832f9a1bf86185d70e6b63ea1fb0 | [] | no_license | HutEight/openeb | 461e47932a62922ad096173315dd3ae128fc8528 | 08b7ed3132b4babe732f7becc66ee373919bc7e8 | refs/heads/main | 2023-05-06T00:17:27.466110 | 2021-05-31T06:56:27 | 2021-05-31T06:56:27 | 372,335,807 | 0 | 0 | null | 2021-05-30T23:38:05 | 2021-05-30T23:38:04 | null | UTF-8 | C++ | false | false | 2,731 | cpp | /**********************************************************************************************************************
* Copyright (c) Prophesee S.A. *
* *
* 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. *
**********************************************************************************************************************/
#ifdef _WIN32
#define MODULE_NAME metavision_hal_internal
#else
#define MODULE_NAME metavision_hal
#endif
#include <pybind11/pybind11.h>
#include "metavision/utils/pybind/deprecation_warning_exception.h"
#include "hal_python_binder.h"
#include "metavision/hal/device/device.h"
namespace py = pybind11;
namespace Metavision {
namespace detail {
std::vector<std::function<void(py::module &, py::class_<Device, std::shared_ptr<Device>> &)>> &
get_device_facility_getters_cbs() {
static std::vector<std::function<void(py::module &, py::class_<Device, std::shared_ptr<Device>> &)>> s_vcb_device;
return s_vcb_device;
}
} /* namespace detail */
} // namespace Metavision
PYBIND11_MODULE(MODULE_NAME, m) {
PyEval_InitThreads();
try {
py::module::import("metavision_sdk_base");
} catch (const std::exception &e) {
std::cerr << "Exception Raised while loading metavision_sdk_base: " << e.what() << std::endl;
throw(e);
}
// Register the translation for DeprecationWarningException
py::register_exception<Metavision::DeprecationWarningException>(m, "Deprecated");
Metavision::export_python_bindings<Metavision::metavision_hal>(m);
// Export device and its facilities getter :
auto device_python = py::class_<Metavision::Device, std::shared_ptr<Metavision::Device>>(m, "Device");
const auto &facilities_adders = Metavision::detail::get_device_facility_getters_cbs();
for (auto &f : facilities_adders) {
f(m, device_python);
}
}
| [
"[email protected]"
] | |
cfc65871b169afcf1de7f433e263aa67bb2fc8fb | 0c2df436d549eb254304ccb10c16481464c61495 | /AaronEngine/src/MusicBuffer.h | 8ab82a607a97d3e8adc70aee96f18b3c785748c1 | [] | no_license | abrom010/AaronEngine | 29adb8f78a29ff818673eccd9ecd29bfebc5d6d0 | 3ccb4d674e685559ec7c2d04cc22761a1e78f0ce | refs/heads/master | 2023-06-22T14:10:11.986421 | 2021-07-23T20:22:07 | 2021-07-23T20:22:07 | 382,748,969 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h | #pragma once
#include <AL\al.h>
#include <sndfile.h>
namespace AaronEngine {
class MusicBuffer {
public:
void Play();
//void Pause();
//void Stop();
void UpdateBufferStream();
ALint getSource();
MusicBuffer(const char* filename);
~MusicBuffer();
void Update();
private:
ALuint p_Source;
static const int BUFFER_SAMPLES = 8192;
static const int NUM_BUFFERS = 4;
ALuint p_Buffers[NUM_BUFFERS];
SNDFILE* p_SndFile;
SF_INFO p_Sfinfo;
short* p_Membuf;
ALenum p_Format;
ALint state;
MusicBuffer() = delete;
};
}
| [
"[email protected]"
] | |
ae8502801a0faf1210b4041d3d0e3a00c66ca477 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/PhysicsAnalysis/D3PDMaker/D3PDMakerTest/src/Obj1Obj2MultiAssociationTool.h | b3b5f049009f6fbebb382768dff7f01d91949af1 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | h | // This file's extension implies that it's C, but it's really -*- C++ -*-.
/*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// $Id$
/**
* @file D3PDMakerTest/src/Obj1Obj2MultiAssociationTool.h
* @author scott snyder <[email protected]>
* @date Jan, 2010
* @brief Test code: associate from an Obj1 to a set of Obj2.
*/
#ifndef D3PDMAKERTEST_OBJ1OBJ2MULTIASSOCIATIONTOOL_H
#define D3PDMAKERTEST_OBJ1OBJ2MULTIASSOCIATIONTOOL_H
#include "D3PDMakerUtils/MultiAssociationTool.h"
#include "D3PDMakerTest/Obj1.h"
namespace D3PDTest {
class Obj1;
class Obj2;
/**
* @brief Test code: associate from an Obj1 to a set of Obj2.
*/
class Obj1Obj2MultiAssociationTool
: public D3PD::MultiAssociationTool<Obj1, Obj2>
{
public:
typedef D3PD::MultiAssociationTool<Obj1, Obj2> Base;
/**
* @brief Standard Gaudi tool constructor.
* @param type The name of the tool type.
* @param name The tool name.
* @param parent The tool's Gaudi parent.
*/
Obj1Obj2MultiAssociationTool (const std::string& type,
const std::string& name,
const IInterface* parent);
/**
* @brief Start the iteration for a new association.
* @param p The object from which to associate.
*/
virtual StatusCode reset (const Obj1& p);
/**
* @brief Return a pointer to the next element in the association.
*
* Return 0 when the association has been exhausted.
*/
virtual const Obj2* next ();
private:
int m_which;
std::vector<Obj2>::const_iterator m_it;
std::vector<Obj2>::const_iterator m_end;
};
} // namespace D3PDTest
#endif // not D3PDMAKERTEST_OBJ1OBJ2MULTIASSOCIATIONTOOL_H
| [
"[email protected]"
] | |
2598d32c1cd7a09c35863a89559bac969c2b3f71 | e4c865809ec17692b6805df50a7d589094fb7c2f | /libutils/include/Debug.h | eb23232785f7c52e8077ba5b119656203980577a | [] | no_license | zcl/Mercury-Project | 5634cd7b94cb3e7cd1f4c11c692c4a54445b5810 | 8806f2fde5fa66b13bf88540a60f05a72b7fb56a | refs/heads/master | 2023-06-21T09:17:46.716309 | 2021-05-11T03:00:50 | 2021-05-11T05:44:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,455 | h | /*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _LIBS_UTILS_DEBUG_H_
#define _LIBS_UTILS_DEBUG_H_
#include <stdint.h>
#include <sys/types.h>
namespace Mercury {
// ---------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
const char* stringForIndent(int32_t indentLevel);
typedef void (*debugPrintFunc)(void* cookie, const char* txt);
void printTypeCode(uint32_t typeCode,
debugPrintFunc func = 0, void* cookie = 0);
void printHexData(int32_t indent, const void *buf, size_t length,
size_t bytesPerLine=16, int32_t singleLineBytesCutoff=16,
size_t alignment=0, bool cArrayStyle=false,
debugPrintFunc func = 0, void* cookie = 0);
#ifdef __cplusplus
}
#endif
// ---------------------------------------------------------------------------
}; // namespace Mercury
#endif // _LIBS_UTILS_DEBUG_H_
| [
"[email protected]"
] | |
fd3caa26002446fef51fbf2c22bd639793bfb896 | 6b2679182dd37329e2340ce787f412f9aae75901 | /practices/nocop/stl/vect.cpp | 3e972ed23aed06445e95b3103d592b4d26c0bb4c | [] | no_license | RWTHsniper/projects | d6a30c311f5edd516985e1eb302897e22ac08597 | 7e6a368d0d3cbefca7c9c265bc66b09ac9a3fb5d | refs/heads/master | 2022-06-12T22:31:07.598776 | 2022-06-04T14:07:26 | 2022-06-04T14:07:26 | 155,676,232 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,778 | cpp | #include <iostream>
#include <vector>
// g++ vect.cpp -std=c++11 -o v
class Cat{
public:
explicit Cat (int age): mAge{age}{}
void speak() const{
std::cout << "meow~" << mAge << std::endl;
}
private:
int mAge;
};
class Cat2{
public:
explicit Cat2 (std::string name, int age): mName{std::move(name)},mAge{age}{}
void speak() const{
std::cout << "meow~" << mName << " " << mAge << std::endl;
}
private:
std::string mName;
int mAge;
};
class Cat4{
public:
explicit Cat4 (std::string name): mName{std::move(name)}{
std::cout << mName << "Cat constructor" << std::endl;
}
~Cat4() noexcept // no exception
{
std::cout << mName << "~Cat()" << std::endl;
}
Cat4(const Cat4& other): mName(other.mName)
{
// compiler tries to copy instead of move by default to avoid exceptions
std::cout << mName << "copy constructor" << std::endl;
}
Cat4(Cat4&& other) noexcept: mName{std::move(other.mName)}
{
std::cout << mName << "move Constructor" << std::endl;
}
private:
std::string mName;
};
int main()
{
// vector: container for dynamic array
// when nums disappears in stack, automatically heap mem is freed
// std::vector<int> nums(5); // heap memory
std::vector<int> nums{1,2,3,4};
nums.emplace_back(5);
std::cout << nums.size() << std::endl;
nums.pop_back(); // reduce size
std::cout << nums.size() << std::endl;
for(std::size_t idx=0; idx<nums.size(); idx++){
std::cout << nums[idx] << std::endl;
}
for(auto itr=nums.begin(); itr != nums.end(); itr++){
std::cout << (*itr) << std::endl;
}
// ranged for
for(const int & num: nums){
std::cout << num << std::endl;
}
std::vector<Cat> cats;
cats.emplace_back(Cat(1));
cats.emplace_back(Cat(1));
cats.emplace_back(Cat(1));
cats.emplace_back(Cat(1));
cats.emplace_back(Cat(1));
for(const auto & cat : cats){
cat.speak();
}
std::vector<int> nums2(10000,1);
nums.emplace_back(2);
nums.pop_back();
// vector
// random access O(1)
// insertion or removal of elements at the end O(1)
std::vector<int> nums3(10000,1);
nums3.emplace_back(2);
nums3.pop_back();
// linear in the distance to the end of the vector O(n)
nums3.emplace(nums3.begin(),3); // to put 3 at the beginning, move every element
nums3.erase(nums3.begin());
std::vector<Cat2> cats2;
cats2.emplace_back(Cat2{"cat0",0}); // unnecessary move operations
cats2.emplace_back(Cat2{"cat1",1});
cats2.emplace_back("kitty",2); // just pass arguments for the constructor to avoid declaring temporary variable. Directly declare an object in the vector.
// Cat& cat = cats2.emplace_back("kitty2",2); // c++17
for (const auto& cat : cats2){
cat.speak();
}
/* lecture 4
reserve: reserve capacity to avoid having additional cost to expand a vector
emplace_back costs move and copy
*/
std::vector<Cat4> cats4;
// cats4.reserve(2); // The best way
cats4.emplace_back("Kitty");
cats4.emplace_back("nabi"); // Kitty is moved because nabi is inserted
/* lecture 5
vector for loop
How to check performance?
auto start = std::chrono::high_resolution_clock::now();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end-start;
std::cout << "idx Loop:" << diff.count() << "s\n"
*/
std::cout << "how many elements?" << std::endl;
std::size_t n;
std::cin >> n;
std::vector<int> numsA(n,1);
std::vector<int> numsB(n,1);
std::vector<int> numsC(n,1);
//index based
for(std::size_t idx=0; idx<numsA.size(); idx++)
{
numsA[idx] *= 2;
}
//iterator based
for(auto itr = numsB.begin(); itr != numsB.end(); itr++)
{
(*itr) *= 2;
}
//range based loop
for(auto & num : numsC)
{
num *= 2;
}
// The case where only index based should be used
// If emplace_back is called, the entire vector moves for extension.
// If the size of a vector is changing, index-based should be used
std::vector<int> nums4{0,1,0,1};
//index based
for(std::size_t idx=0; idx<nums4.size(); idx++)
{
if (nums4[idx]==0)
{
nums4.emplace_back(2);
}
}
//iterator based
for(auto itr = nums4.begin(); itr != nums4.end(); itr++)
{
if( (*itr) == 0)
{
nums4.emplace_back(2);
}
}
//range based loop
for(auto & num : nums4)
{
if (num == 0)
{
nums4.emplace_back(2);
}
}
/*
Lecture 5
*/
return 0;
} | [
"[email protected]"
] | |
271315c3e087b7107ca66f725d22a6ec8cf4dbd5 | 847ea2a7310af937a2330e3bf3faae3f04596e7f | /aws-cpp-sdk-transcribestreaming/include/aws/transcribestreaming/model/Item.h | ed928cef8cc7d05a20377fc37dfdc03cc1616981 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | SammyEnigma/aws-sdk-cpp | c8e94f2cd7f58554f321df58b7e97acd1f1481d3 | bd00fe8d76e2a774c6342f659b49d4458658f4c3 | refs/heads/master | 2021-06-15T05:38:13.952172 | 2021-04-16T19:45:32 | 2021-04-16T19:45:32 | 184,485,849 | 0 | 0 | Apache-2.0 | 2021-04-16T20:35:11 | 2019-05-01T21:46:12 | C++ | UTF-8 | C++ | false | false | 11,041 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/transcribestreaming/TranscribeStreamingService_EXPORTS.h>
#include <aws/transcribestreaming/model/ItemType.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace TranscribeStreamingService
{
namespace Model
{
/**
* <p>A word, phrase, or punctuation mark that is transcribed from the input
* audio.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-streaming-2017-10-26/Item">AWS
* API Reference</a></p>
*/
class AWS_TRANSCRIBESTREAMINGSERVICE_API Item
{
public:
Item();
Item(Aws::Utils::Json::JsonView jsonValue);
Item& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The offset from the beginning of the audio stream to the beginning of the
* audio that resulted in the item.</p>
*/
inline double GetStartTime() const{ return m_startTime; }
/**
* <p>The offset from the beginning of the audio stream to the beginning of the
* audio that resulted in the item.</p>
*/
inline bool StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; }
/**
* <p>The offset from the beginning of the audio stream to the beginning of the
* audio that resulted in the item.</p>
*/
inline void SetStartTime(double value) { m_startTimeHasBeenSet = true; m_startTime = value; }
/**
* <p>The offset from the beginning of the audio stream to the beginning of the
* audio that resulted in the item.</p>
*/
inline Item& WithStartTime(double value) { SetStartTime(value); return *this;}
/**
* <p>The offset from the beginning of the audio stream to the end of the audio
* that resulted in the item.</p>
*/
inline double GetEndTime() const{ return m_endTime; }
/**
* <p>The offset from the beginning of the audio stream to the end of the audio
* that resulted in the item.</p>
*/
inline bool EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; }
/**
* <p>The offset from the beginning of the audio stream to the end of the audio
* that resulted in the item.</p>
*/
inline void SetEndTime(double value) { m_endTimeHasBeenSet = true; m_endTime = value; }
/**
* <p>The offset from the beginning of the audio stream to the end of the audio
* that resulted in the item.</p>
*/
inline Item& WithEndTime(double value) { SetEndTime(value); return *this;}
/**
* <p>The type of the item. <code>PRONUNCIATION</code> indicates that the item is a
* word that was recognized in the input audio. <code>PUNCTUATION</code> indicates
* that the item was interpreted as a pause in the input audio.</p>
*/
inline const ItemType& GetType() const{ return m_type; }
/**
* <p>The type of the item. <code>PRONUNCIATION</code> indicates that the item is a
* word that was recognized in the input audio. <code>PUNCTUATION</code> indicates
* that the item was interpreted as a pause in the input audio.</p>
*/
inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }
/**
* <p>The type of the item. <code>PRONUNCIATION</code> indicates that the item is a
* word that was recognized in the input audio. <code>PUNCTUATION</code> indicates
* that the item was interpreted as a pause in the input audio.</p>
*/
inline void SetType(const ItemType& value) { m_typeHasBeenSet = true; m_type = value; }
/**
* <p>The type of the item. <code>PRONUNCIATION</code> indicates that the item is a
* word that was recognized in the input audio. <code>PUNCTUATION</code> indicates
* that the item was interpreted as a pause in the input audio.</p>
*/
inline void SetType(ItemType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }
/**
* <p>The type of the item. <code>PRONUNCIATION</code> indicates that the item is a
* word that was recognized in the input audio. <code>PUNCTUATION</code> indicates
* that the item was interpreted as a pause in the input audio.</p>
*/
inline Item& WithType(const ItemType& value) { SetType(value); return *this;}
/**
* <p>The type of the item. <code>PRONUNCIATION</code> indicates that the item is a
* word that was recognized in the input audio. <code>PUNCTUATION</code> indicates
* that the item was interpreted as a pause in the input audio.</p>
*/
inline Item& WithType(ItemType&& value) { SetType(std::move(value)); return *this;}
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline const Aws::String& GetContent() const{ return m_content; }
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline bool ContentHasBeenSet() const { return m_contentHasBeenSet; }
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline void SetContent(const Aws::String& value) { m_contentHasBeenSet = true; m_content = value; }
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline void SetContent(Aws::String&& value) { m_contentHasBeenSet = true; m_content = std::move(value); }
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline void SetContent(const char* value) { m_contentHasBeenSet = true; m_content.assign(value); }
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline Item& WithContent(const Aws::String& value) { SetContent(value); return *this;}
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline Item& WithContent(Aws::String&& value) { SetContent(std::move(value)); return *this;}
/**
* <p>The word or punctuation that was recognized in the input audio.</p>
*/
inline Item& WithContent(const char* value) { SetContent(value); return *this;}
/**
* <p>Indicates whether a word in the item matches a word in the vocabulary filter
* you've chosen for your real-time stream. If <code>true</code> then a word in the
* item matches your vocabulary filter.</p>
*/
inline bool GetVocabularyFilterMatch() const{ return m_vocabularyFilterMatch; }
/**
* <p>Indicates whether a word in the item matches a word in the vocabulary filter
* you've chosen for your real-time stream. If <code>true</code> then a word in the
* item matches your vocabulary filter.</p>
*/
inline bool VocabularyFilterMatchHasBeenSet() const { return m_vocabularyFilterMatchHasBeenSet; }
/**
* <p>Indicates whether a word in the item matches a word in the vocabulary filter
* you've chosen for your real-time stream. If <code>true</code> then a word in the
* item matches your vocabulary filter.</p>
*/
inline void SetVocabularyFilterMatch(bool value) { m_vocabularyFilterMatchHasBeenSet = true; m_vocabularyFilterMatch = value; }
/**
* <p>Indicates whether a word in the item matches a word in the vocabulary filter
* you've chosen for your real-time stream. If <code>true</code> then a word in the
* item matches your vocabulary filter.</p>
*/
inline Item& WithVocabularyFilterMatch(bool value) { SetVocabularyFilterMatch(value); return *this;}
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline const Aws::String& GetSpeaker() const{ return m_speaker; }
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline bool SpeakerHasBeenSet() const { return m_speakerHasBeenSet; }
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline void SetSpeaker(const Aws::String& value) { m_speakerHasBeenSet = true; m_speaker = value; }
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline void SetSpeaker(Aws::String&& value) { m_speakerHasBeenSet = true; m_speaker = std::move(value); }
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline void SetSpeaker(const char* value) { m_speakerHasBeenSet = true; m_speaker.assign(value); }
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline Item& WithSpeaker(const Aws::String& value) { SetSpeaker(value); return *this;}
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline Item& WithSpeaker(Aws::String&& value) { SetSpeaker(std::move(value)); return *this;}
/**
* <p>If speaker identification is enabled, shows the speakers identified in the
* real-time stream.</p>
*/
inline Item& WithSpeaker(const char* value) { SetSpeaker(value); return *this;}
/**
* <p>A value between 0 and 1 for an item that is a confidence score that Amazon
* Transcribe assigns to each word or phrase that it transcribes.</p>
*/
inline double GetConfidence() const{ return m_confidence; }
/**
* <p>A value between 0 and 1 for an item that is a confidence score that Amazon
* Transcribe assigns to each word or phrase that it transcribes.</p>
*/
inline bool ConfidenceHasBeenSet() const { return m_confidenceHasBeenSet; }
/**
* <p>A value between 0 and 1 for an item that is a confidence score that Amazon
* Transcribe assigns to each word or phrase that it transcribes.</p>
*/
inline void SetConfidence(double value) { m_confidenceHasBeenSet = true; m_confidence = value; }
/**
* <p>A value between 0 and 1 for an item that is a confidence score that Amazon
* Transcribe assigns to each word or phrase that it transcribes.</p>
*/
inline Item& WithConfidence(double value) { SetConfidence(value); return *this;}
private:
double m_startTime;
bool m_startTimeHasBeenSet;
double m_endTime;
bool m_endTimeHasBeenSet;
ItemType m_type;
bool m_typeHasBeenSet;
Aws::String m_content;
bool m_contentHasBeenSet;
bool m_vocabularyFilterMatch;
bool m_vocabularyFilterMatchHasBeenSet;
Aws::String m_speaker;
bool m_speakerHasBeenSet;
double m_confidence;
bool m_confidenceHasBeenSet;
};
} // namespace Model
} // namespace TranscribeStreamingService
} // namespace Aws
| [
"[email protected]"
] | |
677358909f8321d2a8354caaf3a9e3f963de74f5 | 7d407c0fd408bf6762959e8047b7f4a941bf0d5f | /command.hh | 71a14501b0c312e6acf6bf47868ddce291e9e9f2 | [] | no_license | jdidat/MyShell | 44fc451ea8726be9f31040ec91cda09ddd168f12 | 3def4321c25b7834274dd45e31543b1bfb710535 | refs/heads/master | 2021-09-02T14:48:35.003090 | 2018-01-03T08:42:49 | 2018-01-03T08:42:49 | 116,113,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | hh | #ifndef command_h
#define command_h
#include "simpleCommand.hh"
// Command Data Structure
struct Command {
int _numOfAvailableSimpleCommands;
int _numOfSimpleCommands;
SimpleCommand ** _simpleCommands;
char * _outFile;
char * _inFile;
char * _errFile;
int _background;
int _append;
int _inCount;
int _outCount;
void prompt();
void print();
void execute();
void setenvExe(int i);
void unsetenvExe(int i);
void cdExe(int i);
void sourceExe(int i);
void printenvExe();
void clear();
Command();
void insertSimpleCommand( SimpleCommand * simpleCommand );
static Command _currentCommand;
static SimpleCommand *_currentSimpleCommand;
};
#endif
| [
"[email protected]"
] | |
1763dfe723b2f69dcc6d3bb0ffb4ff8c9f9c10c0 | 3cde9a68def762e3f41c4e13cf494c9c99ff0dc5 | /GCS.ino | 391309e5a3f47aff496d2add8c8dedad4135b5ca | [] | no_license | jdrones/ArdustationMega | e2cca150c822732b153fbd983fc8bb5024b4dff7 | e174d05d28f1ac2a4e16b133ea91868fcb0bf086 | refs/heads/master | 2020-04-06T04:15:47.604716 | 2013-11-08T04:55:56 | 2013-11-08T04:55:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,197 | ino | #include "GCS.h"
#include "math.h"
GCS_MAVLINK::GCS_MAVLINK(uint8_t key) :
packet_drops(0),
// parameters
// note, all values not explicitly initialised here are zeroed
waypoint_send_timeout(1000), // 1 second
waypoint_receive_timeout(1000) // 1 second
{
}
void GCS_MAVLINK::init(Stream * port) {
GCS_Class::init(port);
if (port == &Serial) {
// mavlink_comm_0_port = port;
chan = MAVLINK_COMM_0;
} else {
// mavlink_comm_1_port = port;
chan = MAVLINK_COMM_1;
}
_queued_parameter = NULL;
}
void GCS_MAVLINK::update(void) {
// receive new packets
mavlink_message_t msg;
mavlink_status_t status;
status.packet_rx_drop_count = 0;
int debug_msg = 0;
// process received bytes
while (_port->available()) {
uint8_t c = _port->read();
// Try to get a new message
if (mavlink_parse_char(chan, c, &msg, &status)) {
// mavlink_active = 1;
handleMessage(&msg);
// Serial.println("A message");
}
// Handle forwarding
if (gcs_passthrough && gcs3.initialised && gcs0.initialised) {
if (chan == MAVLINK_COMM_0) {
Serial3.write(c);
} else {
Serial.write(c);
}
}
debug_msg = 1;
}
// if (debug_msg == 1)
// Serial.println("End update");
// Update packet drops counter
packet_drops += status.packet_rx_drop_count;
// // send out queued params/ waypoints
// if (NULL != _queued_parameter) {
// send_message(MSG_NEXT_PARAM);
// }
if (!waypoint_receiving && !waypoint_sending) {
return;
}
uint32_t tnow = millis();
// stop waypoint sending if timeout
if (waypoint_sending
&& (millis() - waypoint_timelast_send) > waypoint_send_timeout) {
waypoint_sending = false;
}
// stop waypoint receiving if timeout
if (waypoint_receiving
&& (millis() - waypoint_timelast_receive)
> waypoint_receive_timeout) {
waypoint_receiving = false;
}
}
void GCS_MAVLINK::handleMessage(mavlink_message_t* msg) {
static uint8_t mav_nav = 255;// For setting mode (some require receipt of 2 messages...)
int32_t alt;
switch (msg->msgid) {
case MAVLINK_MSG_ID_HEARTBEAT: {
// Serial.println("Heartbeat");
// decode some info
mavlink_heartbeat_t packet;
mavlink_msg_heartbeat_decode(msg, &packet);
// Make a note of the current time
unsigned long now;
now = millis();
// Update the moving average of heartbeat period
if (ASM.last_hb != 0) {
if (ASM.hb_period == 0)
ASM.hb_period = now - ASM.last_hb;
else
ASM.hb_period = 0.9*ASM.hb_period + 0.1*(now - ASM.last_hb);
}
ASM.last_hb = now;
// Update mode
uav.base_mode = packet.base_mode;
if (uav.sysid != msg->sysid) {
Serial.println("Connected to a new UAV");
// Update the connection time
uav.connTime = millis();
uav.connected = 1;
// Update system id, type and autopilot
uav.sysid = msg->sysid;
uav.type = packet.type;
uav.autopilot = packet.autopilot;
// Update the page structure
Pages::definePages();
Serial.print("UAV Type: ");
switch (uav.type) {
case MAV_TYPE_GENERIC:
Serial.println("Generic");
break;
case MAV_TYPE_FIXED_WING:
Serial.println("Fixed wing");
break;
case MAV_TYPE_QUADROTOR:
Serial.println("Quadrotor");
break;
case MAV_TYPE_HELICOPTER:
Serial.println("Helicopter");
break;
case MAV_TYPE_TRICOPTER:
Serial.println("Tricopter (Nice one!)");
break;
case MAV_TYPE_GROUND_ROVER:
Serial.println("Ground Rover");
break;
default:
Serial.println("Unknown");
}
Serial.print("Autopilot Type: ");
switch (uav.autopilot) {
case MAV_AUTOPILOT_GENERIC:
Serial.println("Generic");
break;
case MAV_AUTOPILOT_PIXHAWK:
Serial.println("Pixhawk");
break;
case MAV_AUTOPILOT_ARDUPILOTMEGA:
Serial.println("Ardupilot Mega");
break;
case MAV_AUTOPILOT_UDB:
Serial.println("UAV Devboard");
break;
case MAV_AUTOPILOT_PX4:
Serial.println("PX4");
break;
default:
Serial.println("Unknown");
}
// Update the page due to the new info
Pages::forceUpdate(0);
}
uav.sysid = msg->sysid;
apm_mav_component = msg->compid;
hbcount++;
break;
}
case MAVLINK_MSG_ID_GLOBAL_POSITION_INT: {
// decode
mavlink_global_position_int_t packet;
mavlink_msg_global_position_int_decode(msg, &packet);
// Save the position
uav.lat = packet.lat / 10000000.0;
uav.lon = packet.lon / 10000000.0;
uav.alt = packet.alt / 1000.0;
uav.vx = packet.vx;
uav.vy = packet.vy;
uav.vz = packet.vz;
uav.vel = sqrt(uav.vx*uav.vx + uav.vy*uav.vy + uav.vz*uav.vz);
break;
}
case MAVLINK_MSG_ID_GPS_RAW_INT : {
// decode
mavlink_gps_raw_int_t packet;
mavlink_msg_gps_raw_int_decode(msg, &packet);
uav.sat_count = packet.satellites_visible;
break;
}
case MAVLINK_MSG_ID_VFR_HUD:
// decode
mavlink_vfr_hud_t packet;
mavlink_msg_vfr_hud_decode(msg, &packet);
uav.airspeed = packet.airspeed;
uav.groundspeed = packet.groundspeed;
uav.climb = packet.climb;
uav.heading = packet.heading;
uav.throttle = packet.throttle;
break;
case MAVLINK_MSG_ID_GPS_STATUS : {
break;
}
case MAVLINK_MSG_ID_ATTITUDE: {
// decode
mavlink_attitude_t packet;
mavlink_msg_attitude_decode(msg, &packet);
// save the attitude
uav.roll = packet.roll;
uav.pitch = packet.pitch;
uav.yaw = packet.yaw;
uav.rollspeed = packet.rollspeed, uav.pitchspeed = packet.pitchspeed;
uav.yawspeed = packet.yawspeed;
break;
}
case MAVLINK_MSG_ID_PARAM_VALUE: // for PIDs etc.
{
mavlink_param_value_t packet;
mavlink_msg_param_value_decode(msg, &packet);
char txt_id[16];
// DEV: Display the parameters over serial
Serial.print(packet.param_index);
Serial.print(": ");
Serial.print(packet.param_id);
Serial.print(" = ");
Serial.print(packet.param_value);
Serial.print(", ");
Serial.println(packet.param_type);
// Update the number of paramters onboard
uav.onboard_param_count = packet.param_count;
// If we're doing the full download, move the counter on one
if (downloading) {
download_index++;
if (download_index < uav.onboard_param_count)
gcs3.param_request(download_index);
else {
downloading = 0;
Serial.println("Finished downloading parameters");
// Now request data stream
data_stream_request();
}
}
if (uav.type == MAV_TYPE_FIXED_WING) {
for (uint8_t i = 0; i < PARAM_COUNT_PLANE; i++) {
strcpy_P(txt_id, (char*) pgm_read_word(&(paramTable_plane[i])));
if (strncmp(txt_id, (const char*) packet.param_id, 16) == 0) {
uav.param_plane[i] = packet.param_value;
uav.param_plane_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
for (uint8_t i = 0; i < PARAM_COUNT_PLANE_CTUN; i++) {
strcpy_P(txt_id, (char*) pgm_read_word(&(paramTable_plane_ctun[i])));
if (strncmp(txt_id, (const char*) packet.param_id, 16) == 0) {
uav.param_plane_ctun[i] = packet.param_value;
uav.param_plane_ctun_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
for (uint8_t i=0;i<PARAM_COUNT_PLANE_NTUN;i++) {
strcpy_P(txt_id, (char*)pgm_read_word(&(paramTable_plane_ntun[i])));
if (strncmp(txt_id,(const char*)packet.param_id, 16) == 0) {
uav.param_plane_ntun[i] = packet.param_value;
uav.param_plane_ntun_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
for (uint8_t i=0;i<PARAM_COUNT_PLANE_TECS;i++) {
strcpy_P(txt_id, (char*)pgm_read_word(&(paramTable_plane_tecs[i])));
if (strncmp(txt_id,(const char*)packet.param_id, 16) == 0) {
uav.param_plane_tecs[i] = packet.param_value;
uav.param_plane_tecs_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
} else if (uav.type == MAV_TYPE_GROUND_ROVER) {
for (uint8_t i = 0; i < PARAM_COUNT_ROVER; i++) {
strcpy_P(txt_id, (char*) pgm_read_word(&(paramTable_rover[i])));
if (strncmp(txt_id, (const char*) packet.param_id, 16) == 0) {
uav.param_rover[i] = packet.param_value;
uav.param_rover_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
} else if (uav.type == MAV_TYPE_HELICOPTER
|| uav.type == MAV_TYPE_TRICOPTER
|| uav.type == MAV_TYPE_QUADROTOR
|| uav.type == MAV_TYPE_HEXAROTOR
|| uav.type == MAV_TYPE_OCTOROTOR) {
for (uint8_t i = 0; i < PARAM_COUNT_COPTER; i++) {
strcpy_P(txt_id,
(char*) pgm_read_word(&(paramTable_copter[i])));
if (strncmp(txt_id, (const char*) packet.param_id, 16) == 0) {
uav.param_copter[i] = packet.param_value;
uav.param_copter_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
for (uint8_t i = 0; i < RATE_PID_COUNT_COPTER; i++) {
strcpy_P(txt_id,
(char*) pgm_read_word(&(paramTable_rate_pid_copter[i])));
if (strncmp(txt_id, (const char*) packet.param_id, 16) == 0) {
uav.rate_pid_copter[i] = packet.param_value;
uav.rate_pid_copter_avail[i] = 1;
// Update the parameter pages
Pages::forceUpdate(Pages::R_PARAM);
}
}
}
// if (strcmp("RATE_RLL_P", (const char*)packet.param_id) == 0) {
// uav.roll2srvP = packet.param_value;
// Serial.println();
// Serial.println(uav.roll2srvP);
// Serial.println();
// }
// else
// Serial.println(packet.param_id);
break;
}
case MAVLINK_MSG_ID_SYS_STATUS: {
mavlink_sys_status_t packet;
mavlink_msg_sys_status_decode(msg, &packet);
// Serial.print("Voltage: ");
// Serial.println(packet.voltage_battery);
// Serial.print("Drop rate: ");
// Serial.println(packet.drop_rate_comm);
// Serial.print("Load: ");
// Serial.println(packet.load);
uav.load = packet.load;
uav.voltage_battery = packet.voltage_battery;
break;
}
case MAVLINK_MSG_ID_RAW_IMU:
case MAVLINK_MSG_ID_SCALED_PRESSURE:
case MAV_COMP_ID_SERVO11: //?
case MAV_COMP_ID_SERVO13: //?
case MAVLINK_MSG_ID_MISSION_CURRENT:
case MAVLINK_MSG_ID_SERVO_OUTPUT_RAW:
case MAVLINK_MSG_ID_RC_CHANNELS_RAW:
case MAVLINK_MSG_ID_HIGHRES_IMU:
case MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT:
case MAVLINK_MSG_ID_ROLL_PITCH_YAW_RATES_THRUST_SETPOINT:
case MAVLINK_MSG_ID_MANUAL_CONTROL:
break;
case MAVLINK_MSG_ID_NAMED_VALUE_FLOAT: {
// mavlink_named_value_float_t packet;
// mavlink_msg_named_value_float_decode(msg, &packet);
//
// Serial.print("Debug: ");
// Serial.print(packet.name);
// Serial.print(" = ");
// Serial.println(packet.value);
break;
}
case MAVLINK_MSG_ID_STATUSTEXT: {
mavlink_statustext_t packet;
mavlink_msg_statustext_decode(msg, &packet);
Serial.print("Severity: ");
Serial.println(packet.severity);
Serial.println(packet.text);
break;
}
// default:
// Serial.println(msg->msgid);
}
}
void GCS_MAVLINK::params_request(void) {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
char tmp[16];
for (int i = 0; i < 16; i++)
tmp[i] = '\0';
Serial.println("Requesting params");
mavlink_msg_param_request_list_pack(0xFF, 0xFA, &msg, uav.sysid,
apm_mav_component);
uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
_port->write(buf, len);
// Update the system downloading flag
downloading = 1;
download_start_time = millis();
}
void GCS_MAVLINK::param_request(int16_t param_index) {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
char tmp[16];
for (int i = 0; i < 16; i++)
tmp[i] = '\0';
if (param_index == 0) {
Serial.println("Requesting parameter list, one by one");
}
// Start by requesting the first one:
mavlink_msg_param_request_read_pack(0xFF, 0xFA, &msg, uav.sysid,
apm_mav_component, tmp, param_index);
uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
_port->write(buf, len);
// Update the system downloading flag
downloading = 1;
download_start_time = millis();
}
void GCS_MAVLINK::param_set(uint8_t param_id, float newVal, char *str_param_id) {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
uint8_t i;
// Construct the packet
mavlink_msg_param_set_pack(0xFF, 0xFA, &msg, uav.sysid, apm_mav_component,
(const char*) str_param_id, newVal, MAV_PARAM_TYPE_REAL32);
// Send it
uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
_port->write(buf, len);
}
void GCS_MAVLINK::data_stream_request(void) {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// const int maxStreams = 6;
// const uint8_t MAVStreams[maxStreams] = {MAV_DATA_STREAM_RAW_SENSORS,
// MAV_DATA_STREAM_EXTENDED_STATUS,
// MAV_DATA_STREAM_RC_CHANNELS,
// MAV_DATA_STREAM_POSITION,
// MAV_DATA_STREAM_EXTRA1,
// MAV_DATA_STREAM_EXTRA2};
// const uint16_t MAVRates[maxStreams] = {0x02, 0x02, 0x05, 0x02, 0x05, 0x02};
const int maxStreams = 4;
const uint8_t MAVStreams[maxStreams] = { MAV_DATA_STREAM_EXTRA1, MAV_DATA_STREAM_EXTRA2,
MAV_DATA_STREAM_EXTENDED_STATUS, MAV_DATA_STREAM_POSITION };
const uint16_t MAVRates[maxStreams] = { 0x10, 0x05, 0x01, 0x01 };
for (int i = 0; i < maxStreams; i++) {
// mavlink_msg_request_data_stream_send(chan,
// apm_mav_system, apm_mav_component,
// MAVStreams[i], MAVRates[i], 1);
mavlink_msg_request_data_stream_pack(20, MAV_COMP_ID_IMU, &msg,
uav.sysid, apm_mav_component, MAVStreams[i], MAVRates[i], 1);
uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
_port->write(buf, len);
//Serial.println(MAVStreams[i]);
//Serial.write(buf, len);
}
// mavlink_msg_request_data_stream_send(chan, 1, 1, MAV_DATA_STREAM_EXTENDED_STATUS, 2, 1);
// mavlink_msg_request_data_stream_send(chan, 1, 1, MAV_DATA_STREAM_EXTRA1, 2, 1);
Serial.print("Requesting mavlink data with ");
Serial.print(uav.sysid);
Serial.print(", ");
Serial.print(apm_mav_component);
Serial.println();
}
void GCS_MAVLINK::data_stream_stop(void) {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
mavlink_msg_request_data_stream_pack(20, MAV_COMP_ID_IMU, &msg, 1, 1, MAV_DATA_STREAM_ALL, 0, 0);
uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
_port->write(buf, len);
}
| [
"[email protected]"
] | |
68cfe3826803ccea9dea2a87b4b7b3fc50d2097a | ee110713d2a41ba2958db6a50e2f6fcbedea6ff3 | /第4章-105-复制带随机指针的链表.cpp | 7684d28f62c48b6342d2cc50576d418850cc254a | [] | no_license | libaoquan95/LintCode | fe3e355bf0cecd828d045d45614dbafa8eb5ff2d | 403a5e1520706cb529e257a74f071658766a0aa7 | refs/heads/master | 2021-01-20T08:06:38.150185 | 2017-08-28T04:18:46 | 2017-08-28T04:18:46 | 90,096,556 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,700 | cpp | #include <iostream>
#include<stack>
#include <map>
using namespace std;
/**
* Definition for singly-linked list with a random pointer.
*/
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
/**
* http://www.lintcode.com/zh-cn/ladder/6/-第4章-105-复制带随机指针的链表
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
RandomListNode * newHead;
RandomListNode * p=head, *q;
if(head == NULL)
return NULL;
q = newHead = new RandomListNode(p->label);
q->random = p->random;
p = p->next;
while(p != NULL)
{
q->next = new RandomListNode(p->label);
q->next->random = p->random;
q = q->next;
p = p->next;
}
return newHead;
}
*/
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
RandomListNode * newHead;
map<RandomListNode *, RandomListNode *> mapRandom;
newHead = createListNext(head, mapRandom);
newHead = createListRandom(head, newHead, mapRandom);
return newHead;
}
RandomListNode *createListNext(RandomListNode *head, map<RandomListNode *, RandomListNode *> &mapRandom) {
// write your code here
RandomListNode * newHead;
RandomListNode * p=head, *q;
if(head == NULL)
return NULL;
q = newHead = new RandomListNode(p->label);
mapRandom.insert(pair<RandomListNode *, RandomListNode *>(p, q));
p = p->next;
//q = q->next;
while(p != NULL)
{
q->next = new RandomListNode(p->label);
mapRandom.insert(pair<RandomListNode *, RandomListNode *>(p, q->next));
q = q->next;
p = p->next;
}
return newHead;
}
RandomListNode *createListRandom(RandomListNode *head,RandomListNode *newHead, map<RandomListNode *, RandomListNode *> &mapRandom) {
// write your code here
RandomListNode * p=head;
RandomListNode * q=newHead;
if(head == NULL)
return NULL;
while(p != NULL)
{
if(p->random != NULL)
{
map<RandomListNode *, RandomListNode *>::iterator it = mapRandom.find(p->random);
q->random = it->second;
}
p = p->next;
q = q->next;
}
return newHead;
}
void display(RandomListNode *head)
{
RandomListNode *l = head;
while(l != NULL)
{
cout<<" "<<l->label;
if(l->random != NULL)
cout<<"→"<<l->random->label;
else
cout<<"→null";
cout<<endl<<"↓"<<endl;
l = l->next;
}
cout<<"null"<<endl;
}
};
int main()
{
Solution s;
RandomListNode l1(1),l2(2),l3(3),l4(4),l5(5),l6(6),l7(7),l8(8);
l1.next = &l2;
l2.next = &l3;
l3.next = &l4;
l4.next = &l5;
l5.next = &l6;
l6.next = &l7;
l7.next = &l8;
l1.random = &l4;
l3.random = &l3;
l4.random = &l5;
l6.random = &l2;
l8.random = &l1;
s.display(&l1);
cout<<endl;
s.display(s.copyRandomList(&l1));
cout<<endl;
return 0;
} | [
"[email protected]"
] | |
ae6db20f193b09df70f326f372aa7b92cb2c320a | 4b3f40290e0c90847e791a106b420afa92af9768 | /include/cn24/util/JSONParsing.h | 08997e94b84b5a56473fdd604b59edd740b5f7ba | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | cvjena/cn24-active | e6004271f0b4948f407d64afadbcaca23cb7cebc | 5f40b63aebd14c0658136b402e3df010e405de05 | refs/heads/master | 2020-04-22T04:58:38.389624 | 2019-02-11T14:31:15 | 2019-02-11T14:31:15 | 170,142,558 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | h | /*
* This file is part of the CN24 semantic segmentation software,
* copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
*
* For licensing information, see the LICENSE file included with this project.
*/
#ifndef CONV_JSONPARSING_H
#define CONV_JSONPARSING_H
#include "../../../external/json/json.hpp"
#define JSON_TRY_DATUM(target_var, json_object, key, otherwise) if(json_object.count(key) == 1 && json_object[key].is_number()) \
{ target_var = json_object[key]; } else { target_var = otherwise; }
#define JSON_TRY_INT(target_var, json_object, key, otherwise) if(json_object.count(key) == 1 && json_object[key].is_number_integer()) \
{ target_var = json_object[key]; } else { target_var = otherwise; }
#define JSON_TRY_BOOL(target_var, json_object, key, otherwise) if(json_object.count(key) == 1 && json_object[key].is_number_integer()) \
{ target_var = ((int)json_object[key] > 0); } else { target_var = otherwise; }
namespace Conv {
using JSON = nlohmann::json;
}
#endif
| [
"[email protected]"
] | |
a861e447c8cc69cf72bbfc21d6bb77e712faabc7 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14000/function14000_schedule_25/function14000_schedule_25_wrapper.cpp | 0da70467743cfd2869b875ae2e002ba3912a5432 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp | #include "Halide.h"
#include "function14000_schedule_25_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64);
Halide::Buffer<int32_t> buf01(64, 64, 64);
Halide::Buffer<int32_t> buf02(64);
Halide::Buffer<int32_t> buf03(64);
Halide::Buffer<int32_t> buf04(64, 64);
Halide::Buffer<int32_t> buf05(64, 64, 64);
Halide::Buffer<int32_t> buf06(64, 64);
Halide::Buffer<int32_t> buf07(64, 64);
Halide::Buffer<int32_t> buf0(64, 64, 64, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14000_schedule_25(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14000/function14000_schedule_25/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"[email protected]"
] | |
1d98943445f681b83a26f6418079ca8ceb1f561c | e12b52e8c0537e98c4f5646f21abb584832ed227 | /sw_expert_academy/1221(gns).cpp | 8d41638cd776b3cdbf06b93066b660bb6cc9d542 | [] | no_license | ja-ho/baekjoon_algorithm | 39610f9c1ba45a90cfd0c55bc88944bc1640cf84 | c70ab0bdaf34a7442d560c8d3b5272c531b6ecc8 | refs/heads/master | 2021-01-19T13:39:23.223623 | 2018-10-07T17:57:34 | 2018-10-07T17:57:34 | 100,852,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | cpp | #include <cstdio>
using namespace std;
char nums[10][4] = { "zro", "one", "two", "thr", "for", "fiv", "six", "svn", "egt", "nin" };
int nums_list[10];
int main() {
int t;
scanf("%d", &t);
int tc = 1;
while (t--) {
for (int i = 0; i < 10; i++) {
nums_list[i] = 0;
}
char temp[5];
int n;
scanf("%s %d", &temp, &n);
for (int i = 0; i < n; i++) {
scanf("%s", temp);
if (temp[0] == 'z') nums_list[0]++;
else if (temp[0] == 'o') nums_list[1]++;
else if (temp[1] == 'w') nums_list[2]++;
else if (temp[1] == 'h') nums_list[3]++;
else if (temp[1] == 'o') nums_list[4]++;
else if (temp[2] == 'v') nums_list[5]++;
else if (temp[2] == 'x') nums_list[6]++;
else if (temp[1] == 'v') nums_list[7]++;
else if (temp[1] == 'g') nums_list[8]++;
else if (temp[0] == 'n') nums_list[9]++;
}
printf("#%d\n", tc++);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < nums_list[i]; j++) {
printf("%s ", nums[i]);
}
}
printf("\n");
}
return 0;
} | [
"[email protected]"
] | |
616ac219e5cd006f3c2bea131257ba003a0c09aa | 925d7c5ee4f145994af10412f69a6bcb7eafea23 | /CppIOExample/BinFileIO.h | 854cb9649eecb98c3d2beff2acf82c94d7bbb620 | [] | no_license | ZhaoTongFeng/CPPIO | 904b70badc77c4db41851cfb5f8fba177ab65568 | 51587d9be73bec8dd086c77b21feeb93aa5615c8 | refs/heads/master | 2022-12-20T18:43:33.485128 | 2020-09-21T05:48:51 | 2020-09-21T05:48:51 | 294,934,928 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 485 | h | #pragma once
namespace MBinFileIO {
//位操作
//把某一位设置成0或者1
void SetBit(int& value, int index, bool isT) {
if (index < 0 || index >= 32) { return; }
value = isT ? value | (1 << index) : value & (~(1 << index));
return;
}
//判断某一位是否为1
void GetMask(int value, int index, bool& isT) {
if (index < 0 || index >= 32) { return; }
isT = ((value >> index) & 1) == 1;
return;
}
}
| [
"[email protected]"
] | |
0e916f8e18e202df41b8c40b20ee5e9ef89edb1f | 31b27a853b6e7dfff71e5bb8b37fdb85fdead9f6 | /генератор стереокартинок полный с++/генератор стереокартинок с++/bmp.h | 742e198b52c9743496b4665a6b560d0fc829ecf9 | [] | no_license | Igor-kor/stereopicture_generator | 230d6183a558b9db3a7b21db38e46181f15717d2 | d3e8ac50ca9eb3976cd5ff218de40a33f0101047 | refs/heads/master | 2023-03-29T07:03:31.555832 | 2020-07-02T08:48:54 | 2020-07-02T08:48:54 | 276,595,785 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 26,838 | h | #pragma once
#include <fstream>
using namespace std;
/*
typedef unsigned __int16 WORD;
typedef struct {
WORD bfType; // 0x4d42 | 0x4349 | 0x5450
int bfSize; // размер файла
int bfReserved; // 0
int bfOffBits; // смещение до поля данных,
// обычно 54 = 16 + biSize
int biSize; // размер струкуры в байтах:
// 40(BITMAPINFOHEADER) или 108(BITMAPV4HEADER)
// или 124(BITMAPV5HEADER)
int biWidth; // ширина в точках
int biHeight; // высота в точках
WORD biPlanes; // всегда должно быть 1
WORD biBitCount; // 0 | 1 | 4 | 8 | 16 | 24 | 32
int biCompression; // BI_RGB | BI_RLE8 | BI_RLE4 |
// BI_BITFIELDS | BI_JPEG | BI_PNG
// реально используется лишь BI_RGB
int biSizeImage; // Количество байт в поле данных
// Обычно устанавливается в 0
int biXPelsPerMeter;// горизонтальное разрешение, точек на дюйм
int biYPelsPerMeter;// вертикальное разрешение, точек на дюйм
int biClrUsed; // Количество используемых цветов
// (если есть таблица цветов)
int biClrImportant; // Количество существенных цветов.
// Можно считать, просто 0
} BMPheader;
*/
//
//typedef int FXPT2DOT30;
//
//typedef struct {
// FXPT2DOT30 ciexyzX;
// FXPT2DOT30 ciexyzY;
// FXPT2DOT30 ciexyzZ;
//} CIEXYZ;
//
//typedef struct {
// CIEXYZ ciexyzRed;
// CIEXYZ ciexyzGreen;
// CIEXYZ ciexyzBlue;
//} CIEXYZTRIPLE;
//
//// bitmap file header
//typedef struct {
// unsigned short bfType;
// unsigned int bfSize;
// unsigned short bfReserved1;
// unsigned short bfReserved2;
// unsigned int bfOffBits;
//} BITMAPFILEHEADER;
//
//// bitmap info header
//typedef struct {
// unsigned int biSize;
// unsigned int biWidth;
// unsigned int biHeight;
// unsigned short biPlanes;
// unsigned short biBitCount;
// unsigned int biCompression;
// unsigned int biSizeImage;
// unsigned int biXPelsPerMeter;
// unsigned int biYPelsPerMeter;
// unsigned int biClrUsed;
// unsigned int biClrImportant;
// unsigned int biRedMask;
// unsigned int biGreenMask;
// unsigned int biBlueMask;
// unsigned int biAlphaMask;
// unsigned int biCSType;
// CIEXYZTRIPLE biEndpoints;
// unsigned int biGammaRed;
// unsigned int biGammaGreen;
// unsigned int biGammaBlue;
// unsigned int biIntent;
// unsigned int biProfileData;
// unsigned int biProfileSize;
// unsigned int biReserved;
//} BITMAPINFOHEADER;
//
//// rgb quad
//typedef struct {
// unsigned char rgbBlue;
// unsigned char rgbGreen;
// unsigned char rgbRed;
// unsigned char rgbReserved;
//} RGBQUAD;
//
//// read bytes
//template <typename Type>
//void read(std::ifstream &fp, Type &result, std::size_t size) {
// fp.read(reinterpret_cast<char*>(&result), size);
//}
//
//unsigned char bitextract(const unsigned int byte, const unsigned int mask) {
// if (mask == 0) {
// return 0;
// }
//
// // определение количества нулевых бит справа от маски
// int
// maskBufer = mask,
// maskPadding = 0;
//
// while (!(maskBufer & 1)) {
// maskBufer >>= 1;
// maskPadding++;
// }
//
// // применение маски и смещение
// return (byte & mask) >> maskPadding;
//}
//
/*
* Windows Bitmap File Loader
* Version 1.2.5 (20120929)
*
* Supported Formats: 1, 4, 8, 16, 24, 32 Bit Images
* Alpha Bitmaps are also supported.
* Supported compression types: RLE 8, BITFIELDS
*
* Created by: Benjamin Kalytta, 2006 - 2012
* Thanks for bug fixes goes to: Chris Campbell
*
* Licence: Free to use, URL to my source and my name is required in your source code.
*
* Source can be found at http://www.kalytta.com/bitmap.h
*
* Warning: This code should not be used in unmodified form in a production environment.
* It should only serve as a basis for your own development.
* There is only a minimal error handling in this code. (Notice added 20111211)
*/
#ifndef BITMAP_H
#define BITMAP_H
#include <iostream>
#include <fstream>
#include <string>
#ifndef __LITTLE_ENDIAN__
#ifndef __BIG_ENDIAN__
#define __LITTLE_ENDIAN__
#endif
#endif
#ifdef __LITTLE_ENDIAN__
#define BITMAP_SIGNATURE 0x4d42
#else
#define BITMAP_SIGNATURE 0x424d
#endif
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
typedef unsigned __int32 uint32_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int8 uint8_t;
typedef __int32 int32_t;
#elif defined(__GNUC__) || defined(__CYGWIN__) || defined(__MWERKS__) || defined(__WATCOMC__) || defined(__PGI) || defined(__LCC__)
#include <stdint.h>
#else
typedef unsigned int uint32_t;
typedef unsigned short int uint16_t;
typedef unsigned char uint8_t;
typedef int int32_t;
#endif
#pragma pack(push, 1)
typedef struct _BITMAP_FILEHEADER {
uint16_t Signature;
uint32_t Size;
uint32_t Reserved;
uint32_t BitsOffset;
} BITMAP_FILEHEADER;
#define BITMAP_FILEHEADER_SIZE 14
typedef struct _BITMAP_HEADER {
uint32_t HeaderSize;
int32_t Width;
int32_t Height;
uint16_t Planes;
uint16_t BitCount;
uint32_t Compression;
uint32_t SizeImage;
int32_t PelsPerMeterX;
int32_t PelsPerMeterY;
uint32_t ClrUsed;
uint32_t ClrImportant;
uint32_t RedMask;
uint32_t GreenMask;
uint32_t BlueMask;
uint32_t AlphaMask;
uint32_t CsType;
uint32_t Endpoints[9]; // see http://msdn2.microsoft.com/en-us/library/ms536569.aspx
uint32_t GammaRed;
uint32_t GammaGreen;
uint32_t GammaBlue;
} BITMAP_HEADER;
typedef struct _RGBA {
uint8_t Red;
uint8_t Green;
uint8_t Blue;
uint8_t Alpha;
} RGBA;
typedef struct _BGRA {
uint8_t Blue;
uint8_t Green;
uint8_t Red;
uint8_t Alpha;
} BGRA;
#pragma pack(pop)
class CBitmap {
public:
BITMAP_FILEHEADER m_BitmapFileHeader;
BITMAP_HEADER m_BitmapHeader;
RGBA *m_BitmapData;
unsigned int m_BitmapSize;
// Masks and bit counts shouldn't exceed 32 Bits
public:
class CColor {
public:
static inline unsigned int BitCountByMask(unsigned int Mask) {
unsigned int BitCount = 0;
while (Mask) {
Mask &= Mask - 1;
BitCount++;
}
return BitCount;
}
static inline unsigned int BitPositionByMask(unsigned int Mask) {
return BitCountByMask((Mask & (~Mask + 1)) - 1);
}
static inline unsigned int ComponentByMask(unsigned int Color, unsigned int Mask) {
unsigned int Component = Color & Mask;
return Component >> BitPositionByMask(Mask);
}
static inline unsigned int BitCountToMask(unsigned int BitCount) {
return (BitCount == 32) ? 0xFFFFFFFF : (1 << BitCount) - 1;
}
static unsigned int Convert(unsigned int Color, unsigned int FromBitCount, unsigned int ToBitCount) {
if (ToBitCount < FromBitCount) {
Color >>= (FromBitCount - ToBitCount);
}
else {
Color <<= (ToBitCount - FromBitCount);
if (Color > 0) {
Color |= BitCountToMask(ToBitCount - FromBitCount);
}
}
return Color;
}
};
public:
CBitmap() : m_BitmapData(0), m_BitmapSize(0) {
Dispose();
}
CBitmap(const char* Filename) : m_BitmapData(0), m_BitmapSize(0) {
Load(Filename);
}
~CBitmap() {
Dispose();
}
void Dispose() {
if (m_BitmapData) {
delete[] m_BitmapData;
m_BitmapData = 0;
}
memset(&m_BitmapFileHeader, 0, sizeof(m_BitmapFileHeader));
memset(&m_BitmapHeader, 0, sizeof(m_BitmapHeader));
}
/* Load specified Bitmap and stores it as RGBA in an internal buffer */
bool Load(const char *Filename) {
std::ifstream file(Filename, std::ios::binary | std::ios::in);
if (file.bad()) {
return false;
}
if (file.is_open() == false) {
return false;
}
Dispose();
file.read((char*)&m_BitmapFileHeader, BITMAP_FILEHEADER_SIZE);
if (m_BitmapFileHeader.Signature != BITMAP_SIGNATURE) {
return false;
}
file.read((char*)&m_BitmapHeader, sizeof(BITMAP_HEADER));
/* Load Color Table */
file.seekg(BITMAP_FILEHEADER_SIZE + m_BitmapHeader.HeaderSize, std::ios::beg);
unsigned int ColorTableSize = 0;
if (m_BitmapHeader.BitCount == 1) {
ColorTableSize = 2;
}
else if (m_BitmapHeader.BitCount == 4) {
ColorTableSize = 16;
}
else if (m_BitmapHeader.BitCount == 8) {
ColorTableSize = 256;
}
// Always allocate full sized color table
BGRA* ColorTable = new BGRA[ColorTableSize]; // std::bad_alloc exception should be thrown if memory is not available
file.read((char*)ColorTable, sizeof(BGRA) * m_BitmapHeader.ClrUsed);
/* ... Color Table for 16 bits images are not supported yet */
m_BitmapSize = GetWidth() * GetHeight();
m_BitmapData = new RGBA[m_BitmapSize];
unsigned int LineWidth = ((GetWidth() * GetBitCount() / 8) + 3) & ~3;
uint8_t *Line = new uint8_t[LineWidth];
file.seekg(m_BitmapFileHeader.BitsOffset, std::ios::beg);
int Index = 0;
bool Result = true;
if (m_BitmapHeader.Compression == 0) {
for (unsigned int i = 0; i < GetHeight(); i++) {
file.read((char*)Line, LineWidth);
uint8_t *LinePtr = Line;
for (unsigned int j = 0; j < GetWidth(); j++) {
if (m_BitmapHeader.BitCount == 1) {
uint32_t Color = *((uint8_t*)LinePtr);
for (int k = 0; k < 8; k++) {
m_BitmapData[Index].Red = ColorTable[Color & 0x80 ? 1 : 0].Red;
m_BitmapData[Index].Green = ColorTable[Color & 0x80 ? 1 : 0].Green;
m_BitmapData[Index].Blue = ColorTable[Color & 0x80 ? 1 : 0].Blue;
m_BitmapData[Index].Alpha = ColorTable[Color & 0x80 ? 1 : 0].Alpha;
Index++;
Color <<= 1;
}
LinePtr++;
j += 7;
}
else if (m_BitmapHeader.BitCount == 4) {
uint32_t Color = *((uint8_t*)LinePtr);
m_BitmapData[Index].Red = ColorTable[(Color >> 4) & 0x0f].Red;
m_BitmapData[Index].Green = ColorTable[(Color >> 4) & 0x0f].Green;
m_BitmapData[Index].Blue = ColorTable[(Color >> 4) & 0x0f].Blue;
m_BitmapData[Index].Alpha = ColorTable[(Color >> 4) & 0x0f].Alpha;
Index++;
m_BitmapData[Index].Red = ColorTable[Color & 0x0f].Red;
m_BitmapData[Index].Green = ColorTable[Color & 0x0f].Green;
m_BitmapData[Index].Blue = ColorTable[Color & 0x0f].Blue;
m_BitmapData[Index].Alpha = ColorTable[Color & 0x0f].Alpha;
Index++;
LinePtr++;
j++;
}
else if (m_BitmapHeader.BitCount == 8) {
uint32_t Color = *((uint8_t*)LinePtr);
m_BitmapData[Index].Red = ColorTable[Color].Red;
m_BitmapData[Index].Green = ColorTable[Color].Green;
m_BitmapData[Index].Blue = ColorTable[Color].Blue;
m_BitmapData[Index].Alpha = ColorTable[Color].Alpha;
Index++;
LinePtr++;
}
else if (m_BitmapHeader.BitCount == 16) {
uint32_t Color = *((uint16_t*)LinePtr);
m_BitmapData[Index].Red = ((Color >> 10) & 0x1f) << 3;
m_BitmapData[Index].Green = ((Color >> 5) & 0x1f) << 3;
m_BitmapData[Index].Blue = (Color & 0x1f) << 3;
m_BitmapData[Index].Alpha = 255;
Index++;
LinePtr += 2;
}
else if (m_BitmapHeader.BitCount == 24) {
uint32_t Color = *((uint32_t*)LinePtr);
m_BitmapData[Index].Blue = Color & 0xff;
m_BitmapData[Index].Green = (Color >> 8) & 0xff;
m_BitmapData[Index].Red = (Color >> 16) & 0xff;
m_BitmapData[Index].Alpha = 255;
Index++;
LinePtr += 3;
}
else if (m_BitmapHeader.BitCount == 32) {
uint32_t Color = *((uint32_t*)LinePtr);
m_BitmapData[Index].Blue = Color & 0xff;
m_BitmapData[Index].Green = (Color >> 8) & 0xff;
m_BitmapData[Index].Red = (Color >> 16) & 0xff;
m_BitmapData[Index].Alpha = Color >> 24;
Index++;
LinePtr += 4;
}
}
}
}
else if (m_BitmapHeader.Compression == 1) { // RLE 8
uint8_t Count = 0;
uint8_t ColorIndex = 0;
int x = 0, y = 0;
while (file.eof() == false) {
file.read((char*)&Count, sizeof(uint8_t));
file.read((char*)&ColorIndex, sizeof(uint8_t));
if (Count > 0) {
Index = x + y * GetWidth();
for (int k = 0; k < Count; k++) {
m_BitmapData[Index + k].Red = ColorTable[ColorIndex].Red;
m_BitmapData[Index + k].Green = ColorTable[ColorIndex].Green;
m_BitmapData[Index + k].Blue = ColorTable[ColorIndex].Blue;
m_BitmapData[Index + k].Alpha = ColorTable[ColorIndex].Alpha;
}
x += Count;
}
else if (Count == 0) {
int Flag = ColorIndex;
if (Flag == 0) {
x = 0;
y++;
}
else if (Flag == 1) {
break;
}
else if (Flag == 2) {
char rx = 0;
char ry = 0;
file.read((char*)&rx, sizeof(char));
file.read((char*)&ry, sizeof(char));
x += rx;
y += ry;
}
else {
Count = Flag;
Index = x + y * GetWidth();
for (int k = 0; k < Count; k++) {
file.read((char*)&ColorIndex, sizeof(uint8_t));
m_BitmapData[Index + k].Red = ColorTable[ColorIndex].Red;
m_BitmapData[Index + k].Green = ColorTable[ColorIndex].Green;
m_BitmapData[Index + k].Blue = ColorTable[ColorIndex].Blue;
m_BitmapData[Index + k].Alpha = ColorTable[ColorIndex].Alpha;
}
x += Count;
// Attention: Current Microsoft STL implementation seems to be buggy, tellg() always returns 0.
if (file.tellg() & 1) {
file.seekg(1, std::ios::cur);
}
}
}
}
}
else if (m_BitmapHeader.Compression == 2) { // RLE 4
/* RLE 4 is not supported */
Result = false;
}
else if (m_BitmapHeader.Compression == 3) { // BITFIELDS
/* We assumes that mask of each color component can be in any order */
uint32_t BitCountRed = CColor::BitCountByMask(m_BitmapHeader.RedMask);
uint32_t BitCountGreen = CColor::BitCountByMask(m_BitmapHeader.GreenMask);
uint32_t BitCountBlue = CColor::BitCountByMask(m_BitmapHeader.BlueMask);
uint32_t BitCountAlpha = CColor::BitCountByMask(m_BitmapHeader.AlphaMask);
for (unsigned int i = 0; i < GetHeight(); i++) {
file.read((char*)Line, LineWidth);
uint8_t *LinePtr = Line;
for (unsigned int j = 0; j < GetWidth(); j++) {
uint32_t Color = 0;
if (m_BitmapHeader.BitCount == 16) {
Color = *((uint16_t*)LinePtr);
LinePtr += 2;
}
else if (m_BitmapHeader.BitCount == 32) {
Color = *((uint32_t*)LinePtr);
LinePtr += 4;
}
else {
// Other formats are not valid
}
m_BitmapData[Index].Red = CColor::Convert(CColor::ComponentByMask(Color, m_BitmapHeader.RedMask), BitCountRed, 8);
m_BitmapData[Index].Green = CColor::Convert(CColor::ComponentByMask(Color, m_BitmapHeader.GreenMask), BitCountGreen, 8);
m_BitmapData[Index].Blue = CColor::Convert(CColor::ComponentByMask(Color, m_BitmapHeader.BlueMask), BitCountBlue, 8);
m_BitmapData[Index].Alpha = CColor::Convert(CColor::ComponentByMask(Color, m_BitmapHeader.AlphaMask), BitCountAlpha, 8);
Index++;
}
}
}
delete[] ColorTable;
delete[] Line;
file.close();
return Result;
}
bool Save(const char* Filename, unsigned int BitCount = 32) {
bool Result = true;
std::ofstream file(Filename, std::ios::out | std::ios::binary);
if (file.is_open() == false) {
return false;
}
BITMAP_FILEHEADER bfh;
BITMAP_HEADER bh;
memset(&bfh, 0, sizeof(bfh));
memset(&bh, 0, sizeof(bh));
bfh.Signature = BITMAP_SIGNATURE;
bfh.BitsOffset = BITMAP_FILEHEADER_SIZE + sizeof(BITMAP_HEADER);
bfh.Size = (GetWidth() * GetHeight() * BitCount) / 8 + bfh.BitsOffset;
bh.HeaderSize = sizeof(BITMAP_HEADER);
bh.BitCount = BitCount;
if (BitCount == 32) {
bh.Compression = 3; // BITFIELD
bh.AlphaMask = 0xff000000;
bh.BlueMask = 0x00ff0000;
bh.GreenMask = 0x0000ff00;
bh.RedMask = 0x000000ff;
}
else if (BitCount == 16) {
bh.Compression = 3; // BITFIELD
bh.AlphaMask = 0x00000000;
bh.BlueMask = 0x0000001f;
bh.GreenMask = 0x000007E0;
bh.RedMask = 0x0000F800;
}
else {
bh.Compression = 0; // RGB
}
unsigned int LineWidth = (GetWidth() + 3) & ~3;
bh.Planes = 1;
bh.Height = GetHeight();
bh.Width = GetWidth();
bh.SizeImage = (LineWidth * BitCount * GetHeight()) / 8;
bh.PelsPerMeterX = 3780;
bh.PelsPerMeterY = 3780;
if (BitCount == 32) {
file.write((char*)&bfh, sizeof(BITMAP_FILEHEADER));
file.write((char*)&bh, sizeof(BITMAP_HEADER));
file.write((char*)m_BitmapData, bh.SizeImage);
}
else if (BitCount < 16) {
uint8_t* Bitmap = new uint8_t[bh.SizeImage];
BGRA *Palette = 0;
unsigned int PaletteSize = 0;
if (GetBitsWithPalette(Bitmap, bh.SizeImage, BitCount, Palette, PaletteSize)) {
bfh.BitsOffset += PaletteSize * sizeof(BGRA);
file.write((char*)&bfh, BITMAP_FILEHEADER_SIZE);
file.write((char*)&bh, sizeof(BITMAP_HEADER));
file.write((char*)Palette, PaletteSize * sizeof(BGRA));
file.write((char*)Bitmap, bh.SizeImage);
}
delete[] Bitmap;
delete[] Palette;
}
else {
uint32_t RedMask = 0;
uint32_t GreenMask = 0;
uint32_t BlueMask = 0;
uint32_t AlphaMask = 0;
if (BitCount == 16) {
RedMask = 0x0000F800;
GreenMask = 0x000007E0;
BlueMask = 0x0000001F;
AlphaMask = 0x00000000;
}
else if (BitCount == 24) {
RedMask = 0x00FF0000;
GreenMask = 0x0000FF00;
BlueMask = 0x000000FF;
}
else {
// Other color formats are not valid
Result = false;
}
if (Result) {
if (GetBits(NULL, bh.SizeImage, RedMask, GreenMask, BlueMask, AlphaMask)) {
uint8_t* Bitmap = new uint8_t[bh.SizeImage];
if (GetBits(Bitmap, bh.SizeImage, RedMask, GreenMask, BlueMask, AlphaMask)) {
file.write((char*)&bfh, sizeof(BITMAP_FILEHEADER));
file.write((char*)&bh, sizeof(BITMAP_HEADER));
file.write((char*)Bitmap, bh.SizeImage);
}
delete[] Bitmap;
}
}
}
file.close();
return Result;
}
unsigned int GetWidth() {
/* Add plausibility test */
// if (abs(m_BitmapHeader.Width) > 8192) {
// m_BitmapHeader.Width = 8192;
// }
return m_BitmapHeader.Width < 0 ? -m_BitmapHeader.Width : m_BitmapHeader.Width;
}
unsigned int GetHeight() {
/* Add plausibility test */
// if (abs(m_BitmapHeader.Height) > 8192) {
// m_BitmapHeader.Height = 8192;
// }
return m_BitmapHeader.Height < 0 ? -m_BitmapHeader.Height : m_BitmapHeader.Height;
}
unsigned int GetBitCount() {
/* Add plausibility test */
// if (m_BitmapHeader.BitCount > 32) {
// m_BitmapHeader.BitCount = 32;
// }
return m_BitmapHeader.BitCount;
}
/* Copies internal RGBA buffer to user specified buffer */
bool GetBits(void* Buffer, unsigned int &Size) {
bool Result = false;
if (Size == 0 || Buffer == 0) {
Size = m_BitmapSize * sizeof(RGBA);
Result = m_BitmapSize != 0;
}
else {
memcpy(Buffer, m_BitmapData, Size);
Result = true;
}
return Result;
}
/* Returns internal RGBA buffer */
void* GetBits() {
return m_BitmapData;
}
/* Copies internal RGBA buffer to user specified buffer and converts it into destination
* bit format specified by component masks.
*
* Typical Bitmap color formats (BGR/BGRA):
*
* Masks for 16 bit (5-5-5): ALPHA = 0x00000000, RED = 0x00007C00, GREEN = 0x000003E0, BLUE = 0x0000001F
* Masks for 16 bit (5-6-5): ALPHA = 0x00000000, RED = 0x0000F800, GREEN = 0x000007E0, BLUE = 0x0000001F
* Masks for 24 bit: ALPHA = 0x00000000, RED = 0x00FF0000, GREEN = 0x0000FF00, BLUE = 0x000000FF
* Masks for 32 bit: ALPHA = 0xFF000000, RED = 0x00FF0000, GREEN = 0x0000FF00, BLUE = 0x000000FF
*
* Other color formats (RGB/RGBA):
*
* Masks for 32 bit (RGBA): ALPHA = 0xFF000000, RED = 0x000000FF, GREEN = 0x0000FF00, BLUE = 0x00FF0000
*
* Bit count will be rounded to next 8 bit boundary. If IncludePadding is true, it will be ensured
* that line width is a multiple of 4. padding bytes are included if necessary.
*
* NOTE: systems with big endian byte order may require masks in inversion order.
*/
bool GetBits(void* Buffer, unsigned int &Size, unsigned int RedMask, unsigned int GreenMask, unsigned int BlueMask, unsigned int AlphaMask, bool IncludePadding = true) {
bool Result = false;
uint32_t BitCountRed = CColor::BitCountByMask(RedMask);
uint32_t BitCountGreen = CColor::BitCountByMask(GreenMask);
uint32_t BitCountBlue = CColor::BitCountByMask(BlueMask);
uint32_t BitCountAlpha = CColor::BitCountByMask(AlphaMask);
unsigned int BitCount = (BitCountRed + BitCountGreen + BitCountBlue + BitCountAlpha + 7) & ~7;
if (BitCount > 32) {
return false;
}
unsigned int w = GetWidth();
//unsigned int LineWidth = (w + 3) & ~3;
unsigned int dataBytesPerLine = (w * BitCount + 7) / 8;
unsigned int LineWidth = (dataBytesPerLine + 3) & ~3;
if (Size == 0 || Buffer == 0) {
//Size = (LineWidth * GetHeight() * BitCount) / 8 + sizeof(unsigned int);
Size = (GetWidth() * GetHeight() * BitCount) / 8 + sizeof(unsigned int);
return true;
}
uint8_t* BufferPtr = (uint8_t*)Buffer;
Result = true;
uint32_t BitPosRed = CColor::BitPositionByMask(RedMask);
uint32_t BitPosGreen = CColor::BitPositionByMask(GreenMask);
uint32_t BitPosBlue = CColor::BitPositionByMask(BlueMask);
uint32_t BitPosAlpha = CColor::BitPositionByMask(AlphaMask);
unsigned int j = 0;
for (unsigned int i = 0; i < m_BitmapSize; i++) {
*(uint32_t*)BufferPtr =
(CColor::Convert(m_BitmapData[i].Blue, 8, BitCountBlue) << BitPosBlue) |
(CColor::Convert(m_BitmapData[i].Green, 8, BitCountGreen) << BitPosGreen) |
(CColor::Convert(m_BitmapData[i].Red, 8, BitCountRed) << BitPosRed) |
(CColor::Convert(m_BitmapData[i].Alpha, 8, BitCountAlpha) << BitPosAlpha);
if (IncludePadding) {
j++;
if (j >= w) {
for (unsigned int k = 0; k < LineWidth - dataBytesPerLine; k++) {
BufferPtr += (BitCount >> 3);
}
j = 0;
}
}
BufferPtr += (BitCount >> 3);
}
Size -= sizeof(unsigned int);
return Result;
}
/* See GetBits().
* It creates a corresponding color table (palette) which have to be destroyed by the user after usage.
*
* Supported Bit depths are: 4, 8
*
* Todo: Optimize, use optimized palette, do ditehring (see my dithering class), support padding for 4 bit bitmaps
*/
bool GetBitsWithPalette(void* Buffer, unsigned int &Size, unsigned int BitCount, BGRA* &Palette, unsigned int &PaletteSize, bool OptimalPalette = false, bool IncludePadding = true) {
bool Result = false;
if (BitCount > 16) {
return false;
}
unsigned int w = GetWidth();
unsigned int dataBytesPerLine = (w * BitCount + 7) / 8;
unsigned int LineWidth = (dataBytesPerLine + 3) & ~3;
if (Size == 0 || Buffer == 0) {
Size = (LineWidth * GetHeight() * BitCount) / 8;
return true;
}
if (OptimalPalette) {
PaletteSize = 0;
// Not implemented
}
else {
if (BitCount == 1) {
PaletteSize = 2;
// Not implemented: Who need that?
}
else if (BitCount == 4) { // 2:2:1
PaletteSize = 16;
Palette = new BGRA[PaletteSize];
for (int r = 0; r < 4; r++) {
for (int g = 0; g < 2; g++) {
for (int b = 0; b < 2; b++) {
Palette[r | g << 2 | b << 3].Red = r ? (r << 6) | 0x3f : 0;
Palette[r | g << 2 | b << 3].Green = g ? (g << 7) | 0x7f : 0;
Palette[r | g << 2 | b << 3].Blue = b ? (b << 7) | 0x7f : 0;
Palette[r | g << 2 | b << 3].Alpha = 0xff;
}
}
}
}
else if (BitCount == 8) { // 3:3:2
PaletteSize = 256;
Palette = new BGRA[PaletteSize];
for (int r = 0; r < 8; r++) {
for (int g = 0; g < 8; g++) {
for (int b = 0; b < 4; b++) {
Palette[r | g << 3 | b << 6].Red = r ? (r << 5) | 0x1f : 0;
Palette[r | g << 3 | b << 6].Green = g ? (g << 5) | 0x1f : 0;
Palette[r | g << 3 | b << 6].Blue = b ? (b << 6) | 0x3f : 0;
Palette[r | g << 3 | b << 6].Alpha = 0xff;
}
}
}
}
else if (BitCount == 16) { // 5:5:5
// Not implemented
}
}
unsigned int j = 0;
uint8_t* BufferPtr = (uint8_t*)Buffer;
for (unsigned int i = 0; i < m_BitmapSize; i++) {
if (BitCount == 1) {
// Not implemented: Who needs that?
}
else if (BitCount == 4) {
*BufferPtr = ((m_BitmapData[i].Red >> 6) | (m_BitmapData[i].Green >> 7) << 2 | (m_BitmapData[i].Blue >> 7) << 3) << 4;
i++;
*BufferPtr |= (m_BitmapData[i].Red >> 6) | (m_BitmapData[i].Green >> 7) << 2 | (m_BitmapData[i].Blue >> 7) << 3;
}
else if (BitCount == 8) {
*BufferPtr = (m_BitmapData[i].Red >> 5) | (m_BitmapData[i].Green >> 5) << 3 | (m_BitmapData[i].Blue >> 5) << 6;
}
else if (BitCount == 16) {
// Not implemented
}
if (IncludePadding) {
j++;
if (j >= w) {
for (unsigned int k = 0; k < (LineWidth - dataBytesPerLine); k++) {
BufferPtr += BitCount / 8;
}
j = 0;
}
}
BufferPtr++;
}
Result = true;
return Result;
}
/* Set Bitmap Bits. Will be converted to RGBA internally */
bool SetBits(void* Buffer, unsigned int Width, unsigned int Height, unsigned int RedMask, unsigned int GreenMask, unsigned int BlueMask, unsigned int AlphaMask = 0) {
if (Buffer == 0) {
return false;
}
uint8_t *BufferPtr = (uint8_t*)Buffer;
Dispose();
m_BitmapHeader.Width = Width;
m_BitmapHeader.Height = Height;
m_BitmapHeader.BitCount = 32;
m_BitmapHeader.Compression = 3;
m_BitmapSize = GetWidth() * GetHeight();
m_BitmapData = new RGBA[m_BitmapSize];
/* Find bit count by masks (rounded to next 8 bit boundary) */
unsigned int BitCount = (CColor::BitCountByMask(RedMask | GreenMask | BlueMask | AlphaMask) + 7) & ~7;
uint32_t BitCountRed = CColor::BitCountByMask(RedMask);
uint32_t BitCountGreen = CColor::BitCountByMask(GreenMask);
uint32_t BitCountBlue = CColor::BitCountByMask(BlueMask);
uint32_t BitCountAlpha = CColor::BitCountByMask(AlphaMask);
for (unsigned int i = 0; i < m_BitmapSize; i++) {
unsigned int Color = 0;
if (BitCount <= 8) {
Color = *((uint8_t*)BufferPtr);
BufferPtr += 1;
}
else if (BitCount <= 16) {
Color = *((uint16_t*)BufferPtr);
BufferPtr += 2;
}
else if (BitCount <= 24) {
Color = *((uint32_t*)BufferPtr);
BufferPtr += 3;
}
else if (BitCount <= 32) {
Color = *((uint32_t*)BufferPtr);
BufferPtr += 4;
}
else {
/* unsupported */
BufferPtr += 1;
}
m_BitmapData[i].Alpha = CColor::Convert(CColor::ComponentByMask(Color, AlphaMask), BitCountAlpha, 8);
m_BitmapData[i].Red = CColor::Convert(CColor::ComponentByMask(Color, RedMask), BitCountRed, 8);
m_BitmapData[i].Green = CColor::Convert(CColor::ComponentByMask(Color, GreenMask), BitCountGreen, 8);
m_BitmapData[i].Blue = CColor::Convert(CColor::ComponentByMask(Color, BlueMask), BitCountBlue, 8);
}
return true;
}
};
#endif | [
"[email protected]"
] | |
0fba9d6a4f5b9e1760d86419550191a5186e86d1 | ba62472adcd1d9ab33b296a2279593bfc00d849b | /appOne/CHARACTER.h | a8a517197aaa7ecaa35a1e5edc51e175e3eff916 | [] | no_license | m38new/cpp_action_game | 5b5485cc5c7b2008e7ab3e937b02a2f8172a92d6 | 4b5820804acd14e6776495ef3e1f3a52d8d543b4 | refs/heads/master | 2023-07-01T21:51:51.137559 | 2021-07-30T04:52:41 | 2021-07-30T04:52:41 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,558 | h | #pragma once
#include"GAME_OBJECT.h"
#include"COLOR.h"
#include"ANIMS.h"
class CHARACTER :
public GAME_OBJECT
{
public:
struct DATA {
//複数アニメor単体アニメor静止画を使用する
//複数アニメーション
class ANIMS* anims = nullptr;
int animId = 0;
//単体アニメーション
class ANIM* anim = nullptr;
ANIM_DATA animData;
//静止画
int img = 0;
//合成色
COLOR color;
char charaId = 0;
int groupId = 0;
float wx = 0;
float wy = 0;
float vx = 0;
float vy = 0;
float speed = 0;
float angle = 0;
float scale = 1;
int hp = 0;
float offsetLeft = 0;
float offsetTop = 0;
float offsetRight = 0;
float offsetBottom = 0;
};
protected:
DATA Chara;
public:
CHARACTER(class GAME* game);
virtual void create();
virtual void init();
virtual void appear(float wx , float wy, float vx, float vy);
virtual void update();
virtual void draw();
virtual void damage();
int hp() { return Chara.hp; }
int groupId() { return Chara.groupId; }
char charaId() { return Chara.charaId; }
float wLeft() { return Chara.wx + Chara.offsetLeft; }
float wTop() { return Chara.wy + Chara.offsetTop; }
float wRight() { return Chara.wx + Chara.offsetRight; }
float wBottom() { return Chara.wy + Chara.offsetBottom; }
void setImgIdx(int i) { Chara.animData.imgIdx = i; }
};
| [
"[email protected]"
] | |
cb79ea720b98dcd8f6fdcc93e6485acfe7b56473 | 72efb5e94aff7a47187c90f342121b8e1483f4c8 | /Spike12/Game State Management/Game State Management/MenuController.cpp | b38f233be8b90fb39b9473556bea5aa6e09a9e1f | [] | no_license | fantanoice/Games-Programming | f2764ee3c4b158d1ee3e83844d159c5fd184d7a0 | 2616d83501032f02b4005cb57741555ba2dbb7eb | refs/heads/master | 2021-01-01T05:47:58.082291 | 2013-11-21T02:10:27 | 2013-11-21T02:10:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | #include "MenuController.h"
#include "MenuState.h"
MenuController::~MenuController(void){
stateContainer = new StateContainer();
}
void MenuController::Menu() {
game->currentState = new MenuState();
}
void MenuController::About() {
}
void MenuController::Help() {
}
void MenuController::World() {
}
void MenuController::Game() {
}
void MenuController::HallOfFame() {
}
void MenuController::Quit() {
} | [
"[email protected]"
] | |
095027e46b87c9e5250f934b32872d17a41dded2 | 9e409a0a4333c376059ef795a336ef580c1ded20 | /codeforces/contest/1151/a/52991920.cpp | 9a214a75f762d1d201d699d00fa6a60f63e3e9bd | [] | no_license | hobby10/problems-solution | 569d4f52f7fe5d437c91041f5f6b9247c70915b1 | f35fb13a34f32b789e707b854eb0778c2c3c8484 | refs/heads/master | 2023-06-14T13:21:38.941953 | 2021-07-07T13:42:04 | 2021-07-07T13:42:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define all(v) ((v).begin()),((v).end())
#define clr(a,b) memset(a,b,sizeof(a))
void debug() {
#ifndef ONLINE_JUDGE
freopen("input.in", "rt", stdin);
// freopen("output.txt", "wt", stdout);
#endif
cout << fixed << setprecision(0);
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
}
int const N = 2e5 + 9, OO = 1e9;
int main() {
debug();
int n, mn = 1e9, cnt =0, k = 0;
string str, res = "ACTG";
cin >> n >> str;
for (int i = 0; i < n; ++i) {
if(i + 4 > n)
break;
cnt = 0, k = 0;
for (int j = i; j < i+4; ++j) {
cnt += min(abs(str[j] - res[k]), 26 - abs(str[j] - res[k]));
++k;
}
mn = min(mn, cnt);
}
cout << mn;
return 0;
} | [
"[email protected]"
] | |
e8e36729b149ab7310578bc3285be0c21c2d0c02 | 8dfce93d6891ae3e949b5f47c5ca8491d1d50230 | /Lorry.cpp | 4ae5825b9659b3d0ff666f63d02c397abd4048cb | [] | no_license | NB1723/lab2.5 | 2a00d48c34f7751bffb43dd5214733bd0fc551c7 | c5a5912ec39169f5e115494fdaffc37cfb8cab71 | refs/heads/master | 2023-04-26T20:26:17.034367 | 2021-05-18T05:14:16 | 2021-05-18T05:14:16 | 368,408,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,149 | cpp | #include "Lorry.h"
#include <sstream>
Lorry::Lorry(const string model, const int cylinder, const double power, const int capacity_of_car)
: car(model, cylinder, power), capacity_of_car(capacity_of_car)
{}
Lorry::Lorry(const Lorry& s)
{
car = s.car;
capacity_of_car = s.capacity_of_car;
}
Lorry& Lorry::operator =(const Lorry& s)
{
car = s.car;
capacity_of_car = s.capacity_of_car;
return*this;
}
ostream& operator << (ostream& out, const Lorry& s)
{
out << string(s);
return out;
}
istream& operator >> (istream& in, Lorry& s)
{
int capacity_of_car;
cout << endl;
cout << "Car = ? "; in >> s.car;
cout << "capacity_of_car = ? "; in >> capacity_of_car;
s.setCapacity_of_car(capacity_of_car);
return in;
}
Lorry::operator string () const {
stringstream ss;
ss << "capacity_of_car = " << capacity_of_car << endl;
return string(car) + ss.str();
}
Lorry& Lorry::operator ++ () {
++car;
return *this;
}
Lorry& Lorry::operator -- () {
--car;
return *this;
}
Lorry Lorry::operator ++ (int)
{
Lorry s(*this);
car++;
return s;
}
Lorry Lorry::operator -- (int)
{
Lorry s(*this);
car--;
return s;
}
Lorry::~Lorry(void)
{} | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.