blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 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 listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0005ccc198b7bc0908027fb27d0013c7905a9f9f | bffa05009ee1947d85a7f6c452dc54e8bf265682 | /BEEngine/include/BEResourceManager.h | 8df009ad87d2a9f759ced21f5e7ae46e7abc52a4 | [] | no_license | lalortiz95/BlackEngine | 4fd2aab91ac1359eb32f654f8734dacbb3908c84 | a038fd13d8d57589f4ee9ac6504a86f5c34b89dc | refs/heads/master | 2020-12-30T15:54:37.609757 | 2017-09-28T03:12:51 | 2017-09-28T03:12:51 | 91,183,217 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 728 | h | #pragma once
#include "BEResource.h"
#include <BEModule.h>
namespace BlackEngine
{
class BEGraphicsAPI;
class BE_ENGINE_EXPORT BEResourceManager : public Module<BEResourceManager>
{
public:
///Default constructor and destructor.
BEResourceManager();
~BEResourceManager();
void Initialize();
void Destroy();
BEResource* LoadResourceFromFile(const String& fileName);
void UnloadResource();
RESOURCE_TYPE GetResourceTypeFromExtension(const String& extension);
Vector<String> GetExtension(const String& fileName);
///mapa que tiene al recurso y un identificador de Úste.
Map<String, BEResource*> m_ResourcesMap;
BEGraphicsAPI* m_GA;
};
BE_ENGINE_EXPORT BEResourceManager& g_ResourceManager();
} | [
"idv14c.cortiz@uartesdigitales.edu.mx"
] | idv14c.cortiz@uartesdigitales.edu.mx |
51c12b67d38c2e8cc4b22743eee53c8a94fa776e | c50794376cf2b7fe96a853091af95976b9880cf3 | /kendryte-freertos-demo-master/shared/tensorflow/lite/tools/make/downloads/absl/absl/hash/internal/hash.h | 466299ed48fa98d11c0ebeb8564388c5a49c7a25 | [] | no_license | liren197968/GameConsole | 475ba1582c03dd86790f05be9ff326c5ad0f5699 | 05321c7bdd43b87d3b1fb6174201e9a014c7782c | refs/heads/main | 2023-03-10T08:29:26.317042 | 2021-02-18T15:33:50 | 2021-02-18T15:33:50 | 340,085,445 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,765 | h | // Copyright 2018 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// -----------------------------------------------------------------------------
// File: hash.h
// -----------------------------------------------------------------------------
//
#ifndef ABSL_HASH_INTERNAL_HASH_H_
#define ABSL_HASH_INTERNAL_HASH_H_
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <deque>
#include <forward_list>
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/base/internal/endian.h"
#include "absl/base/port.h"
#include "absl/container/fixed_array.h"
#include "absl/meta/type_traits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "absl/utility/utility.h"
#include "absl/hash/internal/city.h"
namespace absl {
namespace hash_internal {
// HashStateBase
//
// A hash state object represents an intermediate state in the computation
// of an unspecified hash algorithm. `HashStateBase` provides a CRTP style
// base class for hash state implementations. Developers adding type support
// for `absl::Hash` should not rely on any parts of the state object other than
// the following member functions:
//
// * HashStateBase::combine()
// * HashStateBase::combine_contiguous()
//
// A derived hash state class of type `H` must provide a static member function
// with a signature similar to the following:
//
// `static H combine_contiguous(H state, const unsigned char*, size_t)`.
//
// `HashStateBase` will provide a complete implementations for a hash state
// object in terms of this method.
//
// Example:
//
// // Use CRTP to define your derived class.
// struct MyHashState : HashStateBase<MyHashState> {
// static H combine_contiguous(H state, const unsigned char*, size_t);
// using MyHashState::HashStateBase::combine;
// using MyHashState::HashStateBase::combine_contiguous;
// };
template <typename H>
class HashStateBase {
public:
// HashStateBase::combine()
//
// Combines an arbitrary number of values into a hash state, returning the
// updated state.
//
// Each of the value types `T` must be separately hashable by the Abseil
// hashing framework.
//
// NOTE:
//
// state = H::combine(std::move(state), value1, value2, value3);
//
// is guaranteed to produce the same hash expansion as:
//
// state = H::combine(std::move(state), value1);
// state = H::combine(std::move(state), value2);
// state = H::combine(std::move(state), value3);
template <typename T, typename... Ts>
static H combine(H state, const T& value, const Ts&... values);
static H combine(H state) { return state; }
// HashStateBase::combine_contiguous()
//
// Combines a contiguous array of `size` elements into a hash state, returning
// the updated state.
//
// NOTE:
//
// state = H::combine_contiguous(std::move(state), data, size);
//
// is NOT guaranteed to produce the same hash expansion as a for-loop (it may
// perform internal optimizations). If you need this guarantee, use the
// for-loop instead.
template <typename T>
static H combine_contiguous(H state, const T* data, size_t size);
};
// is_uniquely_represented
//
// `is_uniquely_represented<T>` is a trait class that indicates whether `T`
// is uniquely represented.
//
// A type is "uniquely represented" if two equal values of that type are
// guaranteed to have the same bytes in their underlying storage. In other
// words, if `a == b`, then `memcmp(&a, &b, sizeof(T))` is guaranteed to be
// zero. This property cannot be detected automatically, so this trait is false
// by default, but can be specialized by types that wish to assert that they are
// uniquely represented. This makes them eligible for certain optimizations.
//
// If you have any doubt whatsoever, do not specialize this template.
// The default is completely safe, and merely disables some optimizations
// that will not matter for most types. Specializing this template,
// on the other hand, can be very hazardous.
//
// To be uniquely represented, a type must not have multiple ways of
// representing the same value; for example, float and double are not
// uniquely represented, because they have distinct representations for
// +0 and -0. Furthermore, the type's byte representation must consist
// solely of user-controlled data, with no padding bits and no compiler-
// controlled data such as vptrs or sanitizer metadata. This is usually
// very difficult to guarantee, because in most cases the compiler can
// insert data and padding bits at its own discretion.
//
// If you specialize this template for a type `T`, you must do so in the file
// that defines that type (or in this file). If you define that specialization
// anywhere else, `is_uniquely_represented<T>` could have different meanings
// in different places.
//
// The Enable parameter is meaningless; it is provided as a convenience,
// to support certain SFINAE techniques when defining specializations.
template <typename T, typename Enable = void>
struct is_uniquely_represented : std::false_type {};
// is_uniquely_represented<unsigned char>
//
// unsigned char is a synonym for "byte", so it is guaranteed to be
// uniquely represented.
template <>
struct is_uniquely_represented<unsigned char> : std::true_type {};
// is_uniquely_represented for non-standard integral types
//
// Integral types other than bool should be uniquely represented on any
// platform that this will plausibly be ported to.
template <typename Integral>
struct is_uniquely_represented<
Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>
: std::true_type {};
// is_uniquely_represented<bool>
//
//
template <>
struct is_uniquely_represented<bool> : std::false_type {};
// hash_bytes()
//
// Convenience function that combines `hash_state` with the byte representation
// of `value`.
template <typename H, typename T>
H hash_bytes(H hash_state, const T& value) {
const unsigned char* start = reinterpret_cast<const unsigned char*>(&value);
return H::combine_contiguous(std::move(hash_state), start, sizeof(value));
}
// -----------------------------------------------------------------------------
// AbslHashValue for Basic Types
// -----------------------------------------------------------------------------
// Note: Default `AbslHashValue` implementations live in `hash_internal`. This
// allows us to block lexical scope lookup when doing an unqualified call to
// `AbslHashValue` below. User-defined implementations of `AbslHashValue` can
// only be found via ADL.
// AbslHashValue() for hashing bool values
//
// We use SFINAE to ensure that this overload only accepts bool, not types that
// are convertible to bool.
template <typename H, typename B>
typename std::enable_if<std::is_same<B, bool>::value, H>::type AbslHashValue(
H hash_state, B value) {
return H::combine(std::move(hash_state),
static_cast<unsigned char>(value ? 1 : 0));
}
// AbslHashValue() for hashing enum values
template <typename H, typename Enum>
typename std::enable_if<std::is_enum<Enum>::value, H>::type AbslHashValue(
H hash_state, Enum e) {
// In practice, we could almost certainly just invoke hash_bytes directly,
// but it's possible that a sanitizer might one day want to
// store data in the unused bits of an enum. To avoid that risk, we
// convert to the underlying type before hashing. Hopefully this will get
// optimized away; if not, we can reopen discussion with c-toolchain-team.
return H::combine(std::move(hash_state),
static_cast<typename std::underlying_type<Enum>::type>(e));
}
// AbslHashValue() for hashing floating-point values
template <typename H, typename Float>
typename std::enable_if<std::is_floating_point<Float>::value, H>::type
AbslHashValue(H hash_state, Float value) {
return hash_internal::hash_bytes(std::move(hash_state),
value == 0 ? 0 : value);
}
// Long double has the property that it might have extra unused bytes in it.
// For example, in x86 sizeof(long double)==16 but it only really uses 80-bits
// of it. This means we can't use hash_bytes on a long double and have to
// convert it to something else first.
template <typename H>
H AbslHashValue(H hash_state, long double value) {
const int category = std::fpclassify(value);
switch (category) {
case FP_INFINITE:
// Add the sign bit to differentiate between +Inf and -Inf
hash_state = H::combine(std::move(hash_state), std::signbit(value));
break;
case FP_NAN:
case FP_ZERO:
default:
// Category is enough for these.
break;
case FP_NORMAL:
case FP_SUBNORMAL:
// We can't convert `value` directly to double because this would have
// undefined behavior if the value is out of range.
// std::frexp gives us a value in the range (-1, -.5] or [.5, 1) that is
// guaranteed to be in range for `double`. The truncation is
// implementation defined, but that works as long as it is deterministic.
int exp;
auto mantissa = static_cast<double>(std::frexp(value, &exp));
hash_state = H::combine(std::move(hash_state), mantissa, exp);
}
return H::combine(std::move(hash_state), category);
}
// AbslHashValue() for hashing pointers
template <typename H, typename T>
H AbslHashValue(H hash_state, T* ptr) {
return hash_internal::hash_bytes(std::move(hash_state), ptr);
}
// AbslHashValue() for hashing nullptr_t
template <typename H>
H AbslHashValue(H hash_state, std::nullptr_t) {
return H::combine(std::move(hash_state), static_cast<void*>(nullptr));
}
// -----------------------------------------------------------------------------
// AbslHashValue for Composite Types
// -----------------------------------------------------------------------------
// is_hashable()
//
// Trait class which returns true if T is hashable by the absl::Hash framework.
// Used for the AbslHashValue implementations for composite types below.
template <typename T>
struct is_hashable;
// AbslHashValue() for hashing pairs
template <typename H, typename T1, typename T2>
typename std::enable_if<is_hashable<T1>::value && is_hashable<T2>::value,
H>::type
AbslHashValue(H hash_state, const std::pair<T1, T2>& p) {
return H::combine(std::move(hash_state), p.first, p.second);
}
// hash_tuple()
//
// Helper function for hashing a tuple. The third argument should
// be an index_sequence running from 0 to tuple_size<Tuple> - 1.
template <typename H, typename Tuple, size_t... Is>
H hash_tuple(H hash_state, const Tuple& t, absl::index_sequence<Is...>) {
return H::combine(std::move(hash_state), std::get<Is>(t)...);
}
// AbslHashValue for hashing tuples
template <typename H, typename... Ts>
#if _MSC_VER
// This SFINAE gets MSVC confused under some conditions. Let's just disable it
// for now.
H
#else
typename std::enable_if<absl::conjunction<is_hashable<Ts>...>::value, H>::type
#endif
AbslHashValue(H hash_state, const std::tuple<Ts...>& t) {
return hash_internal::hash_tuple(std::move(hash_state), t,
absl::make_index_sequence<sizeof...(Ts)>());
}
// -----------------------------------------------------------------------------
// AbslHashValue for Pointers
// -----------------------------------------------------------------------------
// AbslHashValue for hashing unique_ptr
template <typename H, typename T, typename D>
H AbslHashValue(H hash_state, const std::unique_ptr<T, D>& ptr) {
return H::combine(std::move(hash_state), ptr.get());
}
// AbslHashValue for hashing shared_ptr
template <typename H, typename T>
H AbslHashValue(H hash_state, const std::shared_ptr<T>& ptr) {
return H::combine(std::move(hash_state), ptr.get());
}
// -----------------------------------------------------------------------------
// AbslHashValue for String-Like Types
// -----------------------------------------------------------------------------
// AbslHashValue for hashing strings
//
// All the string-like types supported here provide the same hash expansion for
// the same character sequence. These types are:
//
// - `std::string` (and std::basic_string<char, std::char_traits<char>, A> for
// any allocator A)
// - `absl::string_view` and `std::string_view`
//
// For simplicity, we currently support only `char` strings. This support may
// be broadened, if necessary, but with some caution - this overload would
// misbehave in cases where the traits' `eq()` member isn't equivalent to `==`
// on the underlying character type.
template <typename H>
H AbslHashValue(H hash_state, absl::string_view str) {
return H::combine(
H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
str.size());
}
// -----------------------------------------------------------------------------
// AbslHashValue for Sequence Containers
// -----------------------------------------------------------------------------
// AbslHashValue for hashing std::array
template <typename H, typename T, size_t N>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::array<T, N>& array) {
return H::combine_contiguous(std::move(hash_state), array.data(),
array.size());
}
// AbslHashValue for hashing std::deque
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::deque<T, Allocator>& deque) {
// TODO(gromer): investigate a more efficient implementation taking
// advantage of the chunk structure.
for (const auto& t : deque) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), deque.size());
}
// AbslHashValue for hashing std::forward_list
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::forward_list<T, Allocator>& list) {
size_t size = 0;
for (const T& t : list) {
hash_state = H::combine(std::move(hash_state), t);
++size;
}
return H::combine(std::move(hash_state), size);
}
// AbslHashValue for hashing std::list
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::list<T, Allocator>& list) {
for (const auto& t : list) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), list.size());
}
// AbslHashValue for hashing std::vector
//
// Do not use this for vector<bool>. It does not have a .data(), and a fallback
// for std::hash<> is most likely faster.
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value && !std::is_same<T, bool>::value,
H>::type
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
return H::combine(H::combine_contiguous(std::move(hash_state), vector.data(),
vector.size()),
vector.size());
}
// -----------------------------------------------------------------------------
// AbslHashValue for Ordered Associative Containers
// -----------------------------------------------------------------------------
// AbslHashValue for hashing std::map
template <typename H, typename Key, typename T, typename Compare,
typename Allocator>
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
H>::type
AbslHashValue(H hash_state, const std::map<Key, T, Compare, Allocator>& map) {
for (const auto& t : map) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), map.size());
}
// AbslHashValue for hashing std::multimap
template <typename H, typename Key, typename T, typename Compare,
typename Allocator>
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
H>::type
AbslHashValue(H hash_state,
const std::multimap<Key, T, Compare, Allocator>& map) {
for (const auto& t : map) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), map.size());
}
// AbslHashValue for hashing std::set
template <typename H, typename Key, typename Compare, typename Allocator>
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
H hash_state, const std::set<Key, Compare, Allocator>& set) {
for (const auto& t : set) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), set.size());
}
// AbslHashValue for hashing std::multiset
template <typename H, typename Key, typename Compare, typename Allocator>
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
H hash_state, const std::multiset<Key, Compare, Allocator>& set) {
for (const auto& t : set) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), set.size());
}
// -----------------------------------------------------------------------------
// AbslHashValue for Wrapper Types
// -----------------------------------------------------------------------------
// AbslHashValue for hashing absl::optional
template <typename H, typename T>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const absl::optional<T>& opt) {
if (opt) hash_state = H::combine(std::move(hash_state), *opt);
return H::combine(std::move(hash_state), opt.has_value());
}
// VariantVisitor
template <typename H>
struct VariantVisitor {
H&& hash_state;
template <typename T>
H operator()(const T& t) const {
return H::combine(std::move(hash_state), t);
}
};
// AbslHashValue for hashing absl::variant
template <typename H, typename... T>
typename std::enable_if<conjunction<is_hashable<T>...>::value, H>::type
AbslHashValue(H hash_state, const absl::variant<T...>& v) {
if (!v.valueless_by_exception()) {
hash_state = absl::visit(VariantVisitor<H>{std::move(hash_state)}, v);
}
return H::combine(std::move(hash_state), v.index());
}
// -----------------------------------------------------------------------------
// AbslHashValue for Other Types
// -----------------------------------------------------------------------------
// AbslHashValue for hashing std::bitset is not defined, for the same reason as
// for vector<bool> (see std::vector above): It does not expose the raw bytes,
// and a fallback to std::hash<> is most likely faster.
// -----------------------------------------------------------------------------
// hash_range_or_bytes()
//
// Mixes all values in the range [data, data+size) into the hash state.
// This overload accepts only uniquely-represented types, and hashes them by
// hashing the entire range of bytes.
template <typename H, typename T>
typename std::enable_if<is_uniquely_represented<T>::value, H>::type
hash_range_or_bytes(H hash_state, const T* data, size_t size) {
const auto* bytes = reinterpret_cast<const unsigned char*>(data);
return H::combine_contiguous(std::move(hash_state), bytes, sizeof(T) * size);
}
// hash_range_or_bytes()
template <typename H, typename T>
typename std::enable_if<!is_uniquely_represented<T>::value, H>::type
hash_range_or_bytes(H hash_state, const T* data, size_t size) {
for (const auto end = data + size; data < end; ++data) {
hash_state = H::combine(std::move(hash_state), *data);
}
return hash_state;
}
// InvokeHashTag
//
// InvokeHash(H, const T&) invokes the appropriate hash implementation for a
// hasher of type `H` and a value of type `T`. If `T` is not hashable, there
// will be no matching overload of InvokeHash().
// Note: Some platforms (eg MSVC) do not support the detect idiom on
// std::hash. In those platforms the last fallback will be std::hash and
// InvokeHash() will always have a valid overload even if std::hash<T> is not
// valid.
//
// We try the following options in order:
// * If is_uniquely_represented, hash bytes directly.
// * ADL AbslHashValue(H, const T&) call.
// * std::hash<T>
// In MSVC we can't probe std::hash or stdext::hash because it triggers a
// static_assert instead of failing substitution.
#if defined(_MSC_VER)
#undef ABSL_HASH_INTERNAL_CAN_POISON_
#else // _MSC_VER
#define ABSL_HASH_INTERNAL_CAN_POISON_ 1
#endif // _MSC_VER
#if defined(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE) && \
ABSL_HASH_INTERNAL_CAN_POISON_
#define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 1
#endif
enum class InvokeHashTag {
kUniquelyRepresented,
kHashValue,
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
kLegacyHash,
#endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
kStdHash,
kNone
};
// HashSelect
//
// Type trait to select the appropriate hash implementation to use.
// HashSelect<T>::value is an instance of InvokeHashTag that indicates the best
// available hashing mechanism.
// See `Note` above about MSVC.
template <typename T>
struct HashSelect {
private:
struct State : HashStateBase<State> {
static State combine_contiguous(State hash_state, const unsigned char*,
size_t);
using State::HashStateBase::combine_contiguous;
};
// `Probe<V, Tag>::value` evaluates to `V<T>::value` if it is a valid
// expression, and `false` otherwise.
// `Probe<V, Tag>::tag` always evaluates to `Tag`.
template <template <typename> class V, InvokeHashTag Tag>
struct Probe {
private:
template <typename U, typename std::enable_if<V<U>::value, int>::type = 0>
static std::true_type Test(int);
template <typename U>
static std::false_type Test(char);
public:
static constexpr InvokeHashTag kTag = Tag;
static constexpr bool value = decltype(
Test<absl::remove_const_t<absl::remove_reference_t<T>>>(0))::value;
};
template <typename U>
using ProbeUniquelyRepresented = is_uniquely_represented<U>;
template <typename U>
using ProbeHashValue =
std::is_same<State, decltype(AbslHashValue(std::declval<State>(),
std::declval<const U&>()))>;
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
template <typename U>
using ProbeLegacyHash =
std::is_convertible<decltype(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<
U>()(std::declval<const U&>())),
size_t>;
#endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
template <typename U>
using ProbeStdHash =
#if ABSL_HASH_INTERNAL_CAN_POISON_
std::is_convertible<decltype(std::hash<U>()(std::declval<const U&>())),
size_t>;
#else // ABSL_HASH_INTERNAL_CAN_POISON_
std::true_type;
#endif // ABSL_HASH_INTERNAL_CAN_POISON_
template <typename U>
using ProbeNone = std::true_type;
public:
// Probe each implementation in order.
// disjunction provides short circuting wrt instantiation.
static constexpr InvokeHashTag value = absl::disjunction<
Probe<ProbeUniquelyRepresented, InvokeHashTag::kUniquelyRepresented>,
Probe<ProbeHashValue, InvokeHashTag::kHashValue>,
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
Probe<ProbeLegacyHash, InvokeHashTag::kLegacyHash>,
#endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
Probe<ProbeStdHash, InvokeHashTag::kStdHash>,
Probe<ProbeNone, InvokeHashTag::kNone>>::kTag;
};
template <typename T>
struct is_hashable : std::integral_constant<bool, HashSelect<T>::value !=
InvokeHashTag::kNone> {};
template <typename H, typename T>
absl::enable_if_t<HashSelect<T>::value == InvokeHashTag::kUniquelyRepresented,
H>
InvokeHash(H state, const T& value) {
return hash_internal::hash_bytes(std::move(state), value);
}
template <typename H, typename T>
absl::enable_if_t<HashSelect<T>::value == InvokeHashTag::kHashValue, H>
InvokeHash(H state, const T& value) {
return AbslHashValue(std::move(state), value);
}
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
template <typename H, typename T>
absl::enable_if_t<HashSelect<T>::value == InvokeHashTag::kLegacyHash, H>
InvokeHash(H state, const T& value) {
return hash_internal::hash_bytes(
std::move(state), ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>{}(value));
}
#endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
template <typename H, typename T>
absl::enable_if_t<HashSelect<T>::value == InvokeHashTag::kStdHash, H>
InvokeHash(H state, const T& value) {
return hash_internal::hash_bytes(std::move(state), std::hash<T>{}(value));
}
// CityHashState
class CityHashState : public HashStateBase<CityHashState> {
// absl::uint128 is not an alias or a thin wrapper around the intrinsic.
// We use the intrinsic when available to improve performance.
#ifdef ABSL_HAVE_INTRINSIC_INT128
using uint128 = __uint128_t;
#else // ABSL_HAVE_INTRINSIC_INT128
using uint128 = absl::uint128;
#endif // ABSL_HAVE_INTRINSIC_INT128
static constexpr uint64_t kMul =
sizeof(size_t) == 4 ? uint64_t{0xcc9e2d51} : uint64_t{0x9ddfea08eb382d69};
template <typename T>
using IntegralFastPath =
conjunction<std::is_integral<T>, is_uniquely_represented<T>>;
public:
// Move only
CityHashState(CityHashState&&) = default;
CityHashState& operator=(CityHashState&&) = default;
// CityHashState::combine_contiguous()
//
// Fundamental base case for hash recursion: mixes the given range of bytes
// into the hash state.
static CityHashState combine_contiguous(CityHashState hash_state,
const unsigned char* first,
size_t size) {
return CityHashState(
CombineContiguousImpl(hash_state.state_, first, size,
std::integral_constant<int, sizeof(size_t)>{}));
}
using CityHashState::HashStateBase::combine_contiguous;
// CityHashState::hash()
//
// For performance reasons in non-opt mode, we specialize this for
// integral types.
// Otherwise we would be instantiating and calling dozens of functions for
// something that is just one multiplication and a couple xor's.
// The result should be the same as running the whole algorithm, but faster.
template <typename T, absl::enable_if_t<IntegralFastPath<T>::value, int> = 0>
static size_t hash(T value) {
return static_cast<size_t>(Mix(Seed(), static_cast<uint64_t>(value)));
}
// Overload of CityHashState::hash()
template <typename T, absl::enable_if_t<!IntegralFastPath<T>::value, int> = 0>
static size_t hash(const T& value) {
return static_cast<size_t>(combine(CityHashState{}, value).state_);
}
private:
// Invoked only once for a given argument; that plus the fact that this is
// move-only ensures that there is only one non-moved-from object.
CityHashState() : state_(Seed()) {}
// Workaround for MSVC bug.
// We make the type copyable to fix the calling convention, even though we
// never actually copy it. Keep it private to not affect the public API of the
// type.
CityHashState(const CityHashState&) = default;
explicit CityHashState(uint64_t state) : state_(state) {}
// Implementation of the base case for combine_contiguous where we actually
// mix the bytes into the state.
// Dispatch to different implementations of the combine_contiguous depending
// on the value of `sizeof(size_t)`.
static uint64_t CombineContiguousImpl(uint64_t state,
const unsigned char* first, size_t len,
std::integral_constant<int, 4>
/* sizeof_size_t */);
static uint64_t CombineContiguousImpl(uint64_t state,
const unsigned char* first, size_t len,
std::integral_constant<int, 8>
/* sizeof_size_t*/);
// Reads 9 to 16 bytes from p.
// The first 8 bytes are in .first, the rest (zero padded) bytes are in
// .second.
static std::pair<uint64_t, uint64_t> Read9To16(const unsigned char* p,
size_t len) {
uint64_t high = little_endian::Load64(p + len - 8);
return {little_endian::Load64(p), high >> (128 - len * 8)};
}
// Reads 4 to 8 bytes from p. Zero pads to fill uint64_t.
static uint64_t Read4To8(const unsigned char* p, size_t len) {
return (static_cast<uint64_t>(little_endian::Load32(p + len - 4))
<< (len - 4) * 8) |
little_endian::Load32(p);
}
// Reads 1 to 3 bytes from p. Zero pads to fill uint32_t.
static uint32_t Read1To3(const unsigned char* p, size_t len) {
return static_cast<uint32_t>((p[0]) | //
(p[len / 2] << (len / 2 * 8)) | //
(p[len - 1] << ((len - 1) * 8)));
}
ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Mix(uint64_t state, uint64_t v) {
using MultType =
absl::conditional_t<sizeof(size_t) == 4, uint64_t, uint128>;
// We do the addition in 64-bit space to make sure the 128-bit
// multiplication is fast. If we were to do it as MultType the compiler has
// to assume that the high word is non-zero and needs to perform 2
// multiplications instead of one.
MultType m = state + v;
m *= kMul;
return static_cast<uint64_t>(m ^ (m >> (sizeof(m) * 8 / 2)));
}
// Seed()
//
// A non-deterministic seed.
//
// The current purpose of this seed is to generate non-deterministic results
// and prevent having users depend on the particular hash values.
// It is not meant as a security feature right now, but it leaves the door
// open to upgrade it to a true per-process random seed. A true random seed
// costs more and we don't need to pay for that right now.
//
// On platforms with ASLR, we take advantage of it to make a per-process
// random value.
// See https://en.wikipedia.org/wiki/Address_space_layout_randomization
//
// On other platforms this is still going to be non-deterministic but most
// probably per-build and not per-process.
ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Seed() {
return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(kSeed));
}
static const void* const kSeed;
uint64_t state_;
};
// CityHashState::CombineContiguousImpl()
inline uint64_t CityHashState::CombineContiguousImpl(
uint64_t state, const unsigned char* first, size_t len,
std::integral_constant<int, 4> /* sizeof_size_t */) {
// For large values we use CityHash, for small ones we just use a
// multiplicative hash.
uint64_t v;
if (len > 8) {
v = absl::hash_internal::CityHash32(reinterpret_cast<const char*>(first), len);
} else if (len >= 4) {
v = Read4To8(first, len);
} else if (len > 0) {
v = Read1To3(first, len);
} else {
// Empty ranges have no effect.
return state;
}
return Mix(state, v);
}
// Overload of CityHashState::CombineContiguousImpl()
inline uint64_t CityHashState::CombineContiguousImpl(
uint64_t state, const unsigned char* first, size_t len,
std::integral_constant<int, 8> /* sizeof_size_t */) {
// For large values we use CityHash, for small ones we just use a
// multiplicative hash.
uint64_t v;
if (len > 16) {
v = absl::hash_internal::CityHash64(reinterpret_cast<const char*>(first), len);
} else if (len > 8) {
auto p = Read9To16(first, len);
state = Mix(state, p.first);
v = p.second;
} else if (len >= 4) {
v = Read4To8(first, len);
} else if (len > 0) {
v = Read1To3(first, len);
} else {
// Empty ranges have no effect.
return state;
}
return Mix(state, v);
}
struct AggregateBarrier {};
// HashImpl
// Add a private base class to make sure this type is not an aggregate.
// Aggregates can be aggregate initialized even if the default constructor is
// deleted.
struct PoisonedHash : private AggregateBarrier {
PoisonedHash() = delete;
PoisonedHash(const PoisonedHash&) = delete;
PoisonedHash& operator=(const PoisonedHash&) = delete;
};
template <typename T>
struct HashImpl {
size_t operator()(const T& value) const { return CityHashState::hash(value); }
};
template <typename T>
struct Hash
: absl::conditional_t<is_hashable<T>::value, HashImpl<T>, PoisonedHash> {};
template <typename H>
template <typename T, typename... Ts>
H HashStateBase<H>::combine(H state, const T& value, const Ts&... values) {
return H::combine(hash_internal::InvokeHash(std::move(state), value),
values...);
}
// HashStateBase::combine_contiguous()
template <typename H>
template <typename T>
H HashStateBase<H>::combine_contiguous(H state, const T* data, size_t size) {
return hash_internal::hash_range_or_bytes(std::move(state), data, size);
}
} // namespace hash_internal
} // namespace absl
#endif // ABSL_HASH_INTERNAL_HASH_H_
| [
"1979379768@qq.com"
] | 1979379768@qq.com |
56d4440295c17c92ca2c93168eb3712cdc00009b | 66dfa5fd4b45da193737b689ba5560d5708f049d | /source/LibFgBase/src/FgMain.cpp | 21a2002bde392535a13263e13562bb79985d6057 | [
"MIT"
] | permissive | lonelyWaiting/FaceGenBaseLibrary | 4a59d2a84d3416ac4253c912e09b76891f9d8aeb | b3594184e66f30cb7377ede4039b6a7085b8c9de | refs/heads/master | 2020-12-25T22:07:21.105068 | 2016-05-17T18:25:42 | 2016-05-17T18:25:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,015 | cpp | //
// Copyright (c) 2015 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
// Authors: Andrew Beatty
//
#include "stdafx.h"
#include "FgMain.hpp"
#include "FgDiagnostics.hpp"
#include "FgOut.hpp"
#include "FgStdString.hpp"
#include "FgSyntax.hpp"
#include "FgFileSystem.hpp"
#include "FgTime.hpp"
using namespace std;
FgArgs
fgArgs(int argc,const char * argv[])
{
FgArgs args;
for (int ii=0; ii<argc; ++ii)
args.push_back(string(argv[ii]));
return args;
}
FgArgs
fgArgs(int argc,const wchar_t * argv[])
{
FgArgs args;
for (int ii=0; ii<argc; ++ii) {
FgString tmp(argv[ii]);
args.push_back(tmp.m_str);
}
return args;
}
int
fgMainConsole(FgCmdFunc func,int argc,const char * argv[])
{
// Final EOL required to due fgout idiom of fgnl at beginning of line:
#ifdef _WIN32
// Windows cmd.exe automatically adds an EOL so we only need one more:
#define FLUSH fgout << endl
#else
#define FLUSH fgout << endl << endl
#endif
try
{
FgArgs args = fgArgs(argc,argv);
func(args);
FLUSH;
return 0;
}
catch(FgExceptionCommandSyntax const &)
{
// Don't use std::cout directly since errors need to be logged if logging is on:
fgout.setCout(true);
fgout << "RETURNS:"
<< endl << " 0 -- Successful completion"
<< endl << " -1 -- FaceGen exception"
<< endl << " -2 -- Standard library exception"
<< endl << " -3 -- Unknown exception"
<< endl << " -4 -- This message";
FLUSH;
return -4;
}
catch(FgException const & e)
{
fgout.setCout(true);
fgout << endl << "ERROR (FG exception): " << e.no_tr_message();
FLUSH;
return -1;
}
catch(std::bad_alloc const &)
{
fgout.setCout(true);
fgout << fgnl << "ERROR (std::bad_alloc): OUT OF MEMORY";
#ifndef FG_64
fgout << fgnl << "Try running a 64-bit binary instead of this 32-bit binary";
#endif
FLUSH;
return -2;
}
catch(std::exception const & e)
{
fgout.setCout(true);
fgout << endl << "ERROR (std::exception): " << e.what();
FLUSH;
return -2;
}
catch(...)
{
fgout.setCout(true);
fgout << endl << "ERROR (unknown type):";
FLUSH;
return -3;
}
}
int
fgMainConsole(FgCmdFunc func,int argc,const wchar_t * argv[])
{
try
{
FgArgs args = fgArgs(argc,argv);
func(args);
FLUSH;
return 0;
}
catch(FgExceptionCommandSyntax const &)
{
// Don't use std::cout directly since errors need to be logged if logging is on:
fgout.setCout(true);
fgout << "RETURNS:"
<< endl << " 0 -- Successful completion"
<< endl << " -1 -- FaceGen exception"
<< endl << " -2 -- Standard library exception"
<< endl << " -3 -- Unknown exception"
<< endl << " -4 -- This message";
FLUSH;
return -4;
}
catch(FgException const & e)
{
fgout.setCout(true);
fgout << endl << "ERROR (FG exception): " << e.no_tr_message();
FLUSH;
return -1;
}
catch(std::bad_alloc const &)
{
fgout.setCout(true);
fgout << fgnl << "ERROR (std::bad_alloc): OUT OF MEMORY";
#ifndef FG_64
fgout << fgnl << "Try running a 64-bit binary instead of this 32-bit binary";
#endif
FLUSH;
return -2;
}
catch(std::exception const & e)
{
fgout.setCout(true);
fgout << endl << "ERROR (std::exception): " << e.what();
FLUSH;
return -2;
}
catch(...)
{
fgout.setCout(true);
fgout << endl << "ERROR (unknown type):";
FLUSH;
return -3;
}
}
| [
"abeatty@facegen.com"
] | abeatty@facegen.com |
f80534ba7e8b321384b64aa7dde22e247721bec7 | a49413c32519c269b6e4c6d6abe4611f7ef88990 | /cpp/ItemController.h | ff6c372b5d7c65ace01a69d93b7fb8e954fdae87 | [
"MIT"
] | permissive | 0ndorio/kata_gilded_rose | 92cf85b2157a2c6b777f1658cb108568df29eaaa | 968716207192c37fd9601c7707e4d5119d62cb36 | refs/heads/master | 2021-01-13T01:04:29.482120 | 2016-04-27T22:00:51 | 2016-04-27T22:06:43 | 55,439,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | h | #ifndef ITEM_CONTROLLER_H
#define ITEM_CONTROLLER_H
#include <map>
#include <string>
#include <vector>
#include "Item.h"
class ItemController
{
public:
enum class SpecialItem {
NONE, AGED_BRIE, BACKSTAGE_PASS, SULFURAS
};
static const std::map<const SpecialItem, const std::string> names;
static SpecialItem specialItemType(const Item &item);
ItemController(std::vector<Item> &items);
void updateItems();
private:
std::vector<Item> &items;
void updateSellIn(Item &item) const;
void updateQuality(Item &item) const;
};
#endif //ITEM_CONTROLLER_H
| [
"bruno.kirschner@online.de"
] | bruno.kirschner@online.de |
8430d667557bca9ecf90ab09651f765d271d418c | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/ISA2+dmb.st+dmb.sy+po.c.cbmc.cpp | 39c918682f3ee5764d59400da292febb1f58001a | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 43,109 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 4:atom_2_X0_1:1
// 5:atom_2_X2_0:1
// 6:thr0:1
// 7:thr1:1
// 8:thr2:1
#define ADDRSIZE 9
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
buff(0,8) = 0;
pw(0,8) = 0;
cr(0,8) = 0;
iw(0,8) = 0;
cw(0,8) = 0;
cx(0,8) = 0;
is(0,8) = 0;
cs(0,8) = 0;
crmax(0,8) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
buff(1,8) = 0;
pw(1,8) = 0;
cr(1,8) = 0;
iw(1,8) = 0;
cw(1,8) = 0;
cx(1,8) = 0;
is(1,8) = 0;
cs(1,8) = 0;
crmax(1,8) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
buff(2,8) = 0;
pw(2,8) = 0;
cr(2,8) = 0;
iw(2,8) = 0;
cw(2,8) = 0;
cx(2,8) = 0;
is(2,8) = 0;
cs(2,8) = 0;
crmax(2,8) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
buff(3,8) = 0;
pw(3,8) = 0;
cr(3,8) = 0;
iw(3,8) = 0;
cw(3,8) = 0;
cx(3,8) = 0;
is(3,8) = 0;
cs(3,8) = 0;
crmax(3,8) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
mem(8+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
co(8,0) = 0;
delta(8,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46
// br label %label_1, !dbg !47
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !45), !dbg !48
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !38, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !50
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbst(), !dbg !51
// dumbst: Guess
cds[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cds[1] >= cdy[1]);
ASSUME(cds[1] >= cw(1,0+0));
ASSUME(cds[1] >= cw(1,0+1));
ASSUME(cds[1] >= cw(1,0+2));
ASSUME(cds[1] >= cw(1,3+0));
ASSUME(cds[1] >= cw(1,4+0));
ASSUME(cds[1] >= cw(1,5+0));
ASSUME(cds[1] >= cw(1,6+0));
ASSUME(cds[1] >= cw(1,7+0));
ASSUME(cds[1] >= cw(1,8+0));
ASSUME(creturn[1] >= cds[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !42, metadata !DIExpression()), !dbg !52
// call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !52
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !54
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !57, metadata !DIExpression()), !dbg !71
// br label %label_2, !dbg !53
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !70), !dbg !73
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !74
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !56
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !74
// %conv = trunc i64 %0 to i32, !dbg !57
// call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !71
// call void (...) @dmbsy(), !dbg !58
// dumbsy: Guess
old_cdy = cdy[2];
cdy[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[2] >= old_cdy);
ASSUME(cdy[2] >= cisb[2]);
ASSUME(cdy[2] >= cdl[2]);
ASSUME(cdy[2] >= cds[2]);
ASSUME(cdy[2] >= cctrl[2]);
ASSUME(cdy[2] >= cw(2,0+0));
ASSUME(cdy[2] >= cw(2,0+1));
ASSUME(cdy[2] >= cw(2,0+2));
ASSUME(cdy[2] >= cw(2,3+0));
ASSUME(cdy[2] >= cw(2,4+0));
ASSUME(cdy[2] >= cw(2,5+0));
ASSUME(cdy[2] >= cw(2,6+0));
ASSUME(cdy[2] >= cw(2,7+0));
ASSUME(cdy[2] >= cw(2,8+0));
ASSUME(cdy[2] >= cr(2,0+0));
ASSUME(cdy[2] >= cr(2,0+1));
ASSUME(cdy[2] >= cr(2,0+2));
ASSUME(cdy[2] >= cr(2,3+0));
ASSUME(cdy[2] >= cr(2,4+0));
ASSUME(cdy[2] >= cr(2,5+0));
ASSUME(cdy[2] >= cr(2,6+0));
ASSUME(cdy[2] >= cr(2,7+0));
ASSUME(cdy[2] >= cr(2,8+0));
ASSUME(creturn[2] >= cdy[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !63, metadata !DIExpression()), !dbg !78
// call void @llvm.dbg.value(metadata i64 1, metadata !65, metadata !DIExpression()), !dbg !78
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !60
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 1;
mem(0+2*1,cw(2,0+2*1)) = 1;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// %cmp = icmp eq i32 %conv, 1, !dbg !61
// %conv1 = zext i1 %cmp to i32, !dbg !61
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !66, metadata !DIExpression()), !dbg !71
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !67, metadata !DIExpression()), !dbg !81
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !69, metadata !DIExpression()), !dbg !81
// store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !63
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !64
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !86, metadata !DIExpression()), !dbg !104
// br label %label_3, !dbg !58
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !103), !dbg !106
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !88, metadata !DIExpression()), !dbg !107
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !61
// LD: Guess
old_cr = cr(3,0+2*1);
cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0+2*1)] == 3);
ASSUME(cr(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cr(3,0+2*1) >= 0);
ASSUME(cr(3,0+2*1) >= cdy[3]);
ASSUME(cr(3,0+2*1) >= cisb[3]);
ASSUME(cr(3,0+2*1) >= cdl[3]);
ASSUME(cr(3,0+2*1) >= cl[3]);
// Update
creg_r1 = cr(3,0+2*1);
crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+2*1) < cw(3,0+2*1)) {
r1 = buff(3,0+2*1);
} else {
if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) {
ASSUME(cr(3,0+2*1) >= old_cr);
}
pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1));
r1 = mem(0+2*1,cr(3,0+2*1));
}
ASSUME(creturn[3] >= cr(3,0+2*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !90, metadata !DIExpression()), !dbg !107
// %conv = trunc i64 %0 to i32, !dbg !62
// call void @llvm.dbg.value(metadata i32 %conv, metadata !87, metadata !DIExpression()), !dbg !104
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !92, metadata !DIExpression()), !dbg !110
// %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !64
// LD: Guess
old_cr = cr(3,0);
cr(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0)] == 3);
ASSUME(cr(3,0) >= iw(3,0));
ASSUME(cr(3,0) >= 0);
ASSUME(cr(3,0) >= cdy[3]);
ASSUME(cr(3,0) >= cisb[3]);
ASSUME(cr(3,0) >= cdl[3]);
ASSUME(cr(3,0) >= cl[3]);
// Update
creg_r2 = cr(3,0);
crmax(3,0) = max(crmax(3,0),cr(3,0));
caddr[3] = max(caddr[3],0);
if(cr(3,0) < cw(3,0)) {
r2 = buff(3,0);
} else {
if(pw(3,0) != co(0,cr(3,0))) {
ASSUME(cr(3,0) >= old_cr);
}
pw(3,0) = co(0,cr(3,0));
r2 = mem(0,cr(3,0));
}
ASSUME(creturn[3] >= cr(3,0));
// call void @llvm.dbg.value(metadata i64 %1, metadata !94, metadata !DIExpression()), !dbg !110
// %conv4 = trunc i64 %1 to i32, !dbg !65
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !91, metadata !DIExpression()), !dbg !104
// %cmp = icmp eq i32 %conv, 1, !dbg !66
// %conv5 = zext i1 %cmp to i32, !dbg !66
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !95, metadata !DIExpression()), !dbg !104
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !96, metadata !DIExpression()), !dbg !114
// %2 = zext i32 %conv5 to i64
// call void @llvm.dbg.value(metadata i64 %2, metadata !98, metadata !DIExpression()), !dbg !114
// store atomic i64 %2, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !68
// ST: Guess
iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,4);
cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,4)] == 3);
ASSUME(active[cw(3,4)] == 3);
ASSUME(sforbid(4,cw(3,4))== 0);
ASSUME(iw(3,4) >= max(creg_r1,0));
ASSUME(iw(3,4) >= 0);
ASSUME(cw(3,4) >= iw(3,4));
ASSUME(cw(3,4) >= old_cw);
ASSUME(cw(3,4) >= cr(3,4));
ASSUME(cw(3,4) >= cl[3]);
ASSUME(cw(3,4) >= cisb[3]);
ASSUME(cw(3,4) >= cdy[3]);
ASSUME(cw(3,4) >= cdl[3]);
ASSUME(cw(3,4) >= cds[3]);
ASSUME(cw(3,4) >= cctrl[3]);
ASSUME(cw(3,4) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,4) = (r1==1);
mem(4,cw(3,4)) = (r1==1);
co(4,cw(3,4))+=1;
delta(4,cw(3,4)) = -1;
ASSUME(creturn[3] >= cw(3,4));
// %cmp7 = icmp eq i32 %conv4, 0, !dbg !69
// %conv8 = zext i1 %cmp7 to i32, !dbg !69
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !99, metadata !DIExpression()), !dbg !104
// call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !100, metadata !DIExpression()), !dbg !117
// %3 = zext i32 %conv8 to i64
// call void @llvm.dbg.value(metadata i64 %3, metadata !102, metadata !DIExpression()), !dbg !117
// store atomic i64 %3, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !71
// ST: Guess
iw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,5);
cw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,5)] == 3);
ASSUME(active[cw(3,5)] == 3);
ASSUME(sforbid(5,cw(3,5))== 0);
ASSUME(iw(3,5) >= max(creg_r2,0));
ASSUME(iw(3,5) >= 0);
ASSUME(cw(3,5) >= iw(3,5));
ASSUME(cw(3,5) >= old_cw);
ASSUME(cw(3,5) >= cr(3,5));
ASSUME(cw(3,5) >= cl[3]);
ASSUME(cw(3,5) >= cisb[3]);
ASSUME(cw(3,5) >= cdy[3]);
ASSUME(cw(3,5) >= cdl[3]);
ASSUME(cw(3,5) >= cds[3]);
ASSUME(cw(3,5) >= cctrl[3]);
ASSUME(cw(3,5) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,5) = (r2==0);
mem(5,cw(3,5)) = (r2==0);
co(5,cw(3,5))+=1;
delta(5,cw(3,5)) = -1;
ASSUME(creturn[3] >= cw(3,5));
// ret i8* null, !dbg !72
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !127, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i8** %argv, metadata !128, metadata !DIExpression()), !dbg !167
// %0 = bitcast i64* %thr0 to i8*, !dbg !83
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !83
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !129, metadata !DIExpression()), !dbg !169
// %1 = bitcast i64* %thr1 to i8*, !dbg !85
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !85
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !133, metadata !DIExpression()), !dbg !171
// %2 = bitcast i64* %thr2 to i8*, !dbg !87
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !87
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !134, metadata !DIExpression()), !dbg !173
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !135, metadata !DIExpression()), !dbg !174
// call void @llvm.dbg.value(metadata i64 0, metadata !137, metadata !DIExpression()), !dbg !174
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !90
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !138, metadata !DIExpression()), !dbg !176
// call void @llvm.dbg.value(metadata i64 0, metadata !140, metadata !DIExpression()), !dbg !176
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !92
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !141, metadata !DIExpression()), !dbg !178
// call void @llvm.dbg.value(metadata i64 0, metadata !143, metadata !DIExpression()), !dbg !178
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !94
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !144, metadata !DIExpression()), !dbg !180
// call void @llvm.dbg.value(metadata i64 0, metadata !146, metadata !DIExpression()), !dbg !180
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !96
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !147, metadata !DIExpression()), !dbg !182
// call void @llvm.dbg.value(metadata i64 0, metadata !149, metadata !DIExpression()), !dbg !182
// store atomic i64 0, i64* @atom_2_X0_1 monotonic, align 8, !dbg !98
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !150, metadata !DIExpression()), !dbg !184
// call void @llvm.dbg.value(metadata i64 0, metadata !152, metadata !DIExpression()), !dbg !184
// store atomic i64 0, i64* @atom_2_X2_0 monotonic, align 8, !dbg !100
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !101
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !102
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call12 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !103
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !104, !tbaa !105
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r4 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r4 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r4 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !109
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !110, !tbaa !105
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r5 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r5 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r5 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call14 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !111
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !112, !tbaa !105
// LD: Guess
old_cr = cr(0,8);
cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,8)] == 0);
ASSUME(cr(0,8) >= iw(0,8));
ASSUME(cr(0,8) >= 0);
ASSUME(cr(0,8) >= cdy[0]);
ASSUME(cr(0,8) >= cisb[0]);
ASSUME(cr(0,8) >= cdl[0]);
ASSUME(cr(0,8) >= cl[0]);
// Update
creg_r6 = cr(0,8);
crmax(0,8) = max(crmax(0,8),cr(0,8));
caddr[0] = max(caddr[0],0);
if(cr(0,8) < cw(0,8)) {
r6 = buff(0,8);
} else {
if(pw(0,8) != co(8,cr(0,8))) {
ASSUME(cr(0,8) >= old_cr);
}
pw(0,8) = co(8,cr(0,8));
r6 = mem(8,cr(0,8));
}
ASSUME(creturn[0] >= cr(0,8));
// %call15 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !113
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !154, metadata !DIExpression()), !dbg !199
// %6 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !115
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %6, metadata !156, metadata !DIExpression()), !dbg !199
// %conv = trunc i64 %6 to i32, !dbg !116
// call void @llvm.dbg.value(metadata i32 %conv, metadata !153, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !158, metadata !DIExpression()), !dbg !202
// %7 = load atomic i64, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !118
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r8 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r8 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r8 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %7, metadata !160, metadata !DIExpression()), !dbg !202
// %conv19 = trunc i64 %7 to i32, !dbg !119
// call void @llvm.dbg.value(metadata i32 %conv19, metadata !157, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !162, metadata !DIExpression()), !dbg !205
// %8 = load atomic i64, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !121
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r9 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r9 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r9 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i64 %8, metadata !164, metadata !DIExpression()), !dbg !205
// %conv23 = trunc i64 %8 to i32, !dbg !122
// call void @llvm.dbg.value(metadata i32 %conv23, metadata !161, metadata !DIExpression()), !dbg !167
// %and = and i32 %conv19, %conv23, !dbg !123
creg_r10 = max(creg_r8,creg_r9);
ASSUME(active[creg_r10] == 0);
r10 = r8 & r9;
// call void @llvm.dbg.value(metadata i32 %and, metadata !165, metadata !DIExpression()), !dbg !167
// %and24 = and i32 %conv, %and, !dbg !124
creg_r11 = max(creg_r7,creg_r10);
ASSUME(active[creg_r11] == 0);
r11 = r7 & r10;
// call void @llvm.dbg.value(metadata i32 %and24, metadata !166, metadata !DIExpression()), !dbg !167
// %cmp = icmp eq i32 %and24, 1, !dbg !125
// br i1 %cmp, label %if.then, label %if.end, !dbg !127
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r11);
ASSUME(cctrl[0] >= 0);
if((r11==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([106 x i8], [106 x i8]* @.str.1, i64 0, i64 0), i32 noundef 73, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !128
// unreachable, !dbg !128
r12 = 1;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !131
// %10 = bitcast i64* %thr1 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !131
// %11 = bitcast i64* %thr0 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !131
// ret i32 0, !dbg !132
ret_thread_0 = 0;
ASSERT(r12== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
6568ce76f98645abb0d2167e9fd7b803fe94e1b1 | 3beea0b47160b4ea44fba0db7730abc1196a5b25 | /examples/example/example.ino | f46f1afab271af89142a232b6a08bedfd50d1135 | [] | no_license | huangshaun/ESP8266_ILI9341_QRCODE | 79b9cbc01ce018f4ac39ab15e63295b44bb3e406 | d9cce588f3844eb378ef7b7216d24d19d084478e | refs/heads/master | 2021-01-18T07:24:50.135499 | 2017-03-16T02:09:25 | 2017-03-16T02:09:25 | 84,288,514 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 825 | ino | /* *********************************************************************************
* ESP8266 QRcode
* dependency library :
* ESP8266 TFT Driver for ili9341 SPI display
*
* LCD_SCK --> D5
* LCD_CS --> D2
* LCD_SDI --> D7
* LCD_SDO --> D6
* LCD_DC --> D1
* LCD_RST --> RST
***********************************************************************************/
#include <SPI.h>
#include <ILI9341_QRCODE.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#define TFT_DC D1
#define TFT_CS D2
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
ILI9341_QRcode tftqrcode(&tft);
void setup()
{
Serial.begin(115200);
Serial.println("");
Serial.println("Starting...");
tft.begin();
tft.fillScreen(ILI9341_WHITE);
tftqrcode.QR_Code_create("123456",20,20);
}
void loop()
{
}
| [
"ayabreay2@hotmail.com"
] | ayabreay2@hotmail.com |
73aa598320f9a738ab7b2f9c4628a6f8b2c64cfd | 830f2fb3a85ef09eabdaff75180bc0ae12fca050 | /vEngine/vPass.h | fc60dec7ac89f706f7cab662837bc0951efa4f1e | [] | no_license | WeyrSDev/vEngine-b | abe8d34cbb75e9f50fa5d678e95e44dcc5bbd88c | f41ca718fbed00f5c143a7b2158f821274b2c020 | refs/heads/master | 2021-05-14T12:24:10.422201 | 2018-02-03T23:34:00 | 2018-02-03T23:34:00 | 116,407,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | h | #pragma once
#include "vInclude.h"
namespace vEngine {
class Engine;
class Technique;
class Pass {
public:
Pass(Engine& game, Technique& technique, ID3DX11EffectPass* pass);
private:
Pass(const Pass& rhs);
Pass& operator=(const Pass& rhs);
public:
Technique& GetTechnique();
ID3DX11EffectPass* GetPass() const;
const D3DX11_PASS_DESC& PassDesc() const;
const std::string& Name() const;
void CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC* inputElementDesc, UINT numElements, ID3D11InputLayout **inputLayout);
void Apply(UINT flags, ID3D11DeviceContext* context);
private:
Engine& mGame;
Technique& mTechnique;
ID3DX11EffectPass* mPass;
D3DX11_PASS_DESC mPassDesc;
std::string mName;
};
} | [
"damian_yarker@hotmail.com"
] | damian_yarker@hotmail.com |
a80129686288d3387ae4b8b83dbaeba4519b9395 | ebe37c98061f115d5c3307af3731360da537c8b2 | /Practice/36/C++/36/main.cpp | 88fbeb378e2b3f2132467e7c87f35a502542dcec | [] | no_license | FaeLeFly/Programming | 1d3cec1e2e29f0fa448b40c7a8f9c3be6f29b88e | b5ef566948428dfcf333f93e483620490fa352d0 | refs/heads/master | 2023-04-29T07:45:50.242403 | 2021-05-17T12:45:40 | 2021-05-17T12:45:40 | 296,833,804 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,637 | cpp | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
const auto PI = 3.141592653589793;
class Point{
enum system_coord{Cartesian, Polar};
double a1, a2;
system_coord coord_system;
std::string thing;
public:
Point(double a1 = 0, double a2 = 0, system_coord coord_system = Cartesian) {
this->a1 = a1;
this->a2 = a2;
this->coord_system = coord_system;
}
bool operator ==( Point& other) {
double x1, y1, x2, y2;
x1=get_x();
y1= get_y();
x2=other.get_x();
y2=other.get_y();
if(fabs(x1-x2)<10e-10 && fabs(y1-y2)<10e-10) return true;
return false;
}
bool operator !=( Point& other) {
return !(*this == other);
}
friend std::istream& operator >> (std::istream &what, Point &that){
std::string::size_type sz;
what >> that.thing;
std::string os= that.thing;
that.a1 = std::stod(os.substr(os.find('(',0)+1,os.find(',',0)-1),&sz);
that.a2 = std::stod(os.substr(os.find(',',0)+1,os.find(')',0)-1),&sz);
that.coord_system = Cartesian;
what.unget();
return what;
}
friend std::ostream& operator << (std::ostream &what,Point &that){
std::cout << '('<<that.a1 << ','<<that.a2 << ')' ;
return what;
}
double get_x(){
if (coord_system == Cartesian) {
return a1;
}
return get_r()*cos(get_phi());
}
double get_y(){
if (coord_system == Cartesian) {
return a2;
}
return get_r()*sin(get_phi());
}
double get_r(){
if (coord_system == Polar) {
return a1;
}
return hypot(a1, a2);
}
double get_phi(){
if (coord_system == Polar) {
return a2;
}
return atan2(a2, a1);
}
void set_x(double x){
if (coord_system == Cartesian) {
a1 = x;
return;
}
double y = get_y();
a1 = x;
a2 = y;
coord_system = Cartesian;
}
void set_y(double y){
if (coord_system == Cartesian) {
a2 = y;
return;
}
double x = get_x();
a1 = x;
a2 = y;
coord_system = Cartesian;
}
void set_r(double r){
if (coord_system == Polar) {
a1 = r;
return;
}
double phi = get_phi();
a1 = r;
a2 = phi;
coord_system = Polar;
}
void set_phi(double phi){
if (coord_system == Polar) {
a2 = phi;
return;
}
double r = get_r();
a1 = r;
a2 = phi;
coord_system = Polar;
}
};
int main() {
std::vector<Point> original;
std::ifstream fin("data.txt");
if (!fin.is_open()) {
std::cout << "Can't open file" << std::endl;
return 1;
} else {
while (!fin.eof()) {
Point p;
fin >> p;
fin.ignore(2);
original.push_back(p);
}
fin.close();
}
std::vector<Point> simulacrum(original);
for (auto& p : simulacrum) {
std::cout << p;
p.set_x(p.get_x() + 10);
p.set_phi(p.get_phi() + 180*PI/180);
p.set_y(-p.get_y());
p.set_x(-p.get_x() - 10);
std::cout << p << std::endl;
}
if (std::equal(original.begin(), original.end(), simulacrum.begin()))
std::cout << "\nIt works!\n";
else
std::cout << "\nIt not works!\n";
}
| [
"contriigor@gmail.com"
] | contriigor@gmail.com |
eaa4d82a92e96c86730fce6e715cd2fb02aed441 | 084454708583f973177dd8afc3ed1a3d87f42470 | /2021 Rocky Mountain Regional Programming Contest/I.cpp | d9cce420e7630e08c2966e6c29bb2c4eba5b1e4d | [] | no_license | truongcongthanh2000/TrainACM-ICPC-OLP | 53b0ac9de5c7f7794969bbf4f0849549357990cb | 6f5ebc7ef65ca26a332c1f69e25989f2cbe379f4 | refs/heads/master | 2022-12-12T05:53:40.785634 | 2022-12-10T09:28:09 | 2022-12-10T09:28:09 | 233,577,493 | 62 | 26 | null | null | null | null | UTF-8 | C++ | false | false | 2,428 | cpp | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define INP "input"
#define OUT "output"
/* some template */
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& a) {
out << (int)a.size() << '\n';
for (const auto& v : a) out << v << ' ';
out << endl;
return out;
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<vector<T> >& a) {
out << (int)a.size() << '\n';
for (const auto& v : a) {
for (const auto& value : v) out << value << ' ';
out << endl;
}
return out;
}
template <typename T>
std::istream& operator>>(std::istream& is, std::vector<T>& v) {
std::copy(std::istream_iterator<T>(is), std::istream_iterator<T>(), std::back_inserter(v));
return is;
}
/* end template */
const long long INF_LL = 1e18;
const int INF = 1e9 + 100;
const long double EPS = 1e-6;
const int BLOCK = 550;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
void open_file() {
#ifdef THEMIS
freopen(INP ".txt","r",stdin);
freopen(OUT ".txt","w",stdout);
#endif // THEMIS
}
const int maxN = 1e6 + 100;
const int MOD = 1e9 + 7;
void sol() {
int n, C;
cin >> n >> C;
vector<int> w(n, 0);
for (int i = 0; i < n; i++) cin >> w[i];
vector<int> ans(n + 2, 0);
int s = 0, e = 0, sum = w[0];
while (s < n) {
if (s <= e) {
ans[s] += 1;
ans[e + 1] -= 1;
}
if (e == n - 1) {
s++;
continue;
}
if (sum + w[e + 1] > C) {
sum -= w[s];
s++;
} else {
sum += w[e + 1];
e++;
}
}
for (int i = 1; i < n; i++) ans[i] += ans[i - 1];
for (int i = 0; i < n; i++) cout << ans[i] << "\n";
}
void solve() {
clock_t start, end;
start = clock();
int T = 1;
// cin >> T;
int TestCase = 0;
while (T--) {
TestCase += 1;
cerr << "Processing test = " << TestCase << '\n';
//cout << "Case #" << TestCase << ": ";
sol();
//if (T) cout << '\n';
}
end = clock();
cerr << "Time = " << (double)(end - start) / (double)CLOCKS_PER_SEC << '\n';
}
int main(int argc,char *argv[]) {
//srand(time(nullptr));
ios_base::sync_with_stdio(0); cin.tie(nullptr); cout.tie(nullptr);
open_file();
solve();
return 0;
}
| [
"truongcongthanh2000@gmail.com"
] | truongcongthanh2000@gmail.com |
08c7e533a999f7c15be3c807eea0133ec35e0aff | f57b7f5491e444ceafdfc95e9cc15e396066024a | /TP1/TP1/Club.h | f1d0ddf9e3d0ad4d31cd7db8409a491b94cd9564 | [] | no_license | BeatBender/H17_POO_MiniProjet | 6283a72e0023c7ace038c3aa3b12cbbd86a48dbc | 1603406c21cd194de065dcdbb0052a4d653a4208 | refs/heads/master | 2021-01-18T03:23:33.992651 | 2017-04-19T14:38:21 | 2017-04-19T14:38:21 | 85,825,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | h | #include <string>
#include <vector>
#ifndef CLUB_H_
#define CLUB_H_
#include "Date.h"
#include "Joueur.h"
#include "Palmares.h"
#include "Stade.h"
#include "Personne.h"
#include "Entraineur.h"
#include "Contrat.h"
using namespace std;
class Joueur;
class Personne;
class Entraineur;
class Contrat;
class Club
{
public:
Club();
~Club();
//Get
string GetNom();
string GetHistoire();
string GetCouleur();
string GetVille();
Date GetDate();
vector<Joueur*> GetEffectif();
Palmares GetPalmares();
int GetNbTitres();
vector<Entraineur*> GetEntraineurs();
Stade GetStade();
vector<Personne> GetStaff();
vector<Contrat*> GetContrat();
//Set
void SetNom();
void SetNom2(string);
void SetHistoire();
void SetCouleur();
void SetVille();
void SetDate();
void SetEffectif();
void SetPalmares();
void SetStade();
void SetStaff();
void AfficherJoueurs();
void AddContrat(Contrat*);
private:
string nom, histoire, couleur, ville;
Date annee_creation;
vector<Joueur*> effectif;
vector<Entraineur*> entraineurs;
Palmares palmares;
vector<string> titres;
Stade stade;
vector<Personne*> staff;
vector<Contrat*> contrats;
};
#endif | [
"levesque_patrick_2@hotmail.com"
] | levesque_patrick_2@hotmail.com |
1ad85c66622ddb45183f5637c609d37a0d98d9f8 | ce52632a58d2d67e55dbb21d17ceca43d0036fa0 | /include/ray/physics_capsule_component.h | 7a65278bdbe0d8dd8bfa74858666314098931817 | [
"BSD-3-Clause"
] | permissive | netdebug/ray | b17257fa53afc789802ed1cec28413b82c27ebad | 906d3991ddd232a7f78f0e51f29aeead008a139a | refs/heads/master | 2020-03-31T12:46:15.214089 | 2018-06-06T11:06:48 | 2018-06-06T11:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,951 | h | // +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software 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 ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | 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 _H_PHYSICS_CAPSULE_COMPONENT_H_
#define _H_PHYSICS_CAPSULE_COMPONENT_H_
#include <ray/physics_shape_component.h>
_NAME_BEGIN
class PhysicsShapeCapsule;
class PhysicsCapsuleComponent : public PhysicsShapeComponent
{
__DeclareSubClass(PhysicsCapsuleComponent, PhysicsShapeComponent)
public:
PhysicsCapsuleComponent() noexcept;
PhysicsCapsuleComponent(float radius, float height) noexcept;
~PhysicsCapsuleComponent() noexcept;
void setRadius(float radius) noexcept;
void setHeight(float height) noexcept;
private:
virtual void onActivate() noexcept;
virtual void onDeactivate() noexcept;
virtual PhysicsShapePtr getCollisionShape() noexcept;
virtual GameComponentPtr clone() const noexcept;
private:
PhysicsCapsuleComponent(const PhysicsCapsuleComponent&) noexcept = delete;
PhysicsCapsuleComponent& operator=(const PhysicsCapsuleComponent&)noexcept = delete;
private:
std::shared_ptr<PhysicsShapeCapsule> _shape;
};
_NAME_END
#endif | [
"2221870259@qq.com"
] | 2221870259@qq.com |
a1312ae7934820fbb9a76044c7dfb53fbf46c413 | ea47f676b998cc00da94ad59782f37dddec52995 | /hack/microwave.cpp | e90e02a588deb04213ecb75e75652e3227a00555 | [] | no_license | ChoZenTime/moneysense | 6765576be41765a8ac40b88b972753e67cd181ee | 94bde9661fd5202c378ab69af41edaa2b46ddfcb | refs/heads/master | 2020-06-06T03:14:28.747695 | 2019-04-17T09:08:43 | 2019-04-17T09:08:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,819 | cpp | #include "microwave.h"
HANDLE _out = NULL, _old_out = NULL;
HANDLE _err = NULL, _old_err = NULL;
HANDLE _in = NULL, _old_in = NULL;
namespace fridge
{
/*
* @brief Create console
*
* Create and attach a console window to the current process
*/
void AttachConsole()
{
_old_out = GetStdHandle(STD_OUTPUT_HANDLE);
_old_err = GetStdHandle(STD_ERROR_HANDLE);
_old_in = GetStdHandle(STD_INPUT_HANDLE);
::AllocConsole() && ::AttachConsole(GetCurrentProcessId());
_out = GetStdHandle(STD_OUTPUT_HANDLE);
_err = GetStdHandle(STD_ERROR_HANDLE);
_in = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(_out,
ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
SetConsoleMode(_in,
ENABLE_INSERT_MODE | ENABLE_EXTENDED_FLAGS |
ENABLE_PROCESSED_INPUT | ENABLE_QUICK_EDIT_MODE);
}
/*
* @brief Detach console
*
* Detach and destroy the attached console
*/
void DetachConsole()
{
if (_out && _err && _in) {
FreeConsole();
if (_old_out)
SetStdHandle(STD_OUTPUT_HANDLE, _old_out);
if (_old_err)
SetStdHandle(STD_ERROR_HANDLE, _old_err);
if (_old_in)
SetStdHandle(STD_INPUT_HANDLE, _old_in);
}
}
/*
* @brief Print to console
*
* Replacement to printf that works with the newly created console
*/
bool ConsolePrint(const char* fmt, ...)
{
if (!_out)
return false;
char buf[1024];
va_list va;
va_start(va, fmt);
_vsnprintf_s(buf, 1024, fmt, va);
va_end(va);//im missing 5 chromosomes
return !!WriteConsoleA(_out, buf, static_cast<DWORD>(strlen(buf)), nullptr, nullptr);
}
/*
* @brief Blocks execution until a key is pressed on the console window
*
*/
char ConsoleReadKey()
{
if (!_in)
return false;
auto key = char{ 0 };
auto keysread = DWORD{ 0 };
ReadConsoleA(_in, &key, 1, &keysread, nullptr);
return key;
}
} | [
"deikun.andre@yandex.ru"
] | deikun.andre@yandex.ru |
d5ecd1e2dd6a8dc6ec9c431544990277751eade2 | 2ea6c3b799bd32caa178f7e461e4cd399235f2f9 | /Source/TestingGrounds/TP_ThirdPerson/AI/Tasks/BTTask_SelectWaypoint.cpp | 2f9900f6286e96a3881bec54d8103b13fab92ab2 | [] | no_license | Szyszkojad666/TestingGrounds | cf06eb634b7ee90480c6d5fd6d11e3ab1e173b4e | 01be1ee6d03d1a50c572d9271c32464cbeaf27dd | refs/heads/master | 2020-04-19T19:58:14.504311 | 2019-03-06T20:33:33 | 2019-03-06T20:33:33 | 168,402,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,235 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "BTTask_SelectWaypoint.h"
#include "Components/PatrolComponent.h"
#include "Runtime/AIModule/Classes/BehaviorTree/BlackboardComponent.h"
#include "Runtime/AIModule/Classes/AIController.h"
EBTNodeResult::Type UBTTask_SelectWaypoint::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
Super::ExecuteTask(OwnerComp, NodeMemory);
auto BlackboardComp = OwnerComp.GetBlackboardComponent();
auto Index = BlackboardComp->GetValueAsInt(IndexKey.SelectedKeyName);
auto Controller = OwnerComp.GetAIOwner();
UPatrolComponent* PatrolComp;
if (Controller)
{
UActorComponent* ActorComponent = Controller->GetPawn()->GetComponentByClass(UPatrolComponent::StaticClass());
PatrolComp = Cast<UPatrolComponent>(ActorComponent);
if (PatrolComp)
{
Index = FMath::Fmod(Index + 1, PatrolComp->PatrolPoints.Num());
if (PatrolComp->PatrolPoints[Index])
{
BlackboardComp->SetValueAsObject(WaypointKey.SelectedKeyName, PatrolComp->PatrolPoints[Index]);
BlackboardComp->SetValueAsInt(IndexKey.SelectedKeyName, Index);
}
}
}
//UE_LOG(LogTemp, Warning, TEXT("Index: %i"), Index);
return EBTNodeResult::Succeeded;
}
| [
"rozmarynowski.r@gmail.com"
] | rozmarynowski.r@gmail.com |
5eae3d7fb6e4fb500ed43a1d9188d12d8c3bd764 | 57fa84e55f5944a435ec2510bfc9a64532ab9d92 | /src/qt/deftchainunits.h | 7cdea4ee46db1bfbb580b73e4971acb9ff771c3e | [
"MIT"
] | permissive | barrystyle/deftchain-0.17 | 133d3bffec152738166a01bd14d6d2a26962432a | d93b9307d8919117b10129a2828cb98833a1c9a1 | refs/heads/master | 2020-04-17T01:26:28.232962 | 2018-09-30T12:18:20 | 2018-09-30T12:20:27 | 166,091,970 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,128 | h | // Copyright (c) 2011-2018 The Bitcoin Core developers
// Copyright (c) 2018 The Deftchain developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DEFTCHAIN_QT_DEFTCHAINUNITS_H
#define DEFTCHAIN_QT_DEFTCHAINUNITS_H
#include <amount.h>
#include <QAbstractListModel>
#include <QString>
// U+2009 THIN SPACE = UTF-8 E2 80 89
#define REAL_THIN_SP_CP 0x2009
#define REAL_THIN_SP_UTF8 "\xE2\x80\x89"
#define REAL_THIN_SP_HTML " "
// U+200A HAIR SPACE = UTF-8 E2 80 8A
#define HAIR_SP_CP 0x200A
#define HAIR_SP_UTF8 "\xE2\x80\x8A"
#define HAIR_SP_HTML " "
// U+2006 SIX-PER-EM SPACE = UTF-8 E2 80 86
#define SIXPEREM_SP_CP 0x2006
#define SIXPEREM_SP_UTF8 "\xE2\x80\x86"
#define SIXPEREM_SP_HTML " "
// U+2007 FIGURE SPACE = UTF-8 E2 80 87
#define FIGURE_SP_CP 0x2007
#define FIGURE_SP_UTF8 "\xE2\x80\x87"
#define FIGURE_SP_HTML " "
// QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces
// correctly. Workaround is to display a space in a small font. If you
// change this, please test that it doesn't cause the parent span to start
// wrapping.
#define HTML_HACK_SP "<span style='white-space: nowrap; font-size: 6pt'> </span>"
// Define THIN_SP_* variables to be our preferred type of thin space
#define THIN_SP_CP REAL_THIN_SP_CP
#define THIN_SP_UTF8 REAL_THIN_SP_UTF8
#define THIN_SP_HTML HTML_HACK_SP
/** Bitcoin unit definitions. Encapsulates parsing and formatting
and serves as list model for drop-down selection boxes.
*/
class BitcoinUnits: public QAbstractListModel
{
Q_OBJECT
public:
explicit BitcoinUnits(QObject *parent);
/** Bitcoin units.
@note Source: https://en.deftchain.it/wiki/Units . Please add only sensible ones
*/
enum Unit
{
BTC,
mBTC,
uBTC,
SAT
};
enum SeparatorStyle
{
separatorNever,
separatorStandard,
separatorAlways
};
//! @name Static API
//! Unit conversion and formatting
///@{
//! Get list of units, for drop-down box
static QList<Unit> availableUnits();
//! Is unit ID valid?
static bool valid(int unit);
//! Long name
static QString longName(int unit);
//! Short name
static QString shortName(int unit);
//! Longer description
static QString description(int unit);
//! Number of Satoshis (1e-8) per unit
static qint64 factor(int unit);
//! Number of decimals left
static int decimals(int unit);
//! Format as string
static QString format(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard);
//! Format as string (with unit)
static QString formatWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard);
//! Format as HTML string (with unit)
static QString formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard);
//! Parse string to coin amount
static bool parse(int unit, const QString &value, CAmount *val_out);
//! Gets title for amount column including current display unit if optionsModel reference available */
static QString getAmountColumnTitle(int unit);
///@}
//! @name AbstractListModel implementation
//! List model for unit drop-down selection box.
///@{
enum RoleIndex {
/** Unit identifier */
UnitRole = Qt::UserRole
};
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
///@}
static QString removeSpaces(QString text)
{
text.remove(' ');
text.remove(QChar(THIN_SP_CP));
#if (THIN_SP_CP != REAL_THIN_SP_CP)
text.remove(QChar(REAL_THIN_SP_CP));
#endif
return text;
}
//! Return maximum number of base units (Satoshis)
static CAmount maxMoney();
private:
QList<BitcoinUnits::Unit> unitlist;
};
typedef BitcoinUnits::Unit BitcoinUnit;
#endif // DEFTCHAIN_QT_DEFTCHAINUNITS_H
| [
"barrystyle@westnet.com.au"
] | barrystyle@westnet.com.au |
dce4bad804509b1cc2e73568e0a67b0bf2fe54ce | 08f116e96ce5648e5ee94f6456384ef9a2fb198a | /src/map.cpp | 86b3035f3f0af87b6b38d20c8479d2926cafda71 | [] | no_license | IoMargaris/CppND-Capstone-PacMan | 36e96897a3a24e5088c1f05cb0ca80e653ebacff | 46c23640276b82f3febb9d002d333a908427b69a | refs/heads/master | 2022-12-16T06:14:36.627664 | 2020-09-06T14:38:54 | 2020-09-06T14:38:54 | 292,488,408 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | cpp | #include <iostream>
#include <sstream>
#include "map.h"
Map::Map(size_t grid_width, size_t grid_height, std::string filename)
: grid_width(grid_width), grid_height(grid_height)
{
map.resize(grid_width, std::vector<Status>(grid_height));
file.open(filename);
}
Map::~Map()
{
file.close();
}
void Map::Initialize()
{
std::string line;
char word;
char c;
int row = 0;
while (std::getline(file, line))
{
int col = 0;
std::stringstream ss(line);
while (ss >> word >> c)
{
switch (word)
{
case 'u':
SetMapElement(col, row, Status::kFree);
col++;
break;
case 'o':
SetMapElement(col, row, Status::kFood);
IncreaseTotalFood();
col++;
break;
case 'S':
SetMapElement(col, row, Status::kSpecial);
IncreaseTotalFood();
col++;
break;
case 'W':
SetMapElement(col, row, Status::kWall);
col++;
break;
default:
break;
}
}
row++;
}
}
void Map::Print()
{
for (int i = 0; i < grid_width; i++)
{
for (int j = 0; j < grid_height; j++)
{
std::cout << ParseStatus(GetMapElement(i, j)) << ' ';
}
std::cout << "\n";
}
}
char Map::ParseStatus(Status const &status) const
{
switch (status)
{
case Status::kFree:
return 'u';
break;
case Status::kFood:
return 'o';
break;
case Status::kSpecial:
return 'S';
case Status::kWall:
return 'W';
break;
default:
break;
}
}
Status Map::GetMapElement(int i, int j) const
{
return map[i][j];
}
void Map::SetMapElement(int i, int j, Status status)
{
map[i][j] = status;
} | [
"johnmargaris90@gmail.com"
] | johnmargaris90@gmail.com |
de7028e7480326cfc9db3a0fe333109c617bbd45 | 96bd3291bc2eafbe87ab8d943fd608da08b8991d | /DBProject/DB_test/DB_test/DBProviderFactory.cpp | a8984d1a7ed8f5f8767b457c7a93fa708029446c | [] | no_license | azhdan/DB | 1faecab190a70e1f1359101e3c0da934f58f1d08 | 968f701697a5950df97c95a5aeca8470275fc885 | refs/heads/master | 2021-01-10T13:21:52.021586 | 2016-03-04T11:33:20 | 2016-03-04T11:33:20 | 51,001,604 | 0 | 0 | null | 2016-03-04T11:43:04 | 2016-02-03T13:32:10 | C | UTF-8 | C++ | false | false | 150 | cpp | #include "StdAfx.h"
#include "DBProviderFactory.h"
DBProviderFactory::DBProviderFactory(void)
{
}
DBProviderFactory::~DBProviderFactory(void)
{
}
| [
"azhdan23@gmail.com"
] | azhdan23@gmail.com |
fef692aee41d641d6c9e6511acc59fbc6ecbd89f | 2759e0481ec8a3ebcad8251e20c235d1e71f3590 | /native/lib/ProductMatrix.cc | 373409c53aed5719e2920fcce1ee2450349c7f07 | [] | no_license | rhli/Degraded-First-Scheduler | 167031b6af31901ea2108bb643465eccd9222b42 | aac85775c6d5236fb64dff1855f39fa81dd6479a | refs/heads/master | 2021-01-10T22:09:59.327000 | 2014-04-22T02:48:59 | 2014-04-22T02:48:59 | 40,526,434 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,247 | cc | /* VERSION 0.1
* Now this is a systematical version
* hopefully, it will be a XORized version after several days...(Apr 17th, 2012)
* Implemented by LI Runhui from CUHK
* I just implement the most simple one of the Product Matrix paper.
* Just the MSR point, because we are more interested in the MSR side.
* d=2k-2
* alpha=k-1 ...
* I wanna make a library, which can produce the encoding matrix
* decoding scheme and so on
* Most importantly, I wanna support multi-node failure, exact repair, I mean. Hope
* this is a meaningful work.
* Further versions will cover:
* Systematic code,
* d is larger than 2k-2...
*/
# include "ProductMatrix.hh"
# define EXPERIMENT 1
# define DEGRADED_MODE 1
int enumerate_init(int range,int number,int* array){
for(int i=0;i<number;i++){
array[i]=i;
}
return 0;
}
int enumerate_next(int range,int number,int* array){
int marker=-1;
for(int i=number-1;i>=0;i--){
if(array[i]==range+i-number){
continue;
}else{
marker=i;
break;
}
}
if(marker==-1){
return 1;
}else{
array[marker]++;
for(int i=marker+1;i<number;i++){
array[i]=array[marker]+i-marker;
}
return 0;
}
}
ProductMatrix::ProductMatrix(int n,int k,int w){
_encoding_matrix=NULL;
_msg_mapping=NULL;
_delta=NULL;
_received=NULL;
_downloading_list=NULL;
_encoding_schedule=NULL;
_sr_mapping_table=NULL;
_inverse_sr_mapping_table=NULL;
_ori_encoding_matrix=NULL;
_XORed_ori_encoding_matrix=NULL;
_encode_offline_matrix=NULL;
_binary_encode_offline_matrix=NULL;
_encode_offline_schedule=NULL;
_recovery_equations=NULL;
_binary_recovery_equations=NULL;
_recovery_schedule=NULL;
_virtual_failed_list=NULL;
_repair_list=NULL;
_degraded_read_schedule=NULL;
_real_n=n;
_real_k=k;
_conf_k_=n-k+1;
_conf_n_=2*_conf_k_-1;
_fake_num=_conf_k_-_real_k;
_conf_w_=w;
_chunk_number_per_node_=_conf_k_-1;
_systemetical_chunk_num_=_conf_k_*(_conf_k_-1);
_encoded_chunk_num_=(_conf_n_-_conf_k_)*(_conf_k_-1);
_total_chunk_num_=_systemetical_chunk_num_+_encoded_chunk_num_;
_XORed_chunk_number_per_node_=_chunk_number_per_node_*_conf_w_;
_XORed_systemetical_chunk_num_=_systemetical_chunk_num_*_conf_w_;
_XORed_encoded_chunk_num_=_encoded_chunk_num_*_conf_w_;
_XORed_total_chunk_num_=_total_chunk_num_*_conf_w_;
_XOR_flag=1;
_schedule_flag=1;
_SSE_flag=1;
}
int ProductMatrix::restoreEverything(char* buffer){
memcpy((char*)&_inverse_table, buffer,sizeof(char*));
memcpy((char*)&_msg_mapping, buffer+1*sizeof(char*),sizeof(char*));
memcpy((char*)&_delta, buffer+2*sizeof(char*),sizeof(char*));
memcpy((char*)&_received, buffer+3*sizeof(char*),sizeof(char*));
memcpy((char*)&_sr_mapping_table, buffer+4*sizeof(char*),sizeof(char*));
memcpy((char*)&_inverse_sr_mapping_table, buffer+5*sizeof(char*),sizeof(char*));
memcpy((char*)&_encoding_matrix, buffer+6*sizeof(char*),sizeof(char*));
memcpy((char*)&_ori_encoding_matrix, buffer+7*sizeof(char*),sizeof(char*));
memcpy((char*)&_XORed_ori_encoding_matrix, buffer+8*sizeof(char*),sizeof(char*));
memcpy((char*)&_encoding_schedule, buffer+9*sizeof(char*),sizeof(char*));
memcpy((char*)&_encode_offline_matrix, buffer+10*sizeof(char*),sizeof(char*));
memcpy((char*)&_binary_encode_offline_matrix, buffer+11*sizeof(char*),sizeof(char*));
memcpy((char*)&_encode_offline_schedule, buffer+12*sizeof(char*),sizeof(char*));
memcpy((char*)&_recovery_equations, buffer+13*sizeof(char*),sizeof(char*));
memcpy((char*)&_binary_recovery_equations, buffer+14*sizeof(char*),sizeof(char*));
memcpy((char*)&_downloading_list, buffer+15*sizeof(char*),sizeof(char*));
memcpy((char*)&_recovery_schedule, buffer+16*sizeof(char*),sizeof(char*));
return 0;
}
int ProductMatrix::backUpEverything(char* buffer){
memcpy(buffer, (char*)&_inverse_table,sizeof(char*));
memcpy(buffer+1*sizeof(char*), (char*)&_msg_mapping,sizeof(char*));
memcpy(buffer+2*sizeof(char*), (char*)&_delta,sizeof(char*));
memcpy(buffer+3*sizeof(char*), (char*)&_received,sizeof(char*));
memcpy(buffer+4*sizeof(char*), (char*)&_sr_mapping_table,sizeof(char*));
memcpy(buffer+5*sizeof(char*), (char*)&_inverse_sr_mapping_table,sizeof(char*));
memcpy(buffer+6*sizeof(char*), (char*)&_encoding_matrix,sizeof(char*));
memcpy(buffer+7*sizeof(char*), (char*)&_ori_encoding_matrix,sizeof(char*));
memcpy(buffer+8*sizeof(char*), (char*)&_XORed_ori_encoding_matrix,sizeof(char*));
memcpy(buffer+9*sizeof(char*), (char*)&_encoding_schedule,sizeof(char*));
memcpy(buffer+10*sizeof(char*), (char*)&_encode_offline_matrix,sizeof(char*));
memcpy(buffer+11*sizeof(char*), (char*)&_binary_encode_offline_matrix,sizeof(char*));
memcpy(buffer+12*sizeof(char*), (char*)&_encode_offline_schedule,sizeof(char*));
memcpy(buffer+13*sizeof(char*), (char*)&_recovery_equations,sizeof(char*));
memcpy(buffer+14*sizeof(char*), (char*)&_binary_recovery_equations,sizeof(char*));
memcpy(buffer+15*sizeof(char*), (char*)&_downloading_list,sizeof(char*));
memcpy(buffer+16*sizeof(char*), (char*)&_recovery_schedule,sizeof(char*));
return 0;
}
int ProductMatrix::cleanup(){
/*
* mode==0 means do not free encoded related stuff
* mode==1 means free everything
*/
if(_received!=NULL){
//printf("freeing _received\n");
free(_received);
_received=NULL;
}
if(_sr_mapping_table!=NULL){
//printf("freeing _sr_mapping_table\n");
free(_sr_mapping_table);
_sr_mapping_table=NULL;
}
if(_inverse_sr_mapping_table!=NULL){
//printf("freeing _inverse_sr_mapping_table\n");
free(_inverse_sr_mapping_table);
_inverse_sr_mapping_table=NULL;
}
if(_encode_offline_matrix!=NULL){
//printf("freeing _encode_offline_matrix\n");
free(_encode_offline_matrix);
_encode_offline_matrix=NULL;
}
if(_binary_encode_offline_matrix!=NULL){
//printf("freeing _binary_encode_offline_matrix\n");
free(_binary_encode_offline_matrix);
_binary_encode_offline_matrix=NULL;
}
if(_recovery_equations!=NULL){
//printf("freeing _recovery_equations\n");
free(_recovery_equations);
_recovery_equations=NULL;
}
if(_binary_recovery_equations!=NULL){
//printf("freeing _binary_recovery_equations\n");
free(_binary_recovery_equations);
_binary_recovery_equations=NULL;
}
if(_downloading_list!=NULL){
//printf("freeing _downloading_list\n");
free(_downloading_list);
_downloading_list=NULL;
}
if(_encode_offline_schedule!=NULL){
//printf("freeing _encoding_offline_schedule\n");
jerasure_free_schedule(_encode_offline_schedule);
_encode_offline_schedule=NULL;
}
if(_recovery_schedule!=NULL){
//printf("freeing _recovery_schedule\n");
jerasure_free_schedule(_recovery_schedule);
_recovery_schedule=NULL;
}
//if(mode==1){
// if(_ori_encoding_matrix!=NULL){
// //printf("freeing _ori_encoding_matrix\n");
// free(_ori_encoding_matrix);
// _ori_encoding_matrix=NULL;
// }
// if(_XORed_ori_encoding_matrix!=NULL){
// //printf("freeing _XORed_ori_encoding_matrix\n");
// free(_XORed_ori_encoding_matrix);
// _XORed_ori_encoding_matrix=NULL;
// }
// if(_inverse_table!=NULL){
// //printf("freeing encoding_matrix\n");
// free(_inverse_table);
// _inverse_table=NULL;
// }
// if(_encoding_matrix!=NULL){
// //printf("freeing encoding_matrix\n");
// free(_encoding_matrix);
// _encoding_matrix=NULL;
// }
// if(_msg_mapping!=NULL){
// //printf("freeing _msg_mapping\n");
// free(_msg_mapping);
// _msg_mapping=NULL;
// }
// if(_delta!=NULL){
// //printf("freeing _delta\n");
// free(_delta);
// _delta=NULL;
// }
// if(_encoding_schedule!=NULL){
// //printf("freeing _encoding_schedule\n");
// jerasure_free_schedule(_encoding_schedule);
// _encoding_schedule=NULL;
// }
//}
return 0;
}
int ProductMatrix::set_f_nocal(int number,int* list){
_conf_f_=number;
_failed_node_list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
_failed_node_list[i]=list[i]+_fake_num;
}
}
int ProductMatrix::set_f(int number,int* list){
_conf_f_=number;
_failed_node_list=list;
this->multi_node_repair(_conf_f_,_failed_node_list);
if(_recovery_equations==NULL){
return 1;
}
//generate encoding_offline_matrix
/*_encode_offline_matrix=(int*)calloc(_conf_f_*(_conf_k_-1),sizeof(int));
for(int i=0;i<_conf_f_;i++){
memcpy((char*)_encode_offline_matrix+i*(_conf_k_-1)*sizeof(int),
(char*)_encoding_matrix+_failed_node_list[i]*(2*_conf_k_-2)*sizeof(int),
(_conf_k_-1)*sizeof(int));
}*/
/*if(_XOR_flag==1){
_binary_encode_offline_matrix=
jerasure_matrix_to_bitmatrix(_conf_k_-1,_conf_f_,_conf_w_,
_encode_offline_matrix);
if(_schedule_flag==1){
//generate a schedule
_encode_offline_schedule=jerasure_smart_bitmatrix_to_schedule(_conf_k_-1,_conf_f_,_conf_w_,
_binary_encode_offline_matrix);
}
}
//generate _binary_recovery_equations & corresponding schedule
if(_XOR_flag==1){
_binary_recovery_equations=
jerasure_matrix_to_bitmatrix(_conf_f_*(2*_conf_k_-2),_conf_f_*(_conf_k_-1),_conf_w_,
_recovery_equations);
if(_schedule_flag==1){
//generate recovery schedule
_recovery_schedule=
jerasure_smart_bitmatrix_to_schedule(_conf_f_*(2*_conf_k_-2),_conf_f_*(_conf_k_-1),_conf_w_,
_binary_recovery_equations);
}
}*/
return 0;
}
int ProductMatrix::set_f2_nocal(int vnumber,int* vlist,int number,int* list){
_conf_f_=vnumber;
_failed_node_list=vlist;
_repair_number=number;
_repair_list=list;
}
int ProductMatrix::set_f2(int vnumber,int* vlist,int number,int* list){
_conf_f_=vnumber;
_failed_node_list=(int*)calloc(vnumber,sizeof(int));
for(int i=0;i<number;i++){
_failed_node_list[i]=vlist[i]+_fake_num;
}
_repair_number=number;
_repair_list=list;
_repair_list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
_repair_list[i]=list[i]+_fake_num;
}
if(_recovery_equations!=NULL){
free(_recovery_equations);
_recovery_equations=NULL;
}
this->multi_node_repair(_conf_f_,_failed_node_list);
if(_recovery_equations==NULL){
return 1;
}
int* temp=(int*)calloc(_repair_number*(_conf_k_-1)*_conf_f_*(2*_conf_k_-2),sizeof(int));
int index=0;
//show_matrix(_recovery_equations,(_conf_k_-1)*vnumber,vnumber*(2*_conf_k_-2));
for(int i=0;i<_conf_f_;i++){
if(_failed_node_list[i]==_repair_list[index]){
memcpy(temp+index*(_conf_k_-1)*_conf_f_*(2*_conf_k_-2),
_recovery_equations+i*(_conf_k_-1)*_conf_f_*(2*_conf_k_-2),
(_conf_k_-1)*_conf_f_*(2*_conf_k_-2)*sizeof(int));
index++;
if(index==number){
break;
}
}
}
free(_recovery_equations);
_recovery_equations=temp;
//generate encoding_offline_matrix
_encode_offline_matrix=(int*)calloc(_conf_f_*(_conf_k_-1),sizeof(int));
for(int i=0;i<_conf_f_;i++){
memcpy((char*)_encode_offline_matrix+i*(_conf_k_-1)*sizeof(int),
(char*)_encoding_matrix+_failed_node_list[i]*(2*_conf_k_-2)*sizeof(int),(_conf_k_-1)*sizeof(int));
}
int* send_coefficient=(int *)calloc((_conf_n_-_conf_f_)*_conf_f_*_systemetical_chunk_num_,sizeof(int));
if(_XOR_flag==1){
_binary_encode_offline_matrix=jerasure_matrix_to_bitmatrix(_conf_k_-1,_conf_f_,_conf_w_,
_encode_offline_matrix);
if(_schedule_flag==1){
//generate a schedule
_encode_offline_schedule=jerasure_smart_bitmatrix_to_schedule(_conf_k_-1,_conf_f_,_conf_w_,
_binary_encode_offline_matrix);
}
}
//generate _binary_recovery_equations & corresponding schedule
if(_XOR_flag==1){
_binary_recovery_equations=jerasure_matrix_to_bitmatrix(_conf_f_*(2*_conf_k_-2),
_repair_number*(_conf_k_-1),
_conf_w_,
_recovery_equations);
//show_matrix(_binary_recovery_equations,
// _repair_number*(_conf_k_-1)*_conf_w_,
// (2*_conf_f_-2)*_conf_k_*_conf_w_);
//show_matrix(_recovery_equations,_repair_number*(_conf_k_-1),_conf_f_*(2*_conf_k_-2));
//show_matrix(_binary_recovery_equations,
// _repair_number*(_conf_k_-1)*_conf_w_,
// _conf_f_*(2*_conf_k_-2)*_conf_w_);
if(_schedule_flag==1){
//generate recovery schedule
_recovery_schedule=jerasure_smart_bitmatrix_to_schedule(_conf_f_*(2*_conf_k_-2),
_repair_number*(_conf_k_-1),
_conf_w_,
_binary_recovery_equations);
//show_shedule(_recovery_schedule);
}
}
return 0;
}
int ProductMatrix::set_f3_nocal(int vnumber,int* vlist,int number,int* list){
_conf_f_=vnumber;
_repair_number=number;
_virtual_failed_list=(int*)calloc(vnumber,sizeof(int));
_failed_node_list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
_failed_node_list[i]=list[i]+_fake_num;
}
for(int i=0;i<vnumber;i++){
_virtual_failed_list[i]=vlist[i]+_fake_num;
}
}
int ProductMatrix::set_f3(int vnumber,int* vlist,int number,int* list){
_conf_f_=vnumber;
_repair_number=number;
_virtual_failed_list=(int*)calloc(vnumber,sizeof(int));
_failed_node_list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
_failed_node_list[i]=list[i]+_fake_num;
}
for(int i=0;i<vnumber;i++){
_virtual_failed_list[i]=vlist[i]+_fake_num;
}
if(_recovery_equations!=NULL){
free(_recovery_equations);
_recovery_equations=NULL;
}
this->multi_node_repair(_conf_f_,_failed_node_list);
if(_recovery_equations==NULL){
return 1;
}
int* temp=(int*)calloc(_repair_number*(_conf_k_-1)*_conf_f_*(2*_conf_k_-2),sizeof(int));
int index=0;
//show_matrix(_recovery_equations,(_conf_k_-1)*vnumber,vnumber*(2*_conf_k_-2));
for(int i=0;i<_conf_f_;i++){
if(_failed_node_list[i]==_repair_list[index]){
memcpy(temp+index*(_conf_k_-1)*_conf_f_*(2*_conf_k_-2),
_recovery_equations+i*(_conf_k_-1)*_conf_f_*(2*_conf_k_-2),
(_conf_k_-1)*_conf_f_*(2*_conf_k_-2)*sizeof(int));
index++;
if(index==number){
break;
}
}
}
free(_recovery_equations);
_recovery_equations=temp;
//generate encoding_offline_matrix
_encode_offline_matrix=(int*)calloc(_conf_f_*(_conf_k_-1),sizeof(int));
for(int i=0;i<_conf_f_;i++){
memcpy((char*)_encode_offline_matrix+i*(_conf_k_-1)*sizeof(int),
(char*)_encoding_matrix+_failed_node_list[i]*(2*_conf_k_-2)*sizeof(int),(_conf_k_-1)*sizeof(int));
}
int* send_coefficient=(int *)calloc((_conf_n_-_conf_f_)*_conf_f_*_systemetical_chunk_num_,sizeof(int));
if(_XOR_flag==1){
_binary_encode_offline_matrix=jerasure_matrix_to_bitmatrix(_conf_k_-1,_conf_f_,_conf_w_,
_encode_offline_matrix);
if(_schedule_flag==1){
//generate a schedule
_encode_offline_schedule=jerasure_smart_bitmatrix_to_schedule(_conf_k_-1,_conf_f_,_conf_w_,
_binary_encode_offline_matrix);
}
}
//generate _binary_recovery_equations & corresponding schedule
if(_XOR_flag==1){
_binary_recovery_equations=jerasure_matrix_to_bitmatrix(_conf_f_*(2*_conf_k_-2),
_repair_number*(_conf_k_-1),
_conf_w_,
_recovery_equations);
if(_schedule_flag==1){
//generate recovery schedule
_recovery_schedule=jerasure_smart_bitmatrix_to_schedule(_conf_f_*(2*_conf_k_-2),
_repair_number*(_conf_k_-1),
_conf_w_,
_binary_recovery_equations);
}
}
return 0;
}
int ProductMatrix::systematical(){
//Let the first k node to be the systemetical node
int row_num=_conf_k_*(_conf_k_-1);
_msg_mapping=(int*)calloc(_systemetical_chunk_num_*_systemetical_chunk_num_,sizeof(int));
inverse_matrix(_ori_encoding_matrix,_msg_mapping,_conf_k_*(_conf_k_-1));
_ori_encoding_matrix=matrix_multiply2(_ori_encoding_matrix,
_msg_mapping,
_total_chunk_num_,
_systemetical_chunk_num_,_systemetical_chunk_num_);
return 0;
}
int ProductMatrix::print_parameters(){
printf("Product Matrix n:%d\n",_conf_n_);
printf("Product Matrix k:%d\n",_conf_k_);
printf("Product Matrix w:%d\n",_conf_w_);
}
int ProductMatrix::generate_encoding_matrix(){
//this is for generating encoding matrix
//construcing encoding matrix
//The coding matrix have n rows and (2k-2) columns
int row_num=_conf_n_;
int column_num=2*_conf_k_-2;
generate_inverse_table();
_encoding_matrix=(int*)calloc(row_num*column_num,sizeof(int));
_delta=(int*)calloc(_conf_n_,sizeof(int));
_received=(int*)calloc((2*_conf_k_-2)*_conf_k_*(_conf_k_-1),sizeof(int));
for(int i=0;i<_conf_n_;i++){
_encoding_matrix[i*column_num]=1;
}
int current=1;
for(int i=0;i<row_num;i++){
while(1){
if(current>pow(2,_conf_w_)){
_conf_w_++;
printf("W increased to %d\n",_conf_w_);
free(_encoding_matrix);
free(_inverse_table);
free(_delta);
free(_received);
_encoding_matrix=NULL;
generate_inverse_table();
this->generate_encoding_matrix();
return 0;
}
_encoding_matrix[i*column_num+1]=current;
for(int j=2;j<column_num;j++){
_encoding_matrix[i*column_num+j]=galois_multiply(current,_encoding_matrix[i*column_num+j-1]);
}
//distinction check
int distinct=1;
for(int j=0;j<i;j++){
if(_encoding_matrix[j*column_num+_conf_k_-1]==_encoding_matrix[i*column_num+_conf_k_-1]){
distinct=0;
break;
}
}
if(distinct==0){
current++;
continue;
}else{
_delta[i]=_encoding_matrix[i*column_num+_conf_k_-1];
current++;
break;
}
}
}
int* message_matrix=(int*)calloc((2*_conf_k_-2)*(_conf_k_-1),sizeof(int));
int index=0;
for(int i=0;i<_conf_k_-1;i++){
for(int j=i;j<_conf_k_-1;j++){
message_matrix[i*(_conf_k_-1)+j]=index;
message_matrix[j*(_conf_k_-1)+i]=index;
index++;
}
}
for(int i=0;i<_conf_k_-1;i++){
for(int j=i;j<_conf_k_-1;j++){
message_matrix[(i+_conf_k_-1)*(_conf_k_-1)+j]=index;
message_matrix[(j+_conf_k_-1)*(_conf_k_-1)+i]=index;
index++;
}
}
_ori_encoding_matrix=(int*)calloc(_conf_n_*(_conf_k_-1)*_conf_k_*(_conf_k_-1),sizeof(int));
for(int i=0;i<_conf_n_;i++){
for(int j=0;j<_conf_k_-1;j++){
for(int k=0;k<2*_conf_k_-2;k++){
int pos=message_matrix[k*(_conf_k_-1)+j];
_ori_encoding_matrix[(i*(_conf_k_-1)+j)*_conf_k_*(_conf_k_-1)+pos]=
_encoding_matrix[i*(2*_conf_k_-2)+k];
}
}
}
systematical();
if(_XOR_flag==1){
encoding_matrix_XORization();
}else{
return 0;
}
return 0;
}
int ProductMatrix::encoding_matrix_XORization(){
_XORed_ori_encoding_matrix=jerasure_matrix_to_bitmatrix(_systemetical_chunk_num_,_total_chunk_num_,_conf_w_,
_ori_encoding_matrix);
if(_schedule_flag==1){
_encoding_schedule=jerasure_smart_bitmatrix_to_schedule(_conf_k_,_conf_n_-_conf_k_,
_XORed_chunk_number_per_node_,
_XORed_ori_encoding_matrix+_XORed_systemetical_chunk_num_*_XORed_systemetical_chunk_num_);
}
return 0;
}
int ProductMatrix::show_encoding_matrix(){
for(int i=0;i<_conf_n_;i++){
for(int j=0;j<2*_conf_k_-2;j++){
printf("%4d",_encoding_matrix[i*(2*_conf_k_-2)+j]);
}
printf("\n");
}
return 0;
}
int* ProductMatrix::single_node_repair(int failed,int* _downloading_list){
if(failed>=_conf_n_){
printf("Product Matrix Error: Wrong failed node index\n");
exit(0);
}
int* origin=(int*)calloc((2*_conf_k_-2)*(2*_conf_k_-2),sizeof(int));
int index=0;
for(int i=0;i<2*_conf_k_-1;i++){
if(failed>_downloading_list[i]){
memcpy((char*)origin+i*(2*_conf_k_-2)*sizeof(int),
(char*)_encoding_matrix+_downloading_list[i]*(2*_conf_k_-2)*sizeof(int),
(2*_conf_k_-2)*sizeof(int));
}else if(failed<_downloading_list[i]){
memcpy((char*)origin+(i-1)*(2*_conf_k_-2)*sizeof(int),
(char*)_encoding_matrix+_downloading_list[i]*(2*_conf_k_-2)*sizeof(int),
(2*_conf_k_-2)*sizeof(int));
}
}
int* desmatrix=(int*)calloc((2*_conf_k_-2)*(2*_conf_k_-2),sizeof(int));
inverse_matrix(origin,desmatrix,2*_conf_k_-2);
free(origin);
return desmatrix;
}
int ProductMatrix::update_downloading_list(){
int* unlost_node=(int*)calloc(2*_conf_k_-1-_conf_f_,sizeof(int));
int connected_nodes=2*_conf_k_-1-_conf_f_;
int index=0;
for(int i=0;i<2*_conf_k_-1;i++){
if(is_failed(_downloading_list[i])==0){
unlost_node[index]=_downloading_list[i];
index++;
}
}
int marker=-1;
for(int i=connected_nodes-1;i>=0;i--){
int larger=0;
for(int j=unlost_node[i]+1;j<_conf_n_;j++){
if(is_failed(j)==0){
larger++;
}
}
if(larger==connected_nodes-1-i){
;
}else{
//find a larger index
for(int j=unlost_node[i]+1;j<_conf_n_;j++){
if(is_failed(j)==0){
unlost_node[i]=j;
break;
}
}
for(int j=i+1;j<connected_nodes;j++){
for(int k=unlost_node[j-1]+1;k<_conf_n_;k++){
if(is_failed(k)==0){
unlost_node[j]=k;
break;
}
}
}
for(int j=0;j<_conf_f_;j++){
_downloading_list[j]=_failed_node_list[j];
}
for(int j=0;j<connected_nodes;j++){
_downloading_list[j+_conf_f_]=unlost_node[j];
}
for(int k=1;k<2*_conf_k_-1;k++){
for(int j=k;j>0;j--){
if(_downloading_list[j]<_downloading_list[j-1]){
int temp=_downloading_list[j];
_downloading_list[j]=_downloading_list[j-1];
_downloading_list[j-1]=temp;
}else{
break;
}
}
}
return 0;
}
}
return 1;
}
int ProductMatrix::test_validity(int number,int* list){
this->set_f(number,list);
if(_recovery_equations!=NULL){
_virtual_failed_list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
_virtual_failed_list[i]=list[i];
}
return 0;
}else{
//Actually, it is quite rarely happened
//So the efficience is not so important
//first, let's make a list of unfailed nodes
int unfailed[_conf_n_-number];
int index=0;
for(int i=0;i<_conf_n_;i++){
int failed_flag=0;
for(int j=0;j<number;j++){
if(i==list[j]){
failed_flag=1;
break;
}
}
if(failed_flag==0){
unfailed[index]=i;
index++;
}
}
//create a new list containing the virtual failed nodes
int* added_list=(int*)calloc(_conf_n_-number,sizeof(int));
_virtual_failed_list=(int*)calloc(_conf_n_-_conf_k_,sizeof(int));
int fulfill_flag=0;
for(int i=0;i<_conf_n_-_conf_k_-number;i++){
_virtual_f=number+i+1;
//add 1+i failed nodes
enumerate_init(_conf_n_-number,i+1,added_list);
while(1){
memcpy((char*)_virtual_failed_list,(char*)list,number*sizeof(int));
//insert the virtual failed nodes
for(int j=0;j<i+1;j++){
int inserted=unfailed[added_list[j]];
//printf("inserted: %d\n",inserted);
int position=number+j;
for(int k=0;k<number+j;k++){
if(_virtual_failed_list[k]>inserted){
position=k;
break;
}
}
for(int k=number+j;k>position;k--){
_virtual_failed_list[k]=_virtual_failed_list[k-1];
}
_virtual_failed_list[position]=inserted;
}
//test whether the new list is OK
this->set_f(_virtual_f,_virtual_failed_list);
if(_recovery_equations!=NULL){
fulfill_flag=1;
break;
}else{
if(enumerate_next(_conf_n_-number,i+1,added_list)==1){
break;
}
}
}
if(fulfill_flag==1){
break;
}
}
free(added_list);
}
return _virtual_f-number;
}
int ProductMatrix::test_validity2(int number,int* ilist){
int* list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
list[i]=ilist[i]+_fake_num;
}
this->set_f(number,list);
if(_recovery_equations!=NULL){
_virtual_failed_list=(int*)calloc(number,sizeof(int));
for(int i=0;i<number;i++){
_virtual_failed_list[i]=ilist[i];
}
return 0;
}else{
//Actually, it is quite rarely happened
//So the efficience is not so important
//first, let's make a list of unfailed nodes
int unfailed[_real_n-number];
int index=0;
for(int i=_fake_num;i<_conf_n_;i++){
int failed_flag=0;
for(int j=0;j<number;j++){
if(i==list[j]){
failed_flag=1;
break;
}
}
if(failed_flag==0){
unfailed[index]=i;
index++;
}
}
//create a new list containing the virtual failed nodes
int* added_list=(int*)calloc(_real_n-number,sizeof(int));
_virtual_failed_list=(int*)calloc(_real_n-_conf_k_,sizeof(int));
int fulfill_flag=0;
for(int i=0;i<_real_n-_real_k-number;i++){
_virtual_f=number+i+1;
//add 1+i failed nodes
enumerate_init(_real_n-number,i+1,added_list);
while(1){
memcpy((char*)_virtual_failed_list,(char*)list,number*sizeof(int));
//insert the virtual failed nodes
for(int j=0;j<i+1;j++){
int inserted=unfailed[added_list[j]];
//printf("inserted: %d\n",inserted);
int position=number+j;
for(int k=0;k<number+j;k++){
if(_virtual_failed_list[k]>inserted){
position=k;
break;
}
}
for(int k=number+j;k>position;k--){
_virtual_failed_list[k]=_virtual_failed_list[k-1];
}
_virtual_failed_list[position]=inserted;
}
//test whether the new list is OK
this->set_f(_virtual_f,_virtual_failed_list);
if(_recovery_equations!=NULL){
fulfill_flag=1;
break;
}else{
if(enumerate_next(_conf_n_-number,i+1,added_list)==1){
break;
}
}
}
if(fulfill_flag==1){
break;
}
}
free(added_list);
for(int i=0;i<_virtual_f;i++){
_virtual_failed_list[i]-=_fake_num;
}
}
return _virtual_f-number;
}
int* ProductMatrix::multi_node_repair(int number,int* list){
//The number of virtual chunks is (number-1)*number
//Picking out the nodes to send data.
_downloading_list=(int*)calloc((2*_conf_k_-1),sizeof(int));
int* equations=(int*)calloc(number*number*(number-1)*(2*_conf_k_-2),sizeof(int));
_recovery_equations=(int*)calloc(number*(_conf_k_-1)*number*(2*_conf_k_-2),sizeof(int));
//int* chunks__received=(int*)calloc(number*(2*_conf_k_-2)*_conf_k_*(_conf_k_-1),sizeof(int));
int involve=0;
for(int i=0;i<number;i++){
_downloading_list[i]=list[i];
}
int index=number;
int position=0;
while(index!=2*_conf_k_-1){
int i;
for(i=0;i<index;i++){
if(_downloading_list[i]==position){
break;
}
}
if(i==index){
_downloading_list[index]=position;
index++;
}
position++;
}
//sort the downloading list
for(int i=1;i<2*_conf_k_-1;i++){
for(int j=i;j>0;j--){
if(_downloading_list[j]<_downloading_list[j-1]){
int temp=_downloading_list[j];
_downloading_list[j]=_downloading_list[j-1];
_downloading_list[j-1]=temp;
}else{
break;
}
}
}
int* coeffience=(int*)calloc(number*number*(number-1)*(number-1),sizeof(int));
int* inverse_coeffience=(int*)calloc(number*number*(number-1)*(number-1),sizeof(int));
int fposition[number];
int cposition[number*(number-1)];
//find coefficients and ...
for(int i=0;i<number;i++){
int* result=this->single_node_repair(list[i],_downloading_list);
int* equa=(int*)malloc((_conf_k_-1)*(2*_conf_k_-2)*sizeof(int));
for(int j=0;j<_conf_k_-1;j++){
for(int k=0;k<2*_conf_k_-2;k++){
equa[j*(2*_conf_k_-2)+k]=result[j*(2*_conf_k_-2)+k];
}
}
for(int j=0;j<_conf_k_-1;j++){
for(int k=0;k<2*_conf_k_-2;k++){
equa[j*(2*_conf_k_-2)+k]^=galois_multiply(_delta[list[i]],
result[(j+_conf_k_-1)*(2*_conf_k_-2)+k]);
memcpy((char*)_recovery_equations+((i*(_conf_k_-1)+j)*number+i)*(2*_conf_k_-2)*sizeof(int),
(char*)equa+j*(2*_conf_k_-2)*sizeof(int),
(2*_conf_k_-2)*sizeof(int));
}
}
for(int m=0;m<i;m++){
int* sending_coeffience=(int*)calloc((2*_conf_k_-2),sizeof(int));
int sendto=m;
for(int j=0;j<_conf_k_-1;j++){
for(int k=0;k<2*_conf_k_-2;k++){
sending_coeffience[k]^=
galois_multiply(_encoding_matrix[list[sendto]*(2*_conf_k_-2)+j],
equa[j*(2*_conf_k_-2)+k]);
}
}
memcpy((char*)equations+((i*(number-1)+m)*number*(2*_conf_k_-2)+i*(2*_conf_k_-2))*sizeof(int),
(char*)sending_coeffience,(2*_conf_k_-2)*sizeof(int));
free(sending_coeffience);
}
for(int m=i+1;m<number;m++){
int* sending_coeffience=(int*)calloc((2*_conf_k_-2),sizeof(int));
int sendto=m;
for(int j=0;j<_conf_k_-1;j++){
for(int k=0;k<2*_conf_k_-2;k++){
sending_coeffience[k]^=
galois_multiply(_encoding_matrix[list[sendto]*(2*_conf_k_-2)+j],
equa[j*(2*_conf_k_-2)+k]);
}
}
memcpy((char*)equations+((i*(number-1)+m-1)*number*(2*_conf_k_-2)+i*(2*_conf_k_-2))*sizeof(int),
(char*)sending_coeffience,(2*_conf_k_-2)*sizeof(int));
free(sending_coeffience);
}
free(equa);
free(result);
}
for(int i=0;i<number;i++){
for(int j=0;j<2*_conf_k_-1;j++){
if(list[i]==_downloading_list[j]){
fposition[i]=j;
break;
}
}
}
//cposition mean the positions of the virtual chunks
for(int i=0;i<number;i++){
for(int j=0;j<i;j++){
cposition[i*(number-1)+j]=i*(2*_conf_k_-2)+fposition[j];
}
for(int j=i+1;j<number;j++){
cposition[i*(number-1)+j-1]=i*(2*_conf_k_-2)+fposition[j]-1;
}
}
//show_matrix(equations,number*(number-1),number*(2*_conf_k_-2));
for(int i=0;i<number*(number-1);i++){
for(int j=0;j<number*(number-1);j++){
coeffience[j*number*(number-1)+i]=equations[j*number*(2*_conf_k_-2)+cposition[i]];
equations[j*number*(2*_conf_k_-2)+cposition[i]]=0;
}
}
for(int i=0;i<number*(number-1);i++){
int sender=i/(number-1);
int receiver=i%(number-1);
if(receiver>=sender){
receiver++;
}
if(receiver<sender){
sender--;
}
coeffience[i*number*(number-1)+receiver*(number-1)+sender]^=1;
}
int ret_val=inverse_matrix(coeffience,inverse_coeffience,number*(number-1));
if(ret_val==1){
show_failed_nodes();
if(update_downloading_list()==1){
free(equations);
free(coeffience);
free(inverse_coeffience);
free(_recovery_equations);
_recovery_equations=NULL;
return NULL;
}
}
int* final=matrix_multiply2(inverse_coeffience,equations,number*(number-1),
number*(2*_conf_k_-2),number*(number-1));
//show_matrix(final,number*(number-1),number*(2*_conf_k_-2));
for(int i=0;i<number*(number-1);i++){
int sender=i/(number-1);
int receiver=i%(number-1);
int column_pos;
if(receiver>=sender){
receiver++;
column_pos=sender*(2*_conf_k_-2)+fposition[receiver]-1;
}else{
column_pos=sender*(2*_conf_k_-2)+fposition[receiver];
}
for(int j=0;j<number*(_conf_k_-1);j++){
if(_recovery_equations[j*number*(2*_conf_k_-2)+column_pos]!=0){
int factor=_recovery_equations[j*number*(2*_conf_k_-2)+column_pos];
for(int k=0;k<number*(2*_conf_k_-2);k++){
_recovery_equations[j*number*(2*_conf_k_-2)+k]^=
galois_multiply(final[i*number*(2*_conf_k_-2)+k],factor);
}
_recovery_equations[j*number*(2*_conf_k_-2)+column_pos]=0;
}
}
}
//show_matrix(_recovery_equations,number*(_conf_k_-1),number*(2*_conf_k_-2));
free(equations);
free(final);
free(coeffience);
free(inverse_coeffience);
/*
* Create _sr_mapping_table, which shows the chunk position in the recovery equations
* also _inverse_sr_mapping_table, which look up chunk position by index in
* recovery equations
*/
_sr_mapping_table=(int*)calloc(_conf_f_*(2*_conf_k_-1-number),sizeof(int));
_inverse_sr_mapping_table=(int*)calloc(_conf_f_*(2*_conf_k_-2),sizeof(int));
int sen_index=0;
for(int i=0;i<2*_conf_k_-1;i++){
//i is the index of sender
if(is_failed(_downloading_list[i])==0){
//this means it is a real provider
;
}else{
continue;
}
for(int j=0;j<_conf_f_;j++){
if(_downloading_list[i]>_failed_node_list[j]){
_sr_mapping_table[sen_index*_conf_f_+j]=j*(2*_conf_k_-2)+i-1;
_inverse_sr_mapping_table[j*(2*_conf_k_-2)+i-1]=sen_index*_conf_f_+j;
}else{
_sr_mapping_table[sen_index*_conf_f_+j]=j*(2*_conf_k_-2)+i;
_inverse_sr_mapping_table[j*(2*_conf_k_-2)+i]=sen_index*_conf_f_+j;
}
}
sen_index++;
}
return _recovery_equations;
}
int ProductMatrix::encode_offline_recovery2(char* content,char* buffer,int length){
if(_XOR_flag!=1){
//Without XOR optimization, Galois Field operations
int chunksize=length/_chunk_number_per_node_;
for(int i=0;i<_chunk_number_per_node_;i++){
//Each chunk per round
char* rbuffer=content+i*chunksize;
for(int j=0;j<_conf_f_;j++){
if(_SSE_flag==0){
galois_w08_region_multiply(rbuffer,
_encode_offline_matrix[
j*_chunk_number_per_node_+i],
chunksize,
buffer+j*chunksize,1);
}else{
ff_add_mulv_local((uint8_t*)buffer+j*chunksize,
(uint8_t*)rbuffer,
_encode_offline_matrix[
j*_chunk_number_per_node_+i],
chunksize);
}
}
}
return 0;
}
int chunksize=length/_XORed_chunk_number_per_node_;
if(_XOR_flag==1){
if(_schedule_flag==1){
int index=0;
while(_encode_offline_schedule[index][0]!=-1){
if(_encode_offline_schedule[index][0]<_conf_k_-1){
XOR_buffer(buffer+((_encode_offline_schedule[index][2]-_conf_k_+1)*_conf_w_+
_encode_offline_schedule[index][3])*chunksize,
content+(_encode_offline_schedule[index][0]*_conf_w_+
_encode_offline_schedule[index][1])*chunksize,
chunksize);
}else{
XOR_buffer(buffer+((_encode_offline_schedule[index][2]-_conf_k_+1)*_conf_w_+
_encode_offline_schedule[index][3])*chunksize,
buffer+((_encode_offline_schedule[index][0]-_conf_k_+1)*_conf_w_+
_encode_offline_schedule[index][1])*chunksize,
chunksize);
}
index++;
}
}else{
for(int i=0;i<_XORed_chunk_number_per_node_;i++){
//Each chunk per round
char* rbuffer=content+i*chunksize;
for(int j=0;j<_conf_f_*_conf_w_;j++){
if(_binary_encode_offline_matrix[j*_XORed_chunk_number_per_node_+i]==0){
continue;
}
XOR_buffer(buffer+j*chunksize,rbuffer,chunksize);
}
}
}
}
return 0;
}
char* ProductMatrix::encode_offline_recovery(char* content,int length){
int chunk_num_per_node=_XORed_chunk_number_per_node_;
int chunksize=length/_XORed_chunk_number_per_node_;
char* send_chunk=(char*)calloc(_conf_f_*_conf_w_*chunksize,sizeof(char));
if(_XOR_flag==1){
if(_schedule_flag==1){
int index=0;
while(_encode_offline_schedule[index][0]!=-1){
if(_encode_offline_schedule[index][0]<(_conf_k_-1)){
XOR_buffer(send_chunk+((_encode_offline_schedule[index][2]-_conf_k_+1)*_conf_w_+
_encode_offline_schedule[index][3])*chunksize,
content+(_encode_offline_schedule[index][0]*_conf_w_+
_encode_offline_schedule[index][1])*chunksize,
chunksize);
}else{
XOR_buffer(send_chunk+((_encode_offline_schedule[index][2]-_conf_k_+1)*_conf_w_+
_encode_offline_schedule[index][3])*chunksize,
send_chunk+((_encode_offline_schedule[index][0]-_conf_k_+1)*_conf_w_+
_encode_offline_schedule[index][1])*chunksize,
chunksize);
}
index++;
}
}else{
for(int i=0;i<chunk_num_per_node;i++){
//Each chunk per round
char* rbuffer=content+i*chunksize;
for(int j=0;j<_conf_f_*_conf_w_;j++){
if(_binary_encode_offline_matrix[j*chunk_num_per_node+i]==0){
continue;
}
XOR_buffer(send_chunk+j*chunksize,rbuffer,chunksize);
}
}
}
}
return send_chunk;
}
int ProductMatrix::pos_in_downloadinglist(int index){
for(int i=0;i<2*_conf_k_-1;i++){
if(index==_downloading_list[i]){
return i;
}
}
return -1;
}
int ProductMatrix::reconstruct_lost_data3(char* received_chunks,char* reconstructed_chunks,int length){
//show_matrix(_recovery_equations,_repair_number*(_conf_k_-1),_conf_f_*(2*_conf_k_-2));
if(_XOR_flag!=1){
//Without XOR optimization
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_chunk_number_per_node_;
//printf("%d\n",chunk_size);
int rec_equations_column_num=_conf_f_*connected;
for(int i=0;i<connected_nodes;i++){
for(int j=0;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j];
char* rbuffer=received_chunks+(i*_conf_f_+j)*chunk_size;
for(int l=0;l<_repair_number*_chunk_number_per_node_;l++){
if(_SSE_flag==0){
galois_w08_region_multiply(rbuffer,
_recovery_equations[l*rec_equations_column_num+
_sr_mapping_table[i*_conf_f_+j]],
chunk_size,
reconstructed_chunks+l*chunk_size,1);
}else{
ff_add_mulv_local((uint8_t *)reconstructed_chunks+l*chunk_size,
(uint8_t*)rbuffer,
_recovery_equations[l*rec_equations_column_num+
_sr_mapping_table[i*_conf_f_+j]],
chunk_size);
}
}
}
}
return 0;
}
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_XORed_chunk_number_per_node_;
int rec_equations_column_num=_conf_f_*connected*_conf_w_;
//Do regeneration
if((_XOR_flag==1)&&(_schedule_flag==0)){
for(int i=0;i<connected_nodes;i++){
for(int j=0;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j]*_conf_w_;
for(int k=0;k<_conf_w_;k++){
//get a _received chunk
char* rbuffer=received_chunks+((i*_conf_f_+j)*_conf_w_+k)*chunk_size;
int pos_in_rec=sr_pos+k;
for(int l=0;l<_repair_number*_XORed_chunk_number_per_node_;l++){
if(_binary_recovery_equations[l*rec_equations_column_num+pos_in_rec]==1){
XOR_buffer(reconstructed_chunks+l*chunk_size,
rbuffer,
chunk_size);
}
}
}
}
}
}else if((_XOR_flag==1)&&(_schedule_flag==1)){
int index=0;
while(_recovery_schedule[index][0]!=-1){
if(_recovery_schedule[index][0]<_conf_f_*(2*_conf_k_-2)){
XOR_buffer(reconstructed_chunks+((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][3])*chunk_size,
received_chunks+(_inverse_sr_mapping_table[_recovery_schedule[index][0]]*_conf_w_+
_recovery_schedule[index][1])*chunk_size,
chunk_size);
}else{
XOR_buffer(reconstructed_chunks+((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][3])*chunk_size,
reconstructed_chunks+((_recovery_schedule[index][0]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][1])*chunk_size,
chunk_size);
}
index++;
}
}
return 0;
}
int ProductMatrix::reconstruct_lost_data4(char* received_chunks,char* reconstructed_chunks,int length){
//TODO:modify this!!!
//show_matrix(_recovery_equations,_repair_number*(_conf_k_-1),_conf_f_*(2*_conf_k_-2));
if(_XOR_flag!=1){
//Without XOR optimization
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_chunk_number_per_node_;
//printf("%d\n",chunk_size);
int rec_equations_column_num=_conf_f_*connected;
for(int i=_fake_num;i<connected_nodes;i++){
for(int j=0;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j];
char* rbuffer=received_chunks+((i-_fake_num)*_conf_f_+j)*chunk_size;
for(int l=0;l<_repair_number*_chunk_number_per_node_;l++){
if(_SSE_flag==0){
galois_w08_region_multiply(rbuffer,
_recovery_equations[l*rec_equations_column_num+
_sr_mapping_table[i*_conf_f_+j]],
chunk_size,
reconstructed_chunks+l*chunk_size,1);
}else{
ff_add_mulv_local((uint8_t *)reconstructed_chunks+l*chunk_size,
(uint8_t*)rbuffer,
_recovery_equations[l*rec_equations_column_num+
_sr_mapping_table[i*_conf_f_+j]],
chunk_size);
}
}
}
}
return 0;
}
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_XORed_chunk_number_per_node_;
int rec_equations_column_num=_conf_f_*connected*_conf_w_;
//Do regeneration
if((_XOR_flag==1)&&(_schedule_flag==0)){
for(int i=0;i<connected_nodes;i++){
for(int j=_fake_num;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j]*_conf_w_;
for(int k=0;k<_conf_w_;k++){
//get a _received chunk
char* rbuffer=received_chunks+(((i-_fake_num)*_conf_f_+j)*_conf_w_+k)*chunk_size;
int pos_in_rec=sr_pos+k;
for(int l=0;l<_repair_number*_XORed_chunk_number_per_node_;l++){
if(_binary_recovery_equations[l*rec_equations_column_num+pos_in_rec]==1){
XOR_buffer(reconstructed_chunks+l*chunk_size,
rbuffer,
chunk_size);
}
}
}
}
}
}else if((_XOR_flag==1)&&(_schedule_flag==1)){
int index=0;
int start=_fake_num*_conf_f_;
//printf("chunk size:%d\n",chunk_size);
//printf("eq addr:%x\n",_recovery_equations);
//printf("eq addr:%x\n",_binary_recovery_equations);
//for(int i=0;i<_repair_number*(_conf_k_-1)*_conf_w_;i++){
// for(int j=0;j<(2*_conf_k_-2)*_conf_f_*_conf_w_;j++){
// printf("%4d",_binary_recovery_equations[
// i*(2*_conf_k_-2)*_conf_f_*_conf_w_+j]);
// }
// printf("\n");
//}
//printf("\n");
//show_shedule(_recovery_schedule);
while(_recovery_schedule[index][0]!=-1){
//printf("%4d:%4d%4d%4d%4d%4d\n",index,
// _encoding_schedule[index][0],
// _encoding_schedule[index][1],
// _encoding_schedule[index][2],
// _encoding_schedule[index][3],
// _encoding_schedule[index][4]
// );
if((_inverse_sr_mapping_table[_recovery_schedule[index][0]]<start)
&&(_recovery_schedule[index][0]<_conf_f_*(2*_conf_k_-2))){
index++;
continue;
}
if(_recovery_schedule[index][0]<_conf_f_*(2*_conf_k_-2)){
//printf("1:%d %d\n",((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
// _recovery_schedule[index][3])*chunk_size,
// (_inverse_sr_mapping_table[_recovery_schedule[index][0]]*_conf_w_+
// _recovery_schedule[index][1]-start)*chunk_size);
XOR_buffer(reconstructed_chunks+((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][3])*chunk_size,
received_chunks+((_inverse_sr_mapping_table[_recovery_schedule[index][0]]-start)*_conf_w_+
_recovery_schedule[index][1])*chunk_size,
chunk_size);
}else{
//printf("%4d:%4d%4d%4d%4d%4d\n",index,
// _recovery_schedule[index][0],
// _recovery_schedule[index][1],
// _recovery_schedule[index][2],
// _recovery_schedule[index][3],
// _recovery_schedule[index][4]
// );
//printf("2:%d %d\n",((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
// _recovery_schedule[index][3])*chunk_size,
// ((_recovery_schedule[index][0]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
// _recovery_schedule[index][1])*chunk_size);
XOR_buffer(reconstructed_chunks+((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][3])*chunk_size,
reconstructed_chunks+((_recovery_schedule[index][0]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][1])*chunk_size,
chunk_size);
}
index++;
}
}
return 0;
}
int ProductMatrix::reconstruct_lost_data2(char* _received_chunks,char* reconstructed_chunks,int length){
if(_XOR_flag!=1){
//Without XOR optimization
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_chunk_number_per_node_;
int rec_equations_column_num=_conf_f_*connected;
for(int i=0;i<connected_nodes;i++){
for(int j=0;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j];
char* rbuffer=_received_chunks+(i*_conf_f_+j)*chunk_size;
for(int l=0;l<_conf_f_*_chunk_number_per_node_;l++){
if(_SSE_flag==0){
galois_w08_region_multiply(rbuffer,
_recovery_equations[l*rec_equations_column_num+
_sr_mapping_table[i*_conf_f_+j]],
chunk_size,
reconstructed_chunks+l*chunk_size,1);
}else{
ff_add_mulv_local((uint8_t*)reconstructed_chunks+l*chunk_size,
(uint8_t*)rbuffer,
_recovery_equations[l*rec_equations_column_num+
_sr_mapping_table[i*_conf_f_+j]],
chunk_size);
}
}
}
}
return 0;
}
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_XORed_chunk_number_per_node_;
//char* reconstructed_chunks=(char*)calloc(_conf_f_*_XORed_chunk_number_per_node_*chunk_size,sizeof(char));
int rec_equations_column_num=_conf_f_*connected*_conf_w_;
//Do regeneration
if((_XOR_flag==1)&&(_schedule_flag==0)){
for(int i=0;i<connected_nodes;i++){
for(int j=0;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j]*_conf_w_;
//printf("sr_pos:%d\n",sr_pos);
for(int k=0;k<_conf_w_;k++){
//get a _received chunk
char* rbuffer=_received_chunks+((i*_conf_f_+j)*_conf_w_+k)*chunk_size;
int pos_in_rec=sr_pos+k;
//printf(" pos_in_rec:%d\n",pos_in_rec);
for(int l=0;l<_conf_f_*_XORed_chunk_number_per_node_;l++){
//printf(" index:%d\n",l*rec_equations_column_num+pos_in_rec);
if(_binary_recovery_equations[l*rec_equations_column_num+pos_in_rec]==1){
XOR_buffer(reconstructed_chunks+l*chunk_size,
rbuffer,
chunk_size);
}
}
}
}
}
}else if((_XOR_flag==1)&&(_schedule_flag==1)){
int index=0;
while(_recovery_schedule[index][0]!=-1){
if(_recovery_schedule[index][0]<_conf_f_*(2*_conf_k_-2)){
XOR_buffer(reconstructed_chunks+((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][3])*chunk_size,
_received_chunks+(_inverse_sr_mapping_table[_recovery_schedule[index][0]]*_conf_w_+
_recovery_schedule[index][1])*chunk_size,
chunk_size);
}else{
XOR_buffer(reconstructed_chunks+((_recovery_schedule[index][2]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][3])*chunk_size,
reconstructed_chunks+((_recovery_schedule[index][0]-_conf_f_*(2*_conf_k_-2))*_conf_w_+
_recovery_schedule[index][1])*chunk_size,
chunk_size);
}
index++;
}
}
return 0;
}
char* ProductMatrix::reconstruct_lost_data(char** _received_chunks,int length){
int chunk_num_per_node=_XORed_chunk_number_per_node_;
int connected=2*_conf_k_-2;
int connected_nodes=2*_conf_k_-1-_conf_f_;
int chunk_size=length/_XORed_chunk_number_per_node_;
char* reconstructed_chunks=(char*)calloc(_conf_f_*chunk_num_per_node*chunk_size,sizeof(char));
int rec_equations_column_num=_conf_f_*connected*_conf_w_;
int* binary_recovery_equations=jerasure_matrix_to_bitmatrix(_conf_f_*(2*_conf_k_-2),_conf_f_*(_conf_k_-1),_conf_w_,
_recovery_equations);
//Do regeneration
for(int i=0;i<connected_nodes;i++){
for(int j=0;j<_conf_f_;j++){
int sr_pos=_sr_mapping_table[i*_conf_f_+j]*_conf_w_;
for(int k=0;k<_conf_w_;k++){
//get a _received chunk
char* rbuffer=_received_chunks[i]+(j*_conf_w_+k)*chunk_size;
int pos_in_rec=sr_pos+k;
for(int l=0;l<_conf_f_*chunk_num_per_node;l++){
if(binary_recovery_equations[l*rec_equations_column_num+pos_in_rec]==1){
XOR_buffer(reconstructed_chunks+l*chunk_size,
rbuffer,
chunk_size);
}
}
}
}
}
return reconstructed_chunks;
}
char* ProductMatrix::encode(char* content, int length){
int ori_chunk_num=_XORed_systemetical_chunk_num_;
int chunk_size=length/_XORed_systemetical_chunk_num_;
char* buffer=(char*)calloc(length*_conf_n_/_conf_k_,sizeof(char));
int base=_XORed_systemetical_chunk_num_*_XORed_systemetical_chunk_num_;
memcpy(buffer,content,length);
if(_schedule_flag==0){
for(int i=0;i<_XORed_encoded_chunk_num_;i++){
char* target=buffer+(_XORed_systemetical_chunk_num_+i)*chunk_size;
for(int j=0;j<_XORed_systemetical_chunk_num_;j++){
if(_XORed_ori_encoding_matrix[base+i*_XORed_systemetical_chunk_num_+j]==1){
XOR_buffer(target,content+j*chunk_size,chunk_size);
}
}
}
}else{
int index=0;
while(1){
if(_encoding_schedule[index][0]!=-1){
XOR_buffer(buffer+(_encoding_schedule[index][2]*_XORed_chunk_number_per_node_+
_encoding_schedule[index][3])*chunk_size,
buffer+(_encoding_schedule[index][0]*_XORed_chunk_number_per_node_+
_encoding_schedule[index][1])*chunk_size,
chunk_size);
index++;
}else{
break;
}
}
}
return buffer;
}
int ProductMatrix::encode2(char* content,char* buffer, int length){
if(_XOR_flag!=1){
int chunk_size=length/_systemetical_chunk_num_;
int base=_systemetical_chunk_num_*_systemetical_chunk_num_;
for(int i=0;i<_encoded_chunk_num_;i++){
char* target=buffer+i*chunk_size;
for(int j=0;j<_systemetical_chunk_num_;j++){
if(_SSE_flag==0){
galois_w08_region_multiply(content+j*chunk_size,
_ori_encoding_matrix[base+
i*_systemetical_chunk_num_+j],
chunk_size,target,1);
}else{
ff_add_mulv_local((uint8_t*)target,
(uint8_t*)content+j*chunk_size,
_ori_encoding_matrix[base+
i*_systemetical_chunk_num_+j],
chunk_size);
}
}
}
return 0;
}
int chunk_size=length/_XORed_systemetical_chunk_num_;
int base=_XORed_systemetical_chunk_num_*_XORed_systemetical_chunk_num_;
if(_schedule_flag==0){
for(int i=0;i<_XORed_encoded_chunk_num_;i++){
char* target=buffer+i*chunk_size;
for(int j=0;j<_XORed_systemetical_chunk_num_;j++){
if(_XORed_ori_encoding_matrix[base+i*_XORed_systemetical_chunk_num_+j]==1){
XOR_buffer(target,content+j*chunk_size,chunk_size);
}
}
}
}else{
int index=0;
while(1){
if(_encoding_schedule[index][0]!=-1){
if(_encoding_schedule[index][0]<_conf_k_){
XOR_buffer(buffer+((_encoding_schedule[index][2]-_conf_k_)*_XORed_chunk_number_per_node_+
_encoding_schedule[index][3])*chunk_size,
content+(_encoding_schedule[index][0]*_XORed_chunk_number_per_node_+
_encoding_schedule[index][1])*chunk_size,
chunk_size);
}else{
XOR_buffer(buffer+((_encoding_schedule[index][2]-_conf_k_)*_XORed_chunk_number_per_node_+
_encoding_schedule[index][3])*chunk_size,
buffer+((_encoding_schedule[index][0]-_conf_k_)*_XORed_chunk_number_per_node_+
_encoding_schedule[index][1])*chunk_size,
chunk_size);
}
index++;
}else{
break;
}
}
}
return 0;
}
int ProductMatrix::encode3(char* content,char* buffer, int length){
if(_XOR_flag!=1){
int chunk_size=length/_systemetical_chunk_num_;
int base=_systemetical_chunk_num_*_systemetical_chunk_num_;
int start=_fake_num*_chunk_number_per_node_;
for(int i=0;i<_encoded_chunk_num_;i++){
char* target=buffer+i*chunk_size;
for(int j=start;j<_systemetical_chunk_num_;j++){
if(_SSE_flag==0){
galois_w08_region_multiply(content+(j-start)*chunk_size,
_ori_encoding_matrix[base+
i*_systemetical_chunk_num_+j],
chunk_size,target,1);
}else{
ff_add_mulv_local((uint8_t*)target,
(uint8_t*)content+(j-start)*chunk_size,
_ori_encoding_matrix[base+
i*_systemetical_chunk_num_+j],
chunk_size);
}
}
}
return 0;
}
int chunk_size=length/(_XORed_systemetical_chunk_num_-
_fake_num*_XORed_chunk_number_per_node_);
int base=_XORed_systemetical_chunk_num_*_XORed_systemetical_chunk_num_;
int start=_fake_num*_XORed_chunk_number_per_node_;
if(_schedule_flag==0){
for(int i=0;i<_XORed_encoded_chunk_num_;i++){
char* target=buffer+i*chunk_size;
for(int j=start;j<_XORed_systemetical_chunk_num_;j++){
if(_XORed_ori_encoding_matrix[base+i*_XORed_systemetical_chunk_num_+j]==1){
XOR_buffer(target,content+(j-start)*chunk_size,chunk_size);
}
}
}
}else{
int index=0;
while(1){
if(_encoding_schedule[index][0]!=-1){
//printf("%4d:%4d%4d%4d%4d%4d\n",index,
// _encoding_schedule[index][0],
// _encoding_schedule[index][1],
// _encoding_schedule[index][2],
// _encoding_schedule[index][3],
// _encoding_schedule[index][4]
// );
if(_encoding_schedule[index][0]<(_conf_k_-_real_k)){
index++;
continue;
}
if((_encoding_schedule[index][0]<_conf_k_)){
//printf("1:%d %d\n",((_encoding_schedule[index][2]-_conf_k_)*_XORed_chunk_number_per_node_+
// _encoding_schedule[index][3])*chunk_size,
// (_encoding_schedule[index][0]*_XORed_chunk_number_per_node_+
// _encoding_schedule[index][1]-start)*chunk_size);
XOR_buffer(buffer+((_encoding_schedule[index][2]-_conf_k_)*_XORed_chunk_number_per_node_+
_encoding_schedule[index][3])*chunk_size,
content+(_encoding_schedule[index][0]*_XORed_chunk_number_per_node_+
_encoding_schedule[index][1]-start)*chunk_size,
chunk_size);
}else{
//printf("2:%d %d\n",((_encoding_schedule[index][2]-_conf_k_)*_XORed_chunk_number_per_node_+
// _encoding_schedule[index][3])*chunk_size,
// ((_encoding_schedule[index][0]-_conf_k_)*_XORed_chunk_number_per_node_+
// _encoding_schedule[index][1])*chunk_size);
XOR_buffer(buffer+((_encoding_schedule[index][2]-_conf_k_)*_XORed_chunk_number_per_node_+
_encoding_schedule[index][3])*chunk_size,
buffer+((_encoding_schedule[index][0]-_conf_k_)*_XORed_chunk_number_per_node_+
_encoding_schedule[index][1])*chunk_size,
chunk_size);
}
index++;
}else{
break;
}
}
}
return 0;
}
| [
"lrhdiy@gmail.com"
] | lrhdiy@gmail.com |
cee77d4e5cefc2420eeea3cb9798058714aaae9e | 93c74b2633e48a150bed9683bd8f2ae45c36e3cd | /nau/src/nau/math/spherical.cpp | 25d2ae3e39b2b398646939a7f3be2b3edf6db400 | [
"MIT"
] | permissive | dwlcj/nau | 24bef27516cc73c8691a52b45e589920144ae127 | a2871647bcca1dc2bf94dba7f9b94029572ab7fd | refs/heads/master | 2020-04-09T21:12:03.041212 | 2018-11-20T00:18:46 | 2018-11-20T00:18:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,580 | cpp | #include "nau/math/spherical.h"
#include "nau/math/utils.h"
using namespace nau::math;
// Tolerance factor to prevent division by 0
static const double tol = FLT_EPSILON;
vec2
Spherical::toSpherical(float x, float y ,float z)
{
vec2 result;
vec3 aux(x,y,z);
aux.normalize();
result.y = asin(aux.y);
if (aux.z >= 0)
result.x = asin(aux.x / sqrt(aux.x*aux.x + aux.z*aux.z));
else
result.x = (float)M_PI - asin(aux.x / sqrt(aux.x*aux.x + aux.z*aux.z));
return result;
}
vec3
Spherical::toCartesian(float alpha, float beta)
{
vec3 v;
float beta_aux, alpha_aux;
if (beta > M_PI * 0.5f) {
beta_aux = (float)M_PI - beta;
alpha_aux = alpha - (float)M_PI;
}
else if (beta < -(float)M_PI * 0.5f) {
beta_aux = (float)M_PI - beta;
alpha_aux = alpha - (float)M_PI;
}
else {
beta_aux = beta;
alpha_aux = alpha;
}
v.x = cos(beta_aux) * sin(alpha_aux);
v.z = cos(beta_aux) * cos(alpha_aux);
v.y = sin(beta_aux);
return v;
}
vec3
Spherical::getRightVector(float alpha, float beta)
{
float alpha_aux;
vec3 v;
if (beta > M_PI * 0.5f) {
alpha_aux = alpha - (float)M_PI * 0.5f;
}
else if (beta < -M_PI * 0.5f) {
alpha_aux = alpha - (float)M_PI * 0.5f;
}
else {
alpha_aux = alpha - (float)M_PI * 0.5f;
}
v.x = cos(0.0f) * sin(alpha_aux);
v.z = cos(0.0f) * cos(alpha_aux);
v.y = sin(0.0f);
return v;
}
vec3
Spherical::getNaturalUpVector(float alpha, float beta)
{
float alpha_aux, beta_aux;
vec3 v;
// 2nd quadrant
if (beta > M_PI * 0.5f) {
alpha_aux = alpha;
beta_aux = (float)M_PI - beta;
}
// 3rd quadrant
else if (beta < -M_PI * 0.5f) {
alpha_aux = alpha - (float)M_PI;
beta_aux = (float)M_PI - beta;
}
// 1st quadrant
else if ( beta >= 0.0f) {
alpha_aux = alpha - (float)M_PI;
beta_aux = beta;
}
// 4th quadrant
else {
alpha_aux = alpha;
beta_aux = beta;
}
v.x = (float)cos(M_PI * 0.5f - fabs(beta_aux)) * sin(alpha_aux);
v.z = (float)cos(M_PI * 0.5f - fabs(beta_aux)) * cos(alpha_aux);
v.y = (float)sin(M_PI * 0.5f - fabs(beta_aux));
return v;
//if (m_ElevationAngle >= 0)
// alpha = m_ZXAngle - M_PI;
//else
// alpha = m_ZXAngle;
//m_UpVector.x = cos( float(M_PI * 0.5 - fabs(m_ElevationAngle)) ) * sin( alpha );
//m_UpVector.z = cos( float(M_PI * 0.5 - fabs(m_ElevationAngle)) ) * cos( alpha );
//m_UpVector.y = sin( float(M_PI * 0.5 - fabs(m_ElevationAngle)) );
}
float
Spherical::capBeta(float beta)
{
if (beta > M_PI * 0.48)
return (float)M_PI * 0.48f;
else if (beta < -M_PI * 0.48)
return - (float)M_PI * 0.48f;
else
return beta;
}
| [
"arf@di.uminho.pt"
] | arf@di.uminho.pt |
963f779432ef921311a2afcee3b8e3337937ac5c | 2423df5f5e7994f84ce01a5902b3ada507b5083c | /main.cpp | cbffcdd373eecfaec594736d96dc6920fc04e88b | [] | no_license | ExXidad/Bifurkations | 4acde3d1d7b38dab3586d38dc97c9e497290f6c9 | 98473b17ad8ff5bf0f0f8a8b3a6559475ea7adb0 | refs/heads/master | 2023-03-04T10:11:11.212913 | 2021-02-13T06:19:50 | 2021-02-13T06:19:50 | 338,511,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 794 | cpp | #include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
double xNextF(const double &x, const double &r)
{
return 4 * r * x * (1 - x);
}
int main()
{
double x0Step = 0.1;
for (int x0n = 1; x0n <= 4; ++x0n)
{
std::fstream file;
file.open("../results/" + std::to_string(x0n), std::ios::out);
for (double r = 0; r <= 1; r += 0.0001)
{
double x = x0n * x0Step;
double xNext = xNextF(x, r);
bool converged = false;
for (int n = 0; n < 1000; ++n)
{
x = xNext;
xNext = xNextF(x, r);
file << r << "\t" << xNext << std::endl;
converged = true;
}
file << r << "\t" << xNext << std::endl;
// if (!converged)
// {
// std::cout << "Didn't converge" << std::endl;
// }
}
file.close();
}
return 0;
} | [
"kolesnikov.iv@gmail.com"
] | kolesnikov.iv@gmail.com |
7b2ffab1ccf22a75735be7b177cdf7bb4a56e7d3 | 57753b5f8282f7efcdf04e5ad24d84390d7e44b6 | /PlasmaSimulation/Simulation.cpp | 1522027fc319291d1f9d7440b710cd7b68f4f26b | [] | no_license | ghessova/PlasmaSimulation | 75ee23438d326186bbf2f890b238a72f47302b5b | 671d1cdefd524a5495aa30c6f12e6c4f41f5c5ae | refs/heads/master | 2020-03-24T21:06:57.970865 | 2018-09-17T22:18:25 | 2018-09-17T22:18:25 | 143,014,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,968 | cpp | #include <iostream>
#include <fstream>
#include "Simulation.h"
#include <random>
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <map>
// simulation parameters and constants
const int grid = 100;
const long int macroPartsCount = 1e5; // number of macro particles
const int steps = 100; // number of simulation steps
const double gridWidth = 1e-2; // grid width (m) // or 1e-2
const double gridHeight = 1e-2; // grid height (m)
const double particlesDensity = 1e12; // electrons per meter^2 // or 10^8
const double particlesCount = particlesDensity * gridWidth * gridHeight; // computed number of particles
const double macroPartSize = particlesCount / macroPartsCount; // number of particles (ions / electrons) in macro particle (real/used particles) .. or 1e8
const double q = 1.60217662e-19; // charge of electron
const double macroQ = macroPartSize * q;
const double maxVelocity = 1;
const double epsilon = 8.854e-12; // permitivity
const double elMass = 9.1e-31; // electron mass (kg)
const double ionMass = 1.673e-27; // ion mass (kg)
const double PI = 3.141592653589793;
// magnetic field
const double theta = PI / 4; // angle
const double B0 = 1.15; // size
//int crashCount;
int plateCrashCount; // number of particles that crashed on the plates
int gapCount; // number of particles in the gap
const double gap = 0.2 * gridWidth; // gap width: ----------- ----------
const double plateHeight = 0.23 * gridHeight; // height of the plates surroundind the gap
double elPotential[grid + 1][grid + 1]; // phi - electron potential field (nodes)
double iontPotential[grid + 1][grid + 1]; // rho - ion potential field
double cellWidth = gridWidth / grid;
double cellHeight = gridHeight / grid;
const double T_e = 1e7; // electron temperature (Kelvins)
const double T_i = 1e7; // ion temperature (Kelvins)
const double k_B = 1.38064852e-23; // m2 kg s-2 K-1 (Boltzman)
double cMult = macroPartsCount / macroPartSize;
const double v_Te = sqrt((k_B * T_e) / (cMult * elMass)); // m s-1
const double v_Ti = sqrt((k_B * T_i) / (cMult * ionMass));
//double const dt = 1e-12;
// Half of maximum allowed time not to croos double cell (conditions are allright)
double const dt = 5e-12;
// Constructor
Simulation::Simulation() {
}
// initialize specified 2D field to 0
void init2DField(double field[grid + 1][grid + 1]) {
for (int x = 0; x < grid + 1; x++) {
for (int y = 0; y < grid + 1; y++) {
field[x][y] = 0;
}
}
}
std::vector<double> operator+(std::vector<double> a, std::vector<double> b) {
std::vector<double> res(a.size());
for (unsigned int i = 0; i < a.size(); i++) {
res[i] = a[i] + b[i];
}
return res;
}
std::vector<double> operator*(double a, std::vector<double> b) {
std::vector<double> res(b.size());
for (unsigned int i = 0; i < b.size(); i++) {
res[i] = a*b[i];
}
return res;
}
/*
Utility function for filling 3D vector.
*/
std::vector<double> fillVector(double a, double b, double c) {
std::vector<double> res(3);
res[0] = a;
res[1] = b;
res[2] = c;
return res;
}
std::vector<double> crossProduct(std::vector<double> a, std::vector<double> b) {
std::vector<double> result(3);
int j, k;
for (int i = 0; i < 3; i++) {
j = (i + 1) % 3;
k = (i + 2) % 3;
result[i] = a[j] * b[k] - a[k] * b[j];
}
return result;
}
double getVectorSize(std::vector<double> vec) {
double size = 0;
for (int i = 0; i < vec.size(); i++) {
size += vec.at(i)*vec.at(i);
}
return sqrt(size);
}
/**
* Generates macroparticles in the beginning of the simulation.
* This method is called twice - once for electrons and then for ions.
*/
std::vector<Particle *> Simulation::initialize(bool isSource, double velocityRange) {
std::vector<Particle *> particles; // vector of macro-particles (ions / electrons)
double rm = double(RAND_MAX);
time_t t;
srand((unsigned)time(&t));
for (int i = 0; i < macroPartsCount; i++) {
// coordinates
double x = rand() / rm; // number between 0 and 1
double y = rand() / rm;
double *coordinates = (double *)malloc(2 * sizeof(double));
coordinates[0] = x * gridWidth;
if (isSource) {
coordinates[1] = y * gridHeight;
}
else {
coordinates[1] = plateHeight + y * (gridHeight - plateHeight); // the particles are not generated below the plate level
}
// velocity vector
double *velocity = (double *)malloc(3 * sizeof(double));
//do {
// velocity vector - auxiliary variables
double u1 = (rand() / rm);
double u2 = (rand() / rm);
double u3 = (rand() / rm);
double u4 = (rand() / rm);
if (u1 == 0) {
u1++;
}
if (u2 == 0) {
u2++;
}
if (u3 == 0) {
u3++;
}
if (u4 == 0) {
u4++;
}
velocity[0] = sqrt(-2 * log(u1)) * cos(2 * PI * u2) * (velocityRange/sqrt(3)); // x
velocity[1] = sqrt(-2 * log(u1)) * sin(2 * PI * u2) * (velocityRange/sqrt(3)); // y
velocity[2] = sqrt(-2 * log(u3)) * cos(2 * PI * u4) * (velocityRange/sqrt(3)); // z
//} while (getVectorSize(fillVector(velocity[0], velocity[1], velocity[2])) > velocityRange);
Particle *particle = createParticle(coordinates, velocity);
particles.push_back(particle);
}
return particles;
}
bool intersectsThePlate(double x, double y) {
return y <= plateHeight && (x <= gridWidth / 2 - gap / 2 || x >= gridWidth / 2 + gap / 2);
}
/*
Evaluates coordinates and velocities of the particles using Boris scheme.
*/
void boris(std::vector<Particle *> *particles, std::vector<double> *ex, std::vector<double> *ey, bool electrons) {
std::vector<double> B(3); // magnetic field
B = fillVector(B0 * sin(theta), -B0 *cos(theta), 0);
std::vector<double> ef(3), vm(3), s(3), T(3), E, coords, v;
double m; // mass
int charge; // +-1
if (electrons) {
m = elMass;
charge = -1;
}
else {
m = ionMass;
charge = 1;
}
for (int i = 0; i < particles->size(); i++) { // iteration through particles
Particle *particle = particles->at(i);
double x = particle->coords[0];
double y = particle->coords[1];
double vx = particle->velocity[0];
double vy = particle->velocity[1];
double vz = particle->velocity[2];
coords = fillVector(x, y, 0);
v = fillVector(vx, vy, vz);
E = fillVector(ex->at(i), ey->at(i), 0);
for (int j = 0; j < 3; j++) {
ef[j] = charge * q / m*dt / 2 * E[j];
T[j] = charge * q*B[j] * dt / m / 2;
}
double T_vel = getVectorSize(T);
for (int j = 0; j < 3; j++) {
s[j] = 2 * T[j] / (1 + T_vel * T_vel);
}
vm = v + ef;
v = vm + crossProduct(vm + crossProduct(vm, T), s) + ef;
coords = coords + dt * v;
particle->coords[0] = coords.at(0);
particle->coords[1] = coords.at(1);
particle->velocity[0] = v.at(0);
particle->velocity[1] = v.at(1);
particle->velocity[2] = v.at(2);
}
}
/*
Evaluates coordinates and velocities of the source particles.
No forces affect these particles, only the particles that reach the area borders are reflected.
No plates included.
Returns vector of reflected particles.
*/
std::vector<Particle *> source(std::vector<Particle *> *particles, bool areElectrons) {
std::vector<Particle *> reflectedParticles;
double dtx = areElectrons ? dt*2 : dt;
for (int i = 0; i < particles->size(); i++) { // iteration through particles
Particle *particle = particles->at(i);
double x = particle->coords[0];
double y = particle->coords[1];
double vx = particle->velocity[0];
double vy = particle->velocity[1];
double vz = particle->velocity[2];
// without forces
x = x + dtx * vx;
y = y + dtx * vy;
bool isReflected = false;
// position is out of range -> the particle is reflected
if (x < 0) {
x = -x;
vx = -vx;
isReflected = true;
}
if (x > gridWidth) {
x = 2 * gridWidth - x;
vx = -vx;
isReflected = true;
}
if (y > gridHeight) {
y = 2 * gridHeight - y;
vy = -vy;
isReflected = true;
}
if (y < 0) { // special case
y = gridHeight + y;
isReflected = true;
}
particle->coords[0] = x;
particle->coords[1] = y;
particle->velocity[0] = vx;
particle->velocity[1] = vy;
particle->velocity[2] = vz;
if (isReflected) {
Particle *copy = createParticleCopy(particle);
reflectedParticles.push_back(copy);
}
}
//std::cout << reflectedParticles.size() << std::endl;
return reflectedParticles;
}
void printParticles(std::vector<Particle *> v, const char* fileName) {
//typedef std::vector<Particle *>::iterator it_type;
std::ofstream outputFile;
outputFile.open(fileName);
for (int i = 0; i < v.size(); i++) {
Particle *particle = v.at(i);
outputFile << particle->coords[0] << " " << particle->coords[1] << std::endl;
}
outputFile.close();
}
void printMatrix (double phi[grid +1][grid+1], const char* fileName) {
//typedef std::vector<Particle *>::iterator it_type;
std::ofstream outputFile;
outputFile.open(fileName);
//for (int j = grid; j >= 0; j--) { // inner nodes
for (int j = 0; j < grid + 1; j++) { // inner nodes
for (int i = 0; i < grid + 1; i++) {
outputFile << phi[i][j] << " ";
}
outputFile << std::endl;
}
outputFile.close();
}
void printVector(std::vector<double> *numbers, const char *fileName) {
std::ofstream outputFile;
outputFile.open(fileName);
for (int i = 0; i < numbers->size(); i++) {
outputFile << numbers->at(i) << std::endl;
}
outputFile.close();
}
void printFrequencies(std::map<double, int> *map, const char* fileName) {
std::ofstream outputFile;
outputFile.open(fileName);
typedef std::map<double, int>::iterator it_type;
for (it_type iterator = map->begin(); iterator != map->end(); iterator++) {
outputFile << iterator->first << " " << iterator->second << std::endl;;
}
outputFile.close();
}
double getCellIndex(double position, double range, int cellsCount) {
if (position == range) { // the particle is on the border
return cellsCount - 1;
}
return position * cellsCount / range;
}
/*
This method counts electric charge in the nodes of the grid using the cloud-in-cell algorithm.
The values are later used for getting the electric potential.
see https://pdfs.semanticscholar.org/5010/d47d9fcc9539cc315a54400cae2ce17eb1e2.pdf
rho - chargeField - output parameter
Q - charge
*/
void countCharge(std::vector<Particle *> *particles, double rho[grid + 1][grid + 1], double Q) {
for (int i = 0; i < particles->size(); i++) { // iteration through particles
Particle *particle = particles->at(i);
double x = particle->coords[0];
double y = particle->coords[1];
// indexes of node in the grid (node matrix) // todo rename
int cellX = getCellIndex(x, gridWidth, grid);
int cellY = getCellIndex(y, gridHeight, grid);
double dx = x - cellX * cellWidth; // x distance from the left bottom corner of the cell
double dy = y - cellY * cellHeight; // y distance from the left bottom corner of the cell
rho[cellX][cellY] += Q * (cellWidth - dx) * (cellHeight - dy) / (cellWidth * cellHeight);
rho[cellX + 1][cellY] += Q * dx * (cellHeight - dy) / (cellWidth * cellHeight);
rho[cellX][cellY + 1] += Q * (cellWidth - dx) * dy / (cellWidth * cellHeight);
rho[cellX + 1][cellY + 1] += Q * dx * dy / (cellWidth * cellHeight);
}
}
double getIntervalSize(double min, double max, int intervals) {
return (max - min) / intervals;
}
double getMapKey(double velocity, double intervalSize) {
int intervalIndex = velocity / intervalSize;
return intervalIndex * intervalSize;
}
/*
Adds velocity to map of their frequencies.
Map key is lower boundary of velocity interval.
*/
void addToMap(std::map<double, int> *velocities, double velocity, double intervalSize) {
// first determine map key
double key = getMapKey(velocity, intervalSize);
// insert
if (velocities->count(key) == 0) {
velocities->insert(std::pair<double, int>(key, 1));
}
else {
double freq = velocities->at(key);
freq++;
velocities->erase(key);
velocities->insert(std::pair<double, int>(key, freq));
}
}
void getVelocities(std::vector<Particle *> *particles, std::vector<double> *velocities, double *min, double *max) {
*min = v_Te * 10;
*max = 0;
double velocity;
for (int i = 0; i < particles->size(); i++) {
Particle *particle = particles->at(i);
std::vector<double> vel = fillVector(particle->velocity[0], particle->velocity[1], particle->velocity[2]);
velocity = getVectorSize(vel);
if (velocity < *min) {
*min = velocity;
}
if (velocity > *max) {
*max = velocity;
}
velocities->push_back(velocity);
}
}
void createFreqMap(std::map<double, int> *map, std::vector<double> *velocities, double min, double max, int intervals) {
double intervalSize = getIntervalSize(min, max, intervals);
for (int i = 0; i < velocities->size(); i++) {
addToMap(map, velocities->at(i), intervalSize);
}
}
void velocityCheck(std::vector<Particle *> *particles, const char* outputFile) {
int intervals = 100;
std::vector<double> velocities;
double min = 0;
double max = 0;
getVelocities(particles, &velocities, &min, &max);
std::map<double, int> map;
createFreqMap(&map, &velocities, min, max, intervals);
printFrequencies(&map, outputFile);
}
/*
iters - number of iterations
*/
double getOmega(int iters) {
return 2 / (1 + sin(PI * iters / (iters + 1)));
}
/*
rho - matrix of charges - input parameter
phi - matrix of potentials - output parameter
iters - number of iterations of SOR
i - simulation step
*/
void countPotential(double rho[grid + 1][grid + 1], double phi[grid + 1][grid + 1], int iters, int i) {
double omega = getOmega(iters);
for (int k = 0; k < iters; k++) {
for (int i = 0; i < grid + 1; i++) { // outer nodes
phi[i][0] = phi[i][1];
phi[i][grid] = phi[i][grid - 1];
phi[0][i] = phi[1][i];
phi[grid][i] = phi[grid - 1][i];
}
// SOR - Successive over-relaxation - iterative method
// see https://en.wikipedia.org/wiki/Successive_over-relaxation
for (int i = 1; i < grid; i++) { // inner nodes
for (int j = 1; j < grid; j++) {
double x = i * cellWidth; // absolute coordinates of the nodes
double y = j * cellHeight;
if (intersectsThePlate(x, y)) { // on the plates, the potential is zero
phi[i][j] = 0;
}
else {
phi[i][j] = (1 - omega) * phi[i][j] + (omega / 4) * (phi[i][j + 1] + phi[i + 1][j] + phi[i - 1][j] + phi[i][j - 1] + rho[i][j] * cellWidth * cellHeight / epsilon);
}
}
}
//getchar();
}
}
/*
phi - matrix of potentials - input parameter
e - electric field - output parameter
*/
void countElectricField(double e[grid + 1][grid + 1][2], double phi[grid + 1][grid + 1]) {
for (int i = 1; i < grid; i++) {
for (int j = 1; j < grid; j++) {
e[i][j][0] = (phi[i][j - 1] - phi[i][j + 1]) / (2 * cellWidth); // ex
e[i][j][1] = (phi[i - 1][j] - phi[i + 1][j]) / (2 * cellHeight); // ey
}
}
// border values
for (int i = 0; i <= grid; i++) {
// ex
e[0][i][0] = e[1][i][0];
e[grid][i][0] = e[grid - 1][i][0];
e[i][0][0] = e[i][1][0];
e[i][grid][0] = e[i][grid - 1][0];
// ey
e[0][i][1] = e[1][i][1];
e[grid][i][1] = e[grid - 1][i][1];
e[i][0][1] = e[i][1][1];
e[i][grid][1] = e[i][grid - 1][1];
}
}
double bilinearInterpolation(double x, double y, double x1, double x2, double y1, double y2, double fQ11, double fQ12, double fQ21, double fQ22) {
double fxy1 = (x2 - x) * fQ11 / (x2 - x1) + (x - x1) * fQ21 / (x2 - x1);
double fxy2 = (x2 - x) * fQ12 / (x2 - x1) + (x - x1) * fQ22 / (x2 - x1);
return (y2 - y) * fxy1 / (y2 - y1) + (y - y1) * fxy2 / (y2 - y1);
}
/*
e - electric field in grid nodes
particles - ions or electrons
ex -
*/
void interpolateElectricField(double e[grid + 1][grid + 1][2], std::vector<Particle *> *particles, std::vector<double> *ex, std::vector<double> *ey) {
for (int i = 0; i < particles->size(); i++) { // iteration through particles
Particle *particle = particles->at(i);
double x = particle->coords[0];
double y = particle->coords[1];
// indexes of node in the grid (node matrix)
int cellX = getCellIndex(x, gridWidth, grid);
int cellY = getCellIndex(y, gridHeight, grid);
ex->push_back(bilinearInterpolation(x, y, cellX * cellWidth, (cellX + 1) * cellWidth, cellY * cellHeight, (cellY + 1) * cellHeight, e[cellX][cellY][0], e[cellX][cellY + 1][0], e[cellX + 1][cellY][0], e[cellX + 1][cellY + 1][0]));
ey->push_back(bilinearInterpolation(x, y, cellX * cellWidth, (cellX + 1) * cellWidth, cellY * cellHeight, (cellY + 1) * cellHeight, e[cellX][cellY][1], e[cellX][cellY + 1][1], e[cellX + 1][cellY][1], e[cellX + 1][cellY + 1][1]));
//particle->ex = ex;
//particle->ey = ey;
//particle->ez = 0; // ez
}
//getchar();
}
std::vector<Particle *> deterministicInitialize() {
std::vector<Particle *> particles; // vector of macro-particles (ions / electrons)
for (int i = 0; i < macroPartsCount; i++) {
double *coordinates = (double *)malloc(2 * sizeof(double));
coordinates[0] = gridWidth / 2;
coordinates[1] = gridHeight / 2;
double *velocity = (double *)malloc(3 * sizeof(double));
velocity[0] = 0;
velocity[1] = 0;
velocity[2] = 0;
Particle *particle = createParticle(coordinates, velocity);
particles.push_back(particle);
}
return particles;
}
void initElField(double elField[grid + 1][grid + 1][2]) {
for (int i = 0; i < grid + 1; i++) {
for (int j = 0; j < grid + 1; j++) {
elField[i][j][0] = 0;
elField[i][j][1] = 0;
}
}
}
void init1DArray(double eArray[macroPartsCount]) {
for (int i = 0; i < grid + 1; i++) {
eArray[i] = 0;
}
}
void initVector(std::vector<double> *vec, int count) {
for (int i = 0; i < count; i++) {
vec->push_back(0);
}
}
bool isOutOfTheBox(double x, double y, bool isSource) {
if (x < 0 || x > gridWidth || y < 0 || y > gridHeight) {
return true;
}
if (!isSource && intersectsThePlate(x, y)) {
plateCrashCount++;
return true;
}
return false;
}
void checkParticles(std::vector<Particle *> *particles, std::vector<Particle* > *out, bool erase) {
out->clear();
int count = 0;
for (int i = particles->size() - 1; i >= 0 ; i--) {
Particle *particle = particles->at(i);
double x = particle->coords[0];
double y = particle->coords[1];
if (isOutOfTheBox(x,y,!erase)) {
if (erase) {
particles->erase(particles->begin() + i);
}
//free(particle);
count++ ;
out->push_back(particle);
}
}
count = count;
}
/*
Adds reflected source particles to the vector of particles in the simulated area.
*/
void addParticles(std::vector<Particle *> *particles, std::vector<Particle *> *reflected) {
for (int i = 0; i < reflected->size(); i++) {
if (particles->size() >= macroPartsCount) {
break;
}
particles->push_back(reflected->at(i));
}
}
void Simulation::simulate() {
// particles in external source
std::vector<Particle *> sourceElectrons = initialize(true, v_Te);
std::vector<Particle *> sourceIons = initialize(true, v_Ti);
// particles in simulated area
std::vector<Particle *> electrons = initialize(false, v_Te);
std::vector<Particle *> ions = initialize(false, v_Ti);
double rho[grid + 1][grid + 1]; // charge matrix
double phi[grid + 1][grid + 1]; // potential matrix
double elField[grid + 1][grid + 1][2]; // matrix of electric field vectors
initElField(elField);
std::vector<double> ex;
std::vector<double> ey;
std::vector<Particle *> outIonsSource;
std::vector<Particle *> outElectronsSource;
std::vector<Particle *> outIonsSimulation;
std::vector<Particle *> outElectronsSimulation;
std::vector<double> potentialVector;
for (int t = 0; t < steps; t = t++ /*+ dt*/) { // time iteration
plateCrashCount = 0;
gapCount = 0;
outIonsSource.clear();
outElectronsSource.clear();
outIonsSource = source(&sourceIons, false);
outElectronsSource = source(&sourceElectrons, true);
// add reflected particles from source to simulation
addParticles(&ions, &outIonsSource);
addParticles(&electrons, &outElectronsSource);
// 2. charge in grid nodes (both ions and electrons contribute)
init2DField(rho);
countCharge(&ions, rho, macroQ);
countCharge(&electrons, rho, -macroQ);
// 3. potential in grid nodes (is obtained from charge)
init2DField(phi);
countPotential(rho, phi, 400, t);
potentialVector.push_back(phi[10][25]);
countElectricField(elField, phi);
ex.clear();
ey.clear();
interpolateElectricField(elField, &electrons, &ex, &ey);
interpolateElectricField(elField, &ions, &ex, &ey);
boris(&electrons, &ex, &ey, true);
boris(&ions, &ex, &ey, false);
// check which particles are out of the box
checkParticles(&ions, &outIonsSimulation, true);
checkParticles(&electrons, &outElectronsSimulation, true);
if (t == 0) {
printMatrix(phi, "potential0.txt");
printMatrix(rho, "charge0.txt");
printParticles(electrons, "electrons0.txt");
}
if (t % 5 == 0) {
std::cout << "Step " << t << " completed." << std::endl;
std::cout << "Simulation Electrons out " << outElectronsSimulation.size() << std::endl;
std::cout << "Source Electrons out " << outElectronsSource.size() << std::endl;
std::cout << "CrashPlates " << plateCrashCount << std::endl;
}
}
printParticles(electrons, "electrons.txt");
printParticles(ions, "ions.txt");
printParticles(sourceElectrons, "electronsSource.txt");
printParticles(sourceIons, "ionsSource.txt");
printMatrix(rho, "charge.txt");
printMatrix(phi, "potential.txt");
printVector(&potentialVector, "potentialZone.txt");
velocityCheck(&sourceElectrons, "checksource.txt");
velocityCheck(&electrons, "elVelocities.txt");
velocityCheck (&ions, "ionVelocities.txt");
velocityCheck(&outIonsSimulation, "outIonsSimulation.txt");
velocityCheck(&outElectronsSimulation, "outElectronsSimulation.txt");
velocityCheck(&outIonsSource, "outIonsSource.txt");
velocityCheck(&outElectronsSource, "outElectronsSource.txt");
//std::cout << plateCrashCount << std::endl;
//std::cout << gapCount << std::endl;
}
| [
"g.hessova@seznam.cz"
] | g.hessova@seznam.cz |
214251c46920b5f5fd524d328b2fea08ec709373 | a1fbf16243026331187b6df903ed4f69e5e8c110 | /cs/engine/xrGame/ui/UILine.cpp | 196ab1c3429dbf626fa8ada334aa9ca7ea8694a1 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | OpenXRay/xray-15 | ca0031cf1893616e0c9795c670d5d9f57ca9beff | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | refs/heads/xd_dev | 2023-07-17T23:42:14.693841 | 2021-09-01T23:25:34 | 2021-09-01T23:25:34 | 23,224,089 | 64 | 23 | NOASSERTION | 2019-04-03T17:50:18 | 2014-08-22T12:09:41 | C++ | UTF-8 | C++ | false | false | 6,766 | cpp | // File: UILine.cpp
// Description: Single text line
// Created: 05.04.2005
// Author: Serge Vynnycheko
// Mail: narrator@gsc-game.kiev.ua
//
// Copyright 2005 GSC Game World
#include "stdafx.h"
#include "UILine.h"
#include "uilinestd.h"
#include "UIColorAnimatorWrapper.h"
CUIColorAnimatorWrapper CUILine::m_animation;
//#define LOG_ALL_LINES
#ifdef LOG_ALL_LINES
int ListLinesCount = 0;
struct DBGList{
CUILine* wnd;
int num;
};
xr_vector<DBGList> dbg_list_lines;
void dump_list_lines(){
Msg("------Total Lines %d",dbg_list_lines.size());
xr_vector<DBGList>::iterator _it = dbg_list_lines.begin();
for(;_it!=dbg_list_lines.end();++_it)
Msg("--leak detected ---- Line = %d",(*_it).num);
}
#else
void dump_list_lines(){}
#endif
CUILine::CUILine(){
m_tmpLine = NULL;
m_animation.SetColorAnimation("ui_map_area_anim");
m_animation.Cyclic(true);
#ifdef LOG_ALL_LINES
ListLinesCount++;
dbg_list_lines.push_back(DBGList());
dbg_list_lines.back().wnd = this;
dbg_list_lines.back().num = ListLinesCount;
#endif
}
CUILine::~CUILine(){
xr_delete(m_tmpLine);
#ifdef LOG_ALL_LINES
xr_vector<DBGList>::iterator _it = dbg_list_lines.begin();
bool bOK = false;
for(;_it!=dbg_list_lines.end();++_it){
if((*_it).wnd == this){
bOK = true;
dbg_list_lines.erase(_it);
break;
}
}
if(!bOK)
Msg("CUILine::~CUILine()!!!!!!!!!!!!!!!!!!!!!!! cannot find window in list");
#endif
}
CUILine::CUILine(const CUILine& other){
m_subLines = other.m_subLines;
m_tmpLine = NULL;
#ifdef LOG_ALL_LINES
ListLinesCount++;
dbg_list_lines.push_back(DBGList());
dbg_list_lines.back().wnd = this;
dbg_list_lines.back().num = ListLinesCount;
#endif
}
CUILine& CUILine::operator =(const CUILine& other){
m_subLines = other.m_subLines;
xr_delete(m_tmpLine);
return (*this);
}
void CUILine::AddSubLine(const xr_string& str, u32 color){
CUISubLine sline;
sline.m_color = color;
sline.m_text = str;
m_subLines.push_back(sline);
}
void CUILine::AddSubLine(const char* str, u32 color){
CUISubLine sline;
sline.m_color = color;
sline.m_text = str;
m_subLines.push_back(sline);
}
void CUILine::AddSubLine(const CUISubLine* subLine){
m_subLines.push_back(*subLine);
}
void CUILine::Clear(){
m_subLines.clear();
}
void CUILine::ProcessNewLines()
{
for (u32 i=0; i < m_subLines.size(); i++){
StrSize pos = m_subLines[i].m_text.find("\\n");
if (pos != npos)
{
CUISubLine sbLine;
if (pos)
sbLine = *m_subLines[i].Cut2Pos((int)pos-1);
sbLine.m_last_in_line = true;
m_subLines.insert(m_subLines.begin()+i, sbLine);
m_subLines[i+1].m_text.erase(0,2);
if (m_subLines[i+1].m_text.empty()){
m_subLines.erase(m_subLines.begin()+i+1);
}
}
}
}
void CUILine::Draw(CGameFont* pFont, float x, float y) const{
float length = 0;
int size = m_subLines.size();
for (int i=0; i<size; i++)
{
m_subLines[i].Draw(pFont, x+length, y);
float ll = pFont->SizeOf_(m_subLines[i].m_text.c_str()); //. all ok
UI()->ClientToScreenScaledWidth(ll);
length += ll;
}
}
int CUILine::GetSize(){
int sz = 0;
int size = m_subLines.size();
for (int i=0; i<size; i++)
sz += (int)m_subLines[i].m_text.size();
return sz;
}
const CUILine* CUILine::GetEmptyLine(){
xr_delete(m_tmpLine);
m_tmpLine = new CUILine();
return m_tmpLine;
}
bool CUILine::GetWord(Word& w, const xr_string& text, int begin) const{
if (text.empty())
return false;
StrSize first, last, lastsp/*last space*/;
first = text.find_first_not_of(' ', begin);
last = text.find_first_of(' ', first);
if( npos==last && npos==first )
return false;
if( npos==last && npos!=first )
{
w.pos = (int)first;
w.len = (int)(text.length()-first);
w.len_full = w.len;
return true;
}
lastsp = text.find_first_not_of(' ', last);
if (npos == lastsp && npos == first) // maybe we have string only with spaces
{
first = text.find_first_of(' ',begin);
last = text.find_last_of(' ',begin);
if (npos == first) //suxxx it is empty string
return false;
w.pos = (int)first;
w.len = (int)(last - first + 1);
w.len_full = w.len;
return true;
}
if (npos == lastsp)
lastsp = last;
else
--lastsp;
if (npos == last && npos != first)
last = text.size() - 1;
else
--last;
if (npos == lastsp)
lastsp = last;
first = begin;
w.pos = (int) first;
w.len = (int)(last - first + 1);
w.len_full = (int)(lastsp - first + 1);
#ifdef DEBUG
if (npos != first && (npos == last || npos == lastsp ))
R_ASSERT2(false,"CUILine::InitPos -- impossible match");
#endif
return true;
}
bool CUILine::InitPos(Position& pos) const
{
Word w;
pos.curr_subline = 0;
if (GetWord(w, m_subLines[0].m_text, 0))
pos.word_1 = w;
else
return false;
if (GetWord(w, m_subLines[0].m_text, w.last_space() + 1))
pos.word_2 = w;
else if (m_subLines.size() > 1 && GetWord(w, m_subLines[1].m_text, 0))
pos.word_2 = w;
return true;
}
bool CUILine::IncPos(Position& pos) const{
u32 totalLinesCount = m_subLines.size();
if (totalLinesCount < pos.curr_subline)
return false;
Word w;
u32 curLine = pos.curr_subline;
if ( ! pos.is_separated() )
{
if (GetWord(w, m_subLines[curLine].m_text, pos.word_2.last_space() + 1))
{
pos.word_1 = pos.word_2;
pos.word_2 = w;
return true;
}
else if (curLine + 1 <= totalLinesCount - 1)
{
if (GetWord(w, m_subLines[curLine + 1].m_text, 0))
{
pos.word_1 = pos.word_2;
pos.word_2 = w;
return true;
}
}
else
return false;
}
else if (curLine + 1 <= totalLinesCount -1)
{
if (GetWord(w, m_subLines[curLine + 1].m_text, pos.word_2.last_space() + 1))
{
pos.word_1 = pos.word_2;
pos.word_2 = w;
pos.curr_subline = curLine + 1;
return true;
}
else if (curLine + 2 <= totalLinesCount -1)
if (GetWord(w, m_subLines[curLine + 2].m_text, 0))
{
pos.word_1 = pos.word_2;
pos.word_2 = w;
pos.curr_subline = curLine + 1;
return true;
}
return false;
}
return false;
}
const CUILine* CUILine::Cut2Pos(Position& pos, bool to_first){
xr_delete(m_tmpLine);
m_tmpLine = new CUILine();
int last;
if (to_first || !pos.is_separated())
last = pos.curr_subline - 1;
else
last = pos.curr_subline;
for (int i = 0; i<= last; i++)
{
m_tmpLine->AddSubLine(&m_subLines[i]);
if (m_subLines[i].m_last_in_line) // check if this subline must be last in line
{
for (int j = 0; j<= i; j++)
m_subLines.erase(m_subLines.begin());
return m_tmpLine;
}
}
if (to_first)
m_tmpLine->AddSubLine(m_subLines[last + 1].Cut2Pos(pos.word_1.last_space()));
else
m_tmpLine->AddSubLine(m_subLines[last + 1].Cut2Pos(pos.word_2.last_space()));
for (int i = 0; i<= last; i++)
m_subLines.erase(m_subLines.begin());
return m_tmpLine;
}
| [
"paul-kv@yandex.ru"
] | paul-kv@yandex.ru |
7889d8c9ce9eeed86a3314f045c08cff842a1d92 | 8edabc1463dd0d7ff66478f3daabc39fd1ec4d2b | /tools/pvxvct.cpp | e72f179c99f4694caf66b44f7efe1b8d8810009e | [
"BSD-3-Clause"
] | permissive | jeonghanlee/pvxs | b295fef2d9cbdf9d6a58715e6fc27d157a9ba601 | 6bb0a364bed580064148031cd76051e74f1b385a | refs/heads/master | 2022-04-17T15:22:16.999991 | 2020-04-13T19:07:38 | 2020-04-14T04:39:22 | 255,680,588 | 0 | 0 | BSD-3-Clause | 2020-04-14T17:39:57 | 2020-04-14T17:39:56 | null | UTF-8 | C++ | false | false | 9,191 | cpp | /**
* Copyright - See the COPYRIGHT that is included with this distribution.
* pvxs is distributed subject to a Software License Agreement found
* in file LICENSE that is included with this distribution.
*/
#include <event2/event.h>
#include <cstring>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <tuple>
#include <regex>
#include <epicsVersion.h>
#include <epicsEvent.h>
#include <epicsGetopt.h>
#include <osiSock.h>
#include <pvxs/log.h>
#include <udp_collector.h>
#include <utilpvt.h>
#include <pvaproto.h>
namespace pva = pvxs;
namespace {
DEFINE_LOGGER(out, "pvxvct");
// parse hostname, IP, or IP+netmask
std::pair<uint32_t, uint32_t>
parsePeer(const char *optarg)
{
// nameorip
// nameorip/##
// nameorip/###.###.###.###
// static is safe as we only use from main() thread
static std::regex netname("([^/:]*)(?:/([0-9.]+))?");
std::cmatch match;
if(!std::regex_match(optarg, match, netname)) {
throw std::runtime_error(pva::SB()<<"Expected host name or IP range. not "<<optarg);
}
in_addr addr, mask;
if(hostToIPAddr(match[1].str().c_str(), &addr)) {
throw std::runtime_error(pva::SB()<<"Expected a host name or IP. not "<<match[1].str());
}
mask.s_addr = INADDR_BROADCAST;
if(match[2].length()) {
auto smask = match[2].str();
if(smask.find_first_of('.')!=smask.npos) {
if(!evutil_inet_pton(AF_INET, smask.c_str(), &mask)) {
throw std::runtime_error(pva::SB()<<"Expected netmask. not "<<smask);
}
} else {
// only # of bits. eg. "/24"
std::istringstream strm(match[2].str());
unsigned nbit=0;
if((strm>>nbit).good()) {
throw std::runtime_error(pva::SB()<<"Expected number of bits. not "<<match[2]);
}
mask.s_addr = htonl(0xffffffff<<(32-nbit));
}
}
// 1.2.3.4/24 === 1.2.3.0/24
addr.s_addr &= mask.s_addr;
return std::make_pair(addr.s_addr, mask.s_addr);
}
void usage(const char *name)
{
std::cerr<<"Usage: "<<name<<" [-C|-S] [-B hostip[:port]] [-H hostip]\n"
"\n"
"PV Access Virtual Cable Tester\n"
"\n"
"Assist in troubleshooting network (mis)configuration by listening\n"
"for (some) PVA client/server UDP traffic.\n"
"\n"
" -h Print this message\n"
" -V Print version and exit.\n"
" -C Show only client Searches\n"
" -S Show only server Beacons\n"
" -B hostip[:port] Listen on the given interface(s). May be repeated.\n"
" -H host Show only message sent from this peer. May be repeated.\n"
" -P pvname Show only searches for this PV name. May be repeated.\n"
<<std::endl;
}
} // namespace
int main(int argc, char *argv[])
{
try {
// group options used from callback
struct {
bool verbose = false;
bool client = false, server = false;
// IP, netmask
// stored in network byte order
std::vector<std::pair<uint32_t, uint32_t>> peers;
std::set<std::string> pvnames;
bool allowPeer(const pva::SockAddr& peer) {
if(peers.empty())
return true;
if(peer.family()!=AF_INET)
return false;
for(auto& pair : peers) {
if((peer->in.sin_addr.s_addr & pair.second) == pair.first) {
return true;
}
}
return false;
}
} opts;
std::vector<pva::SockAddr> bindaddrs;
{
int opt;
while ((opt = getopt(argc, argv, "hVvCSH:B:P:")) != -1) {
switch(opt) {
case 'h':
usage(argv[0]);
return 0;
case 'V':
std::cout<<pva::version_str()<<"\n";
std::cout<<EPICS_VERSION_STRING<<"\n";
std::cout<<"libevent "<<event_get_version()<<"\n";
return 0;
default:
usage(argv[0]);
std::cerr<<"\nUnknown argument: "<<char(opt)<<std::endl;
return 1;
case 'v':
opts.verbose = true;
break;
case 'C':
opts.client = true;
break;
case 'S':
opts.server = true;
break;
case 'B': {
pva::SockAddr addr;
int slen = addr.size();
if(evutil_parse_sockaddr_port(optarg, &addr->sa, &slen)) {
throw std::runtime_error(pva::SB()<<"Expected address[:port] to bind. Not "<<optarg);
}
if(addr.port()==0)
addr.setPort(5076);
bindaddrs.push_back(addr);
}
break;
case 'P':
opts.pvnames.insert(optarg);
break;
case 'H':
opts.peers.push_back(parsePeer(optarg));
break;
}
}
}
// apply defaults
if(!opts.client && !opts.server) {
opts.client = opts.server = true;
}
if(bindaddrs.empty()) {
bindaddrs.emplace_back(pva::SockAddr::any(AF_INET, 5076));
}
pva::logger_level_set("pvxvct", opts.verbose ? pvxs::Level::Debug : pvxs::Level::Info);
pva::logger_config_env(); // from $PVXS_LOG
log_debug_printf(out, "Show Search: %s\nShow Beacon: %s\n", opts.client?"yes":"no", opts.server?"yes":"no");
if(opts.client && opts.pvnames.empty()) {
log_debug_printf(out, "Show all PV names\n%s", "");
} else {
for(const auto& name : opts.pvnames) {
log_debug_printf(out, "Show PV: %s\n", name.c_str());
}
}
if(opts.peers.empty()) {
log_debug_printf(out, "No peer filter\n%s", "");
} else if(out.test(pvxs::Level::Debug)) {
for(const auto& tup : opts.peers) {
in_addr addr, netmask;
std::tie(addr.s_addr, netmask.s_addr) = tup;
char abuf[16];
char nbuf[16];
evutil_inet_ntop(AF_INET, &addr, abuf, sizeof(abuf));
evutil_inet_ntop(AF_INET, &netmask, nbuf, sizeof(nbuf));
log_debug_printf(out, "Show from %s/%s\n", abuf, nbuf);
}
}
auto searchCB = [&opts](const pva::UDPManager::Search& msg)
{
if(!opts.client || !opts.allowPeer(msg.src))
return;
if(!opts.pvnames.empty()) {
bool show = false;
for(const auto pv : msg.names) {
show = opts.pvnames.find(pv.name)!=opts.pvnames.end();
if((show = opts.pvnames.find(pv.name)!=opts.pvnames.end()))
break;
}
if(!show)
return;
}
log_info_printf(out, "%s Searching for:\n", msg.src.tostring().c_str());
for(const auto pv : msg.names) {
log_info_printf(out, " \"%s\"\n", pv.name);
}
};
auto beaconCB = [&opts](const pva::UDPManager::Beacon& msg)
{
if(!opts.server || !opts.allowPeer(msg.src))
return;
const auto& guid = msg.guid;
log_info_printf(out, "%s Beacon %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x %s\n",
msg.src.tostring().c_str(),
guid[0], guid[1], guid[2], guid[3], guid[4], guid[5], guid[6], guid[7], guid[8], guid[9], guid[10], guid[11],
msg.server.tostring().c_str());
};
std::vector<std::pair<std::unique_ptr<pva::UDPListener>, std::unique_ptr<pva::UDPListener>>> listeners;
listeners.reserve(bindaddrs.size());
for(auto& baddr : bindaddrs) {
auto manager = pva::UDPManager::instance();
listeners.emplace_back(manager.onSearch(baddr, searchCB),
manager.onBeacon(baddr, beaconCB));
listeners.back().first->start();
listeners.back().second->start();
log_debug_printf(out, "Bind: %s\n", baddr.tostring().c_str());
}
epicsEvent done;
pva::SigInt handle([&done](){
done.trigger();
});
done.wait();
log_info_printf(out, "Done\n%s", "");
errlogFlush();
return 0;
}catch(std::runtime_error& e) {
errlogFlush();
std::cerr<<"Error: "<<e.what()<<std::endl;
return 1;
}
}
| [
"mdavidsaver@gmail.com"
] | mdavidsaver@gmail.com |
4015a249dde47942e2e65ee65615c7d4fed302fa | 519351b04bd4f29794851511c8857cc6a3a93d3f | /include/equiv_mutation_class_loader.h | 0e78721fd10db404a4be63576428d58b00391025 | [
"Apache-2.0"
] | permissive | jwlawson/qv | 803ce081b8a24e428d17c003e8c28c844d0b6f2b | 25f1aa8d47f9d657ff074359c057f8c16e5f728c | refs/heads/master | 2021-06-22T22:48:56.830435 | 2017-05-17T13:14:48 | 2017-05-17T13:14:48 | 18,249,762 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,570 | h | /*
* equiv_mutation_class_loader.h
* Copyright 2014-2015 John Lawson
*
* 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.
*/
/**
* Version of the MutationClassLoader which uses EquivQuiverMatrices. Mostly the
* same but the equivalence requires some extra fiddling to reduce the number of
* mutations needed.
*/
#pragma once
#include "mutation_class_loader.h"
#include <unordered_set>
#include "equiv_quiver_matrix.h"
namespace cluster {
class EquivMutationClassLoader : public MutationClassLoader<EquivQuiverMatrix> {
private:
typedef EquivQuiverMatrix M;
public:
EquivMutationClassLoader();
EquivMutationClassLoader(const M& initial);
protected:
virtual void seen_matrix(std::shared_ptr<M> mat,
std::shared_ptr<M> previous,
const int vertex);
virtual void unseen_matrix(std::shared_ptr<M> matrix,
std::shared_ptr<M> previous,
const int vertex);
virtual bool have_seen(std::shared_ptr<M> matrix);
private:
std::unordered_set<std::shared_ptr<M>> set_;
};
}
| [
"john@jwlawson.co.uk"
] | john@jwlawson.co.uk |
d0744e014384e09568db6aecc2ae74086dcdcf94 | 66850287022cb5be903052d74bb5c9b1f48581ca | /src/offsets.h | e0c9784286116d4faa7f16574ad19f5a80584b3c | [
"MIT"
] | permissive | heinermann/teippi | 1088586081bd77b34bed077a73954d16f39aaba8 | dbcdf65313df1fc1fda8ba1f1d8cf2b9b360db44 | refs/heads/master | 2020-12-25T10:24:44.380784 | 2015-09-02T16:03:41 | 2015-09-02T16:03:41 | 41,609,412 | 0 | 0 | null | 2015-08-29T22:35:28 | 2015-08-29T22:35:28 | null | UTF-8 | C++ | false | false | 25,647 | h | #ifndef OFFSETS_HOO
#define OFFSETS_HOO
#include "types.h"
#include <type_traits>
template <typename type>
class offset
{
public:
inline offset() : val(0) {}
inline constexpr offset(uintptr_t val_) : val(val_) {}
inline offset(void *val_) : val((uintptr_t)val_) {}
//inline operator uintptr_t() const { return val; }
inline constexpr void* v() const { return (void *)val; }
inline constexpr operator void*() const { return v(); }
inline constexpr void *operator+ (uintptr_t num) const { return (void *)(val + num); }
inline constexpr type &as() const { return *(type *)(val); }
inline constexpr type &operator* () const { return as(); }
inline constexpr type *operator-> () const { return (type *)(val); }
inline constexpr type& operator[](int pos) const { return ((type *)(val))[pos]; }
uintptr_t val;
};
namespace bw
{
const offset<void *> main_window_hwnd = 0x0051BFB0;
const offset<uint32_t> window_active = 0x0051BFA8;
const offset<Surface> game_screen = 0x006CEFF0;
const offset<uint32_t> needs_full_redraw = 0x006D5E1C;
const offset<DrawLayer> draw_layers = 0x006CEF50;
const offset<void *> trans_list = 0x006D5E14;
const offset<void *> game_screen_redraw_trans = 0x006D5E18;
const offset<uint8_t> no_draw = 0x0051A0E9;
const offset<uint8_t> screen_redraw_tiles = 0x006CEFF8;
const offset<uint32_t> unk_frame_state = 0x006D11F0;
const offset<uint32_t> frames_progressed_at_once = 0x005124D4;
const offset<uint8_t> draw_sprites = 0x006D11EC;
const offset<uint32_t> is_paused = 0x006509C4;
const offset<uint32_t> next_frame_tick = 0x0051CE94;
const offset<uint32_t> unk_6D11E8 = 0x006D11E8;
const offset<uint32_t> ai_interceptor_target_switch = 0x006957D0;
const offset<uint32_t> lurker_hits_used = 0x0064DEA8;
const offset<uint32_t> lurker_hits_pos = 0x0064EEC8;
const offset<Unit *> lurker_hits = 0x0064DEC8;
const offset<uint32_t> game_speed = 0x006CDFD4;
const offset<uint32_t> game_speed_waits = 0x005124D8;
const offset<Ai::Region *> player_ai_regions = 0x0069A604;
const offset<Ai::PlayerData> player_ai = 0x0068FEE8;
const offset<uint8_t *> aiscript_bin = 0x0068C104;
const offset<uint8_t *> bwscript_bin = 0x0068C108;
const offset<Ai::DataList<Ai::Script>> first_active_ai_script = 0x0068C0FC;
const offset<Ai::DataList<Ai::Town>> active_ai_towns = 0x006AA050;
const offset<Ai::ResourceAreaArray> resource_areas = 0x00692688;
const offset<uint32_t> elapsed_seconds = 0x0058D6F8;
const offset<uint32_t> frame_count = 0x0057F23C;
const offset<uint32_t> keep_alive_count = 0x006556E8;
const offset<uint32_t> desync_happened = 0x006552A8;
const offset<uint32_t> net_player_flags = 0x0057F0B8;
const offset<NetPlayer> net_players = 0x0066FE20;
const offset<uint32_t> self_net_player = 0x0051268C;
const offset<uint8_t> sync_data = 0x0065EB30;
const offset<uint8_t> sync_frame = 0x0065EB2E;
const offset<uint32_t> sync_hash = 0x0063FD28;
const offset<Ai::DataList<Ai::GuardAi>> first_guard_ai = 0x00685108;
const offset<uint8_t> is_ingame = 0x006556E0;
const offset<uint8_t> is_bw = 0x0058F440;
const offset<uint8_t> is_multiplayer = 0x0057F0B4;
const offset<uint8_t> team_game = 0x00596875;
const offset<uint32_t> last_error = 0x0066FF60;
const offset<uint32_t> is_replay = 0x006D0F14;
const offset<uint32_t> replay_show_whole_map = 0x006D0F1C;
const offset<uint32_t> replay_paused = 0x006D11B0;
const offset<uint32_t> player_exploration_visions = 0x0057EEB8;
const offset<uint32_t> player_visions = 0x0057F0B0;
const offset<uint32_t> replay_visions = 0x006D0F18;
const offset<x32> mouse_clickpos_x = 0x006CDDC4;
const offset<y32> mouse_clickpos_y = 0x006CDDC8;
const offset<uint8_t> shift_down = 0x00596A28;
const offset<uint8_t> ctrl_down = 0x00596A29;
const offset<uint8_t> alt_down = 0x00596A2A;
const offset<uint8_t> redraw_transport_ui = 0x006CA9F0;
const offset<int32_t> ui_transported_unit_hps = 0x006CA950;
const offset<uint32_t> ui_hitpoints = 0x006CA94C;
const offset<uint32_t> ui_shields = 0x006CA9EC;
const offset<uint32_t> ui_energy = 0x006CAC0C;
const offset<uint32_t> ignore_unit_flag80_clear_subcount = 0x006D5BD0;
const offset<uint32_t> order_wait_reassign = 0x0059CCA4;
const offset<uint32_t> secondary_order_wait_reassign = 0x006283E8;
const offset<uint32_t> dying_unit_creep_disappearance_count = 0x00658AE4;
const offset<x32> original_tile_width = 0x006D0F08;
const offset<y32> original_tile_height = 0x006D0C6C;
const offset<uint16_t *> original_tiles = 0x006D0C68;
const offset<uint8_t *> creep_tile_borders = 0x006D0E80;
const offset<uint16_t *> map_tile_ids = 0x005993C4;
const offset<uint32_t *> megatiles = 0x00628494; // Scenario.chk MTXM
const offset<void *> scenario_chk_STR = 0x005993D4;
const offset<uint32_t> scenario_chk_STR_size = 0x005994D8;
const offset<Surface *> current_canvas = 0x006CF4A8;
const offset<uint32_t> minimap_dot_count = 0x0059C2B8;
const offset<uint32_t> minimap_dot_checksum = 0x0059C1A8;
const offset<uint8_t> minimap_resource_color = 0x006CEB39;
const offset<uint8_t> minimap_color_mode = 0x06D5BBE;
const offset<uint8_t> player_minimap_color = 0x00581DD6;
const offset<uint8_t> enemy_minimap_color = 0x006CEB34;
const offset<uint8_t> ally_minimap_color = 0x006CEB31;
const offset<uint16_t> LeaderBoardUpdateCount_Patch = 0x00489D2D;
const offset<uint8_t> trigger_pause = 0x006509B4;
const offset<uint32_t> dont_progress_frame = 0x006509C4;
const offset<uint8_t> player_unk_650974 = 0x00650974;
const offset<uint8_t> leaderboard_needs_update = 0x00685180; // Not sure
const offset<uint8_t> victory_status = 0x0058D700;
const offset<uint32_t> trigger_current_player = 0x006509B0;
const offset<uint32_t> trigger_cycle_count = 0x006509A0;
const offset<TriggerList> triggers = 0x0051A280;
const offset<uint32_t> countdown_timer = 0x006509C0;
const offset<uint32_t> trigger_portrait_active = 0x0068AC4C;
const offset<uint32_t> player_waits = 0x00650980;
const offset<uint8_t> player_wait_active = 0x006509B8;
const offset<Trigger *> current_trigger = 0x006509AC;
const offset<uint32_t> options = 0x006CDFEC;
const offset<int (__fastcall *)(TriggerAction *)> trigger_actions = 0x00512800;
const offset<Location> locations = 0x0058DC60;
const offset<uint32_t> trig_kill_unit_count = 0x005971E0;
const offset<uint32_t> trig_remove_unit_active = 0x005971DC;
const offset<Unit *> client_selection_group = 0x00597208;
const offset<Unit *> client_selection_group2 = 0x0059724C;
const offset<Unit *> client_selection_group3 = 0x006284B8;
const offset<uint32_t> client_selection_count = 0x0059723D;
const offset<uint8_t> client_selection_changed = 0x0059723C;
const offset<Unit *> selection_groups = 0x006284E8;
const offset<uint8_t> selection_iterator = 0x006284B6;
const offset<Unit *> selection_hotkeys = 0x0057FE60;
const offset<uint16_t> recent_selection_times = 0x0063FE40;
const offset<Unit *> selection_rank_order = 0x00597248;
const offset<uint8_t> self_alliance_colors = 0x00581D6A;
const offset<uint8_t> alliances = 0x0058D634;
const offset<uint32_t> frame_counter = 0x0057EEBC;
const offset<void *> SelectHotkeySwitch = 0x00484B64;
const offset<uint8_t> is_targeting = 0x00641694;
const offset<uint8_t> is_queuing_command = 0x00596A28;
const offset<uint32_t> is_placing_building = 0x00640880;
const offset<uint16_t> placement_unit_id = 0x0064088A;
const offset<uint8_t> placement_order = 0x0064088D;
const offset<uint32_t> lobby_command_user = 0x00512680;
const offset<uint8_t> command_user = 0x00512678;
const offset<uint8_t> select_command_user = 0x0051267C;
const offset<uint32_t> local_player_id = 0x00512684;
const offset<uint32_t> local_unique_player_id = 0x00512688;
const offset<uint8_t> team_game_main_player = 0x0057F1CC;
const offset<uint32_t> player_turn_size = 0x00654A80;
const offset<uint8_t *> player_turns = 0x006554B4;
const offset<uint32_t> player_download = 0x0068F4FC;
const offset<uint32_t> public_game = 0x005999CC;
const offset<uint8_t> net_players_watched_briefing = 0x006556D8;
const offset<uint32_t> player_objectives_string_id = 0x0058D6C4;
const offset<uint8_t> briefing_state = 0x006554B0;
const offset<uint8_t> force_button_refresh = 0x0068C1B0;
const offset<uint8_t> force_portrait_refresh = 0x0068AC74;
const offset<uint8_t> ui_refresh = 0x0068C1F8;
const offset<Control *> unk_control = 0x0068C1E8;
const offset<void *> unk_control_value = 0x0068C1EC;
const offset<Dialog *> load_screen = 0x0057F0DC;
const offset<uint8_t> ground_order_id = 0x00641691;
const offset<uint8_t> unit_order_id = 0x00641692;
const offset<uint8_t> obscured_unit_order_id = 0x00641693;
const offset<x16u> map_width = 0x00628450;
const offset<y16u> map_height = 0x006284B4;
const offset<x16u> map_width_tiles = 0x0057F1D4;
const offset<y16u> map_height_tiles = 0x0057F1D6;
const offset<uint32_t *> map_tile_flags = 0x006D1260;
const offset<uint8_t> upgrade_level_sc = 0x0058D2B0;
const offset<uint8_t> upgrade_level_bw = 0x0058F2FE;
const offset<uint8_t> tech_level_sc = 0x0058CF44;
const offset<uint8_t> tech_level_bw = 0x0058F140;
const offset<uint32_t> unit_strength = 0x006BB210;
const offset<uint32_t> cheat_flags = 0x006D5A6C;
const offset<uint8_t> image_flags = 0x006CEFB5;
const offset<ImgRenderFuncs> image_renderfuncs = 0x005125A0;
const offset<ImgUpdateFunc> image_updatefuncs = 0x00512510;
const offset<uint8_t *> iscript = 0x006D1200;
const offset<Unit *> active_iscript_unit = 0x006D11FC;
const offset<void *> active_iscript_flingy = 0x006D11F4;
const offset<Bullet *> active_iscript_bullet = 0x006D11F8;
const offset<RevListHead<Unit, 0x0>> first_active_unit = 0x00628430;
const offset<RevListHead<Unit, 0x0>> first_hidden_unit = 0x006283EC;
const offset<RevListHead<Unit, 0x0>> first_revealer = 0x006283F4;
const offset<RevListHead<Unit, 0x0>> first_dying_unit = 0x0062842C;
const offset<RevListHead<Unit, 0x68>> first_player_unit = 0x006283F8;
const offset<RevListHead<Unit, 0xf8>> first_pylon = 0x0063FF54;
const offset<RevListHead<Unit, 0xf0>> first_invisible_unit = 0x0063FF5C;
const offset<uint32_t> pylon_refresh = 0x0063FF44;
const offset<RevListHead<Flingy, 0x0>> first_active_flingy = 0x0063FF34;
const offset<RevListHead<Flingy, 0x0>> last_active_flingy = 0x0063FEC8;
const offset<uint8_t> previous_flingy_flags = 0x0063FEC0;
const offset<uint8_t> current_flingy_flags = 0x0063FEC2;
const offset<x16u> new_flingy_x = 0x0063FED4;
const offset<y16u> new_flingy_y = 0x0063FECC;
const offset<x16u> old_flingy_x = 0x0063FEC4;
const offset<y16u> old_flingy_y = 0x0063FED0;
const offset<uint8_t> new_flingy_flags = 0x0063FEC0;
const offset<x32> new_exact_x = 0x0063FED8;
const offset<y32> new_exact_y = 0x0063FF40;
const offset<uint8_t> show_startwalk_anim = 0x0063FF30;
const offset<uint8_t> show_endwalk_anim = 0x0063FEC1;
const offset<uint32_t> reveal_unit_area = 0x0066FF70;
const offset<Unit *> last_active_unit = 0x0059CC9C;
const offset<Unit *> last_hidden_unit = 0x00628428;
const offset<Unit *> last_revealer = 0x00628434;
const offset<Unit *> last_dying_unit = 0x0059CC98;
const offset<Unit *> dodge_unit_from_path = 0x006BEE88;
const offset<Pathing::PathingSystem *> pathing = 0x006D5BFC;
const offset<int32_t> position_search_units_count = 0x006BEE64;
const offset<uint32_t> position_search_results_count = 0x006BEE6C;
const offset<uint32_t> position_search_results_offsets = 0x006BEE70;
const offset<x32> unit_max_width = 0x006BEE68;
const offset<y32> unit_max_height = 0x006BB930;
const offset<uint8_t> unit_positions_x = 0x0066FF78;
const offset<uint8_t> units = 0x0059CCA8; // Repurposed
const offset<x16u> screen_pos_x_tiles = 0x0057F1D0;
const offset<y16u> screen_pos_y_tiles = 0x0057F1D2;
const offset<x16u> screen_x = 0x0062848C;
const offset<y16u> screen_y = 0x006284A8;
const offset<RevListHead<Sprite, 0x0>> horizontal_sprite_lines = 0x00629688;
const offset<ListHead<Sprite, 0x0>> horizontal_sprite_lines_rev = 0x00629288;
const offset<Sprite *> first_active_lone_sprite = 0x00654874;
const offset<Sprite *> first_active_fow_sprite = 0x00654868;
const offset<Surface> minimap_surface = 0x0059C194;
const offset<uint8_t> fog_variance_amount = 0x00657A9C;
const offset<uint8_t *> fog_arr1 = 0x006D5C14;
const offset<uint8_t *> fog_arr2 = 0x006D5C0C;
const offset<Sprite *> cursor_marker = 0x00652918;
const offset<uint8_t> draw_cursor_marker = 0x00652920;
const offset<ListHead<Bullet, 0x0>> last_active_bullet = 0x0064DEAC;
const offset<RevListHead<Bullet, 0x0>> first_active_bullet = 0x0064DEC4;
const offset<uint32_t> damage_multiplier = 0x00515B88;
const offset<uint32_t> all_units_count = 0x00582324;
const offset<uint32_t> player_men_deaths = 0x00581E74;
const offset<uint32_t> player_men_kills = 0x00581EA4;
const offset<uint32_t> player_men_kill_score = 0x00581F04;
const offset<uint32_t> player_building_deaths = 0x00581FC4;
const offset<uint32_t> player_building_kills = 0x00581FF4;
const offset<uint32_t> player_building_kill_score = 0x00582054;
const offset<uint32_t> player_factory_deaths = 0x005820E4;
const offset<uint32_t> player_factory_kills = 0x00582114;
const offset<uint32_t> unit_deaths = 0x0058A364;
const offset<uint32_t> unit_kills = 0x005878A4;
const offset<uint32_t> building_count = 0x00581E44;
const offset<uint32_t> men_score = 0x00581ED4;
const offset<uint32_t> completed_units_count = 0x00584DE4;
const offset<uint32_t> zerg_supply_used = 0x00582174;
const offset<uint32_t> terran_supply_used = 0x00582204;
const offset<uint32_t> protoss_supply_used = 0x00582294;
const offset<uint32_t> zerg_supply_available = 0x00582144;
const offset<uint32_t> terran_supply_available = 0x005821D4;
const offset<uint32_t> protoss_supply_available = 0x00582264;
const offset<uint32_t> zerg_supply_max = 0x005821A4;
const offset<uint32_t> terran_supply_max = 0x00582234;
const offset<uint32_t> protoss_supply_max = 0x005822C4;
const offset<uint32_t> minerals = 0x0057F0F0;
const offset<uint32_t> gas = 0x0057F120;
const offset<uint16_t> tileset = 0x0057F1DC;
const offset<uint8_t> current_energy_req = 0x006563AA;
const offset<Tbl *> stat_txt_tbl = 0x006D1238;
const offset<Tbl *> network_tbl = 0x006D1220;
const offset<uint32_t> use_rng = 0x006D11C8;
const offset<uint32_t> rng_calls = 0x0051C610;
const offset<uint32_t> all_rng_calls = 0x0051CA18;
const offset<uint32_t> rng_seed = 0x051CA14;
const offset<Player> players = 0x0057EEE0;
const offset<uint32_t> vision_update_count = 0x0051CE98;
const offset<uint8_t> vision_updated = 0x0051CE9C;
const offset<uint32_t> visions = 0x0057F1EC;
const offset<int32_t> circle = 0x00512D28;
const offset<int (__fastcall *) (Unit *, int, int, Unit **target, int unit_id)> GetRightClickOrder = 0x005153FC;
const offset<int (__stdcall *) (int, Rect32 *, uint8_t **, int *, int)> SDrawLockSurface_Import = 0x004FE5A0;
const offset<int (__stdcall *) (int, uint8_t *, int, int)> SDrawUnlockSurface_Import = 0x004FE59C;
const offset<ReplayData *> replay_data = 0x00596BBC;
const offset<uint32_t> unk_57F240 = 0x0057F240;
const offset<uint32_t> unk_59CC7C = 0x0059CC7C;
const offset<uint32_t> unk_6D5BCC = 0x006D5BCC;
const offset<char> map_path = 0x0057FD3C;
const offset<uint16_t> campaign_mission = 0x0057F244;
const offset<GameData> game_data = 0x005967F8;
const offset<File *> loaded_save = 0x006D1218;
const offset<uint8_t> load_succeeded = 0x006D121C;
const offset<uint32_t> unk_51CA1C = 0x0051CA1C;
const offset<uint8_t> unk_57F1E3 = 0x0057F1E3;
const offset<uint8_t> unk_6CEF8C = 0x006CEF8C;
const offset<uint8_t *> pylon_power_mask = 0x006D5BD8;
const offset<void *> map_mpq_handle = 0x00596BC4;
const offset<PlacementBox> placement_boxes = 0x00640960;
const offset<uint32_t> has_effects_scode = 0x00596CCC;
const offset<uint32_t> gameid = 0x006D5A64;
const offset<void *> playback_commands = 0x006D0F24;
const offset<uint32_t> menu_screen_id = 0x006D11BC;
const offset<uint8_t> scmain_state = 0x00596904;
const offset<void *> unk_6D120C = 0x006D120C;
const offset<void *> unk_596898 = 0x00596898;
const offset<void *> unk_5968E0 = 0x005968E0;
const offset<void *> unk_5968FC = 0x005968FC;
const offset<uint32_t> popup_dialog_active = 0x006D1214;
const offset<Control *> popup_dialog = 0x006D5BF4;
const offset<uint32_t> is_ingame2 = 0x006D5BC8;
const offset<uint32_t> leave_game_tick = 0x0059CC88;
const offset<uint32_t> snp_id = 0x0059688C;
const offset<uint32_t> unk_sound = 0x0051A208; // Actually unk struct
const offset<uint32_t> unk_006CE2A0 = 0x006CE2A0; // Also unk struct
const offset<GrpSprite *> image_grps = 0x0051CED0;
const offset<BlendPalette> blend_palettes = 0x005128F8;
const offset<uint32_t> scenario_chk_length = 0x006D0F20;
const offset<void *> scenario_chk = 0x006D0F24;
const offset<ReplayHeader> replay_header = 0x006D0F30;
const offset<char *> campaign_map_names = 0x0059C080;
const offset<Unit *> ai_building_placement_hack = 0x006D5DCC;
const offset<uint8_t> building_placement_state = 0x006408F8;
const offset<Unit *> last_bullet_spawner = 0x0064DEB0;
const offset<uint32_t> player_build_minecost = 0x006CA51C;
const offset<uint32_t> player_build_gascost = 0x006CA4EC;
const offset<uint8_t> player_race = 0x0057F1E2;
const offset<uint8_t> cloak_distortion = 0x005993D8;
const offset<uint8_t> cloak_remap_palette = 0x005993D8;
const offset<uint8_t> default_grp_remap = 0x0050CDC1;
const offset<uint8_t> shadow_remap = 0x005985A0;
const offset<uint8_t> download_percentage = 0x0066FBF9;
const offset<uint32_t> update_lobby_glue = 0x005999D4;
const offset<uint8_t *> joined_game_packet = 0x006D5C78;
const offset<uint8_t> save_races = 0x0057F1C0;
const offset<uint8_t> save_player_to_original = 0x0066FF34;
const offset<uint32_t> saved_seed = 0x00596BB4;
const offset<uint32_t> lobby_state = 0x0066FBFA;
const offset<uint32_t> in_lobby = 0x00596888;
const offset<MapDl *> map_download = 0x00596890;
const offset<uint32_t> local_net_player = 0x0051268C;
const offset<uint32_t> loaded_local_player_id = 0x0057F1B0;
const offset<uint32_t> loaded_local_unique_player_id = 0x00596BAC;
const offset<uint16_t> own_net_player_flags = 0x0066FF30;
const offset<uint8_t> user_select_slots = 0x0059BDA8;
const offset<uint8_t> replay_user_select_slots = 0x006D11A1;
const offset<uint8_t> force_layout = 0x0058D5B0;
const offset<uint8_t> player_types_unused = 0x0066FF3C;
const offset<Player> temp_players = 0x0059BDB0;
const offset<uint32_t> current_palette_rgba = 0x005994E0;
const offset<void *> FindClosestIndex = 0x004BDB30; // Actually a function
const offset<uint16_t> next_scmain_state = 0x0051CE90;
const offset<uint8_t> error_happened = 0x006D5A10;
const offset<uint32_t> nooks_and_crannies_error = 0x006D5BF8;
const offset<char> chat_messages = 0x00640B60;
const offset<uint8_t> starting_player_types = 0x0057F1B4;
// Some kind of league thing, size 0xc00?
const offset<char> validation_replay_path = 0x00628668;
namespace dat
{
const offset<uint32_t> units_dat_flags = 0x00664080;
const offset<uint8_t> units_dat_group_flags = 0x006637A0;
const offset<uint8_t> units_dat_rclick_action = 0x00662098;
const offset<Rect16> units_dat_dimensionbox = 0x006617C8;
const offset<uint16_t> units_dat_placement_box = 0x00662860;
const offset<uint8_t> units_dat_attack_unit_order = 0x00663320;
const offset<uint8_t> units_dat_attack_move_order = 0x00663A50;
const offset<uint8_t> units_dat_return_to_idle_order = 0x00664898;
const offset<uint8_t> units_dat_ai_idle_order = 0x00662EA0;
const offset<uint8_t> units_dat_human_idle_order = 0x00662268;
const offset<uint8_t> units_dat_space_required = 0x00664410;
const offset<uint8_t> units_dat_space_provided = 0x00660988;
const offset<uint8_t> units_dat_air_weapon = 0x006616E0;
const offset<uint8_t> units_dat_ground_weapon = 0x006636B8;
const offset<int32_t> units_dat_hitpoints = 0x00662350;
const offset<uint16_t> units_dat_shields = 0x00660E00;
const offset<uint8_t> units_dat_has_shields = 0x006647B0;
const offset<uint8_t> units_dat_armor_upgrade = 0x006635D0;
const offset<uint8_t> units_dat_armor = 0x0065FEC8;
const offset<uint8_t> units_dat_armor_type = 0x00662180;
const offset<uint16_t> units_dat_kill_score = 0x00663EB8;
const offset<uint16_t> units_dat_build_score = 0x00663408;
const offset<uint16_t> units_dat_build_time = 0x00660428;
const offset<uint8_t> units_dat_ai_flags = 0x00660178;
const offset<uint8_t> units_dat_sight_range = 0x00663238;
const offset<uint8_t> units_dat_target_acquisition_range = 0x00662DB8;
const offset<uint16_t> units_dat_subunit = 0x006607C0;
const offset<uint16_t> units_dat_mine_cost = 0x00663888;
const offset<uint16_t> units_dat_gas_cost = 0x0065FD00;
const offset<uint8_t> units_dat_elevation_level = 0x00663150;
const offset<uint8_t> units_dat_flingy = 0x006644F8;
const offset<uint8_t> units_dat_direction = 0x006605F0;
const offset<uint16_t> weapons_dat_outer_splash = 0x00657780;
const offset<uint16_t> weapons_dat_middle_splash = 0x006570C8;
const offset<uint16_t> weapons_dat_inner_splash = 0x00656888;
const offset<uint8_t> weapons_dat_effect = 0x006566F8;
const offset<uint8_t> weapons_dat_upgrade = 0x006571D0;
const offset<uint16_t> weapons_dat_damage = 0x00656EB0;
const offset<uint16_t> weapons_dat_upgrade_bonus = 0x00657678;
const offset<uint8_t> weapons_dat_damage_type = 0x00657258;
const offset<uint8_t> weapons_dat_cooldown = 0x00656FB8;
const offset<uint32_t> weapons_dat_min_range = 0x00656A18;
const offset<uint32_t> weapons_dat_max_range = 0x00657470;
const offset<uint8_t> weapons_dat_behaviour = 0x00656670;
const offset<uint16_t> weapons_dat_error_msg = 0x00656568;
const offset<uint8_t> weapons_dat_x_offset = 0x00657910;
const offset<uint32_t> weapons_dat_flingy = 0x00656CA8;
const offset<uint8_t> weapons_dat_death_time = 0x00657040;
const offset<uint8_t> weapons_dat_launch_spin = 0x00657888;
const offset<uint8_t> weapons_dat_attack_angle = 0x00656990;
const offset<int32_t> flingy_dat_top_speed = 0x006C9EF8;
const offset<uint32_t> flingy_dat_halt_distance = 0x006C9930;
const offset<uint16_t> flingy_dat_acceleration = 0x006C9C78;
const offset<uint16_t> flingy_dat_sprite = 0x006CA318;
const offset<uint8_t> flingy_dat_movement_type = 0x006C9858;
const offset<uint16_t> sprites_dat_image = 0x00666160;
const offset<uint8_t> images_dat_drawfunc = 0x00669E28;
const offset<int8_t *> images_dat_shield_overlay = 0x0052E5C8;
const offset<void *> images_dat_attack_overlay = 0x0051F2A8;
const offset<uint32_t> images_dat_damage_overlay = 0x0066A210;
const offset<uint8_t> images_dat_draw_if_cloaked = 0x00667718;
const offset<uint16_t> techdata_dat_energy_cost = 0x00656380;
const offset<uint16_t> techdata_dat_label = 0x006562A0;
const offset<uint16_t> upgrades_dat_label = 0x00655A40;
const offset<uint8_t> orders_dat_targeting_weapon = 0x00665880;
const offset<uint8_t> orders_dat_use_weapon_targeting = 0x00664B00;
const offset<uint8_t> orders_dat_energy_tech = 0x00664E00;
const offset<uint8_t> orders_dat_obscured = 0x00665400;
const offset<uint8_t> orders_dat_interruptable = 0x00665040;
const offset<uint16_t> orders_dat_highlight = 0x00664EC0;
const offset<uint8_t> orders_dat_terrain_clip = 0x006654C0;
const offset<uint8_t> orders_dat_fleeable = 0x00664C80;
const offset<uint8_t> orders_dat_unknown7 = 0x00665100;
const offset<uint8_t> orders_dat_subunit_inheritance = 0x00664A40;
}
namespace storm
{
extern intptr_t base_diff;
}
namespace funcs
{
namespace storm
{
using bw::storm::base_diff;
}
#include "funcs.autogen"
}
namespace base
{
const uintptr_t starcraft = 0x00400000;
const uintptr_t storm = 0x15000000;
const uintptr_t battle = 0x19000000;
const uintptr_t standard = 0x1D000000;
}
}
using namespace bw::dat;
using namespace bw::funcs;
void SetStormOffsets(int diff);
#endif // OFFSETS_HOO
| [
"ittevien@gmail.com"
] | ittevien@gmail.com |
4f21db8549d6369b35275e8de6072e3bd1324d38 | c99beb1d087c79e2810dfc672dcc6ed4de729dfd | /01coding/1785_binary_search_heap_construction.cpp | 24302fd9e7add739575892d9b8a037294b8d4604 | [] | no_license | ddbzdnql/CS97 | 9e863f43fed8e7fe0747b22ca534cfdb0dccd2b0 | d9cc9ebe9f9a4888c9822fe3c45d15173d5c555b | refs/heads/master | 2020-04-12T10:28:05.593296 | 2019-02-13T06:29:44 | 2019-02-13T06:29:44 | 162,430,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,058 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
class node{
public:
int priority;
char * label;
int left;
int right;
} * arr[50001];
void print_tree(node ** needle, int max_p, int size){
node * temp = needle[max_p];
needle[max_p] = needle[0];
needle[0] = temp;
int l = 1, r = size-1, l_max = 0, r_max = 0;
while(l <= r){
if (strcmp(needle[l]->label, needle[0]->label) > 0){
temp = needle[l];
needle[l] = needle[r];
needle[r] = temp;
if (r_max == 0 || needle[r_max]->priority < needle[r]->priority){
r_max = r;
}
r--;
}
else{
if (l_max == 0 || needle[l_max]->priority < needle[l]->priority){
l_max = l;
}
l++;
}
}
printf("(");
if (l-1 > 1){
print_tree(needle+1, l_max-1, l-1);
}
else{
if (l-1 != 0){
printf("(%s/%d)", needle[1]->label, needle[1]->priority);
}
}
printf("%s/%d", needle[0]->label, needle[0]->priority);
if (size-l > 1){
print_tree(needle+r+1, r_max-l, size-l);
}
else{
if (size-l != 0){
printf("(%s/%d)", needle[r+1]->label, needle[r+1]->priority);
}
}
printf(")");
}
int main(){
int l;
unsigned seed = 1221;
scanf("%d", &l);
char delim[] = "/";
while(l != 0){
int i = 0;
while(i < l){
i++;
char str[17];
scanf("%s", str);
char * ptr = strtok(str, delim);
char * la = (char *)calloc(8, sizeof(char));
strcpy(la, str);
ptr = strtok(NULL, ptr);
int p = atoi(ptr);
if (arr[i] == NULL){
arr[i] = (node *)malloc(sizeof(node));
}
arr[i]->priority = p;
arr[i]->label = la;
arr[i]->left = 0;
arr[i]->right = 0;
}
//random_shuffle(arr+1, arr+l+1);
int max_p = 0;
for (int i=1; i<=l; i++){
if (max_p==0 || arr[max_p]->priority < arr[i]->priority){
max_p = i;
}
}
print_tree(arr+1, max_p-1, l);
printf("\n");
scanf("%d", &l);
}
}
| [
"gdbzdnql@gmail.com"
] | gdbzdnql@gmail.com |
65e294bea986845307b0796e1bc2225bf18604d0 | 477c8309420eb102b8073ce067d8df0afc5a79b1 | /Utilities/VisItBridge/databases/Velodyne/avtVelodyneFileFormat.h | ebccc39cec3cf984a1b33127eb54ffff24899dc3 | [
"LicenseRef-scancode-paraview-1.2"
] | permissive | aashish24/paraview-climate-3.11.1 | e0058124e9492b7adfcb70fa2a8c96419297fbe6 | c8ea429f56c10059dfa4450238b8f5bac3208d3a | refs/heads/uvcdat-master | 2021-07-03T11:16:20.129505 | 2013-05-10T13:14:30 | 2013-05-10T13:14:30 | 4,238,077 | 1 | 0 | NOASSERTION | 2020-10-12T21:28:23 | 2012-05-06T02:32:44 | C++ | UTF-8 | C++ | false | false | 6,018 | h | /*****************************************************************************
*
* Copyright (c) 2000 - 2010, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-400142
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* 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 disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*
*****************************************************************************/
//
// This code was contributed to the VisIt project by Corvid Technologies
// on February 10, 2010.
//
// ************************************************************************* //
// avtVelodyneFileFormat.h //
// ************************************************************************* //
#ifndef AVT_Velodyne_FILE_FORMAT_H
#define AVT_Velodyne_FILE_FORMAT_H
#include <map>
using std::map;
#include <vector>
#include <string>
#include <vtkPoints.h>
#include <vtkFloatArray.h>
#include <VelodyneReader.h>
#include <avtSTSDFileFormat.h>
// ****************************************************************************
// Class: avtVelodyneFileFormat
//
// Purpose:
// Reads in Velodyne files as a plugin to VisIt.
//
// Programmer: hpan -- generated by xml2avt
// Creation: Thu Aug 7 11:38:59 PDT 2008
//
// ****************************************************************************
class avtVelodyneFileFormat : public avtSTSDFileFormat
{
public:
avtVelodyneFileFormat(const char *filename);
virtual ~avtVelodyneFileFormat();
//
// This is used to return unconvention data -- ranging from material
// information to information about block connectivity.
//
virtual void *GetAuxiliaryData(const char *var, const char *type,
void *args, DestructorFunction &);
//
// These are used to declare what the current time and cycle are for the
// file. These should only be defined if the file format knows what the
// time and/or cycle is.
//
virtual bool ReturnsValidCycle() const { return true; };
virtual int GetCycle(void);
virtual bool ReturnsValidTime() const { return true; };
virtual double GetTime(void);
virtual const char *GetType(void) { return "Velodyne"; };
virtual void FreeUpResources(void);
virtual vtkDataSet *GetMesh(const char *);
virtual vtkDataArray *GetVar(const char *);
virtual vtkDataArray *GetVectorVar(const char *);
protected:
int readNodeIndex();
int readNodeCoord();
int readdElements( int grp, int bufsz, int* elmt );
int readNodeBaseVariableNames();
int isNodeBasedVariable( const std::string& name );
//int isVectorVariable( int grp, const char* varname );
int isTensorVariable( int grp, const char* varname );
void convert2dVectorTo3dVector( int num, float* val );
void convert1dVectorTo3dVector( int num, float* val );
// sym tensor (xx,yy,zz,xy,yz,zx)
void convertSymTensorToFullTensor( int num, float* val );
protected:
// DATA MEMBERS
VelodyneReader *reader_;
int idx_mn_, idx_mx_;
// node based variables, which are shared between Solid and Shell
int *map_; // node index mapping, from read-in index to dataset order
vtkPoints *crd_; // node coordindates
int nnvs_; // number of node based variables
std::vector<std::string> nvname_;
std::vector<vtkFloatArray*> nvdata_;
vtkObjectBase *pobj_;
virtual void PopulateDatabaseMetaData(avtDatabaseMetaData *);
protected:
static const std::string node_name;
static const std::string solid_name;
static const std::string shell_name;
static const std::string surface_name;
static const std::string particle_name;
static const std::string tiednode_name;
static const std::string sph_name;
static const std::string invalid_name;
static std::string composeName( const std::string& m, const std::string& v, const char app='/' );
static void decomposeName( const std::string& s, std::string& m, std::string& v );
static int getTypeId( const char* name );
static const std::string& getTypeName( int type );
};
#endif
| [
"aashish.chaudhary@kitware.com"
] | aashish.chaudhary@kitware.com |
7aaebcd79712ec9d05ce4334a7ccbc872d7bda18 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/ext/random/logistic_distribution/operators/serialize.cc | a359c85c3e5bc467ec345c53d61054f82d344900 | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 1,312 | cc | // { dg-do run { target c++11 } }
// { dg-require-cstdint "" }
//
// 2014-07-11 Edward M. Smith-Rowland <3dw4rd@verizon.net>
//
// Copyright (C) 2014-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
//
// This library 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 library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// Class template logistic_distribution
// 26.5.1.6 Random number distribution requirements [rand.req.dist]
#include <ext/random>
#include <sstream>
#include <testsuite_hooks.h>
void
test01()
{
std::stringstream str;
__gnu_cxx::logistic_distribution<double> u(1.5, 3.0), v;
std::minstd_rand0 rng;
u(rng); // advance
str << u;
str >> v;
VERIFY( u == v );
}
int
main()
{
test01();
return 0;
}
| [
"rink@rink.nu"
] | rink@rink.nu |
78104518288a193df7734da84db643a434cb13a8 | a9ddea89efd4ab2de44056bf7fc836919f62fb17 | /DX_3D_STUDY/cASELoader.h | 5092c89136cad491de5fda4bb1561caf392986a6 | [] | no_license | hyunsang-shim/study | 63a0fb5da1616afad5f19f32ea8a2186b39e5545 | 8aa2d000647e305e9fafc0b0040f96d9f8827c4d | refs/heads/master | 2021-07-08T03:02:43.127318 | 2019-02-15T03:48:25 | 2019-02-15T03:48:25 | 136,994,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 145 | h | #pragma once
class cASELoader
{
public:
cASELoader();
~cASELoader();
static vector<ASE_Obj> ParseASE(string FileName);
};
| [
"shimhyunsang.dev@gmail.com"
] | shimhyunsang.dev@gmail.com |
6ff4317f8e60409952af2a33272a2ae66b95224a | e2b81b17e8694bcccb574f0eb0e5dada7f82f205 | /BattleTanks/Source/BattleTanks/Public/TankBarrel.h | dd94501faf5b0439e94132035cf4a906c334ef5d | [
"MIT"
] | permissive | StanimirMitev/04_BattleTank | 8a5adc9bc55a59bcbd16d9c1f61cd27bb2113f67 | a041a29c374567f38bbafb3bbf93ed6aba9f7c7d | refs/heads/master | 2020-03-18T16:40:51.752815 | 2019-10-02T13:46:35 | 2019-10-02T13:46:35 | 134,980,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/StaticMeshComponent.h"
#include "Runtime/Core/Public/Math/UnrealMathUtility.h"
#include "Runtime/Engine/Classes/Engine/World.h"
#include "TankBarrel.generated.h"
/**
*
*/
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class BATTLETANKS_API UTankBarrel : public UStaticMeshComponent
{
GENERATED_BODY()
public:
// -1 = max downwards speed, 1 = max upwards speed
void Elevate(float RelativeSpeed);
private:
UPROPERTY(EditAnywhere, Category = Setup)
float MaxDegreesPerSecond = 20.0;
UPROPERTY(EditAnywhere, Category = Setup)
float MaxElevationDegree = 15.0;
UPROPERTY(EditAnywhere, Category = Setup)
float MinElevationDegree = 0.0;
};
| [
"hunterinthestorm@gmail.com"
] | hunterinthestorm@gmail.com |
68db06c1bc5a57ca4aa7e3c27556c0108d4fc112 | 6839815d8871e878057ff8aa761923b84172f0ec | /modules/algorithms/include/pga.h | 0dceddaf107387dbc6d1a96ce7d97af5a223618e | [
"BSD-3-Clause"
] | permissive | graphprocessing/graph_coarsening | 7e2d96b9fae5628ecf93a58c4dadaef237b7135f | c570c7c301be5fe8d521c418402f20c76b147433 | refs/heads/master | 2021-07-13T12:11:12.183890 | 2020-06-24T01:00:24 | 2020-06-24T01:00:24 | 164,952,532 | 3 | 7 | BSD-3-Clause | 2020-06-24T01:00:26 | 2019-01-09T23:09:28 | C++ | UTF-8 | C++ | false | false | 3,073 | h | // Copyright [year] <Copyright Owner>
#ifndef MODULES_ALGORITHMS_INCLUDE_PGA_H_
#define MODULES_ALGORITHMS_INCLUDE_PGA_H_
#include "../../pch/include/precomp.h"
template <typename WeightType, typename MatchingFunction>
Matching PGA(const CSR<WeightType> &graph, MatchingFunction match) {
Matching result;
int size = graph.n;
std::vector <int> ed(size);
std::vector <int> ed1(size);
std::vector <char> used1(size, false);
std::set <std::pair<int, int>> used;
for (int i = 0; i < size; i++) {
ed1[i] = i;
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(ed1.begin(), ed1.end(), g);
std::copy(ed1.begin(), ed1.end(), ed.begin());
auto deg = [&](int k) {
int deg_ans = 0;
for (int i = graph.offset[k]; i < graph.offset[k + 1]; i++) {
if (used.find(std::make_pair(k, graph.edges[i]))
== used.end()) {
deg_ans++;
}
}
if (deg_ans > 0) {
return true;
} else {
return false;
}
};
auto is_edge = [&]() {
int edge_ans = 0;
for (int i = 0; i < graph.n; i++) {
for (int j = graph.offset[i]; j < graph.offset[i + 1]; j++) {
if (used.find(std::make_pair(i, graph.edges[i]))
== used.end()) {
edge_ans++;
}
}
}
return edge_ans;
};
while (is_edge() != 0) {
AL <WeightType> P;
P.n = size;
P.edges.resize(size);
P.weights.resize(size);
P.weight_vertex.resize(size);
int v = -1;
for (unsigned i = 0; i < ed.size(); i++) {
if (deg(ed[i]) && !used1[ed[i]]) {
v = ed[i];
break;
}
}
if (v == -1) break;
while (deg(v)) {
if (used1[v]) break;
int e = -1;
WeightType weight = -1;
for (int i = graph.offset[v]; i < graph.offset[v + 1]; i++) {
if (graph.weights[i] > weight &&
used.find(std::make_pair(v, graph.edges[i])) == used.end() &&
!used1[graph.edges[i]]) {
e = graph.edges[i];
weight = graph.weights[i];
}
}
used1[v] = true;
for (int i = graph.offset[v]; i < graph.offset[v + 1]; i++) {
used.insert(std::make_pair(v, graph.edges[i]));
}
if (e == -1) break;
P.edges[v].push_back(e);
P.weights[v].push_back(weight);
v = e;
}
Matching result_new = match(P);
for (int i = 0; i < result_new.n; i++) {
used1[result_new.edge_b[i]] = true;
used1[result_new.edge_e[i]] = true;
result.edge_b.push_back(result_new.edge_b[i]);
result.edge_e.push_back(result_new.edge_e[i]);
}
result.n += result_new.n;
}
return result;
}
#endif // MODULES_ALGORITHMS_INCLUDE_PGA_H_
| [
"nesoldr@gmail.com"
] | nesoldr@gmail.com |
b036ab927faa1db9ff042d80fc6b1e62ecc0f5a5 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/ClickHouse/2017/12/DDLWorker.cpp | 0a57611854a302e9399196e1b6a292edbd46f35e | [
"BSL-1.0"
] | permissive | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 39,030 | cpp | #include <Interpreters/DDLWorker.h>
#include <Parsers/ASTAlterQuery.h>
#include <Parsers/ASTQueryWithOnCluster.h>
#include <Parsers/ParserQuery.h>
#include <Parsers/parseQuery.h>
#include <Parsers/queryToString.h>
#include <IO/WriteHelpers.h>
#include <IO/ReadHelpers.h>
#include <IO/Operators.h>
#include <IO/ReadBufferFromString.h>
#include <Storages/IStorage.h>
#include <DataStreams/IProfilingBlockInputStream.h>
#include <Interpreters/executeQuery.h>
#include <Interpreters/Cluster.h>
#include <Common/DNSCache.h>
#include <Common/getFQDNOrHostName.h>
#include <Common/setThreadName.h>
#include <Common/Stopwatch.h>
#include <Common/randomSeed.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeArray.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnArray.h>
#include <Common/ZooKeeper/ZooKeeper.h>
#include <Common/ZooKeeper/Lock.h>
#include <Common/isLocalAddress.h>
#include <Poco/Timestamp.h>
#include <random>
#include <pcg_random.hpp>
namespace DB
{
namespace ErrorCodes
{
extern const int UNKNOWN_ELEMENT_IN_CONFIG;
extern const int INVALID_CONFIG_PARAMETER;
extern const int UNKNOWN_FORMAT_VERSION;
extern const int INCONSISTENT_TABLE_ACCROSS_SHARDS;
extern const int INCONSISTENT_CLUSTER_DEFINITION;
extern const int TIMEOUT_EXCEEDED;
extern const int UNKNOWN_TYPE_OF_QUERY;
extern const int UNFINISHED;
extern const int UNKNOWN_STATUS_OF_DISTRIBUTED_DDL_TASK;
}
namespace
{
struct HostID
{
String host_name;
UInt16 port;
HostID() = default;
explicit HostID(const Cluster::Address & address)
: host_name(address.host_name), port(address.port) {}
static HostID fromString(const String & host_port_str)
{
HostID res;
Cluster::Address::fromString(host_port_str, res.host_name, res.port);
return res;
}
String toString() const
{
return Cluster::Address::toString(host_name, port);
}
String readableString() const
{
return host_name + ":" + DB::toString(port);
}
bool isLocalAddress(UInt16 clickhouse_port) const
{
try
{
return DB::isLocalAddress(Poco::Net::SocketAddress(host_name, port), clickhouse_port);
}
catch (const Poco::Exception & e)
{
/// Avoid "Host not found" exceptions
return false;
}
}
static String applyToString(const HostID & host_id)
{
return host_id.toString();
}
};
}
struct DDLLogEntry
{
String query;
std::vector<HostID> hosts;
String initiator; // optional
static constexpr int CURRENT_VERSION = 1;
String toString()
{
WriteBufferFromOwnString wb;
Strings host_id_strings(hosts.size());
std::transform(hosts.begin(), hosts.end(), host_id_strings.begin(), HostID::applyToString);
auto version = CURRENT_VERSION;
wb << "version: " << version << "\n";
wb << "query: " << escape << query << "\n";
wb << "hosts: " << host_id_strings << "\n";
wb << "initiator: " << initiator << "\n";
return wb.str();
}
void parse(const String & data)
{
ReadBufferFromString rb(data);
int version;
rb >> "version: " >> version >> "\n";
if (version != CURRENT_VERSION)
throw Exception("Unknown DDLLogEntry format version: " + DB::toString(version), ErrorCodes::UNKNOWN_FORMAT_VERSION);
Strings host_id_strings;
rb >> "query: " >> escape >> query >> "\n";
rb >> "hosts: " >> host_id_strings >> "\n";
if (!rb.eof())
rb >> "initiator: " >> initiator >> "\n";
else
initiator.clear();
assertEOF(rb);
hosts.resize(host_id_strings.size());
std::transform(host_id_strings.begin(), host_id_strings.end(), hosts.begin(), HostID::fromString);
}
};
struct DDLTask
{
/// Stages of task lifetime correspond ordering of these data fields:
/// Stage 1: parse entry
String entry_name;
String entry_path;
DDLLogEntry entry;
/// Stage 2: resolve host_id and check that
HostID host_id;
String host_id_str;
/// Stage 3.1: parse query
ASTPtr query;
ASTQueryWithOnCluster * query_on_cluster = nullptr;
/// Stage 3.2: check cluster and find the host in cluster
String cluster_name;
ClusterPtr cluster;
Cluster::Address address_in_cluster;
size_t host_shard_num;
size_t host_replica_num;
/// Stage 3.3: execute query
ExecutionStatus execution_status;
bool was_executed = false;
/// Stage 4: commit results to ZooKeeper
};
static std::unique_ptr<zkutil::Lock> createSimpleZooKeeperLock(
std::shared_ptr<zkutil::ZooKeeper> & zookeeper, const String & lock_prefix, const String & lock_name, const String & lock_message)
{
auto zookeeper_holder = std::make_shared<zkutil::ZooKeeperHolder>();
zookeeper_holder->initFromInstance(zookeeper);
return std::make_unique<zkutil::Lock>(std::move(zookeeper_holder), lock_prefix, lock_name, lock_message);
}
static bool isSupportedAlterType(int type)
{
static const std::unordered_set<int> supported_alter_types{
ASTAlterQuery::ADD_COLUMN,
ASTAlterQuery::DROP_COLUMN,
ASTAlterQuery::MODIFY_COLUMN,
ASTAlterQuery::MODIFY_PRIMARY_KEY,
ASTAlterQuery::DROP_PARTITION
};
return supported_alter_types.count(type) != 0;
}
DDLWorker::DDLWorker(const std::string & zk_root_dir, Context & context_, const Poco::Util::AbstractConfiguration * config, const String & prefix)
: context(context_), log(&Logger::get("DDLWorker"))
{
queue_dir = zk_root_dir;
if (queue_dir.back() == '/')
queue_dir.resize(queue_dir.size() - 1);
if (config)
{
task_max_lifetime = config->getUInt64(prefix + ".task_max_lifetime", static_cast<UInt64>(task_max_lifetime));
cleanup_delay_period = config->getUInt64(prefix + ".cleanup_delay_period", static_cast<UInt64>(cleanup_delay_period));
max_tasks_in_queue = std::max(static_cast<UInt64>(1), config->getUInt64(prefix + ".max_tasks_in_queue", max_tasks_in_queue));
}
host_fqdn = getFQDNOrHostName();
host_fqdn_id = Cluster::Address::toString(host_fqdn, context.getTCPPort());
event_queue_updated = std::make_shared<Poco::Event>();
thread = std::thread(&DDLWorker::run, this);
}
DDLWorker::~DDLWorker()
{
stop_flag = true;
event_queue_updated->set();
thread.join();
}
bool DDLWorker::initAndCheckTask(const String & entry_name, String & out_reason)
{
String node_data;
String entry_path = queue_dir + "/" + entry_name;
if (!zookeeper->tryGet(entry_path, node_data))
{
/// It is Ok that node could be deleted just now. It means that there are no current host in node's host list.
out_reason = "The task was deleted";
return false;
}
auto task = std::make_unique<DDLTask>();
task->entry_name = entry_name;
task->entry_path = entry_path;
try
{
task->entry.parse(node_data);
}
catch (...)
{
/// What should we do if we even cannot parse host name and therefore cannot properly submit execution status?
/// We can try to create fail node using FQDN if it equal to host name in cluster config attempt will be sucessfull.
/// Otherwise, that node will be ignored by DDLQueryStatusInputSream.
tryLogCurrentException(log, "Cannot parse DDL task " + entry_name + ", will try to send error status");
String status = ExecutionStatus::fromCurrentException().serializeText();
try
{
createStatusDirs(entry_path);
zookeeper->tryCreate(entry_path + "/finished/" + host_fqdn_id, status, zkutil::CreateMode::Persistent);
}
catch (...)
{
tryLogCurrentException(log, "Can't report the task has invalid format");
}
out_reason = "Incorrect task format";
return false;
}
bool host_in_hostlist = false;
for (const HostID & host : task->entry.hosts)
{
if (!host.isLocalAddress(context.getTCPPort()))
continue;
if (host_in_hostlist)
{
/// This check could be slow a little bit
LOG_WARNING(log, "There are two the same ClickHouse instances in task " << entry_name
<< ": " << task->host_id.readableString() << " and " << host.readableString() << ". Will use the first one only.");
}
else
{
host_in_hostlist = true;
task->host_id = host;
task->host_id_str = host.toString();
}
}
if (host_in_hostlist)
current_task = std::move(task);
else
out_reason = "There is no a local address in host list";
return host_in_hostlist;
}
static void filterAndSortQueueNodes(Strings & all_nodes)
{
all_nodes.erase(std::remove_if(all_nodes.begin(), all_nodes.end(), [] (const String & s) { return !startsWith(s, "query-"); }), all_nodes.end());
std::sort(all_nodes.begin(), all_nodes.end());
}
void DDLWorker::processTasks()
{
LOG_DEBUG(log, "Processing tasks");
Strings queue_nodes = zookeeper->getChildren(queue_dir, nullptr, event_queue_updated);
filterAndSortQueueNodes(queue_nodes);
if (queue_nodes.empty())
return;
bool server_startup = last_processed_task_name.empty();
auto begin_node = server_startup
? queue_nodes.begin()
: std::upper_bound(queue_nodes.begin(), queue_nodes.end(), last_processed_task_name);
for (auto it = begin_node; it != queue_nodes.end(); ++it)
{
String entry_name = *it;
if (current_task)
{
if (current_task->entry_name == entry_name)
{
LOG_INFO(log, "Trying to process task " << entry_name << " again");
}
else
{
LOG_INFO(log, "Task " << current_task->entry_name << " was deleted from ZooKeeper before current host committed it");
current_task = nullptr;
}
}
if (!current_task)
{
String reason;
if (!initAndCheckTask(entry_name, reason))
{
LOG_DEBUG(log, "Will not execute task " << entry_name << " : " << reason);
last_processed_task_name = entry_name;
continue;
}
}
DDLTask & task = *current_task;
bool already_processed = zookeeper->exists(task.entry_path + "/finished/" + task.host_id_str);
if (!server_startup && !task.was_executed && already_processed)
{
throw Exception(
"Server expects that DDL task " + task.entry_name + " should be processed, but it was already processed according to ZK",
ErrorCodes::LOGICAL_ERROR);
}
if (!already_processed)
{
try
{
processTask(task);
}
catch (...)
{
LOG_WARNING(log, "An error occurred while processing task " << task.entry_name << " (" << task.entry.query << ") : "
<< getCurrentExceptionMessage(true));
throw;
}
}
else
{
LOG_DEBUG(log, "Task " << task.entry_name << " (" << task.entry.query << ") has been already processed");
}
last_processed_task_name = task.entry_name;
current_task.reset();
if (stop_flag)
break;
}
}
/// Parses query and resolves cluster and host in cluster
void DDLWorker::parseQueryAndResolveHost(DDLTask & task)
{
{
const char * begin = task.entry.query.data();
const char * end = begin + task.entry.query.size();
ParserQuery parser_query(end);
String description;
task.query = parseQuery(parser_query, begin, end, description);
}
if (!task.query || !(task.query_on_cluster = dynamic_cast<ASTQueryWithOnCluster *>(task.query.get())))
throw Exception("Recieved unknown DDL query", ErrorCodes::UNKNOWN_TYPE_OF_QUERY);
task.cluster_name = task.query_on_cluster->cluster;
task.cluster = context.tryGetCluster(task.cluster_name);
if (!task.cluster)
{
throw Exception("DDL task " + task.entry_name + " contains current host " + task.host_id.readableString()
+ " in cluster " + task.cluster_name + ", but there are no such cluster here.", ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);
}
/// Try to find host from task host list in cluster
/// At the first, try find exact match (host name and ports should be literally equal)
/// If the attempt fails, try find it resolving host name of each instance
const auto & shards = task.cluster->getShardsAddresses();
bool found_exact_match = false;
for (size_t shard_num = 0; shard_num < shards.size(); ++shard_num)
{
for (size_t replica_num = 0; replica_num < shards[shard_num].size(); ++replica_num)
{
const Cluster::Address & address = shards[shard_num][replica_num];
if (address.host_name == task.host_id.host_name && address.port == task.host_id.port)
{
if (found_exact_match)
{
throw Exception("There are two exactly the same ClickHouse instances " + address.readableString()
+ " in cluster " + task.cluster_name, ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);
}
found_exact_match = true;
task.host_shard_num = shard_num;
task.host_replica_num = replica_num;
task.address_in_cluster = address;
}
}
}
if (found_exact_match)
return;
LOG_WARNING(log, "Not found the exact match of host " << task.host_id.readableString() << " from task " << task.entry_name
<< " in cluster " << task.cluster_name << " definition. Will try to find it using host name resolving.");
bool found_via_resolving = false;
for (size_t shard_num = 0; shard_num < shards.size(); ++shard_num)
{
for (size_t replica_num = 0; replica_num < shards[shard_num].size(); ++replica_num)
{
const Cluster::Address & address = shards[shard_num][replica_num];
if (isLocalAddress(address.resolved_address, context.getTCPPort()))
{
if (found_via_resolving)
{
throw Exception("There are two the same ClickHouse instances in cluster " + task.cluster_name + " : "
+ task.address_in_cluster.readableString() + " and " + address.readableString(), ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);
}
else
{
found_via_resolving = true;
task.host_shard_num = shard_num;
task.host_replica_num = replica_num;
task.address_in_cluster = address;
}
}
}
}
if (!found_via_resolving)
{
throw Exception("Not found host " + task.host_id.readableString() + " in definition of cluster " + task.cluster_name,
ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);
}
else
{
LOG_INFO(log, "Resolved host " << task.host_id.readableString() << " from task " << task.entry_name
<< " as host " << task.address_in_cluster.readableString() << " in definition of cluster " << task.cluster_name);
}
}
bool DDLWorker::tryExecuteQuery(const String & query, const DDLTask & task, ExecutionStatus & status)
{
/// Add special comment at the start of query to easily identify DDL-produced queries in query_log
String query_prefix = "/* ddl_entry=" + task.entry_name + " */ ";
String query_to_execute = query_prefix + query;
ReadBufferFromString istr(query_to_execute);
String dummy_string;
WriteBufferFromString ostr(dummy_string);
try
{
Context local_context(context);
executeQuery(istr, ostr, false, local_context, nullptr);
}
catch (...)
{
status = ExecutionStatus::fromCurrentException();
tryLogCurrentException(log, "Query " + query + " wasn't finished successfully");
return false;
}
status = ExecutionStatus(0);
LOG_DEBUG(log, "Executed query: " << query);
return true;
}
void DDLWorker::processTask(DDLTask & task)
{
LOG_DEBUG(log, "Processing task " << task.entry_name << " (" << task.entry.query << ")");
String dummy;
String active_node_path = task.entry_path + "/active/" + task.host_id_str;
String finished_node_path = task.entry_path + "/finished/" + task.host_id_str;
auto code = zookeeper->tryCreateWithRetries(active_node_path, "", zkutil::CreateMode::Ephemeral, dummy);
if (code == ZOK || code == ZNODEEXISTS)
{
// Ok
}
else if (code == ZNONODE)
{
/// There is no parent
createStatusDirs(task.entry_path);
if (ZOK != zookeeper->tryCreateWithRetries(active_node_path, "", zkutil::CreateMode::Ephemeral, dummy))
throw zkutil::KeeperException(code, active_node_path);
}
else
throw zkutil::KeeperException(code, active_node_path);
if (!task.was_executed)
{
try
{
parseQueryAndResolveHost(task);
ASTPtr rewritten_ast = task.query_on_cluster->getRewrittenASTWithoutOnCluster(task.address_in_cluster.default_database);
String rewritten_query = queryToString(rewritten_ast);
LOG_DEBUG(log, "Executing query: " << rewritten_query);
if (auto ast_alter = dynamic_cast<const ASTAlterQuery *>(rewritten_ast.get()))
{
processTaskAlter(task, ast_alter, rewritten_query, task.entry_path);
}
else
{
tryExecuteQuery(rewritten_query, task, task.execution_status);
}
}
catch (const zkutil::KeeperException & e)
{
throw;
}
catch (...)
{
task.execution_status = ExecutionStatus::fromCurrentException("An error occured before execution");
}
/// We need to distinguish ZK errors occured before and after query executing
task.was_executed = true;
}
/// FIXME: if server fails right here, the task will be executed twice. We need WAL here.
/// Delete active flag and create finish flag
zkutil::Ops ops;
ops.emplace_back(std::make_unique<zkutil::Op::Remove>(active_node_path, -1));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(finished_node_path, task.execution_status.serializeText(),
zookeeper->getDefaultACL(), zkutil::CreateMode::Persistent));
zookeeper->multi(ops);
}
void DDLWorker::processTaskAlter(
DDLTask & task,
const ASTAlterQuery * ast_alter,
const String & rewritten_query,
const String & node_path)
{
String database = ast_alter->database.empty() ? context.getCurrentDatabase() : ast_alter->database;
StoragePtr storage = context.getTable(database, ast_alter->table);
bool execute_once_on_replica = storage->supportsReplication();
bool execute_on_leader_replica = false;
for (const auto & param : ast_alter->parameters)
{
if (!isSupportedAlterType(param.type))
throw Exception("Unsupported type of ALTER query", ErrorCodes::NOT_IMPLEMENTED);
if (execute_once_on_replica)
execute_on_leader_replica |= param.type == ASTAlterQuery::DROP_PARTITION;
}
const auto & shard_info = task.cluster->getShardsInfo().at(task.host_shard_num);
bool config_is_replicated_shard = shard_info.hasInternalReplication();
if (execute_once_on_replica && !config_is_replicated_shard)
{
throw Exception("Table " + ast_alter->table + " is replicated, but shard #" + toString(task.host_shard_num + 1) +
" isn't replicated according to its cluster definition", ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);
}
else if (!execute_once_on_replica && config_is_replicated_shard)
{
throw Exception("Table " + ast_alter->table + " isn't replicated, but shard #" + toString(task.host_shard_num + 1) +
" is replicated according to its cluster definition", ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION);
}
if (execute_once_on_replica)
{
/// The following code can perform ALTER twice if:
/// current server acquires the lock, executes replicated alter,
/// loses zookeeper connection and doesn't have time to create /executed node, second server executes replicated alter again
/// To avoid this problem alter() method of replicated tables should be changed and takes into account ddl query id tag.
if (!context.getSettingsRef().distributed_ddl_allow_replicated_alter)
throw Exception("Distributed DDL alters for replicated tables don't work properly yet", ErrorCodes::NOT_IMPLEMENTED);
/// Generate unique name for shard node, it will be used to execute the query by only single host
/// Shard node name has format 'replica_name1,replica_name2,...,replica_nameN'
/// Where replica_name is 'escape(replica_ip_address):replica_port'
/// FIXME: this replica_name could be changed after replica restart
Strings replica_names;
for (const Cluster::Address & address : task.cluster->getShardsAddresses().at(task.host_shard_num))
replica_names.emplace_back(address.resolved_address.host().toString());
std::sort(replica_names.begin(), replica_names.end());
String shard_node_name;
for (auto it = replica_names.begin(); it != replica_names.end(); ++it)
shard_node_name += *it + (std::next(it) != replica_names.end() ? "," : "");
String shard_path = node_path + "/shards/" + shard_node_name;
String is_executed_path = shard_path + "/executed";
zookeeper->createAncestors(shard_path + "/");
bool alter_executed_by_any_replica = false;
{
auto lock = createSimpleZooKeeperLock(zookeeper, shard_path, "lock", task.host_id_str);
pcg64 rng(randomSeed());
for (int num_tries = 0; num_tries < 10; ++num_tries)
{
if (zookeeper->exists(is_executed_path))
{
alter_executed_by_any_replica = true;
break;
}
if (lock->tryLock())
{
tryExecuteQuery(rewritten_query, task, task.execution_status);
if (execute_on_leader_replica && task.execution_status.code == ErrorCodes::NOT_IMPLEMENTED)
{
/// TODO: it is ok to receive exception "host is not leader"
}
zookeeper->create(is_executed_path, task.host_id_str, zkutil::CreateMode::Persistent);
lock->unlock();
alter_executed_by_any_replica = true;
break;
}
std::this_thread::sleep_for(std::chrono::duration<double>(std::uniform_real_distribution<double>(0, 1)(rng)));
}
}
if (!alter_executed_by_any_replica)
task.execution_status = ExecutionStatus(ErrorCodes::NOT_IMPLEMENTED, "Cannot enqueue replicated DDL query");
}
else
{
tryExecuteQuery(rewritten_query, task, task.execution_status);
}
}
void DDLWorker::cleanupQueue()
{
/// Both ZK and Poco use Unix epoch
Int64 current_time_seconds = Poco::Timestamp().epochTime();
constexpr UInt64 zookeeper_time_resolution = 1000;
/// Too early to check
if (last_cleanup_time_seconds && current_time_seconds < last_cleanup_time_seconds + cleanup_delay_period)
return;
last_cleanup_time_seconds = current_time_seconds;
LOG_DEBUG(log, "Cleaning queue");
Strings queue_nodes = zookeeper->getChildren(queue_dir);
filterAndSortQueueNodes(queue_nodes);
size_t num_outdated_nodes = (queue_nodes.size() > max_tasks_in_queue) ? queue_nodes.size() - max_tasks_in_queue : 0;
auto first_non_outdated_node = queue_nodes.begin() + num_outdated_nodes;
for (auto it = queue_nodes.cbegin(); it < queue_nodes.cend(); ++it)
{
String node_name = *it;
String node_path = queue_dir + "/" + node_name;
String lock_path = node_path + "/lock";
zkutil::Stat stat;
String dummy;
try
{
/// Already deleted
if (!zookeeper->exists(node_path, &stat))
continue;
/// Delete node if its lifetmie is expired (according to task_max_lifetime parameter)
Int64 zookeeper_time_seconds = stat.ctime / zookeeper_time_resolution;
bool node_lifetime_is_expired = zookeeper_time_seconds + task_max_lifetime < current_time_seconds;
/// If too many nodes in task queue (> max_tasks_in_queue), delete oldest one
bool node_is_outside_max_window = it < first_non_outdated_node;
if (!node_lifetime_is_expired && !node_is_outside_max_window)
continue;
/// Skip if there are active nodes (it is weak guard)
if (zookeeper->exists(node_path + "/active", &stat) && stat.numChildren > 0)
{
LOG_INFO(log, "Task " << node_name << " should be deleted, but there are active workers. Skipping it.");
continue;
}
/// Usage of the lock is not necessary now (tryRemoveRecursive correctly removes node in a presence of concurrent cleaners)
/// But the lock will be required to implement system.distributed_ddl_queue table
auto lock = createSimpleZooKeeperLock(zookeeper, node_path, "lock", host_fqdn_id);
if (!lock->tryLock())
{
LOG_INFO(log, "Task " << node_name << " should be deleted, but it is locked. Skipping it.");
continue;
}
if (node_lifetime_is_expired)
LOG_INFO(log, "Lifetime of task " << node_name << " is expired, deleting it");
else if (node_is_outside_max_window)
LOG_INFO(log, "Task " << node_name << " is outdated, deleting it");
/// Deleting
{
Strings childs = zookeeper->getChildren(node_path);
for (const String & child : childs)
{
if (child != "lock")
zookeeper->tryRemoveRecursive(node_path + "/" + child);
}
/// Remove the lock node and its parent atomically
zkutil::Ops ops;
ops.emplace_back(std::make_unique<zkutil::Op::Remove>(lock_path, -1));
ops.emplace_back(std::make_unique<zkutil::Op::Remove>(node_path, -1));
zookeeper->multi(ops);
lock->unlockAssumeLockNodeRemovedManually();
}
}
catch (...)
{
LOG_INFO(log, "An error occured while checking and cleaning task " + node_name + " from queue: " + getCurrentExceptionMessage(false));
}
}
}
/// Try to create nonexisting "status" dirs for a node
void DDLWorker::createStatusDirs(const std::string & node_path)
{
zkutil::Ops ops;
auto acl = zookeeper->getDefaultACL();
ops.emplace_back(std::make_unique<zkutil::Op::Create>(node_path + "/active", "", acl, zkutil::CreateMode::Persistent));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(node_path + "/finished", "", acl, zkutil::CreateMode::Persistent));
int code = zookeeper->tryMulti(ops);
if (code != ZOK && code != ZNODEEXISTS)
throw zkutil::KeeperException(code);
}
String DDLWorker::enqueueQuery(DDLLogEntry & entry)
{
if (entry.hosts.empty())
throw Exception("Empty host list in a distributed DDL task", ErrorCodes::LOGICAL_ERROR);
String query_path_prefix = queue_dir + "/query-";
zookeeper->createAncestors(query_path_prefix);
String node_path;
try
{
node_path = zookeeper->create(query_path_prefix, entry.toString(), zkutil::CreateMode::PersistentSequential);
}
catch (const zkutil::KeeperException & e)
{
/// TODO: This condition could be relaxed with additional post-checks
if (e.isTemporaryError())
throw Exception("Unknown status of distributed DDL task", ErrorCodes::UNKNOWN_STATUS_OF_DISTRIBUTED_DDL_TASK);
throw;
}
/// Optional step
try
{
createStatusDirs(node_path);
}
catch (...)
{
LOG_INFO(log, "An error occurred while creating auxiliary ZooKeeper directories in " << node_path << " . They will be created later"
<< ". Error : " << getCurrentExceptionMessage(true));
}
return node_path;
}
void DDLWorker::run()
{
setThreadName("DDLWorker");
LOG_DEBUG(log, "Started DDLWorker thread");
bool initialized = false;
do
{
try
{
try
{
zookeeper = context.getZooKeeper();
zookeeper->createAncestors(queue_dir + "/");
initialized = true;
}
catch (const zkutil::KeeperException & e)
{
if (!e.isHardwareError())
throw;
}
}
catch (...)
{
tryLogCurrentException(log, "Terminating. Cannot initialize DDL queue.");
return;
}
} while (!initialized && !stop_flag);
while (!stop_flag)
{
try
{
processTasks();
LOG_DEBUG(log, "Waiting a watch");
event_queue_updated->wait();
if (stop_flag)
break;
/// TODO: it might delay the execution, move it to separate thread.
cleanupQueue();
}
catch (zkutil::KeeperException & e)
{
if (e.isHardwareError())
{
if (!e.isTemporaryError())
{
LOG_DEBUG(log, "Recovering ZooKeeper session after: " << getCurrentExceptionMessage(false));
while (!stop_flag)
{
try
{
zookeeper = context.getZooKeeper();
break;
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
using namespace std::chrono_literals;
std::this_thread::sleep_for(5s);
}
}
}
else
{
LOG_DEBUG(log, "Retry task processing after: " << getCurrentExceptionMessage(false));
}
}
else
{
LOG_ERROR(log, "Unexpected ZooKeeper error: " << getCurrentExceptionMessage(true) << ". Terminating.");
return;
}
/// Unlock the processing just in case
event_queue_updated->set();
}
catch (...)
{
LOG_ERROR(log, "Unexpected error: " << getCurrentExceptionMessage(true) << ". Terminating.");
return;
}
}
}
class DDLQueryStatusInputSream : public IProfilingBlockInputStream
{
public:
DDLQueryStatusInputSream(const String & zk_node_path, const DDLLogEntry & entry, const Context & context)
: node_path(zk_node_path), context(context), watch(CLOCK_MONOTONIC_COARSE), log(&Logger::get("DDLQueryStatusInputSream"))
{
sample = Block{
{std::make_shared<DataTypeString>(), "host"},
{std::make_shared<DataTypeUInt16>(), "port"},
{std::make_shared<DataTypeInt64>(), "status"},
{std::make_shared<DataTypeString>(), "error"},
{std::make_shared<DataTypeUInt64>(), "num_hosts_remaining"},
{std::make_shared<DataTypeUInt64>(), "num_hosts_active"},
};
for (const HostID & host: entry.hosts)
waiting_hosts.emplace(host.toString());
setTotalRowsApprox(entry.hosts.size());
timeout_seconds = context.getSettingsRef().distributed_ddl_task_timeout;
}
String getName() const override
{
return "DDLQueryStatusInputSream";
}
String getID() const override
{
return "DDLQueryStatusInputSream(" + node_path + ")";
}
Block readImpl() override
{
Block res;
if (num_hosts_finished >= waiting_hosts.size())
return res;
auto zookeeper = context.getZooKeeper();
size_t try_number = 0;
while(res.rows() == 0)
{
if (is_cancelled)
return res;
auto elapsed_seconds = watch.elapsedSeconds();
if (timeout_seconds >= 0 && elapsed_seconds > timeout_seconds)
{
throw Exception("Watching task " + node_path + " is executing too long (" + toString(std::round(elapsed_seconds)) + " sec.)",
ErrorCodes::TIMEOUT_EXCEEDED);
}
if (num_hosts_finished != 0 || try_number != 0)
std::this_thread::sleep_for(std::chrono::milliseconds(50 * std::min(static_cast<size_t>(20), try_number + 1)));
/// TODO: add shared lock
if (!zookeeper->exists(node_path))
{
throw Exception("Cannot provide query execution status. The query's node " + node_path
+ " had been deleted by the cleaner since it was finished (or its lifetime is expired)",
ErrorCodes::UNFINISHED);
}
Strings new_hosts = getNewAndUpdate(getChildrenAllowNoNode(zookeeper, node_path + "/finished"));
++try_number;
if (new_hosts.empty())
continue;
Strings cur_active_hosts = getChildrenAllowNoNode(zookeeper, node_path + "/active");
MutableColumns columns = sample.cloneEmptyColumns();
for (const String & host_id : new_hosts)
{
ExecutionStatus status(-1, "Cannot obtain error message");
{
String status_data;
if (zookeeper->tryGet(node_path + "/finished/" + host_id, status_data))
status.tryDeserializeText(status_data);
}
String host;
UInt16 port;
Cluster::Address::fromString(host_id, host, port);
columns[0]->insert(host);
columns[1]->insert(static_cast<UInt64>(port));
columns[2]->insert(static_cast<Int64>(status.code));
columns[3]->insert(status.message);
columns[4]->insert(static_cast<UInt64>(waiting_hosts.size() - (++num_hosts_finished)));
columns[5]->insert(static_cast<UInt64>(cur_active_hosts.size()));
}
res = sample.cloneWithColumns(std::move(columns));
}
return res;
}
Block getSampleBlock() const
{
return sample.cloneEmpty();
}
~DDLQueryStatusInputSream() override = default;
private:
static Strings getChildrenAllowNoNode(const std::shared_ptr<zkutil::ZooKeeper> & zookeeper, const String & node_path)
{
Strings res;
int code = zookeeper->tryGetChildren(node_path, res);
if (code != ZOK && code != ZNONODE)
throw zkutil::KeeperException(code, node_path);
return res;
}
Strings getNewAndUpdate(const Strings & current_list_of_finished_hosts)
{
Strings diff;
for (const String & host : current_list_of_finished_hosts)
{
if (!waiting_hosts.count(host))
{
if (!ignoring_hosts.count(host))
{
ignoring_hosts.emplace(host);
LOG_INFO(log, "Unexpected host " << host << " appeared " << " in task " << node_path);
}
continue;
}
if (!finished_hosts.count(host))
{
diff.emplace_back(host);
finished_hosts.emplace(host);
}
}
return diff;
}
private:
String node_path;
const Context & context;
Stopwatch watch;
Logger * log;
Block sample;
NameSet waiting_hosts; /// hosts from task host list
NameSet finished_hosts; /// finished hosts from host list
NameSet ignoring_hosts; /// appeared hosts that are not in hosts list
size_t num_hosts_finished = 0;
Int64 timeout_seconds = 120;
};
BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & context)
{
ASTPtr query_ptr;
/// Remove FORMAT ... INTO OUTFILE if exists
if (dynamic_cast<const ASTQueryWithOutput *>(query_ptr_.get()))
{
query_ptr = query_ptr_->clone();
auto query_with_output = dynamic_cast<ASTQueryWithOutput *>(query_ptr.get());
query_with_output->out_file = nullptr;
query_with_output->format = nullptr;
}
else
query_ptr = query_ptr_;
auto query = dynamic_cast<const ASTQueryWithOnCluster *>(query_ptr.get());
if (!query)
{
throw Exception("Distributed execution is not supported for such DDL queries", ErrorCodes::NOT_IMPLEMENTED);
}
if (auto query_alter = dynamic_cast<const ASTAlterQuery *>(query_ptr.get()))
{
for (const auto & param : query_alter->parameters)
{
if (!isSupportedAlterType(param.type))
throw Exception("Unsupported type of ALTER query", ErrorCodes::NOT_IMPLEMENTED);
}
}
ClusterPtr cluster = context.getCluster(query->cluster);
DDLWorker & ddl_worker = context.getDDLWorker();
DDLLogEntry entry;
entry.query = queryToString(query_ptr);
entry.initiator = ddl_worker.getCommonHostID();
Cluster::AddressesWithFailover shards = cluster->getShardsAddresses();
for (const auto & shard : shards)
{
for (const auto & addr : shard)
entry.hosts.emplace_back(addr);
}
String node_path = ddl_worker.enqueueQuery(entry);
BlockIO io;
if (context.getSettingsRef().distributed_ddl_task_timeout == 0)
return io;
auto stream = std::make_shared<DDLQueryStatusInputSream>(node_path, entry, context);
io.in_sample = stream->getSampleBlock();
io.in = std::move(stream);
return io;
}
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
9d1cc2f3049040d065f4319292a17cc6f9d8f057 | 3f1208ae609aaf24a36a0ad99899d90a7a0c9f82 | /components/offline_pages/core/prefetch/prefetch_prefs.cc | 88524f31e35d7fff993ab9345595d2a8057c6a6e | [
"BSD-3-Clause"
] | permissive | macyeez/chromium | 26a093f4bece22107dca95edab3eae5dd641656a | deeaed07d437b8025aa4d4c273a3af4ba6278765 | refs/heads/master | 2023-03-17T13:03:47.487068 | 2019-02-26T14:32:07 | 2019-02-26T14:32:07 | 172,726,283 | 1 | 0 | NOASSERTION | 2019-02-26T14:32:08 | 2019-02-26T14:22:31 | null | UTF-8 | C++ | false | false | 2,562 | 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/offline_pages/core/prefetch/prefetch_prefs.h"
#include "components/offline_pages/core/offline_clock.h"
#include "components/offline_pages/core/offline_page_feature.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/version_info/version_info.h"
namespace offline_pages {
namespace prefetch_prefs {
namespace {
// Prefs only accessed in this file
const char kEnabled[] = "offline_prefetch.enabled";
const char kLimitlessPrefetchingEnabledTimePref[] =
"offline_prefetch.limitless_prefetching_enabled_time";
const char kSendPrefetchTestingHeaderPref[] =
"offline_prefetch.send_testing_header";
} // namespace
const char kBackoff[] = "offline_prefetch.backoff";
void RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterListPref(kBackoff);
registry->RegisterBooleanPref(kEnabled, true);
registry->RegisterTimePref(kLimitlessPrefetchingEnabledTimePref,
base::Time());
registry->RegisterBooleanPref(kSendPrefetchTestingHeaderPref, false);
}
void SetPrefetchingEnabledInSettings(PrefService* prefs, bool enabled) {
prefs->SetBoolean(kEnabled, enabled);
}
bool IsEnabled(PrefService* prefs) {
return IsPrefetchingOfflinePagesEnabled() && prefs->GetBoolean(kEnabled);
}
void SetLimitlessPrefetchingEnabled(PrefService* prefs, bool enabled) {
DCHECK(prefs);
if (enabled)
prefs->SetTime(kLimitlessPrefetchingEnabledTimePref, OfflineTimeNow());
else
prefs->SetTime(kLimitlessPrefetchingEnabledTimePref, base::Time());
}
bool IsLimitlessPrefetchingEnabled(PrefService* prefs) {
base::TimeDelta max_duration;
if (version_info::IsOfficialBuild())
max_duration = base::TimeDelta::FromDays(1);
else
max_duration = base::TimeDelta::FromDays(365);
DCHECK(prefs);
const base::Time enabled_time =
prefs->GetTime(kLimitlessPrefetchingEnabledTimePref);
const base::Time now = OfflineTimeNow();
return (now >= enabled_time) && (now < (enabled_time + max_duration));
}
void SetSendPrefetchTestingHeader(PrefService* prefs, bool enabled) {
DCHECK(prefs);
prefs->SetBoolean(kSendPrefetchTestingHeaderPref, enabled);
}
bool ShouldSendPrefetchTestingHeader(PrefService* prefs) {
DCHECK(prefs);
return prefs->GetBoolean(kSendPrefetchTestingHeaderPref);
}
} // namespace prefetch_prefs
} // namespace offline_pages
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
826529771320e4199194c639b2783d664b0d9961 | b65ca23fb5a76dcf7f6b4651ce821d8352912d0c | /social/src/socialnetworkinterface.cpp | 585633157613cc8576f093a3bd9adcf7c66de1c8 | [] | no_license | pgerdt/nemo-qml-plugins | 527f27a229dc9bf909b2943315c48d45c1988a00 | c00cc336a8abd3dbe666d5c5c6ff3290d848d0d0 | refs/heads/master | 2021-01-17T14:12:31.366074 | 2013-02-27T07:29:39 | 2013-02-27T07:29:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,147 | cpp | /*
* Copyright (C) 2013 Jolla Ltd. <chris.adams@jollamobile.com>
*
* 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 Nemo Mobile nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
*/
#include "socialnetworkinterface.h"
#include "socialnetworkinterface_p.h"
#include "contentiteminterface.h"
#include "identifiablecontentiteminterface.h"
#include <QtCore/QByteArray>
#include <QtCore/QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtDebug>
/*
CacheEntry:
The data in the model is actually a list of cache entries.
Each entry consists of the QVariantMap of data for the object,
and a (lazily constructed) ContentItem ptr.
Specific implementations of the SocialNetwork interface should
use \c SocialNetworkInterfacePrivate::createUncachedEntry() to
create cache entries for data associated with a particular node,
within their implementation of the \c populateDataForNode()
functions.
Once they have constructed cache entries for the related data
objects, the implementation should call
\c SocialNetworkInterfacePrivate::populateCache().
*/
CacheEntry::CacheEntry(const QVariantMap &d, ContentItemInterface *i)
: data(d), item(i), refcount(0)
{
}
CacheEntry::~CacheEntry()
{
if (item)
delete item;
}
ArbitraryRequestHandler::ArbitraryRequestHandler(SocialNetworkInterface *parent)
: QObject(parent), q(parent), reply(0), isError(false)
{
}
ArbitraryRequestHandler::~ArbitraryRequestHandler()
{
if (reply) {
disconnect(reply);
reply->deleteLater();
}
}
bool ArbitraryRequestHandler::request(int requestType, const QString &requestUri, const QVariantMap &queryItems, const QString &postData)
{
if (reply) {
qWarning() << Q_FUNC_INFO << "Warning: cannot start arbitrary request: another arbitrary request is in progress";
return false;
}
QList<QPair<QString, QString> > qil;
QStringList queryItemKeys = queryItems.keys();
foreach (const QString &qik, queryItemKeys)
qil.append(qMakePair<QString, QString>(qik, queryItems.value(qik).toString()));
QUrl url(requestUri);
url.setQueryItems(qil);
QNetworkReply *sniReply = 0;
switch (requestType) {
case SocialNetworkInterface::Get: sniReply = q->d->qnam->get(QNetworkRequest(url)); break;
case SocialNetworkInterface::Post: sniReply = q->d->qnam->post(QNetworkRequest(url), QByteArray::fromBase64(postData.toLatin1())); break;
default: sniReply = q->d->qnam->deleteResource(QNetworkRequest(url)); break;
}
if (sniReply) {
reply = sniReply;
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(errorHandler(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsHandler(QList<QSslError>)));
connect(reply, SIGNAL(finished()), this, SLOT(finishedHandler()));
return true;
}
qWarning() << Q_FUNC_INFO << "Warning: cannot start arbitrary request: null reply";
return false;
}
void ArbitraryRequestHandler::finishedHandler()
{
QByteArray replyData;
if (reply) {
replyData = reply->readAll();
disconnect(reply);
reply->deleteLater();
reply = 0;
}
QVariantMap responseData;
bool errorOccurred = isError;
if (isError) {
// note that errors to arbitrary requests don't cause the SocialNetwork
// to transition to the Error state. They are unrelated to the model.
responseData.insert(QLatin1String("error"), errorMessage);
errorMessage = QString();
isError = false;
} else {
bool ok = false;
QVariantMap parsed = ContentItemInterface::parseReplyData(replyData, &ok);
if (!ok) {
responseData.insert(QLatin1String("response"), replyData);
} else {
responseData = parsed;
}
}
emit q->arbitraryRequestResponseReceived(errorOccurred, responseData);
}
void ArbitraryRequestHandler::errorHandler(QNetworkReply::NetworkError err)
{
switch (err) {
case QNetworkReply::NoError: errorMessage = QLatin1String("QNetworkReply::NoError"); break;
case QNetworkReply::ConnectionRefusedError: errorMessage = QLatin1String("QNetworkReply::ConnectionRefusedError"); break;
case QNetworkReply::RemoteHostClosedError: errorMessage = QLatin1String("QNetworkReply::RemoteHostClosedError"); break;
case QNetworkReply::HostNotFoundError: errorMessage = QLatin1String("QNetworkReply::HostNotFoundError"); break;
case QNetworkReply::TimeoutError: errorMessage = QLatin1String("QNetworkReply::TimeoutError"); break;
case QNetworkReply::OperationCanceledError: errorMessage = QLatin1String("QNetworkReply::OperationCanceledError"); break;
case QNetworkReply::SslHandshakeFailedError: errorMessage = QLatin1String("QNetworkReply::SslHandshakeFailedError"); break;
case QNetworkReply::TemporaryNetworkFailureError: errorMessage = QLatin1String("QNetworkReply::TemporaryNetworkFailureError"); break;
case QNetworkReply::ProxyConnectionRefusedError: errorMessage = QLatin1String("QNetworkReply::ProxyConnectionRefusedError"); break;
case QNetworkReply::ProxyConnectionClosedError: errorMessage = QLatin1String("QNetworkReply::ProxyConnectionClosedError"); break;
case QNetworkReply::ProxyNotFoundError: errorMessage = QLatin1String("QNetworkReply::ProxyNotFoundError"); break;
case QNetworkReply::ProxyTimeoutError: errorMessage = QLatin1String("QNetworkReply::ProxyTimeoutError"); break;
case QNetworkReply::ProxyAuthenticationRequiredError: errorMessage = QLatin1String("QNetworkReply::ProxyAuthenticationRequiredError"); break;
case QNetworkReply::ContentAccessDenied: errorMessage = QLatin1String("QNetworkReply::ContentAccessDenied"); break;
case QNetworkReply::ContentOperationNotPermittedError: errorMessage = QLatin1String("QNetworkReply::ContentOperationNotPermittedError"); break;
case QNetworkReply::ContentNotFoundError: errorMessage = QLatin1String("QNetworkReply::ContentNotFoundError"); break;
case QNetworkReply::AuthenticationRequiredError: errorMessage = QLatin1String("QNetworkReply::AuthenticationRequiredError"); break;
case QNetworkReply::ContentReSendError: errorMessage = QLatin1String("QNetworkReply::ContentReSendError"); break;
case QNetworkReply::ProtocolUnknownError: errorMessage = QLatin1String("QNetworkReply::ProtocolUnknownError"); break;
case QNetworkReply::ProtocolInvalidOperationError: errorMessage = QLatin1String("QNetworkReply::ProtocolInvalidOperationError"); break;
case QNetworkReply::UnknownNetworkError: errorMessage = QLatin1String("QNetworkReply::UnknownNetworkError"); break;
case QNetworkReply::UnknownProxyError: errorMessage = QLatin1String("QNetworkReply::UnknownProxyError"); break;
case QNetworkReply::UnknownContentError: errorMessage = QLatin1String("QNetworkReply::UnknownContentError"); break;
case QNetworkReply::ProtocolFailure: errorMessage = QLatin1String("QNetworkReply::ProtocolFailure"); break;
default: errorMessage = QLatin1String("Unknown QNetworkReply::NetworkError"); break;
}
isError = true;
}
void ArbitraryRequestHandler::sslErrorsHandler(const QList<QSslError> &sslErrors)
{
errorMessage = QLatin1String("SSL error: ");
if (sslErrors.isEmpty()) {
errorMessage += QLatin1String("unknown SSL error");
} else {
foreach (const QSslError &sslE, sslErrors)
errorMessage += sslE.errorString() + QLatin1String("; ");
errorMessage.chop(2);
}
isError = true;
}
SocialNetworkInterfacePrivate::SocialNetworkInterfacePrivate(SocialNetworkInterface *parent)
: q(parent)
, qnam(new QNetworkAccessManager(parent))
, placeHolderNode(new IdentifiableContentItemInterface(parent))
, initialized(false)
, repopulatingCurrentNode(false)
, error(SocialNetworkInterface::NoError)
, status(SocialNetworkInterface::Initializing)
, currentNodePosition(-1)
, nodeStackSize(5)
, arbitraryRequestHandler(0)
{
// Construct the placeholder node. This node is used as a placeholder
// when the client sets a specific nodeIdentifier until the node can
// be retrieved from the social network.
placeHolderNode->classBegin();
placeHolderNode->componentComplete();
}
SocialNetworkInterfacePrivate::~SocialNetworkInterfacePrivate()
{
// remove all cache entries.
QList<IdentifiableContentItemInterface*> cacheEntries = nodeContent.keys();
foreach (IdentifiableContentItemInterface *nodePtr, cacheEntries)
purgeDoomedNode(nodePtr);
}
/*! \internal */
void SocialNetworkInterfacePrivate::filters_append(QDeclarativeListProperty<FilterInterface> *list, FilterInterface *filter)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni) {
filter->setParent(sni);
sni->d->filters.append(filter);
}
}
/*! \internal */
FilterInterface *SocialNetworkInterfacePrivate::filters_at(QDeclarativeListProperty<FilterInterface> *list, int index)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni && sni->d->filters.count() > index && index >= 0)
return sni->d->filters.at(index);
return 0;
}
/*! \internal */
void SocialNetworkInterfacePrivate::filters_clear(QDeclarativeListProperty<FilterInterface> *list)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni) {
foreach (FilterInterface *cf, sni->d->filters)
cf->deleteLater();
sni->d->filters.clear();
}
}
/*! \internal */
int SocialNetworkInterfacePrivate::filters_count(QDeclarativeListProperty<FilterInterface> *list)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni)
return sni->d->filters.count();
return 0;
}
/*! \internal */
void SocialNetworkInterfacePrivate::sorters_append(QDeclarativeListProperty<SorterInterface> *list, SorterInterface *sorter)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni) {
sorter->setParent(sni);
sni->d->sorters.append(sorter);
}
}
/*! \internal */
SorterInterface *SocialNetworkInterfacePrivate::sorters_at(QDeclarativeListProperty<SorterInterface> *list, int index)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni && sni->d->sorters.count() > index && index >= 0)
return sni->d->sorters.at(index);
return 0;
}
/*! \internal */
void SocialNetworkInterfacePrivate::sorters_clear(QDeclarativeListProperty<SorterInterface> *list)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni) {
foreach (SorterInterface *cs, sni->d->sorters)
cs->deleteLater();
sni->d->sorters.clear();
}
}
/*! \internal */
int SocialNetworkInterfacePrivate::sorters_count(QDeclarativeListProperty<SorterInterface> *list)
{
SocialNetworkInterface *sni = qobject_cast<SocialNetworkInterface *>(list->object);
if (sni)
return sni->d->sorters.count();
return 0;
}
/*
Returns the current node which is the central content item.
The model is populated with data related to the node.
The current node is always owned by the SocialNetwork base class;
it might be deleted at any time (e.g., if the cache entry gets purged).
*/
IdentifiableContentItemInterface *SocialNetworkInterfacePrivate::currentNode() const
{
// caller does NOT take ownership. We can (and will) delete it whenever we like.
if (currentNodePosition >= 0 && currentNodePosition < nodeStack.size())
return nodeStack.at(currentNodePosition);
return 0;
}
/*! \internal */
QString SocialNetworkInterfacePrivate::currentNodeIdentifier() const
{
if (currentNodePosition >= 0 && currentNodePosition < nodeStack.size())
return nodeStack.at(currentNodePosition)->identifier();
return QString();
}
/*! \internal */
void SocialNetworkInterfacePrivate::purgeDoomedNode(IdentifiableContentItemInterface *n)
{
QList<CacheEntry*> cacheData = nodeContent.values(n);
foreach (CacheEntry *currData, cacheData)
removeEntryFromNodeContent(n, currData);
CacheEntry *nodeCacheEntry = findCacheEntry(n, false);
if (nodeCacheEntry)
derefCacheEntry(nodeCacheEntry);
}
/*! \internal */
void SocialNetworkInterfacePrivate::maybePurgeDoomedNodes(int count, int direction)
{
// Removes \a count nodes from the node stack. The nodes
// will be removed from the top (most recent) of the stack
// if direction == 1, and from the bottom (least recent)
// of the stack if direction == 0.
// Also purges the associated cached content data, if they
// don't also appear elsewhere in the stack.
if (direction != 0 && direction != 1) {
qWarning() << Q_FUNC_INFO << "Error: invalid direction specified!";
return;
}
if (count > nodeStack.size()) {
qWarning() << Q_FUNC_INFO << "Error: not that many nodes in the stack!";
return;
}
// XXX TODO: this is a terrible algorithm, that iterates over the nodeStack way too many times.
for (int i = count; i > 0; --i) {
// remove the ToS (or BoS) node.
IdentifiableContentItemInterface *doomedNode = direction > 0 ? nodeStack.takeLast() : nodeStack.takeFirst();
if (direction == 0) {
// the current node position needs to be reduced, as all nodes' positions shift down.
currentNodePosition--;
}
// determine whether we need to purge the doomed node.
if (!nodeStack.contains(doomedNode)) {
// the node doesn't appear anywhere else in the navigation breadcrumb trail.
// so we have to delete it and purge our cache of content items for the node.
purgeDoomedNode(doomedNode);
}
}
}
/*! \internal */
void SocialNetworkInterfacePrivate::pushPlaceHolderNode()
{
pushNode(placeHolderNode);
}
/*! \internal */
void SocialNetworkInterfacePrivate::pushNode(IdentifiableContentItemInterface *n)
{
// the caller is responsible for emitting dataChanged() etc.
if (n == 0) {
qWarning() << Q_FUNC_INFO << "Attempted to push null node!";
return;
}
if (currentNodePosition >= nodeStack.size()) {
qWarning() << Q_FUNC_INFO << "Current node not on stack!";
return;
}
IdentifiableContentItemInterface *currentNode = 0;
if (currentNodePosition >= 0)
currentNode = nodeStack.at(currentNodePosition);
if (currentNode == n && currentNode != placeHolderNode)
return; // nothing to do.
// Check to see if we need to replace the placeholder or current node.
if (currentNode == placeHolderNode || repopulatingCurrentNode) {
// this will happen when the node data that the
// derived type requested is received.
repopulatingCurrentNode = false;
if (currentNodePosition != (nodeStack.size() - 1)) {
qWarning() << Q_FUNC_INFO << "Error: placeholder node not the ToS!";
} else {
nodeStack.removeLast();
nodeStack.append(n);
}
return;
}
// Otherwise, we're pushing a new navigable node to the nodeStack.
if (currentNodePosition != (nodeStack.size()-1)) {
// current navigation position is not the top of stack
// ie, they pushed a bunch of nodes, then they called
// SNI::previousNode() one or more times, and now they
// are pushing a node. This node becomes the new top
// of stack. Purge any cache entries beyond the current
// position if applicable.
maybePurgeDoomedNodes(currentNodePosition+1, 1);
} else if (nodeStack.size() == nodeStackSize) {
// current node position is already top of stack, and
// we've reached our max for cached navigation steps.
maybePurgeDoomedNodes(1, 0); // purge the bottom (least recently used) node.
}
nodeStack.append(n);
currentNodePosition = nodeStack.size() - 1; // end up pointing to ToS.
}
/*! \internal */
void SocialNetworkInterfacePrivate::nextNode()
{
// the caller is responsible for emitting dataChanged() etc.
if (currentNodePosition == -1 || nodeStack.size() == 0) {
qWarning() << Q_FUNC_INFO << "No nodes in cache!";
return;
}
if (currentNodePosition == (nodeStack.size() - 1)) {
qWarning() << Q_FUNC_INFO << "Already at last node in cache!";
return;
}
currentNodePosition++;
}
/*! \internal */
void SocialNetworkInterfacePrivate::prevNode()
{
// the caller is responsible for emitting dataChanged() etc.
if (currentNodePosition == -1 || nodeStack.size() == 0) {
qWarning() << Q_FUNC_INFO << "No nodes in cache!";
return;
}
if (currentNodePosition == 0) {
qWarning() << Q_FUNC_INFO << "Already at first node in cache!";
return;
}
currentNodePosition--;
}
/*! \internal */
IdentifiableContentItemInterface *SocialNetworkInterfacePrivate::findCachedNode(const QString &nodeIdentifier)
{
for (int i = 0; i < nodeStack.size(); ++i) {
if (nodeStack.at(i)->identifier() == nodeIdentifier) {
return nodeStack.at(i);
}
}
return 0;
}
/*! \internal */
QList<CacheEntry*> SocialNetworkInterfacePrivate::cachedContent(IdentifiableContentItemInterface *n, bool *ok) const
{
// Types derived from SocialNetworkInterface should call this to retrieve cached content for the node
if (!nodeContent.contains(n)) {
*ok = false;
return QList<CacheEntry*>();
}
*ok = true;
return nodeContent.values(n);
}
/*! \internal */
CacheEntry *SocialNetworkInterfacePrivate::findCacheEntry(const QVariantMap &data, bool create)
{
// have to do a slow search. avoid this if possible.
foreach (CacheEntry *e, cache) {
if (e->data == data)
return e;
}
if (!create)
return 0;
// no such cache entry. create it, but DON'T append it to the cache.
// we append it to the cache (and take ownership of it) when they call
// addEntryToNodeContent().
CacheEntry *newEntry = new CacheEntry(data);
return newEntry;
}
/*! \internal */
CacheEntry *SocialNetworkInterfacePrivate::findCacheEntry(ContentItemInterface *item, bool create)
{
if (cachedItems.contains(item))
return cachedItems.value(item);
if (!create)
return 0;
// no such cache entry. create it, but DON'T append it to the cache.
// we append it to the cache (and take ownership of it) when they call
// addEntryToNodeContent().
CacheEntry *newEntry = new CacheEntry(item->data(), item);
return newEntry;
}
/*! \internal */
void SocialNetworkInterfacePrivate::addEntryToNodeContent(IdentifiableContentItemInterface *item, CacheEntry *entry)
{
if (!nodeContent.contains(item) && currentNode() != item) {
qWarning() << Q_FUNC_INFO << "No such node:" << item;
return;
}
if (nodeContent.find(item, entry) != nodeContent.end()) {
qWarning() << Q_FUNC_INFO << "Entry:" << entry << "already cached as content for node:" << item;
return;
}
entry->refcount++;
if (entry->refcount == 1) {
// new cache entry.
cache.append(entry);
}
nodeContent.insert(item, entry);
}
/*! \internal */
void SocialNetworkInterfacePrivate::removeEntryFromNodeContent(IdentifiableContentItemInterface *item, CacheEntry *entry)
{
if (entry == 0)
return;
int removeCount = nodeContent.remove(item, entry);
if (removeCount == 0) {
qWarning() << Q_FUNC_INFO << "Entry:" << entry << "is not cached as content for node:" << item;
return;
} else if (removeCount > 1) {
qWarning() << Q_FUNC_INFO << "Entry:" << entry << "was cached" << removeCount << "times as content for node:" << item;
}
derefCacheEntry(entry);
}
/*! \internal */
void SocialNetworkInterfacePrivate::updateCacheEntry(CacheEntry *entry, ContentItemInterface *item, const QVariantMap &data)
{
if (item)
entry->item = item;
if (data != QVariantMap())
entry->data = data;
}
/*! \internal */
void SocialNetworkInterfacePrivate::derefCacheEntry(CacheEntry *entry)
{
if (entry->refcount == 0)
qWarning() << Q_FUNC_INFO << "Entry:" << entry << "has not been referenced in the cache";
entry->refcount--;
if (entry->refcount <= 0) {
cache.removeAll(entry);
delete entry;
}
}
/*
This function should be called by specific implementations of the
SocialNetwork interface, to create a cache entry for the current
node whose data is the given \a data, as part of the implementation
for the \c populateDataForNode() functions.
After the cache entries for the current node have all been created,
the implementation should then call
\c SocialNetworkInterfacePrivate::populateCache().
*/
CacheEntry *SocialNetworkInterfacePrivate::createUncachedEntry(const QVariantMap &data)
{
// this function should be called by SocialNetworkInterface derived-types when
// they retrieve data from the service during populateDataForNode().
// After creating an uncached entry for each related content data object they receive
// from the service, they should call populateCache().
CacheEntry *newEntry = new CacheEntry(data);
return newEntry;
}
/*
This function should be called by specific implementations of the
SocialNetwork interface, to populate the cache for the current
node \a n with the cache entries \a c, as part of the implementation
for the \c populateDataForNode() functions.
This function will set \a ok to true if the node \a n is the current
node as expected, and the cache could be populated.
*/
void SocialNetworkInterfacePrivate::populateCache(IdentifiableContentItemInterface *n, const QList<CacheEntry*> c, bool *ok)
{
// Types derived from SocialNetworkInterface should call this to populate the cache
// NOTE: we don't have any limits on cache size. XXX TODO: something sensible?
if (currentNode() != n) {
// the populated node is not the current node... this is an error.
qWarning() << Q_FUNC_INFO << "Attempted to populate cache for non-current node!";
*ok = false;
return;
}
*ok = true;
QList<CacheEntry*> existingGoodEntries;
QList<CacheEntry*> newCacheEntries;
if (nodeContent.contains(n)) {
// updating existing cache entry.
QList<CacheEntry*> oldData = nodeContent.values(n);
QList<CacheEntry*> doomedData;
foreach (CacheEntry *currData, oldData) {
if (c.contains(currData)) {
existingGoodEntries.append(currData);
} else {
doomedData.append(currData);
}
}
// purge old entries from the cache
foreach (CacheEntry *doomedContent, doomedData) {
// not contained in the updated cache.
removeEntryFromNodeContent(n, doomedContent);
}
// add new entries to the cache
foreach (CacheEntry *newEntry, c) {
if (!existingGoodEntries.contains(newEntry)) {
newCacheEntries.append(newEntry);
}
}
} else {
// new cache entry.
newCacheEntries = c;
}
// populate the cache for the node n from the content c.
foreach (CacheEntry *currData, newCacheEntries) {
addEntryToNodeContent(n, currData);
}
}
//----------------------------------------------------
/*!
\qmltype SocialNetwork
\instantiates SocialNetworkInterface
\inqmlmodule org.nemomobile.social 1
\brief Provides an abstraction API for graph- or model-based social
network APIs.
The SocialNetwork type should never be used directly by clients.
Instead, clients should use specific implementations of the SocialNetwork
interface, such as the Facebook adapter.
The SocialNetwork type provides a generic API which allows content
to be retrieved from a social network and exposed via a model.
The API consists of a central \c node which is an IdentifiableContentItem,
which may be specified by the client via the \c nodeIdentifier property.
The data in the model will be populated from the graph connections of
the node.
The model roles are as follows:
\list
\li contentItem - the instantiated ContentItem related to the node
\li contentItemType - the type of the ContentItem related to the node
\li contentItemData - the underlying QVariantMap data of the ContentItem related to the node
\li contentItemIdentifier - the identifier of the ContentItem related to the node, or an empty string
\endlist
Please see the documentation of the Facebook adapter for an example
of how clients can use the SocialNetwork model in an application.
*/
SocialNetworkInterface::SocialNetworkInterface(QObject *parent)
: QAbstractListModel(parent), d(new SocialNetworkInterfacePrivate(this))
{
d->headerData.insert(ContentItemRole, "contentItem");
d->headerData.insert(ContentItemTypeRole, "contentItemType");
d->headerData.insert(ContentItemDataRole, "contentItemData" );
d->headerData.insert(ContentItemIdentifierRole, "contentItemIdentifier");
setRoleNames(d->headerData);
}
SocialNetworkInterface::~SocialNetworkInterface()
{
delete d;
}
void SocialNetworkInterface::classBegin()
{
d->initialized = false;
}
void SocialNetworkInterface::componentComplete()
{
// If you override this implementation, you MUST set d->initialized=true.
d->initialized = true;
}
/*!
\qmlmethod void SocialNetwork::nextNode()
Navigates to the next node in the node stack, if it exists.
The data in the model will be populated from the cache, if cached
data for the node exists. If you want to repopulate the data from
the social network, you must call \c setNodeIdentifier() manually.
The node stack is built up from successive changes to the
\c nodeIdentifier property.
*/
void SocialNetworkInterface::nextNode()
{
IdentifiableContentItemInterface *oldNode = d->currentNode();
d->nextNode();
IdentifiableContentItemInterface *newNode = d->currentNode();
if (oldNode != newNode) {
bool hasCachedContent = false;
QList<CacheEntry*> data = d->cachedContent(newNode, &hasCachedContent);
if (hasCachedContent) {
// call derived class data update:
// perform filtering/sorting based on the defined stuff.
// and then emit dataChanged() etc signals.
updateInternalData(data);
} else {
// call derived class data populate:
// d->populateCache() etc once it's finished retrieving.
// and then updateInternalData() itself.
populateDataForNode(newNode);
}
}
}
/*!
\qmlmethod void SocialNetwork::previousNode()
Navigates to the previous node in the node stack, if it exists.
The data in the model will be populated from the cache, if cached
data for the node exists. If you want to repopulate the data from
the social network, you must call \c setNodeIdentifier() manually.
The node stack is built up from successive changes to the
\c nodeIdentifier property.
*/
void SocialNetworkInterface::previousNode()
{
IdentifiableContentItemInterface *oldNode = d->currentNode();
d->prevNode();
IdentifiableContentItemInterface *newNode = d->currentNode();
if (oldNode != newNode) {
bool hasCachedContent = false;
QList<CacheEntry*> data = d->cachedContent(newNode, &hasCachedContent);
if (hasCachedContent) {
// call derived class data update:
// perform filtering/sorting based on the defined stuff.
// and then emit dataChanged() etc signals.
updateInternalData(data);
} else {
// call derived class data populate:
// d->populateCache() etc once it's finished retrieving.
// and then updateInternalData() itself.
populateDataForNode(newNode);
}
}
}
/*!
\qmlmethod QObject *SocialNetwork::relatedItem(int index)
Returns the ContentItem which is related to the node from the given
\a index of the model data. This is identical to calling
\c data() for the given model index and specifying the \c contentItem
role.
\note Although this function will always return a pointer to a
ContentItem, the return type of the function is QObject*, so that
this function can be used via QMetaObject::invokeMethod().
*/
QObject *SocialNetworkInterface::relatedItem(int index) const
{
QVariant cv = data(QAbstractListModel::index(index), SocialNetworkInterface::ContentItemRole);
if (!cv.isValid())
return 0;
ContentItemInterface *ci = cv.value<ContentItemInterface*>();
return ci;
}
/*!
\qmlproperty SocialNetwork::Status SocialNetwork::status
Holds the current status of the social network.
*/
SocialNetworkInterface::Status SocialNetworkInterface::status() const
{
return d->status;
}
/*!
\qmlproperty SocialNetwork::ErrorType SocialNetwork::error
Holds the most recent error which occurred during initialization
or a network request. Note that it will not be reset if subsequent
operations are successful.
*/
SocialNetworkInterface::ErrorType SocialNetworkInterface::error() const
{
return d->error;
}
/*!
\qmlproperty QString SocialNetwork::errorMessage
Holds the message associated with the most recent error which occurred
during initialization or a network request. Note that it will not be
reset if subsequent operations are successful.
*/
QString SocialNetworkInterface::errorMessage() const
{
return d->errorMessage;
}
/*!
\qmlproperty QString SocialNetwork::nodeIdentifier
Holds the identifier of the "central" content item. This content item
is the \c node of the current view of the social network graph.
The data in the model will be populated from the graph connections
to the node.
If this property is not set, the node will be initialized to the
current user node by the specific social network implementation adapter.
As the client changes the \c nodeIdentifier, the SocialNetwork will
request the related data from the network, and build up a node stack
of visited nodes. For each visited node, a cache of related content
items (model data) is stored. The size of the cache is implementation
specific.
Clients can later navigate down and up the stack using the \l previousNode() and
\l nextNode() functions respectively. Those operations are very cheap
as they do not trigger any network requests in the common case.
If the \c nodeIdentifier is set to an identifier which isn't represented
in the node stack, the \c node property will be set to an empty placeholder
node until the network request completes and the node can be populated with
the downloaded data.
If the \c nodeIdentifier is set to the identifier of the current node,
the cached data for the node will be cleared and the node and its related
data will be reloaded from the network.
*/
QString SocialNetworkInterface::nodeIdentifier() const
{
if (d->pendingCurrentNodeIdentifier.isEmpty())
return d->currentNodeIdentifier(); // normal case.
return d->pendingCurrentNodeIdentifier; // status == Fetching, not sure if it's real yet.
}
void SocialNetworkInterface::setNodeIdentifier(const QString &contentItemIdentifier)
{
IdentifiableContentItemInterface *cachedNode = d->findCachedNode(contentItemIdentifier);
if (d->currentNode() && contentItemIdentifier == d->currentNode()->identifier()) {
// resetting the current node. This tells us to reload the node, clear its cache and repopulate.
d->repopulatingCurrentNode = true;
d->pendingCurrentNodeIdentifier = contentItemIdentifier;
populateDataForNode(contentItemIdentifier); // "unseen node" without pushing placeholder.
} else if (!cachedNode) {
// Unseen node.
// call derived class data populate:
// d->populateCache() etc once it's finished retrieving.
// d->pushNode(newNodePtr).
// and then updateInternalData() itself.
d->pendingCurrentNodeIdentifier = contentItemIdentifier;
d->pushPlaceHolderNode();
emit nodeChanged();
populateDataForNode(contentItemIdentifier); // XXX TODO: do we really want to trigger populate? or wait for user to call populate?
} else {
// We've seen this node before and have it cached.
bool hasCachedContent = false;
QList<CacheEntry*> data = d->cachedContent(cachedNode, &hasCachedContent);
if (hasCachedContent) {
// call derived class data update:
// perform filtering/sorting based on the defined stuff.
// and then emit dataChanged() etc signals.
updateInternalData(data);
} else {
qWarning() << Q_FUNC_INFO << "Error: cached node has no cached content!";
}
}
}
/*!
\qmlproperty IdentifiableContentItem *SocialNetwork::node
Holds the "central" content item, or node, which defines the
current view of the social network graph. The data exposed in the
SocialNetwork model will reflect the connections to the node.
The node must be an identifiable content item (that is, it must
have a unique identifier in the social network graph).
Clients cannot set the node property directly, but instead must
set the \c nodeIdentifier property.
*/
IdentifiableContentItemInterface *SocialNetworkInterface::node() const
{
return d->currentNode();
}
/*!
\qmlproperty QVariantMap SocialNetwork::relevanceCriteria
Holds the social-network-specific relevance criteria which will
be used to calculate the relevance of related content items.
This relevance can be important in filtering and sorting operations.
*/
QVariantMap SocialNetworkInterface::relevanceCriteria() const
{
return d->relevanceCriteria;
}
void SocialNetworkInterface::setRelevanceCriteria(const QVariantMap &rc)
{
d->relevanceCriteria = rc;
}
/*!
\qmlproperty QDeclarativeListProperty<Filter> SocialNetwork::filters
Holds the list of filters which will be applied to the related content
of the node. Only those related content items which match each of the
filters will be exposed as data in the model.
Specific implementations of the SocialNetwork interface may not support
certain standard filter types, or they may not support filtering at all.
*/
QDeclarativeListProperty<FilterInterface> SocialNetworkInterface::filters()
{
return QDeclarativeListProperty<FilterInterface>(this, 0,
&SocialNetworkInterfacePrivate::filters_append,
&SocialNetworkInterfacePrivate::filters_count,
&SocialNetworkInterfacePrivate::filters_at,
&SocialNetworkInterfacePrivate::filters_clear);
}
/*!
\qmlproperty QDeclarativeListProperty<Sorter> SocialNetwork::sorters
Holds the list of sorters which will be applied to the related content
of the node. The order of sorters in the list is important, as it
defines which sorting is applied first.
Specific implementations of the SocialNetwork interface may not support
certain standard sorter types, or they may not support sorting at all.
*/
QDeclarativeListProperty<SorterInterface> SocialNetworkInterface::sorters()
{
return QDeclarativeListProperty<SorterInterface>(this, 0,
&SocialNetworkInterfacePrivate::sorters_append,
&SocialNetworkInterfacePrivate::sorters_count,
&SocialNetworkInterfacePrivate::sorters_at,
&SocialNetworkInterfacePrivate::sorters_clear);
}
/*!
\qmlproperty int SocialNetwork::count
Returns the number of content items related to the \c node
are exposed in the model. Only those content items which
match the specified \c filters will be exposed in the model,
if the specific implementation of the SocialNetwork interface
supports every filter in the \c filters list.
*/
int SocialNetworkInterface::count() const
{
return d->internalData.count();
}
int SocialNetworkInterface::rowCount(const QModelIndex &index) const
{
// only allow non-valid (default) parent index.
if (index.isValid())
return 0;
return d->internalData.count();
}
int SocialNetworkInterface::columnCount(const QModelIndex &index) const
{
// only allow non-valid (default) parent index.
if (index.isValid())
return 0;
return 1;
}
QVariant SocialNetworkInterface::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= d->internalData.count() || index.row() < 0)
return QVariant();
CacheEntry *cacheEntry = d->internalData.at(index.row());
switch (role) {
case ContentItemTypeRole: return QVariant::fromValue(cacheEntry->data.value(NEMOQMLPLUGINS_SOCIAL_CONTENTITEMTYPE).toInt());
case ContentItemDataRole: return QVariant::fromValue(cacheEntry->data);
case ContentItemIdentifierRole: return QVariant::fromValue(cacheEntry->data.value(NEMOQMLPLUGINS_SOCIAL_CONTENTITEMID).toString());
case ContentItemRole: {
if (cacheEntry->item)
return QVariant::fromValue(cacheEntry->item);
// instantiate the item.
ContentItemInterface *newItem = contentItemFromData(const_cast<SocialNetworkInterface*>(this), cacheEntry->data);
d->updateCacheEntry(cacheEntry, newItem); // update the cache.
return QVariant::fromValue(newItem);
}
break;
default: return QVariant();
}
}
QVariant SocialNetworkInterface::headerData(int section, Qt::Orientation orientation, int role) const
{
// Not a table model, so perhaps this is wrong.
if (orientation != Qt::Horizontal)
return QVariant();
if (role == Qt::DisplayRole) {
if (section < d->headerData.size()) {
return d->headerData.value(section);
}
}
return QVariant();
}
/*!
\qmlmethod bool SocialNetwork::arbitraryRequest(SocialNetwork::RequestType requestType, const QString &requestUri, const QVariantMap &queryItems = QVariantMap(), const QString &postData = QString())
Performs the HTTP request of the specified \a requestType (\c Get, \c Post or \c Delete) with
the specified \a requestUri and \a queryItems. If the request is a Post request, the given
\a postData will be converted to a QByteArray via \c{QByteArray::fromBase64(postData.toLatin1())}
and used as the \c Post data.
When a successfully started request is completed, the \c arbitraryRequestResponseReceived()
signal will be emitted, with the response data included as the \c data parameter.
The request will not be started successfully if another arbitrary request is in progress.
Returns true if the request could be started successfully, false otherwise.
*/
bool SocialNetworkInterface::arbitraryRequest(int requestType, const QString &requestUri, const QVariantMap &queryItems, const QString &postData)
{
if (!d->arbitraryRequestHandler)
d->arbitraryRequestHandler = new ArbitraryRequestHandler(this);
return d->arbitraryRequestHandler->request(requestType, requestUri, queryItems, postData);
}
QVariantMap SocialNetworkInterface::contentItemData(ContentItemInterface *contentItem) const
{
// Helper function for SocialNetworkInterface-derived types
return contentItem->dataPrivate();
}
void SocialNetworkInterface::setContentItemData(ContentItemInterface *contentItem, const QVariantMap &data) const
{
// Helper function for SocialNetworkInterface-derived types
contentItem->setDataPrivate(data);
}
bool SocialNetworkInterface::isInitialized() const
{
// Helper function for ContentItemInterface
return d->initialized;
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It will be called to populate the model data as a filtered and
sorted view of the content items related to the specified node in the
social network.
*/
void SocialNetworkInterface::populate()
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must be implemented such that it performs the appropriate
get request to retrieve the data for the specified \c objectIdentifier, or
data related to that object according to the given \c extraPath parameter.
If possible, only the data specified by the \c whichFields parameter should
be retrieved, to minimise network usage. The \c extraData parameter is
implementation specific, and may be used to modify the behaviour of the request.
*/
QNetworkReply *SocialNetworkInterface::getRequest(const QString &, const QString &, const QStringList &, const QVariantMap &)
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
return 0;
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must be implemented such that it performs the appropriate
post request to upload the \c data for the specified \c objectIdentifier, or
data related to that object according to the given \c extraPath parameter.
The \c extraData parameter is implementation specific, and may be used to
modify the behaviour of the request.
*/
QNetworkReply *SocialNetworkInterface::postRequest(const QString &, const QString &, const QVariantMap &, const QVariantMap &)
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
return 0;
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must be implemented such that it performs the appropriate
delete request to delete the object identified by the specified
\c objectIdentifier, or data related to that object according to the given
\c extraPath parameter. The \c extraData parameter is implementation specific,
and may be used to modify the behaviour of the request.
*/
QNetworkReply *SocialNetworkInterface::deleteRequest(const QString &, const QString &, const QVariantMap &)
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
return 0;
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must return an instance of the correct ContentItem-derived type
given the QVariantMap of data. This function is called when the \c contentItem
role for a specific model index is requested via the model data() function, to
instantiate the content item from the content item data lazily.
*/
ContentItemInterface *SocialNetworkInterface::contentItemFromData(QObject *, const QVariantMap &) const
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
return 0;
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must be implemented so that:
1) the provided data should have non-filters-matching-entries removed
2) the filtered data should then be sorted according to the sorters
3) the d->internalData list should be set
4) finally, dataChanged() and any other model signals should be emitted
*/
void SocialNetworkInterface::updateInternalData(QList<CacheEntry*>)
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must be implemented so that:
0) the current model data should be set to empty
1) the related content data should be requested from the service, according to the filters
2) when received, the related content data should be used to populate the cache via d->populateCache()
3) finally, updateInternalData() should be called, passing in the new cache data.
*/
void SocialNetworkInterface::populateDataForNode(IdentifiableContentItemInterface *)
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
}
/*
Specific implementations of the SocialNetwork interface MUST implement this
function. It must be implemented so that:
0) the current model data should be set to empty
1) the given node is requested from the service
2) when received, the node should be pushed to the nodeStack via d->pushNode(n)
3) the related content data should be requested from the service, according to the filters
4) when received, the related content data should be used to populate the cache via d->populateCache()
5) finally, updateInternalData() should be called, passing in the new cache data.
*/
void SocialNetworkInterface::populateDataForNode(const QString &)
{
qWarning() << Q_FUNC_INFO << "Error: this function MUST be implemented by derived types!";
}
| [
"chris.adams@jollamobile.com"
] | chris.adams@jollamobile.com |
6b1835e777573b361423f507d7424a45122df483 | c597f966e0a637592ac929efecb46488387692e1 | /Header.h | 11025032244eec61f934beb94d096cc8c4df13af | [] | no_license | madelynpetty/interpreter | 28348bf3b58e3daa2d256c95fc2e7872e5f3f8e7 | 555d360f3667dd18c4df216cefbfb4b26a60644a | refs/heads/master | 2023-02-20T14:33:40.111549 | 2021-01-18T23:53:57 | 2021-01-18T23:53:57 | 296,182,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | h | //
// Header.h
// lab1
//
// Created by Maddie Johnson on 10/22/20.
// Copyright © 2020 Maddie Johnson. All rights reserved.
//
#ifndef Header_h
#define Header_h
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include "Parameter.h"
using namespace std;
class Header {
public:
// Header();
string toString();
void AddAttribute(Parameter* a);
vector<Parameter*> attributes;
private:
};
#endif /* Header_h */
| [
"madelyn.johnson@gmail.com"
] | madelyn.johnson@gmail.com |
f08df780e8775e669122cee401ace4f1f5e29e0e | 660c77655f29bccd919e141126dd5af31e3f7caf | /01. 语言特性/04.STL/vector01.cpp | 8256b0a53381b5d1760db888de4358666cfe0523 | [] | no_license | caobinxin/c- | b4b7aaac7903759947044a672b217e0163349d43 | 7a4b8b3a5b164bb2d34b101a89e36d9553f3cd25 | refs/heads/master | 2021-09-02T04:24:34.040450 | 2019-06-30T09:47:11 | 2019-06-30T09:47:11 | 187,663,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,917 | cpp | // C++ STL 之 vector 的 capacity 和 size 属性区别
// size 是当前 vector 容器真实占用的大小,也就是容器当前拥有多少个容器。
// capacity 是指在发生 realloc 前能允许的最大元素数,即预分配的内存空间。
// 当然,这两个属性分别对应两个方法:resize() 和 reserve()。
// 使用 resize() 容器内的对象内存空间是真正存在的。
// 使用 reserve() 仅仅只是修改了 capacity 的值,容器内的对象并没有真实的内存空间(空间是"野"的)。
// 此时切记使用 [] 操作符访问容器内的对象,很可能出现数组越界的问题。
#include <iostream>
#include <vector>
using std::vector;
int main(void)
{
vector<int> v;
std::cout<<"v.size() == " << v.size() << " v.capacity() = " << v.capacity() << std::endl;
v.reserve(10);//这里相当于,设置了 每次alloc 增长的空间
std::cout<<"v.size() == " << v.size() << " v.capacity() = " << v.capacity() << std::endl;
v.resize(1);
v.push_back(1);
v.push_back(2);
std::cout<<"v.size() == " << v.size() << " v.capacity() = " << v.capacity() << std::endl;
//下面的操作暂时是对的, 但是很容易出现 数据越界的问题
for(int i = 0; i < v.capacity(); i++){
std::cout << "v.value = " << v[i] << std::endl;
}
//正确的做法
for(int i = 0; i < v.size(); i++){
std::cout << "v.value = " << v[i] << std::endl;
}
return 0;
}
// 相关引申:
// 针对 capacity 这个属性,STL 中的其他容器,如 list map set deque,由于这些容器的内存是散列分布的,
// 因此不会发生类似 realloc() 的调用情况,因此我们可以认为 capacity 属性针对这些容器是没有意义的,因此设计时这些容器没有该属性。
// 在 STL 中,拥有 capacity 属性的容器只有 vector 和 string。 | [
"caobinxin@phoenixos.com"
] | caobinxin@phoenixos.com |
d382f15c3034057a17e8e0ff76d94cad2e7d3f2a | c10b10836b13174327995ee674fba0601ca26852 | /ut/stream/stream_tests.h | f474a9fceb68cc16ef9a854b83e04d97c327b9ec | [] | no_license | Enelar/AX | c7b0431b5cf2fec52519df7df0373257ec214628 | 94475b69572a4220509123b31470dbccb7024ed0 | refs/heads/unstable | 2020-04-05T00:16:48.410690 | 2014-03-17T08:09:29 | 2014-03-17T08:09:29 | 14,269,600 | 1 | 0 | null | 2013-12-13T07:14:38 | 2013-11-10T02:50:45 | C++ | UTF-8 | C++ | false | false | 138 | h | #include "../head.h"
namespace ut
{
void make_stream_tests();
DECLARE_TEST(duct_compiling);
//DECLARE_TEST(fast_memory_copying);
}; | [
"enelar@develop-project.ru"
] | enelar@develop-project.ru |
fc8f25fb01fd4b8800761450322085098a49bafe | 2dbfb3c6b1c8718019ea9fe62c0f1c38398b0fd2 | /Apps/Client/Source/HotlineAdmInSpector.cpp | 01b0f6ee075dae9ab0ba2b8688c1f85f8de1296a | [] | no_license | NebuHiiEjamu/GLoarbLine | f11a76f61448b63e6fd5bf91296514171fbdf921 | 2592629bda74d700fd7cf480f1a5fc1cc67d8d58 | refs/heads/master | 2020-12-01T17:23:11.158214 | 2020-01-07T06:37:53 | 2020-01-07T06:37:53 | 230,709,766 | 0 | 0 | null | 2019-12-29T06:00:07 | 2019-12-29T06:00:06 | null | ISO-8859-7 | C++ | false | false | 53,498 | cpp | /* (c)2007 GLoarbLine Inc. Licensed under GPL - see LICENSE in HotlineSources diresctory */
#include "Hotline.h"
#if WIN32
void _SetWinIcon(TWindow inRef, Int16 inID);
#endif
/* ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ */
CMyAdmITreeView::CMyServerTreeView(CViewHandler *inHandler, const SRect& inBounds, CMyServerWindow *inServerWin)
: CTabbedTreeView(inHandler, inBounds, 240, 241)
{
#if WIN32
mTabHeight = 18;
#endif
#if DISABLE_TABS
mTabHeight = 0;
#endif
mBehaviour = itemBehav_SelectOnlyOne + itemBehav_DoubleClickAction;
mServerWin = inServerWin;
mMaxWidth = 0;
mBigDesc[0] = 0;
// set headers
AddTab("\pName", 80, 80);
AddTab("\pStatus", 1, 1, align_CenterHoriz);
AddTab("\pDescription");
SetTabs(70,17,13);
}
CMyServerTreeView::~CMyServerTreeView()
{
ClearTree();
}
void CMyServerTreeView::SetTabs(Uint8 inTabPercent1, Uint8 inTabPercent2, Uint8 inTabPercent3)
{
if (!inTabPercent1 && !inTabPercent2 && !inTabPercent3)
return;
CPtrList<Uint8> lPercentList;
lPercentList.AddItem(&inTabPercent1);
lPercentList.AddItem(&inTabPercent2);
lPercentList.AddItem(&inTabPercent3);
SetTabPercent(lPercentList);
lPercentList.Clear();
}
void CMyServerTreeView:: SetTabs(Uint16 inTabWidth1, Uint16 inTabWidth2)
{
SetTabWidth(1, inTabWidth1);
SetTabWidth(2, inTabWidth2);
}
void CMyServerTreeView::GetTabs(Uint16& outTabWidth1, Uint16& outTabWidth2)
{
outTabWidth1 = GetTabWidth(1);
outTabWidth2 = GetTabWidth(2);
}
Uint32 CMyServerTreeView::AddTracker(SMyServerInfo *inTracker)
{
if (inTracker->Desc[0] > mBigDesc[0])
UMemory::Copy(mBigDesc, inTracker->Desc, inTracker->Desc[0] + 1);
return AddTreeItem(0, inTracker);
}
Uint32 CMyServerTreeView::AddServer(Uint32 inParentIndex, SMyServerInfo *inServer)
{
if (inServer->Desc[0] > mBigDesc[0])
UMemory::Copy(mBigDesc, inServer->Desc, inServer->Desc[0] + 1);
return AddTreeItem(inParentIndex, inServer, false);
}
void CMyServerTreeView::RefreshTrackers()
{
Uint32 i = 0;
SMyServerInfo *pTrackInfo;
while (GetNextTreeItem(pTrackInfo, i, true))
RefreshTreeItem(i);
}
void CMyServerTreeView::RefreshTracker(Uint32 inTrackerID)
{
Uint32 nIndex = GetTrackerIndex(inTrackerID);
if (nIndex)
RefreshTreeItem(nIndex);
}
Uint32 CMyServerTreeView::GetSelectedTrackerID(bool *outIsBookmark)
{
if (outIsBookmark)
*outIsBookmark = false;
Uint32 nSelectedIndex = GetFirstSelectedTreeItem();
if (!nSelectedIndex)
return 0;
if (nSelectedIndex == 1)
{
if (outIsBookmark)
*outIsBookmark = true;
return 0;
}
if (GetTreeItemLevel(nSelectedIndex) == 1)
{
SMyServerInfo *pTrackInfo = GetTreeItem(nSelectedIndex);
if (pTrackInfo)
return pTrackInfo->Flags;
}
return 0;
}
const Uint8 *CMyServerTreeView::GetSelectedBookmarkName()
{
Uint32 nSelectedIndex = GetFirstSelectedTreeItem();
if (!nSelectedIndex)
return nil;
if (GetTreeItemLevel(nSelectedIndex) == 2 && GetParentTreeIndex(nSelectedIndex) == 1)
{
SMyServerInfo *pTrackInfo = GetTreeItem(nSelectedIndex);
if (pTrackInfo)
return pTrackInfo->Name;
}
return nil;
}
SMyServerInfo *CMyServerTreeView::GetSelectedServInfo(bool &outBookmark)
{
outBookmark = false;
Uint32 nSelectedIndex = GetFirstSelectedTreeItem();
if (nSelectedIndex && GetTreeItemLevel(nSelectedIndex) > 1)
{
SMyServerInfo *pServerInfo = GetTreeItem(nSelectedIndex);
if (pServerInfo)
{
SMyServerInfo *pTrackerInfo = GetParentTreeItem(nSelectedIndex);
if (pTrackerInfo && !pTrackerInfo->Flags)
outBookmark = true;
return pServerInfo;
}
}
return nil;
}
bool CMyServerTreeView::GetSelectedServInfo(bool &outBookmark, Uint8 *outName, Uint8 *outAddress)
{
SMyServerInfo *pServerInfo = GetSelectedServInfo(outBookmark);
if (!pServerInfo)
return false;
if (outName)
UMemory::Copy(outName, pServerInfo->Name, pServerInfo->Name[0] + 1);
if (outAddress)
{
Uint8 *address = (Uint8 *)&pServerInfo->Address;
if (pServerInfo->Port == 5500)
outAddress[0] = UText::Format(outAddress + 1, 31, "%hu.%hu.%hu.%hu", (Uint16)address[0], (Uint16)address[1], (Uint16)address[2], (Uint16)address[3]);
else
outAddress[0] = UText::Format(outAddress + 1, 31, "%hu.%hu.%hu.%hu:%hu", (Uint16)address[0], (Uint16)address[1], (Uint16)address[2], (Uint16)address[3], (Uint16)pServerInfo->Port);
}
return true;
}
Uint32 CMyServerTreeView::GetTotalServerCount()
{
return GetTreeCount();
}
bool CMyServerTreeView::SetTrackerDisclosure(Uint16 inTrackID, Uint8 inDisclosure)
{
Uint32 i = 0;
SMyServerInfo *pTrackInfo;
while (GetNextTreeItem(pTrackInfo, i, true))
{
if (pTrackInfo->Flags == inTrackID)
return SetDisclosure(i, inDisclosure);
}
return false;
}
Uint8 CMyServerTreeView::GetTrackerDisclosure(Uint16 inTrackID)
{
Uint32 i = 0;
SMyServerInfo *pTrackInfo;
while (GetNextTreeItem(pTrackInfo, i, true))
{
if (pTrackInfo->Flags == inTrackID)
return GetDisclosure(i);
}
return optTree_NoDisclosure;
}
Uint32 CMyServerTreeView::GetTrackerIndex(Uint16 inTrackID)
{
Uint32 i = 0;
SMyServerInfo *pTrackInfo;
while (GetNextTreeItem(pTrackInfo, i, true))
{
if (pTrackInfo->Flags == inTrackID)
return i;
}
return 0;
}
void CMyServerTreeView::ExpandAllTrackers()
{
Uint32 i = 0;
SMyServerInfo *pTrackInfo;
while (GetNextTreeItem(pTrackInfo, i, true))
SetDisclosure(i, optTree_Disclosed);
}
void CMyServerTreeView::RemoveServers()
{
Uint32 i = 0;
SMyServerInfo *pTrackerInfo = nil;
while (GetNextTreeItem(pTrackerInfo, i, true))
RemoveChildTree(i);
}
void CMyServerTreeView::RemoveTracker(Uint16 inTrackerID, bool inTracker)
{
Uint32 i = 0;
SMyServerInfo *pTrackerInfo = nil;
while (GetNextTreeItem(pTrackerInfo, i, true))
{
if (pTrackerInfo->Flags == inTrackerID)
{
if (inTracker)
RemoveTreeItem(i);
else
RemoveChildTree(i);
}
}
}
void CMyServerTreeView::SetStatusMsg(Uint16 inTrackerID, const Uint8 inMsg[])
{
Uint32 nIndex = GetTrackerIndex(inTrackerID);
if (!nIndex)
return;
SMyServerInfo *pTrackerInfo = GetTreeItem(nIndex);
if (!pTrackerInfo)
return;
pTrackerInfo->User[0] = UMemory::Copy(pTrackerInfo->User + 1, inMsg + 1, inMsg[0] > sizeof(pTrackerInfo->User) - 1 ? sizeof(pTrackerInfo->User) - 1 : inMsg[0]);
RefreshTreeItem(nIndex);
}
void CMyServerTreeView::SelectionChanged(Uint32 inTreeIndex, SMyServerInfo *inTreeItem, bool inIsSelected)
{
#pragma unused (inTreeItem)
if (inIsSelected)
{
Uint32 nTreeLevel = GetTreeItemLevel(inTreeIndex);
mServerWin->SetEnableTrash((nTreeLevel == 1 && inTreeItem->Flags) || (nTreeLevel == 2 && GetParentTreeIndex(inTreeIndex) == 1));
}
}
void CMyServerTreeView::DisclosureChanged(Uint32 inTreeIndex, SMyServerInfo *inTreeItem, Uint8 inDisclosure)
{
if (inDisclosure == optTree_Disclosed && !GetChildTreeCount(inTreeIndex))
UApplication::PostMessage(1120, &inTreeItem->Flags, sizeof(Uint16));
}
void CMyServerTreeView::ItemDraw(Uint32 inTreeIndex, Uint32 inTreeLevel, SMyServerInfo *inTreeItem, STreeViewItem *inTreeViewItem, TImage inImage, const CPtrList<SRect>& inTabRectList, Uint32 inOptions)
{
#pragma unused(inOptions)
SRect stRect;
SColor stTextCol;
bool bIsActive = IsFocus() && mIsEnabled && inTreeViewItem->bIsSelected;
if (bIsActive)
UUserInterface::GetSysColor(sysColor_InverseHighlight, stTextCol);
else
UUserInterface::GetSysColor(sysColor_Label, stTextCol);
// set color
inImage->SetInkColor(stTextCol);
// set font
inImage->SetFont(kDefaultFont, nil, 9);
if (inTreeLevel == 1 && inTreeItem->Address)
inTreeItem->User[0] = UText::Format(inTreeItem->User + 1, sizeof(inTreeItem->User) - 1, "%lu/%lu", GetChildTreeCount(inTreeIndex), inTreeItem->Address);
// draw item icon and name
const SRect *pBounds = inTabRectList.GetItem(1);
if (pBounds && pBounds->GetWidth())
{
// set rect
stRect = *pBounds;
stRect.top += 2;
stRect.bottom = stRect.top + 16;
stRect.left += 2 + (inTreeLevel == 1 ? 0 : 10);
stRect.right = stRect.left + 16;
// draw icon
if (stRect.right < pBounds->right)
inTreeItem->Icon->Draw(inImage, stRect, align_Center, bIsActive ? transform_Dark : transform_None);
// set rect
stRect = *pBounds;
stRect.top += 3;
stRect.bottom -= 2;
stRect.left += 24 + (inTreeLevel == 1 ? 0 : 10);
if (stRect.right < stRect.left)
stRect.right = stRect.left;
// draw item name
inImage->SetFontEffect(fontEffect_Bold);
inImage->DrawTruncText(stRect, inTreeItem->Name + 1, inTreeItem->Name[0], 0, align_Left | align_CenterVert);
}
// draw status
pBounds = inTabRectList.GetItem(2);
if (pBounds)
{
if (pBounds->GetWidth())
{
// set rect
stRect = *pBounds;
stRect.top += 3;
stRect.bottom -= 2;
stRect.left += 1;
if (stRect.right < stRect.left)
stRect.right = stRect.left;
bool bDrawStatus = true;
if (inTreeLevel > 1)
{
SMyServerInfo *pTrackerInfo = GetParentTreeItem(inTreeIndex);
if (pTrackerInfo && !pTrackerInfo->Flags)
bDrawStatus = false;
}
if (bDrawStatus)
{
inImage->SetFontEffect(fontEffect_Plain);
inImage->DrawTruncText(stRect, inTreeItem->User + 1, inTreeItem->User[0], 0, align_CenterHoriz | align_CenterVert);
}
}
// set bounds
bool bSetBounds = false;
SRect stBounds = mBounds;
Uint32 nRight = inImage->GetTextWidth(mBigDesc + 1, mBigDesc[0]) + 10;
if (nRight > mMaxWidth)
{
mMaxWidth = nRight;
stBounds.right = mMaxWidth + pBounds->right + 4;
bSetBounds = true;
}
CScrollerView *pScrHandler = dynamic_cast<CScrollerView *>(GetHandler());
if (pScrHandler)
{
Int32 nScrWidth = pScrHandler->GetVisibleContentWidth();
if (stBounds.right < nScrWidth)
{
stBounds.right = nScrWidth;
bSetBounds = true;
}
}
if (bSetBounds)
SetBounds(stBounds);
}
// draw description
pBounds = inTabRectList.GetItem(3);
if (pBounds && pBounds->GetWidth())
{
// set rect
stRect = *pBounds;
stRect.top += 3;
stRect.bottom -= 2;
stRect.left += 1;
if (stRect.right < stRect.left)
stRect.right = stRect.left;
inImage->SetFontEffect(fontEffect_Plain);
inImage->DrawTruncText(stRect, inTreeItem->Desc + 1, inTreeItem->Desc[0], 0, align_Left | align_CenterVert);
}
}
/* ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ */
#pragma mark -
CMyServerWindow::CMyServerWindow(CWindow *inParent)
: CWindow(SRect(0,0,330,334), windowLayer_Standard, windowOption_CloseBox | windowOption_ZoomBox | windowOption_Sizeable, 0, inParent)
{
#if WIN32
_SetWinIcon(*this, 233);
#endif
// setup window
SetTitle("\pServers");
SetAutoBounds(windowPos_Center, windowPosOn_WinScreen);
SetLimits(300,150);
// make container view for content
CContainerView *vc = new CContainerView(this, (SRect(0,0,330,334)));
vc->Show();
CLabelView *labl = new CLabelView(vc, SRect(88,8,135,24));
labl->SetFont(kDefaultFont, nil, 9);
labl->SetText("\pSearch:");
labl->Show();
mServerNumLabl = new CLabelView(vc, SRect(222,8,275,24));
mServerNumLabl->SetFont(kDefaultFont, nil, 9);
mServerNumLabl->SetText("\p0/0");
mServerNumLabl->SetSizing(sizing_HorizSticky);
mServerNumLabl->Show();
CScrollerView *Scr = MakeTextBoxView(vc, SRect(140,2,216,28), scrollerOption_Border, &mFilterText);
mFilterText->SetEnterKeyAction(enterKeyAction_Hit);
mFilterText->SetCommandID(TrackCmd_Filter);
mFilterText->SetFont(fd_Default9);
mFilterText->SetSizing(sizing_RightSticky);
mFilterText->Show();
Scr->SetSizing(sizing_RightSticky);
Scr->Show();
CIconButtonView *icb = new CIconButtonView(vc, SRect(3, 3,27,27), nil, nil, 1, nil);
//DebugBreak("On lit giveiconset et affiche icone: %i",gApp->GiveIconSet());
if (gApp->GiveIconSet() == 2){
icb = new CIconButtonView(vc, SRect(3, 3,27,27), viewID_Connect, nil, 3032, nil);
}else if (gApp->GiveIconSet() == 1){
icb = new CIconButtonView(vc, SRect(3, 3,27,27), viewID_Connect, nil, 411, nil);
}
icb->SetTooltipMsg("\pConnect to Server");
icb->SetID(viewID_Connect);
icb->Show();
if (gApp->GiveIconSet() == 2){
icb = new CIconButtonView(vc, SRect(30,3,54,27), TrackCmd_AddTracker, nil, 3033, nil);
}else if (gApp->GiveIconSet() == 1){
icb = new CIconButtonView(vc, SRect(30,3,54,27), TrackCmd_AddTracker, nil, 232, nil);
}
icb->SetTooltipMsg("\pAdd Tracker");
icb->Show();
//DebugBreak("%i",gApp->GiveIconSet());
if (gApp->GiveIconSet() == 2){
icb = new CIconButtonView(vc, SRect(57,3,81,27), viewID_Refresh, nil, 3026, nil);
}else if (gApp->GiveIconSet() == 1){
icb = new CIconButtonView(vc, SRect(57,3,81,27), viewID_Refresh, nil, 205, nil);
}
icb->SetID(viewID_Refresh);
icb->SetTooltipMsg("\pRefresh");
icb->Show();
// help
#if USE_HELP
icb = new CIconButtonView(vc, SRect(276,3,300,27));
icb->SetIconID(iconID_HelpToolbar);
icb->SetID(viewID_HelpServers);
icb->SetTooltipMsg("\pHelp");
icb->SetSizing(sizing_HorizSticky);
icb->Show();
#endif
if (gApp->GiveIconSet() == 2){
icb = new CIconButtonView(vc, SRect(303,3,327,27), viewID_Delete, nil, 3000, nil);
}else if (gApp->GiveIconSet() == 1){
icb = new CIconButtonView(vc, SRect(303,3,327,27), viewID_Delete, nil, 212, nil);
}
icb->SetID(viewID_Delete);
icb->SetTooltipMsg("\pDelete");
icb->SetSizing(sizing_HorizSticky);
icb->Disable();
icb->Show();
mTrash = icb;
//26
mScrChatz = new CScrollerView(vc, SRect(-2,30,332,336));
mScrChatz->SetOptions(scrollerOption_VertBar + scrollerOption_HorizBar + scrollerOption_NoFocusBorder + scrollerOption_Border + scrollerOption_NoBkgnd);
mScrChatz->SetSizing(sizing_BottomRightSticky);
mScrChatz->SetCanFocus(true);
mServerTreeView = new CMyServerTreeView(mScrChatz, SRect(0, 0, mScrChatz->GetVisibleContentWidth(), mScrChatz->GetVisibleContentHeight()), this);
mServerTreeView->SetCanFocus(true);
mServerTreeView->SetSizing(sizing_FullHeight | sizing_FullWidth);
mServerTreeView->SetCommandID(TrackCmd_ServerConnect);
mServerTreeView->Show();
mScrChatz->Show();
}
void CMyServerWindow::UserZoom(const SMouseMsgData& /* inInfo */)
{
SRect r;
Uint32 h, w;
mServerTreeView->GetFullSize(w, h);
GetBounds(r);
r.bottom = r.top + h + 46;
r.right = r.left + w + 15;
if (UWindow::GetZoomBounds(mWindow, r, r))
SetBounds(r);
}
/* ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ */
#pragma mark -
CMyTrackServWindow::CMyTrackServWindow(CWindow *inParent)
: //CWindow(SRect(0,0,(409-133),282), windowLayer_Standard, 0, 0, inParent)
CWindow(SRect(0,0,409,282), windowLayer_Standard, 0, 0, inParent)
{
#if WIN32
_SetWinIcon(*this, 232);
#endif
// setup window
SetTitle("\pNew Account");
SetAutoBounds(windowPos_Center, windowPosOn_WinScreen);
// make container view for content
//CContainerView *vc = new CContainerView(this, (SRect(0,0,(409-133),282)));
CContainerView *vc = new CContainerView(this, (SRect(0,0,409,282)));
vc->Show();
CBoxView *Box = new CBoxView(vc, SRect(4,5,273,82));
Box->SetTitle("\pTracker Info");
Box->SetStyle(boxStyle_Etched);
Box->Show();
CBoxView *Box2 = new CBoxView(vc, SRect(4,115,273,253));
Box2->SetTitle("\pConnection");
Box2->SetStyle(boxStyle_Etched);
Box2->Show();
CBoxView *Box3 = new CBoxView(vc, SRect(12,177,266,246));
Box3->SetStyle(boxStyle_Sunken);
Box3->Show();
CScrollerView *Scr = MakeTextBoxView(vc, SRect(86,21,263,47), scrollerOption_Border, &mName);
mName->SetEnterKeyAction(enterKeyAction_None);
mName->SetEditable(true);
vc->SetFocusView(Scr);
mName->Show();
Scr->Show();
CScrollerView *Scr2 = MakeTextBoxView(vc, SRect(86,51,263,77), scrollerOption_Border, &mAddr);
mAddr->SetEnterKeyAction(enterKeyAction_None);
mAddr->SetEditable(true);
mAddr->Show();
Scr2->Show();
mScrLogin = MakeTextBoxView(vc, SRect(90,183,259,209), scrollerOption_Border, &mLogin);
mLogin->SetEnterKeyAction(enterKeyAction_None);
mLogin->SetEditable(true);
mLogin->Show();
mScrLogin->Show();
mScrPass = MakeTextBoxView(vc, SRect(90,213,259,239), scrollerOption_Border, &mPass);
mPass->SetEnterKeyAction(enterKeyAction_None);
mPass->SetEditable(true);
mPass->Show();
mScrPass->Show();
mLogin->Disable();
mScrLogin->Disable();
mPass->Disable();
mScrPass->Disable();
mDisclose = new CSimpleIconBtnView(vc, SRect(4,86,29,109));
mDisclose->SetIconID(240);
mDisclose->SetCommandID(TrackCmd_Disclose);
mDisclose->Show();
//
mGuest = new CCheckBoxView(vc, SRect(22,133,80,148));
mGuest->SetTitle("\pGuest");
mGuest->SetCommandID(TrackCmd_GuestHit);
mGuest->SetMark(true);
mGuest->SetStyle(1);
mGuest->Show();
mAccount = new CCheckBoxView(vc, SRect(22,157,95,171));
mAccount->SetCommandID(TrackCmd_AccntHit);
mAccount->SetTitle("\pAccount");
mAccount->SetStyle(1);
mAccount->Show();
mAccount->SetExclusiveNext(mGuest);
mGuest->SetExclusiveNext(mAccount);
// make buttons
CButtonView *save, *cancel;
SButtons btns[] = {{TrackCmd_SaveTracker, "\pSave", btnOpt_CommandID | btnOpt_Default, &save}, {cmd_Cancel, "\pCancel", btnOpt_CommandID | btnOpt_Cancel, &cancel}};
CButtonView::BuildButtons(vc, SRect(90,254,270,280), btns);
save->SetSizing(sizing_VertSticky+sizing_HorizSticky);
cancel->SetSizing(sizing_VertSticky+sizing_HorizSticky);
CLabelView *name = new CLabelView(vc, SRect(38,27,79,43));
name->SetText("\pName:");
name->Show();
CLabelView *addr = new CLabelView(vc, SRect(26,55,83,70));
addr->SetText("\pAddress:");
addr->Show();
CLabelView *login = new CLabelView(vc, SRect(46,187,85,202));
login->SetText("\pLogin:");
login->Show();
CLabelView *pass = new CLabelView(vc, SRect(24,217,91,233));
pass->SetText("\pPassword:");
pass->Show();
// set default to be colapsed
Disclose();
}
void CMyTrackServWindow::Disclose()
{
SRect WinBounds;
GetBounds(WinBounds);
Uint32 height = WinBounds.bottom - WinBounds.top;
if (height > 115) // Show Tops, Set Small
{
SRect bounds = WinBounds;
bounds.bottom = bounds.top + 115;
SetBounds(bounds);
SetDiscloseIcon(240);
}
else // Hide Tops, Set Big
{
SRect bounds = WinBounds;
bounds.bottom = bounds.top + 282;
SetBounds(bounds);
SetDiscloseIcon(241);
}
}
/* ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ */
#pragma mark -
CMyTracker::CMyTracker(CWindow *inParent)
{
mServerWin = new CMyServerWindow(inParent);
mServerTreeView = mServerWin->GetServerTreeView();
mLastTrackerID = 1;
mTimer = UTimer::New(TimerProc, this);
AddBookmarksInTree();
RefreshBookmarks();
}
CMyTracker::~CMyTracker()
{
// delete the window because it's dependant on the data structs we're purging now
// should the window own this data? it may make more sense (have a CMyTrackerWin instead of CMyTracker)
delete mServerWin;
mServerWin = nil;
Uint32 i = 0;
SMyTrackerInfo *pTrackerInfo;
while (mTrackerList.GetNext(pTrackerInfo, i))
UMemory::Dispose((TPtr)pTrackerInfo);
mTrackerList.Clear();
i = 0;
SMyServerInfo *pServerInfo = nil;
while (mServerTree.GetNext(pServerInfo, i))
{
UIcon::Release(pServerInfo->Icon);
UMemory::Dispose((TPtr)pServerInfo->Name);
UMemory::Dispose((TPtr)pServerInfo->Desc);
UMemory::Dispose((TPtr)pServerInfo->SearchName);
UMemory::Dispose((TPtr)pServerInfo->SearchDesc);
UMemory::Dispose((TPtr)pServerInfo);
}
mServerTree.Clear();
}
void CMyTracker::ShowServersWindow()
{
if (mServerWin->IsVisible())
mServerWin->BringToFront();
else
mServerWin->Show();
if (mServerWin->IsCollapsed())
mServerWin->Expand();
mServerWin->SetAutoBounds(windowPos_Best, windowPosOn_WinScreen);
}
bool CMyTracker::CloseWindow(CWindow *inWindow)
{
if (inWindow == mServerWin)
{
mServerWin->Hide();
return true;
}
else if (dynamic_cast<CMyTrackServWindow *>(inWindow))
{
delete inWindow;
return true;
}
return false;
}
bool CMyTracker::KeyCommand(Uint32 inCmd, const SKeyMsgData& /*inInfo*/)
{
switch (inCmd)
{
case TrackCmd_AddTracker:
{
mServerTreeView->DeselectAllTreeItems();
CMyTrackServWindow *pWindow = new CMyTrackServWindow(gApp->mAuxParentWin);
pWindow->Show();
}
break;
default:
return false;
}
return true;
}
// returns whether this is from one of my windows and I processed it
bool CMyTracker::WindowHit(CWindow *inWindow, const SHitMsgData& inInfo)
{
switch (inInfo.cmd)
{
// close box
case CWindow::ClassID:
return CloseWindow(inWindow);
break;
case cmd_Cancel:
delete inWindow;
return true;
break;
case TrackCmd_ServerConnect:
if (!EditSelectedTracker())
gApp->DoConnectToTracked(inInfo.param & modKey_Option ? 1 : 0);
break;
case TrackCmd_Filter:
mTimer->Stop();
if (inInfo.type == hitType_Standard)
FilterServerList();
else
mTimer->Start(1000);
inInfo.view->SetHasChanged(false);
break;
case TrackCmd_Disclose:
if (dynamic_cast<CMyTrackServWindow *>(inWindow))
(dynamic_cast<CMyTrackServWindow *>(inWindow))->Disclose();
break;
case TrackCmd_GuestHit:
if (dynamic_cast<CMyTrackServWindow *>(inWindow))
(dynamic_cast<CMyTrackServWindow *>(inWindow))->GuestHit();
break;
case TrackCmd_AccntHit:
if (dynamic_cast<CMyTrackServWindow *>(inWindow))
(dynamic_cast<CMyTrackServWindow *>(inWindow))->AccntHit();
break;
case TrackCmd_SaveTracker:
CMyTrackServWindow *win = dynamic_cast<CMyTrackServWindow *>(inWindow);
if (win)
{
///////////////
/////////////////
Uint8 psAddr[256];
win->GetAddr(psAddr);
if (psAddr[0])
{
Uint8 psName[256];
win->GetName(psName);
Uint8 psLogin[256];
win->GetLogin(psLogin);
Uint8 psPass[256];
win->GetPass(psPass);
Uint8 psComments[256];
pstrcpy(psComments, "\p");
short bIsAccount = win->IsAccount();
Uint32 nTrackerID = mServerTreeView->GetSelectedTrackerID();
if (nTrackerID)
UpdateTrackerInList(nTrackerID, psName, psComments, psAddr, psLogin, psPass, bIsAccount);
else
AddTrackerInList(psName, psComments, psAddr, psLogin, psPass, bIsAccount, mLastTrackerID++);
delete inWindow;
}
else
gApp->DisplayStandardMessage("\pNeed Address", "\pPlease enter the address of this tracker.", icon_Stop, 1);
}
break;
case TrackCmd_AddTracker:
mServerTreeView->DeselectAllTreeItems();
CMyTrackServWindow *pWindow = new CMyTrackServWindow(gApp->mAuxParentWin);
pWindow->Show();
break;
default:
return false;
break;
}
return true;
}
void CMyTracker::TimerProc(void *inContext, void *inObject, Uint32 inMsg, const void *inData, Uint32 inDataSize)
{
#pragma unused(inMsg, inData, inDataSize)
((CMyTracker *)inContext)->Timer((TTimer)inObject);
}
void CMyTracker::Timer(TTimer inTimer)
{
#pragma unused(inTimer)
FilterServerList();
}
void CMyTracker::SetTabs(Uint16 inTabWidth1, Uint16 inTabWidth2)
{
mServerWin->GetServerTreeView()->SetTabs(inTabWidth1, inTabWidth2);
}
void CMyTracker::GetTabs(Uint16& outTabWidth1, Uint16& outTabWidth2)
{
mServerWin->GetServerTreeView()->GetTabs(outTabWidth1, outTabWidth2);
}
void CMyTracker::AddTrackerInList(SMyTrackerInfo *inTracker)
{
mTrackerList.AddItem(inTracker);
AddTrackerInTree(inTracker);
}
void CMyTracker::AddTrackerInList(Uint8 *Name, Uint8 *Comments, Uint8 *inAddress,
Uint8 *Login, Uint8 *Pass, short isAccount,
Uint16 inTrackerID)
{
SMyTrackerInfo *pTrackerInfo = (SMyTrackerInfo*)UMemory::NewClear(sizeof(SMyTrackerInfo));
pstrcpy(pTrackerInfo->Name, Name);
pstrcpy(pTrackerInfo->Comments, Comments);
pstrcpy(pTrackerInfo->Address, inAddress);
pstrcpy(pTrackerInfo->Login, Login);
pstrcpy(pTrackerInfo->Pass, Pass);
pTrackerInfo->hasAccount = isAccount;
pTrackerInfo->nTrackerID = inTrackerID;
mTrackerList.AddItem(pTrackerInfo);
AddTrackerInTree(pTrackerInfo);
}
void CMyTracker::AddBookmarksInTree()
{
SMyServerInfo *pTrackerInfo = (SMyServerInfo *)UMemory::NewClear(sizeof(SMyServerInfo));
if (gApp->GiveIconSet() == 2){
pTrackerInfo->Icon = UIcon::Load(3003);
}else if (gApp->GiveIconSet() == 1){
pTrackerInfo->Icon = UIcon::Load(401);
}
pTrackerInfo->Name = (Uint8 *)UMemory::New(10);
pTrackerInfo->Desc = (Uint8 *)UMemory::New(10);
pTrackerInfo->SearchName = (Uint8 *)UMemory::New(10);
pTrackerInfo->SearchDesc = (Uint8 *)UMemory::New(10);
UMemory::Copy(pTrackerInfo->Name, "\pBookmarks", 10);
UMemory::Copy(pTrackerInfo->Desc, "\pBookmarks", 10);
UMemory::Copy(pTrackerInfo->SearchName, "\pBookmarks", 10);
UMemory::Copy(pTrackerInfo->SearchDesc, "\pBookmarks", 10);
mServerTree.AddItem(0, pTrackerInfo);
mServerTreeView->AddTracker(pTrackerInfo);
}
void CMyTracker::AddTrackersInTree()
{
SMyTrackerInfo **pInfoPtr = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
while (nCount--)
{
SMyTrackerInfo *pTrackerInfo = *pInfoPtr;
AddTrackerInTree(pTrackerInfo);
pInfoPtr++;
}
}
void CMyTracker::AddTrackerInTree(SMyTrackerInfo *inTracker)
{
SMyServerInfo *pTrackerInfo = (SMyServerInfo *)UMemory::NewClear(sizeof(SMyServerInfo));
if (gApp->GiveIconSet() == 2){
pTrackerInfo->Icon = UIcon::Load(3033);
}else if (gApp->GiveIconSet() == 1){
pTrackerInfo->Icon = UIcon::Load(232);
}
pTrackerInfo->Name = (Uint8 *)UMemory::New(inTracker->Name[0] + 1);
pTrackerInfo->Desc = (Uint8 *)UMemory::New(inTracker->Address[0] + 1);
pTrackerInfo->SearchName = (Uint8 *)UMemory::New(inTracker->Name[0] + 1);
pTrackerInfo->SearchDesc = (Uint8 *)UMemory::New(inTracker->Address[0] + 1);
UMemory::Copy(pTrackerInfo->Name, inTracker->Name, inTracker->Name[0] + 1);
UMemory::Copy(pTrackerInfo->Desc, inTracker->Address, inTracker->Address[0] + 1);
UMemory::Copy(pTrackerInfo->SearchName, inTracker->Name, inTracker->Name[0] + 1);
UMemory::Copy(pTrackerInfo->SearchDesc, inTracker->Address, inTracker->Address[0] + 1);
pTrackerInfo->Flags = inTracker->nTrackerID;
mServerTree.AddItem(0, pTrackerInfo);
mServerTreeView->AddTracker(pTrackerInfo);
}
// returns the number of servers in the list, not how many it added
Uint32 CMyTracker::AddListFromData(Uint16 inTrackerID, const Uint8 *inData, Uint32 inDataSize)
{
Uint8 *p = (Uint8 *)inData;
Uint8 *ep = p + inDataSize;
Uint32 addr;
Uint16 port, userCount;
Uint8 *name, *desc;
Uint32 startCount, addCount, nonDupeCount;
startCount = mServerTree.GetTreeCount();
addCount = nonDupeCount = 0;
SMyTrackerInfo *pTrackerInfo = GetTrackerInfoByID(inTrackerID);
if (!pTrackerInfo) return 0;
Uint32 nParentIndex = GetTrackerIndex(inTrackerID);
if (!nParentIndex) return 0;
Uint32 nParentIndexView = mServerTreeView->GetTrackerIndex(inTrackerID);
if (!nParentIndexView) return 0;
while (p < ep)
{
if (ep - p < 12) break;
addr = *((Uint32 *)p)++;
port = FB( *((Uint16 *)p)++ );
userCount = FB( *((Uint16 *)p)++ );
*((Uint16 *)p)++;
name = p;
p += *p + 1;
if (p >= ep) break;
desc = p;
p += *p + 1;
if (p > ep) break;
// if (!IsInList(addr, port))
AddServerInTree(nParentIndex, nParentIndexView, name, desc, addr, port, userCount, 0);
addCount++;
}
UpdateServersCount(inTrackerID);
mServerTreeView->RefreshTreeItem(nParentIndexView);
SetServerCountLabel();
return addCount;
}
void CMyTracker::AddServerInTree(Uint32 inParentIndex, Uint32 inParentIndexView, Uint8 *inName, Uint8 *inDesc, Uint32 inAddress, Uint16 inPort, Uint16 inCount, Uint16 inFlags)
{
SMyServerInfo *pServerInfo = (SMyServerInfo *)UMemory::NewClear(sizeof(SMyServerInfo));
if (inParentIndex == 1){ // it's a bookmark
if (gApp->GiveIconSet() == 2){
pServerInfo->Icon = UIcon::Load(3064);
}else if (gApp->GiveIconSet() == 1){
pServerInfo->Icon = UIcon::Load(408);
}
}else{
if (gApp->GiveIconSet() == 2){
pServerInfo->Icon = UIcon::Load(3020);
}else if (gApp->GiveIconSet() == 1){
pServerInfo->Icon = UIcon::Load(233);
}
}
pServerInfo->Name = (Uint8 *)UMemory::New(inName[0] + 1);
pServerInfo->Desc = (Uint8 *)UMemory::New(inDesc[0] + 1);
pServerInfo->SearchName = (Uint8 *)UMemory::New(inName[0] + 1);
pServerInfo->SearchDesc = (Uint8 *)UMemory::New(inDesc[0] + 1);
pstrcpy(pServerInfo->Name, inName);
pstrcpy(pServerInfo->Desc, inDesc);
Uint8 bufName[256] = "\p";
Uint8 bufDesc[256] = "\p";
pstrcpy(bufName,inName);
pstrcpy(bufDesc,inDesc);
UText::MakeLowercase(bufName+1, bufName[0]);
UText::MakeLowercase(bufDesc+1, bufDesc[0]);
pstrcpy(pServerInfo->SearchName, bufName);
pstrcpy(pServerInfo->SearchDesc, bufDesc);
pServerInfo->Address = inAddress;
pServerInfo->Port = inPort;
pServerInfo->uCount = inCount;
pServerInfo->Flags = inFlags;
pServerInfo->User[0] = UText::IntegerToText(pServerInfo->User + 1, sizeof(pServerInfo->User) - 1, inCount);
mServerTree.AddItem(inParentIndex, pServerInfo);
Uint8 FilterText[256] = "\p";
mServerWin->GetFilterText(FilterText);
if (FilterText[0])
{
if (FilterServer(FilterText, pServerInfo))
mServerTreeView->AddServer(inParentIndexView, pServerInfo);
}
else
mServerTreeView->AddServer(inParentIndexView, pServerInfo);
}
void CMyTracker::UpdateServersCount(Uint32 inTrackerID)
{
Uint32 i = 0;
SMyServerInfo *pTrackerInfo;
while (mServerTree.GetNext(pTrackerInfo, i, true))
{
if (pTrackerInfo->Flags == inTrackerID)
{
pTrackerInfo->Address = mServerTree.GetChildTreeCount(i);
if (!pTrackerInfo->Address)
pTrackerInfo->User[0] = UMemory::Copy(pTrackerInfo->User + 1, "0/0", 3);
break;
}
}
}
void CMyTracker::UpdateTrackerInList(Uint16 inTrackerID, Uint8 *Name, Uint8 *Comments, Uint8 *inAddress, Uint8 *Login, Uint8 *Pass, short isAccount)
{
SMyTrackerInfo *pTrackerInfo = GetTrackerInfoByID(inTrackerID);
if (!pTrackerInfo)
return;
pstrcpy(pTrackerInfo->Name, Name);
pstrcpy(pTrackerInfo->Comments, Comments);
pstrcpy(pTrackerInfo->Address, inAddress);
pstrcpy(pTrackerInfo->Login, Login);
pstrcpy(pTrackerInfo->Pass, Pass);
pTrackerInfo->hasAccount = isAccount;
UpdateTrackerInTree(pTrackerInfo);
}
void CMyTracker::UpdateTrackerInTree(SMyTrackerInfo *inTracker)
{
Uint32 i = 0;
SMyServerInfo *pTrackerInfo;
while (mServerTree.GetNext(pTrackerInfo, i, true))
{
if (pTrackerInfo->Flags == inTracker->nTrackerID)
{
pTrackerInfo->Name = (Uint8 *)UMemory::Reallocate((TPtr)pTrackerInfo->Name, inTracker->Name[0] + 1);
pTrackerInfo->Desc = (Uint8 *)UMemory::Reallocate((TPtr)pTrackerInfo->Desc, inTracker->Address[0] + 1);
pTrackerInfo->SearchName = (Uint8 *)UMemory::Reallocate((TPtr)pTrackerInfo->SearchName, inTracker->Name[0] + 1);
pTrackerInfo->SearchDesc = (Uint8 *)UMemory::Reallocate((TPtr)pTrackerInfo->SearchDesc, inTracker->Address[0] + 1);
UMemory::Copy(pTrackerInfo->Name, inTracker->Name, inTracker->Name[0] + 1);
UMemory::Copy(pTrackerInfo->Desc, inTracker->Address, inTracker->Address[0] + 1);
UMemory::Copy(pTrackerInfo->SearchName, inTracker->Name, inTracker->Name[0] + 1);
UMemory::Copy(pTrackerInfo->SearchDesc, inTracker->Address, inTracker->Address[0] + 1);
mServerTreeView->RefreshTracker(inTracker->nTrackerID);
break;
}
}
}
bool CMyTracker::EditSelectedTracker()
{
Uint32 nTrackerID = mServerTreeView->GetSelectedTrackerID();
if (!nTrackerID)
return false;
SMyTrackerInfo *pTrackerInfo = GetTrackerInfoByID(nTrackerID);
if (!pTrackerInfo)
return true;
CMyTrackServWindow *pWindow = new CMyTrackServWindow(gApp->mAuxParentWin);
pWindow->SetTitle(pTrackerInfo->Name);
pWindow->SetName(pTrackerInfo->Name);
pWindow->SetAddr(pTrackerInfo->Address);
pWindow->SetPass(pTrackerInfo->Pass);
pWindow->SetLogin(pTrackerInfo->Login);
if (pTrackerInfo->hasAccount)
pWindow->AccntHit();
pWindow->Show();
return true;
}
void CMyTracker::RemoveTrackerInList(Uint16 inTrackerID)
{
Uint32 i = 0;
SMyTrackerInfo *pTrackerInfo;
while (mTrackerList.GetNext(pTrackerInfo, i))
{
if (pTrackerInfo->nTrackerID == inTrackerID)
{
mTrackerList.RemoveItem(pTrackerInfo);
UMemory::Dispose((TPtr)pTrackerInfo);
return;
}
}
}
void CMyTracker::RemoveTrackersInTree()
{
Uint32 i = 0;
SMyServerInfo *pServerInfo;
while (mServerTree.GetNext(pServerInfo, i, true))
{
if (!pServerInfo->Flags) // Bookmarks
continue;
SMyTrackerInfo **infoPtr = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
bool bRemoveTracker = true;
while (nCount--)
{
SMyTrackerInfo *pTrackerInfo = *infoPtr;
if (pTrackerInfo->nTrackerID == pServerInfo->Flags &&
pServerInfo->Name[0] == pTrackerInfo->Name[0] && !UMemory::Compare(pServerInfo->Name + 1, pTrackerInfo->Name + 1, pTrackerInfo->Name[0]) &&
pServerInfo->Desc[0] == pTrackerInfo->Address[0] && !UMemory::Compare(pServerInfo->Desc + 1, pTrackerInfo->Address + 1, pTrackerInfo->Address[0]))
{
bRemoveTracker = false;
break;
}
infoPtr++;
}
if (bRemoveTracker)
{
RemoveTrackerInTree(pServerInfo->Flags, true);
i = 0;
}
}
SetServerCountLabel();
}
void CMyTracker::RemoveTrackerInTree(Uint16 inTrackerID, bool inTracker)
{
mServerTreeView->RemoveTracker(inTrackerID, inTracker);
Uint32 i = 0;
SMyServerInfo *pTrackerInfo = nil;
while (mServerTree.GetNext(pTrackerInfo, i, true))
{
if (pTrackerInfo->Flags == inTrackerID)
{
if (inTracker)
{
UIcon::Release(pTrackerInfo->Icon);
UMemory::Dispose((TPtr)pTrackerInfo->Name);
UMemory::Dispose((TPtr)pTrackerInfo->Desc);
UMemory::Dispose((TPtr)pTrackerInfo->SearchName);
UMemory::Dispose((TPtr)pTrackerInfo->SearchDesc);
UMemory::Dispose((TPtr)pTrackerInfo);
}
else
pTrackerInfo->Address = 0;
Uint32 nTrackerIndex = i;
if (mServerTree.GetChildTreeCount(i))
{
pTrackerInfo = mServerTree.GetItem(++i);
do
{
UIcon::Release(pTrackerInfo->Icon);
UMemory::Dispose((TPtr)pTrackerInfo->Name);
UMemory::Dispose((TPtr)pTrackerInfo->Desc);
UMemory::Dispose((TPtr)pTrackerInfo->SearchName);
UMemory::Dispose((TPtr)pTrackerInfo->SearchDesc);
UMemory::Dispose((TPtr)pTrackerInfo);
} while (mServerTree.GetNext(pTrackerInfo, i, true));
}
if (inTracker)
mServerTree.RemoveItem(nTrackerIndex);
else
mServerTree.RemoveChildTree(nTrackerIndex);
SetServerCountLabel();
return;
}
}
}
void CMyTracker::RemoveSelectedItem()
{
// delete tracker
Uint32 nTrackerID = mServerTreeView->GetSelectedTrackerID();
if (nTrackerID)
{
RemoveTrackerInList(nTrackerID);
RemoveTrackerInTree(nTrackerID, true);
SetServerCountLabel();
return;
}
// delete bookmark
const Uint8 *pBookmarkName = mServerTreeView->GetSelectedBookmarkName();
if (pBookmarkName)
{
Uint8 psBookmarkName[256];
UMemory::Copy(psBookmarkName, pBookmarkName, pBookmarkName[0] + 1);
// add the ".hbm" to the file name
#if WIN32
pstrcat(psBookmarkName, "\p.hbm");
#endif
StFileSysRef pBookmarkFile(kProgramFolder, "\pBookmarks", psBookmarkName, fsOption_RequireExistingFile);
if (pBookmarkFile.IsValid())
{
pBookmarkFile->MoveToTrash();
RefreshBookmarks();
}
}
}
void CMyTracker::SetStatusMsg(Uint16 inTrackerID, const Uint8 inMsg[])
{
mServerTreeView->SetStatusMsg(inTrackerID, inMsg);
}
void CMyTracker::SetServerCountLabel()
{
Uint32 nTotalCount = mServerTree.GetTreeCount() - mServerTree.GetRootCount();
Uint32 nListCount = mServerTreeView->GetTotalServerCount() - mServerTreeView->GetRootCount();
Uint8 Status[256] = "\p";
Uint8 LCText[256] = "\p";
Uint8 TCText[256] = "\p";
LCText[0] = UText::IntegerToText(LCText+1, 255, nListCount);
TCText[0] = UText::IntegerToText(TCText+1, 255, nTotalCount);
Status[0] = UText::Format(Status+1, 255, "%#s\/%#s", LCText, TCText);
mServerWin->SetServerNum(Status);
}
bool CMyTracker::IsInList(Uint32 inAddress, Uint16 inPort)
{
Uint32 i = 0;
SMyServerInfo *pServerInfo = nil;
while (mServerTree.GetNext(pServerInfo, i))
{
if (mServerTree.GetItemLevel(i) > 1 && pServerInfo->Address == inAddress && pServerInfo->Port == inPort)
return true;
}
return false;
}
void CMyTracker::FilterServerList()
{
Uint8 FilterText[256];
mServerWin->GetFilterText(FilterText);
FilterServerList(FilterText);
}
short CMyTracker::FilterServer(Uint8 *inText, SMyServerInfo *inServer)
{
if (!(*inText))
return true;
Uint8 bufSearch[256] = "\p";
pstrcpy(bufSearch, inText);
UText::MakeLowercase(bufSearch+1, bufSearch[0]);
SWordPtr wrds[25];
SWordPtr *wrd = wrds;
SWordPtr *lastWrd = wrds + sizeof(wrds) / sizeof(SWordPtr);
Uint8 *p = bufSearch + 1;
Uint8 *q = bufSearch + 1 + bufSearch[0];
while (wrd != lastWrd && p != q)
{
if (*p == '-')
{
*p++;
wrd->negative = 1;
}
else
wrd->negative = 0;
wrd->startWord = p;
Uint8 *spc = UMemory::SearchByte(' ', p, q - p);
if (spc)
{
wrd->wordLen = spc - p;
wrd++;
// skip over multi-spaces if there are any
while (spc != q && *spc == ' ')
spc++;
p = spc;
}
else
{
wrd->wordLen = q - p;
wrd++;
break;
}
}
wrd->startWord = nil; // so we know where we ended
wrd = wrds;
while (wrd->startWord)
{
if ((UMemory::Search(wrd->startWord, wrd->wordLen, inServer->SearchName+1, inServer->SearchName[0]) ||
UMemory::Search(wrd->startWord, wrd->wordLen, inServer->SearchDesc+1, inServer->SearchDesc[0]) ) == wrd->negative) // Contains it
goto dontAddServer;
wrd++;
}
return true;
dontAddServer:
return false;
}
void CMyTracker::FilterServerList(Uint8 *inText)
{
Uint32 nParentIndex = 0;
SMyServerInfo *pServerInfo = nil;
mServerTreeView->RemoveServers();
Uint32 nCount = mServerTree.GetTreeCount();
if (*inText)
{
if (inText[0] == 1)
{
if (inText[1] == '-')
goto displayAllServs;
Uint8 bufSearch[256] = "\p";
pstrcpy(bufSearch, inText);
UText::MakeLowercase(bufSearch+1, bufSearch[0]);
for (Uint32 i=1; i <= nCount; i++)
{
pServerInfo = mServerTree.GetItem(i);
if (!pServerInfo)
continue;
if (mServerTree.GetItemLevel(i) == 1)
nParentIndex = mServerTreeView->GetTrackerIndex(pServerInfo->Flags);
else if (UMemory::SearchByte(inText[1], pServerInfo->SearchName + 1, pServerInfo->SearchName[0]) ||
UMemory::SearchByte(inText[1], pServerInfo->SearchDesc+1, pServerInfo->SearchDesc[0]))
mServerTreeView->AddServer(nParentIndex, pServerInfo);
}
}
else
{
Uint8 bufSearch[256] = "\p";
pstrcpy(bufSearch, inText);
UText::MakeLowercase(bufSearch+1, bufSearch[0]);
// now I need to build a list of offsets for search text, or separate pstrings?
// let's do offsets - I could do a struct with starts and finishes
SWordPtr wrds[25]; // no one's gonna enter more than 25 words
SWordPtr *wrd = wrds;
SWordPtr *lastWrd = wrds + sizeof(wrds) / sizeof(SWordPtr);
Uint8 *p = bufSearch + 1;
Uint8 *q = bufSearch + 1 + bufSearch[0];
while (wrd != lastWrd && p != q)
{
if (*p == '-')
{
*p++;
wrd->negative = 1;
}
else
wrd->negative = 0;
wrd->startWord = p;
Uint8 *spc = UMemory::SearchByte(' ', p, q - p);
if (spc)
{
wrd->wordLen = spc - p;
wrd++;
// skip over multi-spaces if there are any
while (spc != q && *spc == ' ')
spc++;
p = spc;
}
else
{
wrd->wordLen = q - p;
wrd++;
break;
}
}
wrd->startWord = nil; // so we know where we ended
for (Uint32 i=1; i <= nCount; i++)
{
pServerInfo = mServerTree.GetItem(i);
if (!pServerInfo)
continue;
if (mServerTree.GetItemLevel(i) == 1)
{
nParentIndex = mServerTreeView->GetTrackerIndex(pServerInfo->Flags);
}
else
{
wrd = wrds;
bool bAddServer = true;
while (wrd->startWord)
{
if ((UMemory::Search(wrd->startWord, wrd->wordLen, pServerInfo->SearchName+1, pServerInfo->SearchName[0]) ||
UMemory::Search(wrd->startWord, wrd->wordLen, pServerInfo->SearchDesc+1, pServerInfo->SearchDesc[0]) ) == wrd->negative)
{
bAddServer = false;
break;
}
wrd++;
}
if (bAddServer)
mServerTreeView->AddServer(nParentIndex, pServerInfo);
}
}
}
}
else
{
displayAllServs:
for(Uint32 i=1; i <= nCount; i++)
{
pServerInfo = mServerTree.GetItem(i);
if (!pServerInfo)
continue;
if (mServerTree.GetItemLevel(i) == 1)
nParentIndex = mServerTreeView->GetTrackerIndex(pServerInfo->Flags);
else
mServerTreeView->AddServer(nParentIndex, pServerInfo);
}
}
SetServerCountLabel();
mServerTreeView->RefreshTrackers();
}
bool CMyTracker::RefreshBookmarks()
{
Uint16 nTrackerID = 0;
RemoveTrackerInTree(nTrackerID, false);
if (mServerTreeView->GetTrackerDisclosure(nTrackerID) == optTree_Collapsed)
mServerTreeView->SetTrackerDisclosure(nTrackerID, optTree_Disclosed);
TFSRefObj* folder = nil;
try
{
folder = UFS::New(kProgramFolder, nil, "\pBookmarks", fsOption_PreferExistingFolder);
if (!folder)
{
folder = UFS::New(kProgramFolder, nil, "\pServers", fsOption_PreferExistingFolder);
if (!folder)
{
// create a bookmarks folder if none exists
try
{
folder = UFS::New(kProgramFolder, nil, "\pBookmarks");
if(folder)
{
scopekill(TFSRefObj, folder);
folder->CreateFolder();
}
}
catch(...) {}
return false;
}
folder->SetName("\pBookmarks");
}
}
catch(...)
{
delete folder;
throw;
}
scopekill(TFSRefObj, folder);
THdl h = folder->GetListing();
if (h == nil)
{
UpdateServersCount(nTrackerID);
return false;
}
Uint32 nParentIndex = GetTrackerIndex(nTrackerID);
if (!nParentIndex) return false;
Uint32 nParentIndexView = mServerTreeView->GetTrackerIndex(nTrackerID);
if (!nParentIndexView) return false;
try
{
Uint8 name[256];
Uint32 typeCode, creatorCode, flags;
Uint32 offset = 0;
while (UFS::GetListNext(h, offset, name, &typeCode, &creatorCode, nil, nil, nil, &flags))
{
// loose the ".hbm" from the file name
#if WIN32
if (name[0] > 4)
{
Uint8 *p = (name + name[0]) - 3;
if (p[0] == '.' && UText::tolower(p[1]) == 'h' && UText::tolower(p[2]) == 'b' && UText::tolower(p[3]) == 'm')
name[0] -= 4;
}
#endif
if (typeCode == TB((Uint32)'HTbm') && creatorCode == TB((Uint32)'HTLC') && (flags & 1) == 0) // if visible bookmark file
AddServerInTree(nParentIndex, nParentIndexView, name, name, 0, 0, 0, 0);
}
}
catch(...)
{
UMemory::Dispose(h);
throw;
}
UMemory::Dispose(h);
UpdateServersCount(nTrackerID);
SetServerCountLabel();
return true;
}
void CMyTracker::RefreshTrackers()
{
RemoveTrackersInTree();
RefreshBookmarks();
SMyTrackerInfo **infoPtr = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
while (nCount--)
{
SMyTrackerInfo *pTrackerInfo = *infoPtr;
bool bRefreshTracker = false;
Uint32 nTrackerIndex = GetTrackerIndex(pTrackerInfo->nTrackerID);
if (nTrackerIndex)
{
if (!gApp->SearchTrackServTask(pTrackerInfo->nTrackerID))
{
bRefreshTracker = true;
RemoveTrackerInTree(pTrackerInfo->nTrackerID, false);
if (mServerTreeView->GetTrackerDisclosure(pTrackerInfo->nTrackerID) == optTree_Collapsed)
mServerTreeView->SetTrackerDisclosure(pTrackerInfo->nTrackerID, optTree_Disclosed);
}
}
else
{
bRefreshTracker = true;
AddTrackerInTree(pTrackerInfo);
mServerTreeView->SetTrackerDisclosure(pTrackerInfo->nTrackerID, optTree_Disclosed);
}
if (bRefreshTracker)
{
if (pTrackerInfo->hasAccount)
new CMyGetTrackServListTask(pTrackerInfo->Address, pTrackerInfo->Name, pTrackerInfo->nTrackerID, pTrackerInfo->Login, pTrackerInfo->Pass);
else
new CMyGetTrackServListTask(pTrackerInfo->Address, pTrackerInfo->Name, pTrackerInfo->nTrackerID, "\p", "\p");
SetStatusMsg(pTrackerInfo->nTrackerID, "\pConnecting...");
}
infoPtr++;
}
SetServerCountLabel();
}
void CMyTracker::RefreshTrackers(Uint16 inMods)
{
if (inMods & modKey_Option)
{
RefreshTrackers();
return;
}
bool bIsBookmark;
Uint32 nTrackerID = mServerTreeView->GetSelectedTrackerID(&bIsBookmark);
if (!nTrackerID && !bIsBookmark)
{
RefreshTrackers();
return;
}
RemoveTrackersInTree();
SetServerCountLabel();
if (bIsBookmark)
{
RefreshBookmarks();
return;
}
if (gApp->SearchTrackServTask(nTrackerID))
return;
RemoveTrackerInTree(nTrackerID, false);
if (mServerTreeView->GetTrackerDisclosure(nTrackerID) == optTree_Collapsed)
mServerTreeView->SetTrackerDisclosure(nTrackerID, optTree_Disclosed);
SMyTrackerInfo **infoPtr = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
while (nCount--)
{
SMyTrackerInfo *pTrackerInfo = *infoPtr;
if (pTrackerInfo->nTrackerID == nTrackerID)
{
if (pTrackerInfo->hasAccount)
new CMyGetTrackServListTask(pTrackerInfo->Address, pTrackerInfo->Name, pTrackerInfo->nTrackerID, pTrackerInfo->Login, pTrackerInfo->Pass);
else
new CMyGetTrackServListTask(pTrackerInfo->Address, pTrackerInfo->Name, pTrackerInfo->nTrackerID, "\p", "\p");
SetStatusMsg(nTrackerID, "\pConnecting...");
break;
}
infoPtr++;
}
SetServerCountLabel();
}
void CMyTracker::RefreshTracker(Uint16 inTrackerID)
{
if (!inTrackerID)
{
RefreshBookmarks();
return;
}
if (gApp->SearchTrackServTask(inTrackerID))
return;
SMyTrackerInfo **infoPtr = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
while (nCount--)
{
SMyTrackerInfo *pTrackerInfo = *infoPtr;
if (pTrackerInfo->nTrackerID == inTrackerID)
{
Uint32 nTrackerIndex = GetTrackerIndex(pTrackerInfo->nTrackerID);
if (mServerTree.GetChildTreeCount(nTrackerIndex))
return;
if (pTrackerInfo->hasAccount)
new CMyGetTrackServListTask(pTrackerInfo->Address, pTrackerInfo->Name, pTrackerInfo->nTrackerID, pTrackerInfo->Login, pTrackerInfo->Pass);
else
new CMyGetTrackServListTask(pTrackerInfo->Address, pTrackerInfo->Name, pTrackerInfo->nTrackerID, "\p", "\p");
SetStatusMsg(pTrackerInfo->nTrackerID, "\pConnecting...");
break;
}
infoPtr++;
}
SetServerCountLabel();
}
void CMyTracker::SetDefaultTracker()
{
// this gets called on corrupt (or non-existent) prefs file only add if there are no other items in the list.
if (!mTrackerList.GetItemCount() && gApp->mOptions.stTrackerList.GetItemCount())
{
Uint32 i = 0;
SMyDefTrackerInfo *pTrackerInfo;
while (gApp->mOptions.stTrackerList.GetNext(pTrackerInfo, i))
AddTrackerInList(pTrackerInfo->psName, "\p", pTrackerInfo->psAddr, "\p", "\p", false, mLastTrackerID++);
}
}
void CMyTracker::ExpandDefaultTracker()
{
//mServerTreeView->ExpandAllTrackers();
}
bool CMyTracker::GetSelectedServInfo(Uint8 *outName, Uint8 *outAddress, Uint8 *outLogin, Uint8 *outPassword, bool *outUseCrypt)
{
if (outName) outName[0] = 0;
if (outAddress) outAddress[0] = 0;
if (outLogin) outLogin[0] = 0;
if (outPassword) outPassword[0] = 0;
if (outUseCrypt) *outUseCrypt=false;
bool bBookmark;
if (!mServerTreeView->GetSelectedServInfo(bBookmark, outName, outAddress))
return false;
if (bBookmark)
{
// add the ".hbm" to the file name
#if WIN32
pstrcat(outName, "\p.hbm");
#endif
StFileSysRef pBookmarkFile(kProgramFolder, "\pBookmarks", outName, fsOption_RequireExistingFile);
if (pBookmarkFile.IsValid())
gApp->ReadServerFile(pBookmarkFile, outAddress, outLogin, outPassword, outUseCrypt); //////////
// loose the ".hbm" from the file name
#if WIN32
outName[0] -= 4;
#endif
}
return true;
}
Uint32 CMyTracker::GetTrackerIndex(Uint16 inTrackerID)
{
Uint32 i = 0;
SMyServerInfo *pTrackInfo;
while (mServerTree.GetNext(pTrackInfo, i, true))
{
if (pTrackInfo->Flags == inTrackerID)
return i;
}
return 0;
}
SMyTrackerInfo *CMyTracker::GetTrackerInfo(Uint32 inTrakerIndex)
{
SMyTrackerInfo **array = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
if (inTrakerIndex >= 0 && inTrakerIndex < nCount)
return array[inTrakerIndex];
return nil;
}
SMyTrackerInfo *CMyTracker::GetTrackerInfoByID(Uint16 inTrackerID)
{
SMyTrackerInfo **array = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
for (Uint32 i = 0; i < nCount; i++)
if (array[i]->nTrackerID == inTrackerID)
return array[i];
return nil;
}
Uint32 CMyTracker::WritePrefs(TFSRefObj* inFile, Uint32 inOffset)
{
SMyTrackerInfo **array = mTrackerList.GetArrayPtr();
Uint32 nCount = mTrackerList.GetItemCount();
Uint32 nTotalSize = sizeof(Uint32) * 3 + sizeof(SRect)/2 + sizeof(Uint8) * 2 + sizeof(Uint32) * 2;
for (Uint32 i = 0; i < nCount; i++)
{
nTotalSize += array[i]->Login[0] + 1;
nTotalSize += array[i]->Pass[0] + 1;
nTotalSize += array[i]->Address[0] + 1;
nTotalSize += array[i]->Name[0] + 1;
nTotalSize += array[i]->Comments[0] + 1;
nTotalSize += sizeof(Uint16) * 2;
}
StPtr buf(nTotalSize);
CFlatten Flat(buf);
Uint32 nVerNumber = 3; // tracker list version number
Flat.WriteLong(nVerNumber);
Flat.WriteLong(gApp->GiveIconSet()); //write iconSet
//Flat.ReserveLong();
Flat.ReserveLong();
SRect stServerWinBounds;
mServerWin->GetBounds(stServerWinBounds);
Flat.WriteShortRect(stServerWinBounds);
Flat.ReserveByte();
Flat.WriteByte(mServerWin->IsVisible());
Flat.WriteLong(nTotalSize);
Flat.WriteLong(nCount);
for (Uint32 i = 0; i < nCount; i++)
{
Flat.WritePString(array[i]->Login);
Flat.WritePString(array[i]->Pass);
Flat.WritePString(array[i]->Address);
Flat.WritePString(array[i]->Name);
Flat.WritePString(array[i]->Comments);
Flat.WriteWord(array[i]->hasAccount);
Flat.ReserveWord();
}
//Flat.WriteLong(gApp->GiveIconSet());
//DebugBreak("%i",gApp->GiveIconSet());
nTotalSize = Flat.GetSize();
inFile->Write(inOffset, buf, nTotalSize);
return nTotalSize;
}
Uint32 CMyTracker::ReadPrefs(TFSRefObj* inFile, Uint32 inOffset, Uint16 inTabWidth1, Uint16 inTabWidth2, bool iconset)
{
if (iconset){
//DebugBreak("juste pour liconset");
//SMyTrackerInfo *pTrackerInfo2 = nil;
Uint32 nSize = inFile->GetSize() - inOffset;
Uint32 nTotalSize = sizeof(Uint32) * 3 + sizeof(SRect)/2 + sizeof(Uint8) * 2 + sizeof(Uint32) * 2;
StPtr buf(nSize);
nSize = inFile->Read(inOffset, buf, nSize);
CUnflatten unflat(buf, nSize);
if (unflat.NotEnufData(nTotalSize))
DebugBreak("je c pa");
unflat.SkipLong();
gApp->SetIconSet(unflat.ReadLong());
}else{
SMyTrackerInfo *pTrackerInfo = nil;
Uint32 nSize = inFile->GetSize() - inOffset;
Uint32 nTotalSize = sizeof(Uint32) * 3 + sizeof(SRect)/2 + sizeof(Uint8) * 2 + sizeof(Uint32) * 2;
StPtr buf(nSize);
nSize = inFile->Read(inOffset, buf, nSize);
CUnflatten unflat(buf, nSize);
if (unflat.NotEnufData(nTotalSize))
goto corrupt;
Uint32 nVerNumber = unflat.ReadLong();
if (nVerNumber != 3) // tracker list version number
goto corrupt;
unflat.SkipLong();
unflat.SkipLong();
SRect stServerWinBounds;
unflat.ReadShortRect(stServerWinBounds);
mServerWin->SetBounds(stServerWinBounds);
mServerWin->SetAutoBounds(windowPos_Best, windowPosOn_WinScreen);
mServerWin->GetServerTreeView()->SetTabs(inTabWidth1, inTabWidth2);
unflat.SkipByte();
mServerWin->SetVisible(unflat.ReadByte());
unflat.SkipLong();
Uint32 nCount = unflat.ReadLong();
for (Uint32 i = 0; i < nCount; i++)
{
pTrackerInfo = (SMyTrackerInfo *)UMemory::NewClear(sizeof(SMyTrackerInfo));
if (!unflat.ReadPString(pTrackerInfo->Login, 255)) goto corrupt;
if (!unflat.ReadPString(pTrackerInfo->Pass, 255)) goto corrupt;
if (!unflat.ReadPString(pTrackerInfo->Address, 255)) goto corrupt;
if (!unflat.ReadPString(pTrackerInfo->Name, 255)) goto corrupt;
if (!unflat.ReadPString(pTrackerInfo->Comments, 255)) goto corrupt;
pTrackerInfo->hasAccount = unflat.ReadWord();
unflat.SkipWord();
//Uint32 nCount = ;
//DebugBreak("On lit giveiconset avant de lire pref: %i",gApp->GiveIconSet());
//gApp->SetIconSet(unflat.ReadLong());
pTrackerInfo->nTrackerID = mLastTrackerID++;
nTotalSize += pTrackerInfo->Login[0] + pTrackerInfo->Pass[0] + pTrackerInfo->Address[0] + pTrackerInfo->Name[0] + pTrackerInfo->Comments[0] + 5;
nTotalSize += sizeof(Uint16) * 2;
mTrackerList.AddItem(pTrackerInfo);
pTrackerInfo = nil;
}
AddTrackersInTree();
return nTotalSize;
corrupt:
if (pTrackerInfo)
delete pTrackerInfo; // don't want any mem leaks
SetDefaultTracker();
}
return 0;
}
| [
"cmmeurin@gmail.com"
] | cmmeurin@gmail.com |
06ee8775cbb60cde162b9e8a8cbd524d24c74daa | 4cb66c880838633331e305fb88dd77561e53afd8 | /B_WeirdSort.cpp | 42f8f1195d7faf2b020a86f901df17365fdc9013 | [] | no_license | manav2727/CPP | b04fad680a0061ac81f212427e35a24f4ace006d | 60483ec298a83efb0fdf983e68d5ac72b839379e | refs/heads/master | 2023-09-03T03:05:27.548348 | 2021-11-15T02:41:53 | 2021-11-15T02:41:53 | 407,020,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,574 | cpp | #include<bits/stdc++.h>
using namespace std;
//DATATYPES AND DATASTRUCTURES DECLARATION
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef std::vector<ll> vll;
typedef std::vector<int> vii;
typedef std::vector<pll> vpll;
typedef std::vector<vll> vvll;
typedef map<ll,ll>mll;
typedef map<char,ll>mcll;
typedef map<ll,pll>mpll;
typedef set<ll> sll;
// int fact[1000006]={0};
//USEFUL MACROS
#define int long long
#define test ll t;cin>>t;while(t--)
#define var(n) ll n;cin>>n;
#define vars(s) string s;cin>>s;
#define inp(a,n) ll a[n];for(ll i = 0;i<n;i++) cin>>a[i];
#define inpv(a,n) vll a(n);for(ll i = 0;i<n;i++) cin>>a[i];
#define sz(a) a.size()
#define loop(i,a,n) for(ll i=a;i<n;i++)
#define loopr(i,a,n) for(ll i =n-1;i>=a;i--)
#define nl cout<<endl;
#define printarr(a) for(auto i : a) cout<<i<<' ';nl;
#define F first
#define S second
#define pb push_back
#define pqs priority_queue<ll,vll,greater<ll> >
#define setbits(x) __builtin_popcountll(x)
#define mod 1000000007
#define inf 1e18
#define dec(x) cout<<fixed<<setprecision(x)<<endl;
#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define minArr(a) *min_element(arr(a))
#define minVec(a) *min_element(vec(a))
#define maxArr(a) *max_element(arr(a))
#define maxVec(a) *max_element(vec(a))
//USEFUL FUNCTIONS
bool isPrime(ll n){if(n <= 1)return false;if(n <= 3)return true;if(n%2 == 0 || n%3 == 0)return false;for(ll i=5; i*i<=n; i=i+6)if(n%i == 0 || n%(i+2) == 0)return false;return true;}
ll nextPrime(ll N){if(N<=1)return 2;ll prime = N;bool found = false;while(!found){prime++;if(isPrime(prime))found=true;}return prime;}
ll cl(ll n,ll d){return (n+d-1)/d;}
ll gcd(ll a, ll b) {if (b == 0)return a; return gcd(b, a % b);}
ll lcm(ll a,ll b){return (a*b)/(gcd(a,b));}
void print(pll a){cout<<a.F<<' '<<a.S<<' ';nl;}
void print(ll a){cout<<a<<' ';nl}
void print(vll a){for(auto i : a)cout<<i<<' ';nl;}
void print(string s){cout<<s<<' ';nl;}
void printr(vll a,ll start,ll end){for(ll i =start;i<end;i++)cout<<a[i]<<' ';nl;}
void print(ll a,ll b){cout<<a<<' '<<b<<' ';}
ll madd(ll a,ll b){return ((a%mod)+(b%mod))%mod;}
ll mmul(ll a,ll b){return ((a%mod)*(b%mod))%mod;}
ll msub(ll a,ll b){return ((a%mod)-(b%mod)+mod)%mod;}
ll fpow(ll x,ll y,ll p=mod){x%=p;ll sum = 1;while(y){if (y & 1)sum = sum * x; sum %= p; y = y >> 1; x = x * x; x %= p;} return sum;}
bool isPerSquare(long double a) {if(a<0) return false; ll sr = sqrt(a); return (sr*sr == a);}
// void facto() {fact[0]=1;fact[1]=1;for(int i=2;i<1000006;i++)fact[i]=(fact[i-1]*i)%mod;}
string bin(ll n) {return bitset<64> (n).to_string();}
ll countBits( ll number) { return (ll)log2(number)+1;}
bool is(string temp){char c = temp[0]; string s((temp).size(),c); return s<=temp;}
// const ll N = 1e5+1;
void solve(){
var(n)var(m)
inp(arr,n)
inp(p,m)
sort(p,p+m);
for(ll j=0;j<n-1;j++)
{
ll f=0;
for(ll i=0;i<m;i++)
{
if(arr[p[i]-1]>arr[p[i]])
{
swap(arr[p[i]-1],arr[p[i]]);
}
}
for(ll i=0;i<n-1;i++)
{
if(arr[i]>arr[i+1])
{
f=1;
break;
}
}
if(f==0)
{
cout<<"YES\n";
return;
}
}
cout<<"NO\n";
}
signed main()
{
FIO;
test
solve();
} | [
"manavmajithia6@gmail.com"
] | manavmajithia6@gmail.com |
81cf388b7cf72d6de02be263efde217eeb340702 | 77591845b0be887b662ab4153a99ec0c1f162374 | /UVA/673 - Parentheses Balance.cpp | cdc75f8ac655fd87e116a66bc5e002c511248989 | [] | no_license | alexsotocx/competitive-programming | bce7d47cd088114fde86173e03624ee03a6eeccb | daa6056ef036744b5ab5933962a6ebbfc27ebf5d | refs/heads/master | 2020-05-16T21:41:51.261266 | 2015-01-29T02:46:08 | 2015-01-29T02:46:08 | 25,898,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 909 | cpp | #include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
using namespace std;
int main()
{
int n;
cin>>n;
getchar();
while(n--)
{
stack<char>b;
string s;
getline(cin,s);
int i;
bool xd = false, ok = true;
for(i=0; i<s.length(); i++)
{
if(s[i]==']' || s[i]==')')
{
if(!b.empty() &&((s[i]==']' && b.top()=='[') || (s[i]==')' && b.top()=='(')))
{
b.pop();
continue;
}
printf("No\n");
ok=false;
break;
}
if(s[i]=='[' || s[i]=='(')
b.push(s[i]);
}
if(b.empty() && i==s.length()) printf("Yes\n");
else if(!b.empty() && ok)printf("No\n");
}
return 0;
}
| [
"asoto@innventto.com"
] | asoto@innventto.com |
9b0369764dbd0ca8e809311b48977e2be6affaa9 | edaa018b9a74c843b082f5cddafb0ec3740170a1 | /Codeforces30DayTraining/StonesOnTheTable__266A.cpp | 2e06eca80d4610b0182d94b5be21de2169b33f4d | [] | no_license | m0saan/CP | e4eb6b363f68e82d59463281abdf5878188b324d | 88663bf32920403ae1ce4ba4529a8650ac42459a | refs/heads/master | 2023-06-07T13:19:42.217299 | 2021-07-04T19:16:57 | 2021-07-04T19:16:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | cpp | #include <iostream>
#include <string>
using namespace std;
int main() {
int n, ans{};
string S;
cin >> n >> S;
for (int i = 0; i < S.size(); ++i)
if (i + 1 < S.size() && S[i] == S[i + 1]) ans++;
cout << ans << endl;
return 0;
} | [
"moboustta6@gmail.com"
] | moboustta6@gmail.com |
9ebf80332590d851108de32ffea7a3c1d3dde933 | 4b6c931c05a3ac3426b35bcc8c94c6ac32c59bcf | /Dragon/src/protos/caffemodel.pb.cc | c77a916eda87a93dae9cb6e3839c4290ee7b1c3f | [
"BSD-2-Clause"
] | permissive | Junotja/Dragon | 9036f5acdaf24360d8d043f980dd20ce9a826e01 | 6eeac5fec58ed3d0d79f0b4003471e4a641c72f4 | refs/heads/master | 2021-06-22T08:42:46.629020 | 2017-08-26T15:23:14 | 2017-08-26T15:23:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 45,812 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: caffemodel.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "caffemodel.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace {
const ::google::protobuf::Descriptor* BlobShape_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
BlobShape_reflection_ = NULL;
const ::google::protobuf::Descriptor* BlobProto_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
BlobProto_reflection_ = NULL;
const ::google::protobuf::Descriptor* NetParameter_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
NetParameter_reflection_ = NULL;
const ::google::protobuf::Descriptor* LayerParameter_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
LayerParameter_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_caffemodel_2eproto() {
protobuf_AddDesc_caffemodel_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"caffemodel.proto");
GOOGLE_CHECK(file != NULL);
BlobShape_descriptor_ = file->message_type(0);
static const int BlobShape_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobShape, dim_),
};
BlobShape_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
BlobShape_descriptor_,
BlobShape::default_instance_,
BlobShape_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobShape, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobShape, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(BlobShape));
BlobProto_descriptor_ = file->message_type(1);
static const int BlobProto_offsets_[6] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, shape_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, data_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, num_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, channels_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, height_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, width_),
};
BlobProto_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
BlobProto_descriptor_,
BlobProto::default_instance_,
BlobProto_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BlobProto, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(BlobProto));
NetParameter_descriptor_ = file->message_type(2);
static const int NetParameter_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NetParameter, name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NetParameter, layer_),
};
NetParameter_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
NetParameter_descriptor_,
NetParameter::default_instance_,
NetParameter_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NetParameter, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NetParameter, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(NetParameter));
LayerParameter_descriptor_ = file->message_type(3);
static const int LayerParameter_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LayerParameter, name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LayerParameter, blobs_),
};
LayerParameter_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
LayerParameter_descriptor_,
LayerParameter::default_instance_,
LayerParameter_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LayerParameter, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LayerParameter, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(LayerParameter));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_caffemodel_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
BlobShape_descriptor_, &BlobShape::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
BlobProto_descriptor_, &BlobProto::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
NetParameter_descriptor_, &NetParameter::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
LayerParameter_descriptor_, &LayerParameter::default_instance());
}
} // namespace
void protobuf_ShutdownFile_caffemodel_2eproto() {
delete BlobShape::default_instance_;
delete BlobShape_reflection_;
delete BlobProto::default_instance_;
delete BlobProto_reflection_;
delete NetParameter::default_instance_;
delete NetParameter_reflection_;
delete LayerParameter::default_instance_;
delete LayerParameter_reflection_;
}
void protobuf_AddDesc_caffemodel_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\020caffemodel.proto\"\034\n\tBlobShape\022\017\n\003dim\030\001"
" \003(\003B\002\020\001\"\202\001\n\tBlobProto\022\031\n\005shape\030\007 \001(\0132\n."
"BlobShape\022\020\n\004data\030\005 \003(\002B\002\020\001\022\016\n\003num\030\001 \001(\005"
":\0010\022\023\n\010channels\030\002 \001(\005:\0010\022\021\n\006height\030\003 \001(\005"
":\0010\022\020\n\005width\030\004 \001(\005:\0010\"<\n\014NetParameter\022\014\n"
"\004name\030\001 \001(\t\022\036\n\005layer\030d \003(\0132\017.LayerParame"
"ter\"9\n\016LayerParameter\022\014\n\004name\030\001 \001(\t\022\031\n\005b"
"lobs\030\007 \003(\0132\n.BlobProto", 302);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"caffemodel.proto", &protobuf_RegisterTypes);
BlobShape::default_instance_ = new BlobShape();
BlobProto::default_instance_ = new BlobProto();
NetParameter::default_instance_ = new NetParameter();
LayerParameter::default_instance_ = new LayerParameter();
BlobShape::default_instance_->InitAsDefaultInstance();
BlobProto::default_instance_->InitAsDefaultInstance();
NetParameter::default_instance_->InitAsDefaultInstance();
LayerParameter::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_caffemodel_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_caffemodel_2eproto {
StaticDescriptorInitializer_caffemodel_2eproto() {
protobuf_AddDesc_caffemodel_2eproto();
}
} static_descriptor_initializer_caffemodel_2eproto_;
// ===================================================================
#ifndef _MSC_VER
const int BlobShape::kDimFieldNumber;
#endif // !_MSC_VER
BlobShape::BlobShape()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:BlobShape)
}
void BlobShape::InitAsDefaultInstance() {
}
BlobShape::BlobShape(const BlobShape& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:BlobShape)
}
void BlobShape::SharedCtor() {
_cached_size_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
BlobShape::~BlobShape() {
// @@protoc_insertion_point(destructor:BlobShape)
SharedDtor();
}
void BlobShape::SharedDtor() {
if (this != default_instance_) {
}
}
void BlobShape::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BlobShape::descriptor() {
protobuf_AssignDescriptorsOnce();
return BlobShape_descriptor_;
}
const BlobShape& BlobShape::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_caffemodel_2eproto();
return *default_instance_;
}
BlobShape* BlobShape::default_instance_ = NULL;
BlobShape* BlobShape::New() const {
return new BlobShape;
}
void BlobShape::Clear() {
dim_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool BlobShape::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:BlobShape)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int64 dim = 1 [packed = true];
case 1: {
if (tag == 10) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, this->mutable_dim())));
} else if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
1, 10, input, this->mutable_dim())));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:BlobShape)
return true;
failure:
// @@protoc_insertion_point(parse_failure:BlobShape)
return false;
#undef DO_
}
void BlobShape::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:BlobShape)
// repeated int64 dim = 1 [packed = true];
if (this->dim_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_dim_cached_byte_size_);
}
for (int i = 0; i < this->dim_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteInt64NoTag(
this->dim(i), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:BlobShape)
}
::google::protobuf::uint8* BlobShape::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:BlobShape)
// repeated int64 dim = 1 [packed = true];
if (this->dim_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_dim_cached_byte_size_, target);
}
for (int i = 0; i < this->dim_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteInt64NoTagToArray(this->dim(i), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:BlobShape)
return target;
}
int BlobShape::ByteSize() const {
int total_size = 0;
// repeated int64 dim = 1 [packed = true];
{
int data_size = 0;
for (int i = 0; i < this->dim_size(); i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int64Size(this->dim(i));
}
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_dim_cached_byte_size_ = data_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BlobShape::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const BlobShape* source =
::google::protobuf::internal::dynamic_cast_if_available<const BlobShape*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void BlobShape::MergeFrom(const BlobShape& from) {
GOOGLE_CHECK_NE(&from, this);
dim_.MergeFrom(from.dim_);
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void BlobShape::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BlobShape::CopyFrom(const BlobShape& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BlobShape::IsInitialized() const {
return true;
}
void BlobShape::Swap(BlobShape* other) {
if (other != this) {
dim_.Swap(&other->dim_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata BlobShape::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = BlobShape_descriptor_;
metadata.reflection = BlobShape_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int BlobProto::kShapeFieldNumber;
const int BlobProto::kDataFieldNumber;
const int BlobProto::kNumFieldNumber;
const int BlobProto::kChannelsFieldNumber;
const int BlobProto::kHeightFieldNumber;
const int BlobProto::kWidthFieldNumber;
#endif // !_MSC_VER
BlobProto::BlobProto()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:BlobProto)
}
void BlobProto::InitAsDefaultInstance() {
shape_ = const_cast< ::BlobShape*>(&::BlobShape::default_instance());
}
BlobProto::BlobProto(const BlobProto& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:BlobProto)
}
void BlobProto::SharedCtor() {
_cached_size_ = 0;
shape_ = NULL;
num_ = 0;
channels_ = 0;
height_ = 0;
width_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
BlobProto::~BlobProto() {
// @@protoc_insertion_point(destructor:BlobProto)
SharedDtor();
}
void BlobProto::SharedDtor() {
if (this != default_instance_) {
delete shape_;
}
}
void BlobProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BlobProto::descriptor() {
protobuf_AssignDescriptorsOnce();
return BlobProto_descriptor_;
}
const BlobProto& BlobProto::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_caffemodel_2eproto();
return *default_instance_;
}
BlobProto* BlobProto::default_instance_ = NULL;
BlobProto* BlobProto::New() const {
return new BlobProto;
}
void BlobProto::Clear() {
#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \
&reinterpret_cast<BlobProto*>(16)->f) - \
reinterpret_cast<char*>(16))
#define ZR_(first, last) do { \
size_t f = OFFSET_OF_FIELD_(first); \
size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
::memset(&first, 0, n); \
} while (0)
if (_has_bits_[0 / 32] & 61) {
ZR_(num_, width_);
if (has_shape()) {
if (shape_ != NULL) shape_->::BlobShape::Clear();
}
}
#undef OFFSET_OF_FIELD_
#undef ZR_
data_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool BlobProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:BlobProto)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 num = 1 [default = 0];
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &num_)));
set_has_num();
} else {
goto handle_unusual;
}
if (input->ExpectTag(16)) goto parse_channels;
break;
}
// optional int32 channels = 2 [default = 0];
case 2: {
if (tag == 16) {
parse_channels:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &channels_)));
set_has_channels();
} else {
goto handle_unusual;
}
if (input->ExpectTag(24)) goto parse_height;
break;
}
// optional int32 height = 3 [default = 0];
case 3: {
if (tag == 24) {
parse_height:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &height_)));
set_has_height();
} else {
goto handle_unusual;
}
if (input->ExpectTag(32)) goto parse_width;
break;
}
// optional int32 width = 4 [default = 0];
case 4: {
if (tag == 32) {
parse_width:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &width_)));
set_has_width();
} else {
goto handle_unusual;
}
if (input->ExpectTag(42)) goto parse_data;
break;
}
// repeated float data = 5 [packed = true];
case 5: {
if (tag == 42) {
parse_data:
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, this->mutable_data())));
} else if (tag == 45) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
1, 42, input, this->mutable_data())));
} else {
goto handle_unusual;
}
if (input->ExpectTag(58)) goto parse_shape;
break;
}
// optional .BlobShape shape = 7;
case 7: {
if (tag == 58) {
parse_shape:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_shape()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:BlobProto)
return true;
failure:
// @@protoc_insertion_point(parse_failure:BlobProto)
return false;
#undef DO_
}
void BlobProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:BlobProto)
// optional int32 num = 1 [default = 0];
if (has_num()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->num(), output);
}
// optional int32 channels = 2 [default = 0];
if (has_channels()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->channels(), output);
}
// optional int32 height = 3 [default = 0];
if (has_height()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->height(), output);
}
// optional int32 width = 4 [default = 0];
if (has_width()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->width(), output);
}
// repeated float data = 5 [packed = true];
if (this->data_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(5, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_data_cached_byte_size_);
}
for (int i = 0; i < this->data_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteFloatNoTag(
this->data(i), output);
}
// optional .BlobShape shape = 7;
if (has_shape()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, this->shape(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:BlobProto)
}
::google::protobuf::uint8* BlobProto::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:BlobProto)
// optional int32 num = 1 [default = 0];
if (has_num()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->num(), target);
}
// optional int32 channels = 2 [default = 0];
if (has_channels()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->channels(), target);
}
// optional int32 height = 3 [default = 0];
if (has_height()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->height(), target);
}
// optional int32 width = 4 [default = 0];
if (has_width()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->width(), target);
}
// repeated float data = 5 [packed = true];
if (this->data_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
5,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_data_cached_byte_size_, target);
}
for (int i = 0; i < this->data_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteFloatNoTagToArray(this->data(i), target);
}
// optional .BlobShape shape = 7;
if (has_shape()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
7, this->shape(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:BlobProto)
return target;
}
int BlobProto::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional .BlobShape shape = 7;
if (has_shape()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->shape());
}
// optional int32 num = 1 [default = 0];
if (has_num()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->num());
}
// optional int32 channels = 2 [default = 0];
if (has_channels()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->channels());
}
// optional int32 height = 3 [default = 0];
if (has_height()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->height());
}
// optional int32 width = 4 [default = 0];
if (has_width()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->width());
}
}
// repeated float data = 5 [packed = true];
{
int data_size = 0;
data_size = 4 * this->data_size();
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_data_cached_byte_size_ = data_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BlobProto::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const BlobProto* source =
::google::protobuf::internal::dynamic_cast_if_available<const BlobProto*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void BlobProto::MergeFrom(const BlobProto& from) {
GOOGLE_CHECK_NE(&from, this);
data_.MergeFrom(from.data_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_shape()) {
mutable_shape()->::BlobShape::MergeFrom(from.shape());
}
if (from.has_num()) {
set_num(from.num());
}
if (from.has_channels()) {
set_channels(from.channels());
}
if (from.has_height()) {
set_height(from.height());
}
if (from.has_width()) {
set_width(from.width());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void BlobProto::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BlobProto::CopyFrom(const BlobProto& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BlobProto::IsInitialized() const {
return true;
}
void BlobProto::Swap(BlobProto* other) {
if (other != this) {
std::swap(shape_, other->shape_);
data_.Swap(&other->data_);
std::swap(num_, other->num_);
std::swap(channels_, other->channels_);
std::swap(height_, other->height_);
std::swap(width_, other->width_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata BlobProto::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = BlobProto_descriptor_;
metadata.reflection = BlobProto_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int NetParameter::kNameFieldNumber;
const int NetParameter::kLayerFieldNumber;
#endif // !_MSC_VER
NetParameter::NetParameter()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:NetParameter)
}
void NetParameter::InitAsDefaultInstance() {
}
NetParameter::NetParameter(const NetParameter& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:NetParameter)
}
void NetParameter::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
NetParameter::~NetParameter() {
// @@protoc_insertion_point(destructor:NetParameter)
SharedDtor();
}
void NetParameter::SharedDtor() {
if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete name_;
}
if (this != default_instance_) {
}
}
void NetParameter::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* NetParameter::descriptor() {
protobuf_AssignDescriptorsOnce();
return NetParameter_descriptor_;
}
const NetParameter& NetParameter::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_caffemodel_2eproto();
return *default_instance_;
}
NetParameter* NetParameter::default_instance_ = NULL;
NetParameter* NetParameter::New() const {
return new NetParameter;
}
void NetParameter::Clear() {
if (has_name()) {
if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
name_->clear();
}
}
layer_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool NetParameter::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:NetParameter)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(16383);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::PARSE,
"name");
} else {
goto handle_unusual;
}
if (input->ExpectTag(802)) goto parse_layer;
break;
}
// repeated .LayerParameter layer = 100;
case 100: {
if (tag == 802) {
parse_layer:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_layer()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(802)) goto parse_layer;
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:NetParameter)
return true;
failure:
// @@protoc_insertion_point(parse_failure:NetParameter)
return false;
#undef DO_
}
void NetParameter::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:NetParameter)
// optional string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// repeated .LayerParameter layer = 100;
for (int i = 0; i < this->layer_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
100, this->layer(i), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:NetParameter)
}
::google::protobuf::uint8* NetParameter::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:NetParameter)
// optional string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// repeated .LayerParameter layer = 100;
for (int i = 0; i < this->layer_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
100, this->layer(i), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:NetParameter)
return target;
}
int NetParameter::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional string name = 1;
if (has_name()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
}
// repeated .LayerParameter layer = 100;
total_size += 2 * this->layer_size();
for (int i = 0; i < this->layer_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->layer(i));
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void NetParameter::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const NetParameter* source =
::google::protobuf::internal::dynamic_cast_if_available<const NetParameter*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void NetParameter::MergeFrom(const NetParameter& from) {
GOOGLE_CHECK_NE(&from, this);
layer_.MergeFrom(from.layer_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_name(from.name());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void NetParameter::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void NetParameter::CopyFrom(const NetParameter& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool NetParameter::IsInitialized() const {
return true;
}
void NetParameter::Swap(NetParameter* other) {
if (other != this) {
std::swap(name_, other->name_);
layer_.Swap(&other->layer_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata NetParameter::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = NetParameter_descriptor_;
metadata.reflection = NetParameter_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int LayerParameter::kNameFieldNumber;
const int LayerParameter::kBlobsFieldNumber;
#endif // !_MSC_VER
LayerParameter::LayerParameter()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:LayerParameter)
}
void LayerParameter::InitAsDefaultInstance() {
}
LayerParameter::LayerParameter(const LayerParameter& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:LayerParameter)
}
void LayerParameter::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
LayerParameter::~LayerParameter() {
// @@protoc_insertion_point(destructor:LayerParameter)
SharedDtor();
}
void LayerParameter::SharedDtor() {
if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete name_;
}
if (this != default_instance_) {
}
}
void LayerParameter::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* LayerParameter::descriptor() {
protobuf_AssignDescriptorsOnce();
return LayerParameter_descriptor_;
}
const LayerParameter& LayerParameter::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_caffemodel_2eproto();
return *default_instance_;
}
LayerParameter* LayerParameter::default_instance_ = NULL;
LayerParameter* LayerParameter::New() const {
return new LayerParameter;
}
void LayerParameter::Clear() {
if (has_name()) {
if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
name_->clear();
}
}
blobs_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool LayerParameter::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:LayerParameter)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::PARSE,
"name");
} else {
goto handle_unusual;
}
if (input->ExpectTag(58)) goto parse_blobs;
break;
}
// repeated .BlobProto blobs = 7;
case 7: {
if (tag == 58) {
parse_blobs:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_blobs()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(58)) goto parse_blobs;
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:LayerParameter)
return true;
failure:
// @@protoc_insertion_point(parse_failure:LayerParameter)
return false;
#undef DO_
}
void LayerParameter::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:LayerParameter)
// optional string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// repeated .BlobProto blobs = 7;
for (int i = 0; i < this->blobs_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, this->blobs(i), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:LayerParameter)
}
::google::protobuf::uint8* LayerParameter::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:LayerParameter)
// optional string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// repeated .BlobProto blobs = 7;
for (int i = 0; i < this->blobs_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
7, this->blobs(i), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:LayerParameter)
return target;
}
int LayerParameter::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional string name = 1;
if (has_name()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
}
// repeated .BlobProto blobs = 7;
total_size += 1 * this->blobs_size();
for (int i = 0; i < this->blobs_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->blobs(i));
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void LayerParameter::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const LayerParameter* source =
::google::protobuf::internal::dynamic_cast_if_available<const LayerParameter*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void LayerParameter::MergeFrom(const LayerParameter& from) {
GOOGLE_CHECK_NE(&from, this);
blobs_.MergeFrom(from.blobs_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_name(from.name());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void LayerParameter::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LayerParameter::CopyFrom(const LayerParameter& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LayerParameter::IsInitialized() const {
return true;
}
void LayerParameter::Swap(LayerParameter* other) {
if (other != this) {
std::swap(name_, other->name_);
blobs_.Swap(&other->blobs_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata LayerParameter::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = LayerParameter_descriptor_;
metadata.reflection = LayerParameter_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
// @@protoc_insertion_point(global_scope)
| [
"ting.pan@seetatech.com"
] | ting.pan@seetatech.com |
985697e3728dcddfcf3ab2b946b90a28dfc4d015 | 001bd2245fa3f2adc414f68b8b26b07ce6f36625 | /source/WorldServer/Trade.cpp | 754968645826fb18fc15636a29d9fe0eee3fe544 | [] | no_license | lxq2537664558/world | 65e6d61ff0ba6e60b2c30db9fd41339c36b46909 | 576b7017e549caafdbeb5a1eb2a773d5d0c4f5f1 | refs/heads/master | 2020-03-31T08:06:33.642713 | 2018-10-08T06:43:10 | 2018-10-08T06:43:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,280 | cpp | #include "Trade.h"
#include "Items/Items.h"
#include "Entity.h"
#include "Bots/Bot.h"
#include "../common/Log.h"
#include "zoneserver.h"
extern ConfigReader configReader;
extern MasterItemList master_item_list;
Trade::Trade(Entity* trader1, Entity* trader2) {
this->trader1 = trader1;
this->trader2 = trader2;
trader1_accepted = false;
trader2_accepted = false;
trader1_coins = 0;
trader2_coins = 0;
OpenTradeWindow();
}
Trade::~Trade() {
}
int8 Trade::AddItemToTrade(Entity* character, Item* item, int8 quantity, int8 slot) {
LogWrite(PLAYER__ERROR, 0, "Trade", "Player (%s) adding item (%u) to slot %u of the trade window", character->GetName(), item->details.item_id, slot);
if (slot == 255)
slot = GetNextFreeSlot(character);
if (slot < 0 || slot > 11) {
LogWrite(PLAYER__ERROR, 0, "Trade", "Player (%s) tried to add an item to an invalid trade slot (%u)", character->GetName(), slot);
return 255;
}
Entity* other = GetTradee(character);
int8 result = CheckItem(character, item, other->IsBot());
if (result == 0) {
if (character == trader1) {
Trader1ItemAdd(item, quantity, slot);
// Only trader2 can be a bot so only
// need to do the bot check here
if (trader2->IsBot()) {
((Bot*)trader2)->TradeItemAdded(item);
}
}
else if (character == trader2)
Trader2ItemAdd(item, quantity, slot);
else {
LogWrite(PLAYER__ERROR, 0, "Trade", "Player (%s) tried to add an item to a trade but was neither trader1 or trader2", character->GetName());
return 255;
}
}
SendTradePacket();
return result;
}
int8 Trade::CheckItem(Entity* trader, Item* item, bool other_is_bot) {
int8 ret = 0;
map<int8, TradeItemInfo>* list = 0;
map<int8, TradeItemInfo>::iterator itr;
Entity* other = GetTradee(trader);
if (trader == trader1)
list = &trader1_items;
else if (trader == trader2)
list = &trader2_items;
if (list) {
if (trader->IsPlayer()) {
// Check to see if the item is already in the trade
for (itr = list->begin(); itr != list->end(); itr++) {
if (itr->second.item->details.unique_id == item->details.unique_id) {
ret = 1;
break;
}
}
// Only allow heirloom and no-trade items to be traded with a bot
if (!other_is_bot) {
if (item->CheckFlag(NO_TRADE))
ret = 2;
if (item->CheckFlag2(HEIRLOOM))
ret = 3;
if (item->CheckFlag(LORE) && other->IsPlayer() && static_cast<Player*>(other)->HasItem(item->details.item_id, true))
ret = 4;
}
}
}
return ret;
}
void Trade::RemoveItemFromTrade(Entity* character, int8 slot) {
map<int8, TradeItemInfo>* list = 0;
if (character == trader1)
list = &trader1_items;
else if (character == trader2)
list = &trader2_items;
if (list) {
if (list->count(slot) > 0) {
list->erase(slot);
SendTradePacket();
}
else
LogWrite(PLAYER__ERROR, 0, "Trade", "Player (%s) tried to remove an item from a trade slot that was empty ", character->GetName());
}
}
void Trade::AddCoinToTrade(Entity* character, int64 amount) {
if (!character->IsPlayer())
return;
if (character == trader1) {
trader1_coins += amount;
if (!((Player*)character)->HasCoins(trader1_coins)) {
trader1_coins -= amount;
LogWrite(PLAYER__ERROR, 0, "Trade", "Player (%s) tried to add more coins then they had ", character->GetName());
}
}
else if (character == trader2) {
trader2_coins += amount;
if (!((Player*)character)->HasCoins(trader2_coins)) {
trader2_coins -= amount;
LogWrite(PLAYER__ERROR, 0, "Trade", "Player (%s) tried to add more coins then they had ", character->GetName());
}
}
SendTradePacket();
}
void Trade::RemoveCoinFromTrade(Entity* character, int64 amount) {
if (character == trader1)
trader1_coins = (amount >= trader1_coins) ? 0 : trader1_coins - amount;
else if (character == trader2)
trader2_coins = (amount >= trader2_coins) ? 0 : trader2_coins - amount;
SendTradePacket();
}
Entity* Trade::GetTradee(Entity* character) {
if (character == trader1)
return trader2;
else if (character == trader2)
return trader1;
return 0;
}
bool Trade::SetTradeAccepted(Entity* character) {
if (character == trader1)
trader1_accepted = true;
else if (character == trader2)
trader2_accepted = true;
else
return false;
Entity* other = GetTradee(character);
if (other) {
if (other->IsPlayer()) {
shared_ptr<Client> client = other->GetZone()->GetClientBySpawn(other);
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(character));
packet->setDataByName("type", 16);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
else if (other->IsBot()) {
shared_ptr<Client> client = character->GetZone()->GetClientBySpawn(character);
if (trader1_coins > 0) {
CancelTrade(other);
if (client)
client->SimpleMessage(CHANNEL_ERROR, "Bots can't take coins so the trade was canceled.");
return true;
}
else {
if (!((Bot*)other)->CheckTradeItems(&trader1_items)) {
CancelTrade(other);
if (client)
client->SimpleMessage(CHANNEL_ERROR, "There was an item the bot could not equip so the trade was canceled.");
return true;
}
else
trader2_accepted = true;
}
}
if (HasAcceptedTrade(other)) {
CompleteTrade();
return true;
}
}
return false;
}
bool Trade::HasAcceptedTrade(Entity* character) {
if (character == trader1)
return trader1_accepted;
else if (character == trader2)
return trader2_accepted;
return false;
}
void Trade::CancelTrade(Entity* character) {
Entity* other = GetTradee(character);
if (other){
if (other->IsPlayer()) {
shared_ptr<Client> client = other->GetZone()->GetClientBySpawn(other);
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(character));
packet->setDataByName("type", 2);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
else if (other->IsBot())
((Bot*)other)->FinishTrade();
}
trader1->trade = 0;
trader2->trade = 0;
}
void Trade::Trader1ItemAdd(Item* item, int8 quantity, int8 slot) {
trader1_items[slot].item = item;
trader1_items[slot].quantity = quantity;
}
void Trade::Trader2ItemAdd(Item* item, int8 quantity, int8 slot) {
trader2_items[slot].item = item;
trader2_items[slot].quantity = quantity;
}
void Trade::CompleteTrade() {
map<int8, TradeItemInfo>::iterator itr;
map<int32, int8> trader1_item_ids;
map<int32, int8>::iterator itr2;
string log_string = "TradeComplete:\n";
if (trader1->IsPlayer()) {
Player* player = (Player*)trader1;
shared_ptr<Client> client = player->GetZone()->GetClientBySpawn(player);
if (client) {
log_string += "Trader1 = ";
log_string += trader1->GetName();
log_string += "(" + to_string(client->GetCharacterID()) + ")\n";
log_string += "Coins: " + to_string(trader1_coins) + "\n";
log_string += "Items:\n";
player->RemoveCoins(trader1_coins);
for (itr = trader1_items.begin(); itr != trader1_items.end(); itr++) {
// client->RemoveItem can delete the item so we need to store the item id's and quantity to give to trader2
trader1_item_ids[itr->second.item->details.item_id] = itr->second.quantity;
log_string += itr->second.item->name + " (" + to_string(itr->second.item->details.item_id) + ") x" + to_string(itr->second.quantity) + "\n";
client->RemoveItem(itr->second.item, itr->second.quantity);
}
player->AddCoins(trader2_coins);
for (itr = trader2_items.begin(); itr != trader2_items.end(); itr++) {
client->AddItem(itr->second.item->details.item_id, itr->second.quantity);
}
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(trader2));
packet->setDataByName("type", 24);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
}
// trader1 is the player who starts the trade, will never be a bot, if trader1 is not a player something went horribly wrong.
if (trader2->IsPlayer()) {
Player* player = (Player*)trader2;
shared_ptr<Client> client = player->GetZone()->GetClientBySpawn(player);
if (client) {
log_string += "Trader2 = ";
log_string += trader2->GetName();
log_string += "(" + to_string(client->GetCharacterID()) + ")\n";
log_string += "Coins: " + to_string(trader2_coins) + "\n";
log_string += "Items:\n";
player->RemoveCoins(trader2_coins);
for (itr = trader2_items.begin(); itr != trader2_items.end(); itr++) {
log_string += itr->second.item->name + " (" + to_string(itr->second.item->details.item_id) + ") x" + to_string(itr->second.quantity) + "\n";
client->RemoveItem(itr->second.item, itr->second.quantity);
}
player->AddCoins(trader1_coins);
for (itr2 = trader1_item_ids.begin(); itr2 != trader1_item_ids.end(); itr2++) {
client->AddItem(itr2->first, itr2->second);
}
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(trader1));
packet->setDataByName("type", 24);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
}
else if (trader2->IsBot()) {
Bot* bot = (Bot*)trader2;
log_string += "Trader2 is a bot";
for (itr = trader2_items.begin(); itr != trader2_items.end(); itr++) {
bot->RemoveItem(itr->second.item);
}
for (itr2 = trader1_item_ids.begin(); itr2 != trader1_item_ids.end(); itr2++) {
bot->GiveItem(itr2->first);
}
bot->FinishTrade();
}
LogWrite(PLAYER__INFO, 0, "Trade", log_string.c_str());
trader1->trade = 0;
trader2->trade = 0;
}
void Trade::OpenTradeWindow() {
if (trader1->IsPlayer()) {
shared_ptr<Client> client = trader1->GetZone()->GetClientBySpawn(trader1);
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(trader2));
packet->setDataByName("type", 1);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
if (trader2->IsPlayer()) {
shared_ptr<Client> client = trader2->GetZone()->GetClientBySpawn(trader2);
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(trader1));
packet->setDataByName("type", 1);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
}
void Trade::SendTradePacket() {
if (trader1->IsPlayer()) {
shared_ptr<Client> client = trader1->GetZone()->GetClientBySpawn(trader1);
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(trader2));
packet->setDataByName("type", 1);
int8 size = (int8)(trader1_items.size());
int8 i = 0;
map<int8, TradeItemInfo>::iterator itr;
packet->setArrayLengthByName("your_item_count", size);
for (itr = trader1_items.begin(); itr != trader1_items.end(); itr++) {
packet->setArrayDataByName("your_item_unknown1", 1, i);
packet->setArrayDataByName("your_item_unknown2", 1, i);
packet->setArrayDataByName("your_item_slot", itr->first, i);
packet->setArrayDataByName("your_item_id", itr->second.item->details.item_id, i);
packet->setArrayDataByName("your_item_quantity", itr->second.quantity, i);
packet->setArrayDataByName("your_item_icon", itr->second.item->details.icon, i);
packet->setArrayDataByName("your_item_background", 0, i); // No clue on this value yet
i++;
}
int32 plat = 0;
int32 gold = 0;
int32 silver = 0;
int32 copper = 0;
CalculateCoins(trader1_coins, plat, gold, silver, copper);
packet->setDataByName("your_copper", copper);
packet->setDataByName("your_silver", silver);
packet->setDataByName("your_gold", gold);
packet->setDataByName("your_plat", plat);
size = (int8)(trader2_items.size());
i = 0;
packet->setArrayLengthByName("their_item_count", size);
for (itr = trader2_items.begin(); itr != trader2_items.end(); itr++) {
packet->setArrayDataByName("their_item_unknown1", 1, i);
packet->setArrayDataByName("their_item_unknown2", 1, i);
packet->setArrayDataByName("their_item_slot", itr->first, i);
packet->setArrayDataByName("their_item_id", itr->second.item->details.item_id, i);
packet->setArrayDataByName("their_item_quantity", itr->second.quantity, i);
packet->setArrayDataByName("their_item_icon", itr->second.item->details.icon, i);
packet->setArrayDataByName("their_item_background", 0, i); // No clue on this value yet
i++;
}
plat = 0;
gold = 0;
silver = 0;
copper = 0;
CalculateCoins(trader2_coins, plat, gold, silver, copper);
packet->setDataByName("their_copper", copper);
packet->setDataByName("their_silver", silver);
packet->setDataByName("their_gold", gold);
packet->setDataByName("their_plat", plat);
LogWrite(PLAYER__ERROR, 0, "Trade", "packet sent");
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
if (trader2->IsPlayer()) {
shared_ptr<Client> client = trader2->GetZone()->GetClientBySpawn(trader2);
PacketStruct* packet = configReader.getStruct("WS_PlayerTrade", client->GetVersion());
if (packet) {
packet->setDataByName("spawn_id", client->GetPlayer()->GetIDWithPlayerSpawn(trader1));
packet->setDataByName("type", 1);
int8 size = (int8)(trader2_items.size());
int8 i = 0;
map<int8, TradeItemInfo>::iterator itr;
packet->setArrayLengthByName("your_item_count", size);
for (itr = trader2_items.begin(); itr != trader2_items.end(); itr++) {
packet->setArrayDataByName("your_item_unknown1", 1, i);
packet->setArrayDataByName("your_item_unknown2", 1, i);
packet->setArrayDataByName("your_item_slot", itr->first, i);
packet->setArrayDataByName("your_item_id", itr->second.item->details.item_id, i);
packet->setArrayDataByName("your_item_quantity", itr->second.quantity, i);
packet->setArrayDataByName("your_item_icon", itr->second.item->details.icon, i);
packet->setArrayDataByName("your_item_background", 0, i); // No clue on this value yet
i++;
}
int32 plat = 0;
int32 gold = 0;
int32 silver = 0;
int32 copper = 0;
CalculateCoins(trader2_coins, plat, gold, silver, copper);
packet->setDataByName("your_copper", copper);
packet->setDataByName("your_silver", silver);
packet->setDataByName("your_gold", gold);
packet->setDataByName("your_plat", plat);
size = (int8)(trader1_items.size());
i = 0;
packet->setArrayLengthByName("their_item_count", size);
for (itr = trader1_items.begin(); itr != trader1_items.end(); itr++) {
packet->setArrayDataByName("their_item_unknown1", 1, i);
packet->setArrayDataByName("their_item_unknown2", 1, i);
packet->setArrayDataByName("their_item_slot", itr->first, i);
packet->setArrayDataByName("their_item_id", itr->second.item->details.item_id, i);
packet->setArrayDataByName("their_item_quantity", itr->second.quantity, i);
packet->setArrayDataByName("their_item_icon", itr->second.item->details.icon, i);
packet->setArrayDataByName("their_item_background", 0, i); // No clue on this value yet
i++;
}
plat = 0;
gold = 0;
silver = 0;
copper = 0;
CalculateCoins(trader1_coins, plat, gold, silver, copper);
packet->setDataByName("their_copper", copper);
packet->setDataByName("their_silver", silver);
packet->setDataByName("their_gold", gold);
packet->setDataByName("their_plat", plat);
client->QueuePacket(packet->serialize());
safe_delete(packet);
}
}
}
void Trade::CalculateCoins(int64 val, int32& plat, int32& gold, int32& silver, int32& copper) {
int32 tmp = 0;
if (val >= 1000000) {
tmp = val / 1000000;
val -= tmp * 1000000;
plat = tmp;
}
if (val >= 10000) {
tmp = val / 10000;
val -= tmp * 10000;
gold = tmp;
}
if (val >= 100) {
tmp = val / 100;
val -= tmp * 100;
silver = tmp;
}
if (val > 0) {
copper = val;
}
}
int8 Trade::GetNextFreeSlot(Entity* character) {
map<int8, TradeItemInfo>* list = 0;
if (character == trader1)
list = &trader1_items;
else if (character == trader2)
list = &trader2_items;
else
return 255;
int8 ret = 255;
for (int8 index = 0; index < 12; index++) {
if (list->count(index) == 0) {
ret = index;
break;
}
}
return ret;
}
| [
"jon@tyrbo.net"
] | jon@tyrbo.net |
d4d398d9a81c1cfbbbf5b78db4f3a85d784c1c30 | ad572d5ce0be185edc0e4066f55eac78c8970d2c | /src/client/widgets/DialogManager.hpp | aba8976fec270a65af8c026610345504bc744b28 | [
"MIT"
] | permissive | AzariasB/MultiPlayerPong | 086f4b1292d482b851c31457a42ff189c1af9326 | 4b9af38198945b31b05ca83acadccef333e32284 | refs/heads/master | 2021-06-23T13:41:55.204845 | 2019-05-09T04:35:55 | 2019-05-09T04:35:55 | 108,720,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,746 | hpp | /*
* The MIT License
*
* Copyright 2017-2019 azarias.
*
* 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.
*/
/*
* File: DialogManager.hpp
* Author: azarias
*
* Created on 29/3/2018
*/
#pragma once
#include <map>
#include "Widget.hpp"
#include "Dialog.hpp"
#include "src/client/Provider.hpp"
namespace mp {
/**
* @brief The DialogManager class
* class used to handle the dialogs during
* the game.
* The dialogs are not really part of any
* stage or state. They have their own states
* this is managed by the dialogmanager, it
* can be used to show hide different types
* of dialogs
*/
class DialogManager : public Widget
{
public:
/**
* @brief DialogManager constructor
*/
DialogManager();
/**
* @brief draw draws all the visible dialogs
* @param renderer renderer to use
*/
void render(Renderer &renderer) const override;
/**
* @brief handleEvent perform the event on the current dialog
* @param ev event to handle
*/
bool handleEvent(const sf::Event &ev) override;
/**
* @brief update updates all the visible dialogs
* @param elapsed time
*/
bool update(const sf::Time &elapsed) override;
/**
* @brief isActiveDialog checks wether the given dialog is the active dialog
* @param dialogId dialog's id to check
* @return if the given id is the active dialog
*/
bool isActiveDialog(const sf::Uint64 &dialogId);
/**
* @brief hasDialog returns if this dialog is currently existing
* (hiding, showing, visible, ... whatever)
* @param dialogId the id of the dialog to check
* @return if the dialog exists
*/
bool hasDialog(const sf::Uint64 &dialogId) const;
/**
* @brief hasActiveDialogs
* @return wether they are any active dialogs
*/
bool hasActiveDialogs() const;
/**
* @brief hideDialog hides the dialog with the given id
* @param dialogId id of the dialog to hide
* if the dialog does not exist or is already hidden/hiding,
* will do nothing
*/
void hideDialog(sf::Uint64 dialogId);
/**
* @brief input creates an input dialog (a dialog with a simple text input)
* @param title the title of the dialog
* @param question the question to show
* @return a reference to the created dialog
*/
DialogInput &input(const sf::String &title, const sf::String &question);
/**
* @brief message create a message dialog (showing a simple message)
* @param title title of the dialog
* @param message message to show
* @return a reference to the created message dialog
*/
DialogMessage &message(const sf::String &title, const sf::String & message);
/**
* @brief question creates a yes-no question dialog
* @param title the title of the dialog
* @param question the question to show
* @return a reference to the created dialogquestion
*/
DialogQuestion &question(const sf::String &title, const sf::String &question);
~DialogManager() override;
private:
/**
* @brief m_idGenerator used to generate the id of the dialogs
*/
sf::Uint64 m_idGenerator = 0;
/**
* @brief m_activeDialogId id of the active dialog
* 0 means no active dialog
*/
sf::Uint64 m_activeDialogId = 0;
/**
* @brief m_dialogs map containing all the created dialogs
* they are either showing, shown, hiding or hidden
* otherwise they should be destroyed
* A unique_ptr is used because Dialog is an abstract class
*/
std::map<sf::Uint64, std::unique_ptr<Dialog>> m_dialogs;
/**
* @brief removeDialog remves the dialog from the map
* @param dialogId id of the dialog to remove
*/
void removeDialog(sf::Uint64 dialogId);
/**
* @brief closeDialog closes the dialog
* @param dialogId id of the dialog to close
*/
void closeDialog(sf::Uint64 dialogId);
/**
* @brief createDialog create the dialog, and gives it the given arguments
* @param args args to pass to the dialog constructor
* @return a reference to the created dialog
*/
template<typename T, typename ...Args>
T &createDialog(const Args&... args)
{
static_assert(std::is_base_of<Dialog, T>::value, "T must be a subclass of Dialog");
m_activeDialogId = ++m_idGenerator;
std::unique_ptr<T> nwDialog = std::make_unique<T>(m_activeDialogId, args...);
nwDialog->closeSignal.add([this](){closeDialog(m_activeDialogId); });
nwDialog->show(true);
m_dialogs[m_activeDialogId] = std::move(nwDialog);
return static_cast<T&>(*m_dialogs[m_activeDialogId]);
}
};
}
| [
"azarias.boutin@gmail.com"
] | azarias.boutin@gmail.com |
68efe663df056ad0d6a80eed816d8aac0da95437 | 0a87e899e2bd2cd9e8a348c01ba4a8f7b52d3bb3 | /catkin_test/catkin_test1/src/android_app/src/navigation_goalshi.cpp | 8362c71e1b27228f9f3978a2e5d447a46202b4c5 | [] | no_license | boogege/ROS_xiongmao | 28b68d145cba3e87b8f4c256311434778eaf37e4 | 41b9a957243a882b853f8cd8ce38253d3bdca82c | refs/heads/master | 2020-08-19T12:02:49.080683 | 2019-10-18T04:34:44 | 2019-10-18T04:34:44 | 215,803,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,587 | cpp | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <fstream>
#include <sys/stat.h> /**/
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*PPSIX终端控制定义*/
#include <errno.h> /*错误号定义*/
using namespace std;
#define FALSE -1
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <geometry_msgs/PoseWithCovariance.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Quaternion.h>
#include <std_srvs/Empty.h>
#include "sensor_msgs/LaserScan.h"
#include "actionlib_msgs/GoalID.h"
#include "actionlib_msgs/GoalStatusArray.h"
#include "actionlib_msgs/GoalStatus.h"
#include <nav_msgs/Odometry.h>
#include <actionlib_msgs/GoalID.h>
#define LEFT_GO 1
#define LEFT_BACK 2
#define RIGHT_GO 3
#define RIGHT_BACK 4
#define UP 1
#define DOWN 2
#define CATCH_1 3
#define PUT_1 4
#define CATCH_2 5
#define PUT_2 6
bool crash_1=false,crash_2=false,crash_3=false,crash_4=false; //碰撞变量
bool reach=false; //是否到达目标店
actionlib_msgs::GoalID first_goal;
int mcu_cmd=0;
int vel_select=0; //选择LEFT_GO LEFT_BACK RIGHT_GO RIGHT_BACK速度中的一个
int current_point=0; //当前导航点
int goal_n=0;
int current_status=0;
int last_current_status=0;
int first = 0;
bool d0=false;
//发布订阅节点
ros::Publisher pub_cancle;
ros::Publisher pub_goal; //发布目标点
ros::Publisher pub_send_mcu; //向下位机发送指令
ros::Publisher pub_vel; //向cmd_vel话题发送数据
ros::Subscriber sub_status; //订阅当前导航状态
ros::Subscriber sub_pose; //订阅amcl位姿
ros::Subscriber sub_mcu_msg; //读取下位机消息
double nav_point[5][4]={0.437,2.069,-0.107,0.99424,3.48982,-1.16947,-0.0957425,0.995406,4.4735066,2.2740663, 0.03483452,0.9993930};
double goal_point[10][2]={0.38,2.37};
void set_goal(int i)
{
ros::Rate loop_rate(5);
geometry_msgs::PoseStamped msg;
msg.header.frame_id = "map";
msg.header.stamp = ros::Time::now();
msg.pose.position.x=nav_point[i][0];
msg.pose.position.y=nav_point[i][1];
msg.pose.orientation.w=nav_point[i][2];
msg.pose.orientation.z=nav_point[i][3];
pub_goal.publish(msg);
//cout<<"aaaaaaaa"<<endl;
loop_rate.sleep();
goal_n++;
}
void pub_switch()
{
if(current_point>=0&¤t_point<=6)
{
set_goal(current_point);
}
else
{
fprintf(stderr,"Unsupported stop bits\n");
}
}
void *pub_na(void *arg)
{
while(ros::ok())
{
sleep(3);
if(first==0)
pub_switch();
first=1;
}
}
void *send_vel(void *arg)
{
while(ros::ok())
{ ros::Rate loop_rate(10);
// printf("2222222222222222222");
geometry_msgs::Twist msg;
switch(vel_select)
{
case LEFT_GO:msg.linear.x = -0.1;msg.linear.y = 0.1732;break;
case LEFT_BACK:msg.linear.x = 0.1;msg.linear.y = -0.1732;break;
case RIGHT_GO:msg.linear.x = -0.1;msg.linear.y = -0.1732;
// cout<<"5555"<<d0<<std::endl;//printf("111111111111111111111");
break;
case RIGHT_BACK:msg.linear.x = 0.1;msg.linear.y = 0.1732;break;
}
if(d0==true&&reach==false)
{ // cout<<"7777"<<std::endl;
//while(1)
//{
pub_vel.publish(msg);
loop_rate.sleep();
//}
}
if(reach==true)
{ d0=false;
msg.linear.x=0;
msg.linear.y=0;
pub_vel.publish(msg);
reach==false;
//return;
}
}
}
/*
while(ros::ok())
{
//fprintf(stderr,"send vel \n");
if(reach==true)
{
msg.linear.x=0;
msg.linear.y=0;
pub_vel.publish(msg);
return;
}
pub_vel.publish(msg);
loop_rate.sleep();
}
*/
void create_all_thread(void)
{
pthread_t pub_thread ,pub_thread1;
if( (pthread_create( &pub_thread , NULL , pub_na , NULL )) != 0 )
{
perror("Create the mode_change_thread fail");
exit( 1 );
}
if( (pthread_create( &pub_thread1, NULL , send_vel, NULL )) != 0 )
{
perror("Create the mode_change_thread fail");
exit( 1 );
}
}
void sendMcu()
{
char c =187;
std_msgs::String msg;
msg.data[0] = c;
msg.data[1]='c';
switch(mcu_cmd)
{
case CATCH_1: msg.data[1]='c';;break;
case CATCH_2: msg.data[1]='e';;break;
case PUT_1: msg.data[1]='d';;break;
case PUT_2: msg.data[1]='f';;break;
case UP: msg.data[1]='a';;break;
case DOWN: msg.data[1]='b';;break;
}
pub_send_mcu.publish(msg);
sleep(2);
return;
}
void statusCallback(const actionlib_msgs::GoalStatusArray::ConstPtr& msg)
{ //pub_switch();
if (goal_n>0)
{
last_current_status=current_status;
current_status=msg->status_list[0].status;
//cout<<"aaaaaaaa1111qq"<<endl;
if ((current_status==3)&&(last_current_status!=current_status))
{ d0=true;
current_status==0;
//pub_cancle.publish(first_goal);
printf("navigation reach\n");
switch(current_point)
{ d0=true;
case 0: vel_select=RIGHT_GO;//send_vel();
cout<<"ddddd"<<vel_select<<std::endl;
//mcu_cmd=CATCH_1;sleep(1);sendMcu();vel_select=RIGHT_BACK;send_vel();
break;
case 1: vel_select=RIGHT_GO;//send_vel();mcu_cmd=CATCH_2;sendMcu();mcu_cmd=UP; sendMcu();vel_select=RIGHT_BACK;send_vel();
break;
case 2: vel_select=LEFT_GO;//send_vel();mcu_cmd=PUT_1;sendMcu();mcu_cmd=CATCH_1;sendMcu();vel_select=LEFT_BACK;send_vel();
break;
case 3: vel_select=RIGHT_GO;//send_vel();mcu_cmd=PUT_2;sendMcu();mcu_cmd=CATCH_2;sendMcu();vel_select=RIGHT_BACK;send_vel();
break;
case 4: vel_select=LEFT_GO;//send_vel();mcu_cmd=PUT_1;sendMcu();vel_select=LEFT_BACK;send_vel();
break;
}
current_point=10; //到达目标点且执行完抓取动作以后才导航到下一个点
//pub_switch();
}
}
}
//订阅里程计回调函数
void poseCallback(const nav_msgs::Odometry::ConstPtr& odom_pose)
{ //const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& odom
double x = odom_pose->pose.pose.position.x;
double y = odom_pose->pose.pose.position.y;
if(fabs(y-goal_point[0][1])<0.2)
{ geometry_msgs::Twist msg;
reach = true;
//printf("x:==%f y:==%f\n",x,y);
fprintf(stderr,"reach \n");
}
else
{
reach = false;
//fprintf(stderr,"not reach \n");
}
}
//单片机上传数据回调函数
void mcuCallback(const std_msgs::String::ConstPtr& msg)
{
char c = msg->data[0];
int n = c;
switch(n)
{
case 0: crash_1=false;crash_2=false;crash_3=false;crash_4=false;break;
case 1: crash_1=true; break;
case 2: crash_2=true; break;
case 3: crash_3=true; break;
case 4: crash_4=true; break;
case 12: crash_1=true;crash_2=true; break;
case 34: crash_3=true;crash_4=true; break;
}
}
int main(int argc,char** argv)
{
ros::init(argc, argv, "navigation_goal");
ros::NodeHandle n;
create_all_thread();
pub_cancle = n.advertise<actionlib_msgs::GoalID>("move_base/cancel",1);///mobile_base/commands/velocity
//pub_send_mcu = n.advertise<std_msgs::String>("write_serial",1000); //向单片机发送指令
pub_goal = n.advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal",10); //发布导航点
pub_vel = n.advertise<geometry_msgs::Twist>("/cmd_vel_mux/input/teleop", 1000); //向底盘发送速度/cmd_vel_mux/input/teleop
sub_pose = n.subscribe("/odom", 20, poseCallback); //订阅位姿
sub_status = n.subscribe("move_base/status",100,statusCallback); //订阅是否到达目标点
//sub_mcu_msg = n.subscribe("read_serial",100,mcuCallback); //单片机数据
ros::spin();
return 0;
}
| [
"534214146@qq.com"
] | 534214146@qq.com |
dda8c9644171f4bf625cc048dce1d69180c8f20d | d0288f0bbb0c484966bf5b971d954ef3dd104f53 | /Others/datamaker.cpp | 203e73143c0c82e7cf2abb45e092edb4d35ea53b | [] | no_license | zjwzcn07/ACMLibrary | 6b4066118be93fea494650897f0cd4c655305964 | ff8ae387a534db9b37514cae451fd6aa9c6a36ce | refs/heads/master | 2021-01-23T21:43:35.388729 | 2016-09-24T13:49:12 | 2016-09-24T13:49:12 | 47,023,621 | 1 | 0 | null | 2016-09-24T12:51:19 | 2015-11-28T13:00:06 | C++ | UTF-8 | C++ | false | false | 949 | cpp | #include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
using namespace std;
const int N = 100001;
int seed,mult = 131,modnum,n;
typedef struct node{
int val,id;
}node;
bool cmp(node x,node y){
return x.val < y.val;
}
node a[N];
int getrand(int modnum){
seed = (seed * mult) % modnum;
while (seed == 0) seed = rand();
return seed;
}
int makeTree(){
for (int i = 1;i < n;i++)
printf("%d %d\n",a[i].id,a[i+1].id);
}
int makeGraph(int m){
makeTree();
for (int i = 1;i <= n;i++)
a[i].val = getrand(9999997);
sort(a+1,a+n+1,cmp);
for (int i = 1;i <= m-n+1;i++)
printf("%d %d\n",a[i].id,a[i+1].id);
}
int main(){
freopen("1.in","w",stdout);
srand((unsigned)time(0));
seed = rand();
int n = 1000;
for (int i = 1;i <= n;i++){
a[i].val = getrand(999999997);
a[i].id = i;
}
sort(a+1,a+n+1,cmp);
makeGraph(2*n);
}
| [
"williamchenwl880@gmail.com"
] | williamchenwl880@gmail.com |
0aa0e0793a1bcc0352965bda988c63d18b159c18 | 9daae0cf50859611aa23098071f8e75b9a8c3342 | /phylgen.cpp | 3c2b1a6e7304d762616abcecce76bdc71c1554e8 | [
"MIT"
] | permissive | Laakeri/phylogeny-aaai | d05226e80c322a7a7e67ae61316e1e8107b9731b | 4b97a6da97fc2be0e466c2197fbd4b51c036cb5f | refs/heads/master | 2021-08-20T06:33:07.007737 | 2020-07-21T10:46:28 | 2020-07-21T10:46:28 | 206,542,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,974 | cpp | #include <bits/stdc++.h>
#define F first
#define S second
using namespace std;
int main(int argc, char** argv){
if (argc != 6) {
cout<<"args: n, m, k, r, miss"<<endl;
return 0;
}
int n = stoi(argv[1]);
int m = stoi(argv[2]);
int k = stoi(argv[3]);
double r = stod(argv[4]);
double miss = stod(argv[5]);
assert(n>1&&n<=10000);
assert(m>1&&m<=10000);
assert(k>1&&k<=10000);
assert(r>=0&&r<=100);
assert(miss>=0&&miss<=1);
stringstream ss;
ss<<"./msdir/ms "<<n<<" 1 -s "<<m*(k-1)<<" -r "<<r<<" 5000 > phyltemp";
assert(system(ss.str().c_str())==0);
ifstream in("phyltemp");
string tmp;
getline(in, tmp);
getline(in, tmp);
getline(in, tmp);
getline(in, tmp);
assert(tmp == "//");
getline(in, tmp);
stringstream tss(tmp);
tss>>tmp;
assert(tmp == "segsites:");
tss>>tmp;
assert(tmp == to_string(m*(k-1)));
getline(in, tmp);
vector<string> data(n);
for (int i=0;i<n;i++){
getline(in, data[i]);
assert((int)data[i].size() == m*(k-1));
for (char c:data[i]){
assert(c=='0' || c=='1');
}
}
in.close();
cout<<n<<" "<<m<<endl;
std::uniform_real_distribution<double> ur(0, 1);
std::uniform_int_distribution<int> ui(0, k-1);
std::mt19937 re(time(0));
vector<map<string, int>> mm(m);
vector<int> ass(m);
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
string s;
for (int x=0;x<k-1;x++){
s+=data[i][j*(k-1)+x];
}
assert((int)s.size() == k-1);
int t=-1;
if (k==2){
if (s[0]=='0') t=0;
else t=1;
} else{
if (mm[j].count(s)){
t=mm[j][s];
} else if(ass[j]<k){
t=ass[j];
mm[j][s]=t;
ass[j]++;
} else{
t=ui(re);
mm[j][s]=t;
assert(r>0.0001);
}
}
assert(t>=0&&t<k);
if (ur(re)<miss) {
cout<<"?";
} else {
cout<<t;
}
if (j+1<m) cout<<" ";
}
cout<<endl;
}
} | [
"tukotu@dx5-cs-02.pc.helsinki.fi"
] | tukotu@dx5-cs-02.pc.helsinki.fi |
4c1896bfde7f9ca4a7e4114004015b62cd92a7dc | 52d6a6e647020301e0f210a56b3c0e8e16455f42 | /codigo/Grafo.h | cca421c5f6a9ff78b6b8b0c8f2a5e7b9dd0ce060 | [
"Apache-2.0"
] | permissive | renanNun/Teoria-dos-Grafos-2019.3 | 98fa3a4da96f7bcbab0dbc85afbe8a3219032cdc | 51f1ae84ae0d93f85082be68460a58ed8069359d | refs/heads/master | 2022-01-23T09:53:15.885719 | 2019-08-30T19:21:15 | 2019-08-30T19:21:15 | 197,796,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | h | #ifndef GRAFO_H_INCLUDED
#define GRAFO_H_INCLUDED
#include <iostream>
#include "ListaNos.h"
#include "ListaArestas.h"
class Grafo{
private:
public:
Grafo();
~Grafo();
};
#endif // GRAFO_H_INCLUDED
| [
"renannunes400@gmail.com"
] | renannunes400@gmail.com |
9849216141ab4edf7cfb67436df47994a567f700 | 55a2119d2a4abaebded1b7c55a2bd811488286e0 | /BasicTokenizer.h | dcc97c10e90a9848636c5ce1cc19f70df525f28c | [] | no_license | samuel-olivier/Animation | 859735113542483581a543536baf7d70e92b21fc | 1ef20b1466b44a3a39300e10bb74612a0de7ee67 | refs/heads/master | 2021-05-27T06:09:03.605027 | 2014-05-13T07:55:17 | 2014-05-13T07:55:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | h | #ifndef BASICTOKENIZER_H
#define BASICTOKENIZER_H
#include <QVector3D>
class QIODevice;
class BasicTokenizer
{
public:
BasicTokenizer(QIODevice* device);
QString nextToken();
QVector3D nextVector();
float nextFloat();
int nextInt();
private:
bool _isWhiteSpace(char c) const;
QIODevice* _stream;
};
#endif // BASICTOKENIZER_H
| [
"skanight@hotmail.fr"
] | skanight@hotmail.fr |
758cf19c888837dbd1f6e23f2c3fb3e06c91ca48 | bc8ed17f37af50bd390bc1a1630159ecca574594 | /src/test/budget_tests.cpp | 081e5ed2c4efaa1121cab30b23bf58cb9828198e | [
"MIT"
] | permissive | proteanx/BITCORN | aaadef311428d1f07ed584983f037a64ff5a387e | 47dee72f81f89fb4b4d0c91227e9e6c768b81213 | refs/heads/master | 2020-09-07T15:26:33.140311 | 2019-11-16T18:28:08 | 2019-11-16T18:28:08 | 220,827,206 | 0 | 0 | MIT | 2019-11-10T17:49:46 | 2019-11-10T17:49:46 | null | UTF-8 | C++ | false | false | 1,173 | cpp | // Copyright (c) 2018 The BITCORN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode-budget.h"
#include "tinyformat.h"
#include "utilmoneystr.h"
#include "test_bitcorn.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(budget_tests, TestingSetup)
void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue)
{
CBudgetManager budget;
CAmount nBudget = budget.GetTotalBudget(nHeight);
std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue));
BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError);
}
BOOST_AUTO_TEST_CASE(budget_value)
{
SelectParams(CBaseChainParams::TESTNET);
int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1;
CheckBudgetValue(nHeightTest, "testnet", 7300*COIN);
SelectParams(CBaseChainParams::MAIN);
nHeightTest = Params().Zerocoin_Block_V2_Start() + 1;
CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"42760724+bitcornfarmer@users.noreply.github.com"
] | 42760724+bitcornfarmer@users.noreply.github.com |
24302eda05fa5f3007a842e3f77e9667297e1b34 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/HostedShare/UNIX_HostedShare_SOLARIS.hxx | aa4838bc5d99d2ff8e5cfe3b8ba14dfabe7f109e | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,809 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_SOLARIS
#ifndef __UNIX_HOSTEDSHARE_PRIVATE_H
#define __UNIX_HOSTEDSHARE_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
f56ced4747218539451120d242009d3a5cad4aed | df565fff307a2a703d9a865aeb008b4d8908ca65 | /SectionHandout9/SectionHandout9/main.cpp | 7c6479430e62efbdbfb3e5936634561f9d37df88 | [] | no_license | ssLightStalker/ProgrammingAbstractionsSolutions | 07da9f5768c38b1e97a3e8ed61aa3ef80df22373 | 9f7c18a18ad51aed9d8e3679e5d9186c542012d8 | refs/heads/master | 2020-05-23T12:30:22.978948 | 2017-09-05T11:34:02 | 2017-09-05T11:34:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | #include "genlib.h"
#include "Problem_3_FindCycles.h"
#include "Problem_4_WordLadderGraph.h"
int main()
{
// Problem_3_FindCycles_main();
Problem_4_WordLadderGraph_main();
return 0;
}
| [
"antonc27@mail.ru"
] | antonc27@mail.ru |
34058fb0367cb654d66a8e1ba0fa5257a6b8e1f0 | 6418e50ac2c0a60eab137d574692038ee4022d4d | /src/macro/macro_unused.hpp | 394c0b02f83eb2179603be02e4c81942d3bcfe32 | [
"MIT"
] | permissive | yubing84/capo | 3980e39feca960116ce0e023f99a7b753f303425 | f48099f6e4cd5c184400e3ff775fb808b8da297e | refs/heads/master | 2021-01-15T23:53:34.287499 | 2014-06-08T07:59:15 | 2014-06-08T07:59:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | hpp | /*
The Capo Library
Code covered by the MIT License
Author: mutouyun (http://darkc.at)
*/
#ifndef CAPO_MACRO_UNUSED_HPP___
#define CAPO_MACRO_UNUSED_HPP___
////////////////////////////////////////////////////////////////
#ifdef CAPO_UNUSED_
# error "CAPO_UNUSED_ has been defined."
#endif
#if defined(_MSC_VER)
# define CAPO_UNUSED_ __pragma(warning(suppress:4100))
#elif defined(__GNUC__)
# define CAPO_UNUSED_ __attribute__((__unused__))
#else
# define CAPO_UNUSED_
#endif
////////////////////////////////////////////////////////////////
#endif // CAPO_MACRO_UNUSED_HPP___
| [
"mark.lonr@tom.com"
] | mark.lonr@tom.com |
389768d43d9cc1d6755a211efbd90fec82027545 | 4e22d261d7dcf5fe2731d77ba3cfb47c5568977c | /Source/Engine/TempestEngine/Nodes/Behaviors/Repeater.cpp | b39790ff1b76354362302df0679bfaf3f4aa793d | [] | no_license | SeraphinaMJ/Reformed | 2d7424d6d38d1cfaf8d385fade474a27c02103a5 | 8563d35ab2b80ca403b3b57ad80db1173504cf55 | refs/heads/master | 2023-04-06T00:40:34.223840 | 2021-05-06T11:25:51 | 2021-05-06T11:25:51 | 364,884,928 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 831 | cpp | /*!***************************************************************************************
\file Repeater.cpp
\author Charles Boudousquie
\date 9/20/2019
\copyright All content © 2018-2019 DigiPen (USA) Corporation, all rights reserved.
\par
\brief This node restarts and processes its child node every time no matter what.
Because of this it is highly suggested to use this as the root of the
behavior tree.
*****************************************************************************************/
#include "Repeater.hpp"
#ifndef TESTING_NODES
void Repeater::Init()
{
// set phase to ready for child
Decorator::Init();
}
void Repeater::Update(float dt)
{
UpdateDebug();
// when child is done just restart
getTask()->SetPhase(BehaviorPhase::STARTING);
}
#endif
| [
"minjiserak@gmail.com"
] | minjiserak@gmail.com |
0bb47d915cdf5eeae8bc3828ecfc3491519afebe | 288e945732ace900035694661b076ecc1d5d29e8 | /xauconchungdainhatcuabaxau.cpp | ea7a91b1f354747e47092f89d819b6115cc66bc0 | [] | no_license | AtomicOrbital/CppSource | bf440704386cbd200f90b333a7c3c63dfee45abf | 29e312fb1f9b3f1be1c4aee86db8c1942b17bcbd | refs/heads/main | 2023-06-20T00:42:21.656879 | 2021-07-16T08:27:35 | 2021-07-16T08:27:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | cpp | #include<bits/stdc++.h>
#define FORT(i,a,b) for(int i=a;i<b;i++)
#define FORD(i,a,b) for(int i=a-1;i>=b;i--)
#define mp make_pair
#define F first
#define S second
using namespace std;
void solve()
{
string s1,s2,s3;
int a,b,c;
cin>>a>>b>>c;
cin>>s1>>s2>>s3;
s1='.'+s1;
s2=','+s2;
s3='/'+s3;
a++;
b++;
c++;
int F[a+1][b+1][c+1]={};
FORT(i,0,a) F[i][0][0]=0;
FORT(i,0,b) F[0][i][0]=0;
FORT(i,0,c) F[0][0][i]=0;
FORT(i,1,a)
FORT(j,1,b)
FORT(k,0,c)
if (s1[i]==s2[j]&&s2[j]==s3[k]) F[i][j][k]=F[i-1][j-1][k-1]+1;
else F[i][j][k]=max(F[i-1][j][k],max(F[i][j-1][k],F[i][j][k-1]));
cout<<F[a-1][b-1][c-1]<<endl;
}
int main()
{
int T=1;
cin>>T;
FORT(t,0,T) solve();
return 0;
} | [
"phuonghoand2001@gmail.com"
] | phuonghoand2001@gmail.com |
dce2d8320a071ad34d1d456337394a7fb265fedd | 7c4492a3d1856503024ca658f79b74a110400f42 | /blogs/cpp/initchararray.cpp | 6bd09fa2b8be7caad9dee1fad989d3139385ab4a | [] | no_license | labinxu/blogs | 01b51046283075413f9deaecb86baec84fe572ba | 1316c6ad12df5e76097e2a19234840edf28697f3 | refs/heads/master | 2021-06-30T00:16:26.540477 | 2020-10-23T18:05:29 | 2020-10-23T18:05:29 | 180,364,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | cpp | #include <iostream>
using namespace std;
void dosomething(){
char dochars[10]="111111111";
cout<<dochars<<endl;
}
void init(){
char carray1[10]="";
cout<<carray1<<endl;
char *p = &carray1[2];
cout<<p<<endl;
}
int main(){
dosomething();
init();
return 0;
}
| [
"flowinair@gmail.com"
] | flowinair@gmail.com |
c5d4c9eda2481c55ab23f7dc122cb0e8d0cdda65 | bfa9289d287fc447105248cd6a78100062b69a14 | /src/math/Constants.h | 0435d2d70abea0f230d5de5a280f4f557eb2b72c | [] | no_license | etherealvisage/thor | c7b68b3f884ea337599202f7ee9882a56ce0ee4f | ffc04d220f74df2a50d209f336a3b3a17558e728 | refs/heads/master | 2021-01-17T15:36:58.549760 | 2016-09-30T23:16:56 | 2016-09-30T23:16:56 | 69,652,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | h | #ifndef THOR_MATH__CONSTANTS_H
#define THOR_MATH__CONSTANTS_H
#include <cmath>
namespace Thor {
namespace Math {
namespace Constants {
/* Used to represent numerical imprecision in floating-point results. */
const double Epsilon = 1e-7;
const double Pi = M_PI;
};
} // namespace Math
} // namespace Thor
#endif
| [
"ethereal@ethv.net"
] | ethereal@ethv.net |
d2eecfca7cd7e7c49078650676411eb91f1cf6a4 | 01d767e6e0c237a2688aed222153ab80d2640b79 | /1312-minimum-insertion-steps-to-make-a-string-palindrome/1312-minimum-insertion-steps-to-make-a-string-palindrome.cpp | abd08de2c8f388af36e6a15345bef1aefe7cd258 | [] | no_license | Samiatrix/Leetcode-Problems | 75669ec7a11ccfaa61737c84acc7d704c6cd5767 | 529704d47206ccc574af7fa79df85edafcd768db | refs/heads/master | 2022-06-29T05:34:08.326534 | 2022-06-24T10:58:00 | 2022-06-24T10:58:00 | 239,309,504 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | class Solution {
public:
int minInsertions(string s) {
string t = s;
reverse(t.begin(), t.end());
int n = s.size();
vector<vector<int>> dp(n+1, vector<int>(n+1, 0));
vector<int> prev(n+1, 0), curr(n+1, 0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
curr[j] = (s[i-1] == t[j-1]) ? (1 + prev[j-1]) : max(prev[j], curr[j-1]);
}
prev = curr;
}
return n-prev[n];
}
}; | [
"37403386+Samiatrix@users.noreply.github.com"
] | 37403386+Samiatrix@users.noreply.github.com |
50ece2e679f2cc29b854525f04d73a7e843e157f | 9c9b8cbef8640f8caed0cc6938957da7d9d8523f | /oglEngine/src/main.cpp | addc4dbdd7bf22ee0e66464d9d05308b1e5cd7f0 | [] | no_license | LaXiS96/oglEngine | 5be161d1d425ac078e9006cf833b0fa68bd08b4c | f4ed054884c75117b8b427618645bc98aa8b22d8 | refs/heads/master | 2021-05-20T11:44:47.653015 | 2021-04-20T18:07:27 | 2021-04-20T18:07:27 | 252,281,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,835 | cpp | #include <glad/glad.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <assimp/version.h>
#include <iostream>
#include <iomanip>
#include "Shader.h"
#include "Model.h"
#include "Engine.h"
#define WINDOW_WIDTH 1920
#define WINDOW_HEIGHT 1080
using namespace std;
int main(int argc, char** argv) {
cout << "oglEngine v0" << endl << endl;
SDL_version SDLcompiled;
SDL_version SDLlinked;
SDL_VERSION(&SDLcompiled);
SDL_GetVersion(&SDLlinked);
cout << "libSDL2 compiled: " << (int)SDLcompiled.major << '.' << (int)SDLcompiled.minor << '.' << (int)SDLcompiled.patch
<< " linked: " << (int)SDLlinked.major << '.' << (int)SDLlinked.minor << '.' << (int)SDLlinked.patch << endl;
cout << "assimp " << aiGetVersionMajor() << '.' << aiGetVersionMinor() << '.' << aiGetVersionRevision() << endl;
cout << "glm " << GLM_VERSION_MAJOR << '.' << GLM_VERSION_MINOR << '.' << GLM_VERSION_PATCH << '.' << GLM_VERSION_REVISION << endl;
cout << "glad 0.1.33" << endl;
cout << "stb_image 2.25" << endl;
cout << endl;
/*cout << "OpenGL Version: " << GLVersion.major << "." << GLVersion.minor << endl;
cout << "OpenGL Shading Language Version: " << (char*)glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;
cout << "OpenGL Vendor:" << (char*)glGetString(GL_VENDOR) << endl;
cout << "OpenGL Renderer:" << (char*)glGetString(GL_RENDERER) << endl;*/
Engine engine;
engine.Run();
/*Uint32 fpsStartTicks = SDL_GetTicks();
Uint32 fpsFramesCount = 0;
while (running) {
fpsFramesCount++;
Uint32 fpsCurrentTicks = SDL_GetTicks();
if (fpsCurrentTicks - fpsStartTicks >= 1000) {
cout << "FPS: " << fpsFramesCount / ((fpsCurrentTicks - fpsStartTicks) / 1000.0f) << endl;
fpsFramesCount = 0;
fpsStartTicks = SDL_GetTicks();
}
}*/
return 0;
}
| [
"antonio.ceccato@hotmail.it"
] | antonio.ceccato@hotmail.it |
8e416bfb52209c3c0a73f8153539dacc20185016 | 8a540a8e8690dfea402954160cd2379fe3607892 | /Math/MontgomeryModular.h | 45d3c60f397c71c2e1be0a42fb6a250f685e4f02 | [
"WTFPL"
] | permissive | jakobkogler/Algorithm-DataStructures | 597bf55394c77ba1fdbf918871aa9142776e32b9 | f8086642b40cc15f20fbb08fba5ded567773e116 | refs/heads/master | 2023-01-23T03:01:24.578698 | 2023-01-15T11:08:38 | 2023-01-15T11:08:50 | 63,162,129 | 321 | 95 | WTFPL | 2022-08-23T06:35:39 | 2016-07-12T13:54:06 | C++ | UTF-8 | C++ | false | false | 4,172 | h | #pragma once
#include <cstdint>
#include <utility>
#include <ostream>
template <int MOD>
class MontgomeryModular {
public:
using u64 = uint64_t;
using u32 = uint32_t;
using i32 = int32_t;
using MM = MontgomeryModular<MOD>;
MontgomeryModular(u32 value=0) : value(mult(value, r2)) {}
MM& operator+=(MM const& other) {
value += other.value;
value -= (((i32)mod - 1 - (i32)value) >> 31) & (i32)mod;
return *this;
}
MM operator+(MM const& other) const {
MM cpy = *this;
return cpy += other;
}
MM& operator-=(MM const& other) {
value += mod - other.value;
value -= (((i32)mod - 1 - (i32)value) >> 31) & (i32)mod;
return *this;
}
MM operator-(MM const& other) const {
MM cpy = *this;
return cpy -= other;
}
MM operator-() const {
return MM(0) - *this;
}
MM& operator*=(MM const& other) {
value = mult(value, other.value);
return *this;
}
MM operator*(MM const& other) const {
MM cpy = *this;
return cpy *= other;
}
MM& operator/=(MM const& other) {
return *this *= inverse(other);
}
MM operator/(MM const& other) {
MM cpy = *this;
return cpy /= other;
}
friend MM inverse(MM a) {
MM x;
x.value = MM::phase2(MM::reduce(a.value));
return x;
}
friend MM power(MM a, long long e) {
MM res(1);
while (e) {
if (e & 1)
res *= a;
a *= a;
e >>= 1;
}
return res;
}
u32 normal() const {
return reduce(value);
}
friend std::ostream& operator<<(std::ostream& os, MontgomeryModular<MOD> const& mm) {
return os << mm.normal();
}
bool operator==(MontgomeryModular<MOD> const& mm) const {
return value == mm.value;
}
bool operator!=(MontgomeryModular<MOD> const& mm) const {
return value != mm.value;
}
static MM init_inverse(u32 a) {
MM x;
x.value = phase2(a);
return x;
}
u32 value;
static const u32 mod = MOD;
private:
static u32 reduce(u64 x) {
u32 xlow = x;
u32 xhigh = x >> 32;
u32 q = xlow * inv;
i32 a = xhigh - ((u64(q) * mod) >> 32);
a += mod;
a -= (((i32)mod - 1 - (i32)a) >> 31) & (i32)mod;
return a;
}
u32 mult(u32 a, u32 b) const {
return reduce(u64(a) * b);
}
static constexpr u32 compute_inv(u32 mod) {
u32 inv = 1;
for (int i = 0; i < 5; i++)
inv *= 2 - mod * inv;
return inv;
}
static constexpr u32 compute_r2(u32 mod) {
u32 r2 = 1;
for (int i = 0; i < 64; i++) {
r2 <<= 1;
if (r2 >= mod)
r2 -= mod;
}
return r2;
}
static const u32 inv = compute_inv(MOD);
static const u32 r2 = compute_r2(MOD);
// Algorithm A from paper "Improvement to Montgomery Modular Inverse Algorithm"
static std::pair<u32, int> phase1(u32 a) {
auto p = mod;
auto u = p;
auto v = a;
auto r = 0;
auto s = 1;
auto k = 0;
while (v > 0) {
if ((u & 1) == 0) {
u >>= 1;
s <<= 1;
} else if ((v & 1) == 0) {
v >>= 1;
r <<= 1;
} else if (u > v) {
u = (u - v) >> 1;
r += s;
s <<= 1;
} else {
v = (v - u) >> 1;
s += r;
r <<= 1;
}
k++;
if (r >= p)
r -= p;
}
return std::make_pair(p - r, k);
}
static u32 phase2(u32 a) {
auto [r, k] = phase1(a);
for (int i = 0; i < k - 32; i++) {
if ((r & 1) == 0)
r >>= 1;
else
r = (r + mod) >> 1;
}
for (int i = 0; i < 32 - k; i++) {
r <<= 1;
if (r >= mod)
r -= mod;
}
return r;
}
};
| [
"jakob.kogler@gmail.com"
] | jakob.kogler@gmail.com |
cfbd7433e6799d333add14ebfc013576d064b7bb | 29e8daa1dadf6999a0c71f55965650689ee874af | /examples/identify/identify.ino | e2f1570c2be7c2d1a71a205a8359f370a144de73 | [] | no_license | HydroSense/SDI12 | 2f5d0b5fffc26cb5906e4773c06b388f72562870 | 73789e78baef8228528a98e199a092f809b9c070 | refs/heads/master | 2021-01-12T20:59:33.676582 | 2017-10-19T01:15:05 | 2017-10-19T01:15:05 | 47,078,357 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,681 | ino | /*
Example sketch for testing the identify function.
Colby Rome 4-11-16
*/
#include "SDI.h"
#include <Wire.h>
#define SERIAL_OUTPUT_PIN 1
#define FLOW_CONTROL_PIN A3
SDIBusController *SDIBus;
char addr;
void powerSDIMiddlePort(){
// Powers the middle port on the Hydrosense Datalogger 2.1.2
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
Wire.begin();
Wire.beginTransmission(0b1110000);
Wire.write(byte(0x03));
Wire.write(0b00000000); //Sets all pins to output
Wire.endTransmission();
Wire.beginTransmission(0b1110000);
Wire.write(byte(0x01));
Wire.write(0b00000100); //Sets only Port2On. This is either mislabeled
// on the PDF, or incorrectly routed. Pin P2 is on which is incorrectly
// called Port3On
Wire.endTransmission();
}
void setup(){
powerSDIMiddlePort();
// instantiate SDISerial instance with hardware Serial1
pinMode(FLOW_CONTROL_PIN, OUTPUT);
//pinMode(FLOW_CONTROL_PIN, OUTPUT);
SDISerial *mySDISerial = new SDISerial(Serial1, SERIAL_OUTPUT_PIN, FLOW_CONTROL_PIN);
// instantiate SDIBus controller, passing in hardware Serial1 as argument
SDIBus = new SDIBusController(*mySDISerial);
addr = '0'; // Decagon CTD-10 sensor
// For debugging to the computer
Serial.begin(9600);
}
void loop(){
struct SDIDeviceIdentification Decagon; // declare space for result of identify
int res = SDIBus->identify(addr, &Decagon);
if(res != 0){
Serial.print("Error: didn't respond: received ");
Serial.println(res);
}
else{
Serial.println("Success. Read:");
Serial.print("addr: ");
for(int i=0; Decagon.addr[i] != '\0'; i++){
Serial.print(Decagon.addr[i]);
}
Serial.println();
Serial.print("sdiVersion: ");
for(int i=0; Decagon.sdiVersion[i] != '\0'; i++){
Serial.print(Decagon.sdiVersion[i]);
}
Serial.println();
Serial.print("vendor: ");
for(int i=0; Decagon.vendor[i] != '\0'; i++){
Serial.print(Decagon.vendor[i]);
}
Serial.println();
Serial.print("modelNum: ");
for(int i=0; Decagon.modelNum[i] != '\0'; i++){
Serial.print(Decagon.modelNum[i]);
}
Serial.println();
Serial.print("sensorVersion: ");
for(int i=0; Decagon.sensorVersion[i] != '\0'; i++){
Serial.print(Decagon.sensorVersion[i]);
}
Serial.println();
Serial.print("optional: ");
for(int i=0; Decagon.optional[i] != '\0'; i++){
Serial.print(Decagon.optional[i]);
}
Serial.println();
}
delay(1000);
}
| [
"cdr013@bucknell.edu"
] | cdr013@bucknell.edu |
4b786aadbb5ae068c1e9b30a2c13714cf6aa9038 | ebd491e78dd125b9bc2986fbc34109dc75632514 | /Bomberman-GL/Bomberman-GL/stdafx.cpp | bbc0d011007c7d024dc2fc0f12595ee88eeb0014 | [] | no_license | JerisBren/Bomberman-GL | 6cc9b61c348e795ed9b3a53a5d30f3fc3d06306b | cf4da83b5c88352420fd9aed61e08f4df6e87b82 | refs/heads/master | 2020-05-06T20:20:00.749899 | 2014-12-03T15:40:52 | 2014-12-03T15:40:52 | 27,490,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Bomberman-GL.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"ThiagoAngst@hotmail.com"
] | ThiagoAngst@hotmail.com |
47f09140bac075c30bb4ff69e65c51fcdb6dab97 | e9e8064dd3848b85b65e871877c55f025628fb49 | /code/MapEngine/MapBase/新建文件夹/MapBase.cpp | e6e8beec5cb8a4b00f420518ae53391b91ac0646 | [] | no_license | xxh0078/gmapx | eb5ae8eefc2308b8ca3a07f575ee3a27b3e90d95 | e265ad90b302db7da05345e2467ec2587e501e90 | refs/heads/master | 2021-06-02T14:42:30.372998 | 2019-08-29T02:45:10 | 2019-08-29T02:45:10 | 12,397,909 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,423 | cpp | #include "StdAfx.h"
#include "MapBase.h"
#include <stdio.h>
#include "../VOSBase/VOSBase.h"
fun_msg g_fun_msg;
//en_MapType g_enMapType;
string g_strRootPath;
string g_strMapURL = _T("http://mt1.google.cn/vt/lyrs=m@124&hl=zh-CN&gl=cn&x=%d&y=%d&z=%d&s=G");
int g_iMapURLParmType = 123; //1表示x,2表示y,3表示z
//经纬度转墨卡托
MapPoint lonLat2Mercator(MapPoint lonLat,long temp )
{
MapPoint mercator;
double x = lonLat.x *temp/180;//20037508.34
double y = log(tan((90+lonLat.y)*M_PI/360))/(M_PI/180);
y = y *temp/180;
mercator.x = x;
mercator.y = y;
return mercator ;
}
//墨卡托转经纬度
MapPoint Mercator2lonLat(MapPoint mercator,long temp)
{
MapPoint lonLat;
double x = mercator.x/temp*180;
double y = mercator.y/temp*180;
y= 180/M_PI*(2*atan(exp(y*M_PI/180))-M_PI/2);
lonLat.x = x;
lonLat.y = y;
return lonLat;
}
//伪经纬度转墨卡托
MapPoint lonLat2Mercator20(MapPoint lonLat )
{
MapPoint mercator;
double x = lonLat.x *_MAX_PIXEL_20_/180;//20037508.34
double y = log(tan((90+lonLat.y)*M_PI/360))/(M_PI/180);
y = y *_MAX_PIXEL_20_/180;
mercator.x = x;
mercator.y = y;
return mercator ;
}
//伪墨卡托转经纬度
MapPoint Mercator2lonLat20( MapPoint mercator )
{
MapPoint lonLat;
double x = mercator.x/_MAX_PIXEL_20_*180;
double y = mercator.y/_MAX_PIXEL_20_*180;
y= 180/M_PI*(2*atan(exp(y*M_PI/180))-M_PI/2);
lonLat.x = x;
lonLat.y = y;
return lonLat;
} | [
"you@example.com"
] | you@example.com |
4fb3d74ab34794522e00295049f8ff1d6f3337d8 | 363504471a26645c13bda4d17daf1534c8041a23 | /Anarchy-Client/src/Entities/ClientEntityCollection.h | 26916cbce6b8f246c70f1809ca96a7ebab2c8cb2 | [] | no_license | Totomosic/Anarchy | 5eeca4d46f3a93b69098d32f0cb51a64d0386821 | fff1c2a4bb6e6db23b9c09060c07a42882550d3e | refs/heads/master | 2020-12-02T18:44:46.687802 | 2020-03-29T00:39:47 | 2020-03-29T00:39:47 | 231,084,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | h | #pragma once
#include "Lib/Entities/EntityCollection.h"
namespace Anarchy
{
class ClientEntityCollection : public EntityCollection
{
public:
inline static Vector2i InvalidTile = { -1, -1 };
private:
entityid_t m_ControlledEntity;
EntityHandle m_Camera;
EntityHandle m_TileIndicator;
public:
ClientEntityCollection(Scene& scene, Layer& layer);
bool IsControllingEntity(entityid_t networkId) const;
EntityHandle GetCamera() const;
void SetControlledEntity(entityid_t networkId);
void SetCamera(const EntityHandle& camera);
void SetTileIndicator(const EntityHandle& tileIndicator);
Vector2i GetSelectedTile() const;
EntityHandle CreateFromEntityState(const EntityState& state) override;
EntityHandle ApplyEntityState(const EntityState& state) override;
};
} | [
"jordan.thomas.morrison@gmail.com"
] | jordan.thomas.morrison@gmail.com |
6f9e25a7be62bd4d6c94cdb3f755f9aeecf75aa3 | 378a2892eeb5c70ec687e914dc506b80d2470b8e | /DefaultSDL/Player.h | 3de61f1656177aa76e92777020bca99538e1e419 | [] | no_license | NickyAl/Nickys_Simple_2D_Game_Engine | 5cbce331a4fb2bd982120822b60e4867273f2168 | d789f6b1abfd14f47cc10ce6913b0a0747e88f2d | refs/heads/master | 2023-07-22T07:45:51.779720 | 2021-09-03T12:39:45 | 2021-09-03T12:39:45 | 339,091,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | h | #pragma once
#include "Object.h"
#include <SDL_image.h>
#include <iostream>
#include <string>
#include "Window.h"
#include "Animation.h"
class Player
{
private:
Object collisionBox;
Object sprite;
float RS; //resolution setting
//movement5
bool hasJumped;
bool lookingRight;
struct Acceleration
{
float left = 0;
float right = 0;
float up = 0;
float down = 0;
bool none() { return left == 0 && right == 0 && up == 0 && down == 0; }
bool noneOnLR() { return left == 0 && right == 0; } //none on left and right
};
Acceleration acclrtn;
std::vector<Animation> animations;
//index|animation
//0 running right
//1 running left
//2 idle right
//3 idle left
//4 fall right
//5 fall left
//6 jump right
//7 jump left
public:
bool canJump;
Player();
Player(float rs);
void addAnimation(Animation anim) { animations.push_back(anim); }
void updateSprite(float tpf);
void pollEvents(SDL_Event& event, float tpf);
void draw()const;
void gravity(float TPF);
void setSprite(float w, float h, float x, float y, SDL_Texture* texture);
Object& getSprite() { return sprite; }
//for collision
void setCollisionBox(float w, float h, float x, float y, uint8_t r, uint8_t g, uint8_t b, uint8_t a);
Object& getCollisionBox() { return collisionBox; }
Acceleration& getAcclrtn() { return acclrtn; }
float getLocX() { return collisionBox.getX(); }
float getLocY() { return collisionBox.getY(); }
void setLocX(float x) { collisionBox.setX(x); }
void setLocY(float y) { collisionBox.setY(y); }
float getH() { return collisionBox.getH(); }
float getW() { return collisionBox.getW(); }
float getAcsLeft() { return acclrtn.left; }
float getAcsRight() { return acclrtn.right; }
float getAcsUp() { return acclrtn.up; }
float getAcsDown() { return acclrtn.down; }
//update
void updatePosition();
}; | [
"nikitotp@gmail.com"
] | nikitotp@gmail.com |
98ed710177385529cc8cd3e6df082c367655648d | 771a5f9d99fdd2431b8883cee39cf82d5e2c9b59 | /SDK/BP_GH_Rank12_RankDesc_functions.cpp | c22dfa658b3546dc1d1948e5410aa3aee8a3b860 | [
"MIT"
] | permissive | zanzo420/Sea-Of-Thieves-SDK | 6305accd032cc95478ede67d28981e041c154dce | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | refs/heads/master | 2023-03-25T22:25:21.800004 | 2021-03-20T00:51:04 | 2021-03-20T00:51:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | // Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void UBP_GH_Rank12_RankDesc_C::AfterRead()
{
URankDesc::AfterRead();
}
void UBP_GH_Rank12_RankDesc_C::BeforeDelete()
{
URankDesc::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"40242723+alxalx14@users.noreply.github.com"
] | 40242723+alxalx14@users.noreply.github.com |
89b6b6f64c97abc62f72b57a49c845c7edc8f2b3 | 4ccc93c43061a18de9064569020eb50509e75541 | /components/omnibox/shortcuts_database.h | c942dde8c9e18b0bc41c3f98c9d292a1a218cb9b | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | SaschaMester/delicium | f2bdab35d51434ac6626db6d0e60ee01911797d7 | b7bc83c3b107b30453998daadaeee618e417db5a | refs/heads/master | 2021-01-13T02:06:38.740273 | 2015-07-06T00:22:53 | 2015-07-06T00:22:53 | 38,457,128 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,936 | 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 COMPONENTS_OMNIBOX_SHORTCUTS_DATABASE_H_
#define COMPONENTS_OMNIBOX_SHORTCUTS_DATABASE_H_
#include <map>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/gtest_prod_util.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
#include "sql/connection.h"
#include "sql/meta_table.h"
#include "url/gurl.h"
// This class manages the shortcut provider table within the SQLite database
// passed to the constructor. It expects the following schema:
//
// Note: The database stores time in seconds, UTC.
//
// omni_box_shortcuts
// id Unique id of the entry (needed for the sync).
// search_text Text that shortcuts was searched with.
// url The url of the shortcut.
// contents Contents of the original omni-box entry.
// contents_matches Comma separated matches of the |search_text| in
// |contents|, for example "0,0,5,3,9,0".
// description Description of the original omni-box entry.
// description_matches Comma separated matches of the |search_text| in
// |description|.
// last_access_time Time the entry was accessed last, stored in seconds,
// UTC.
// number_of_hits Number of times that the entry has been selected.
class ShortcutsDatabase : public base::RefCountedThreadSafe<ShortcutsDatabase> {
public:
// The following struct encapsulates one previously selected omnibox shortcut.
struct Shortcut {
// The fields of an AutocompleteMatch that we preserve in a shortcut.
struct MatchCore {
MatchCore(const base::string16& fill_into_edit,
const GURL& destination_url,
const base::string16& contents,
const std::string& contents_class,
const base::string16& description,
const std::string& description_class,
int transition,
int type,
const base::string16& keyword);
~MatchCore();
base::string16 fill_into_edit;
GURL destination_url;
base::string16 contents;
// For both contents_class and description_class, we strip MATCH
// classifications; the ShortcutsProvider will re-mark MATCH regions based
// on the user's current typing.
std::string contents_class;
base::string16 description;
std::string description_class;
int transition;
int type;
base::string16 keyword;
};
Shortcut(const std::string& id,
const base::string16& text,
const MatchCore& match_core,
const base::Time& last_access_time,
int number_of_hits);
// Required for STL, we don't use this directly.
Shortcut();
~Shortcut();
std::string id; // Unique guid for the shortcut.
base::string16 text; // The user's original input string.
MatchCore match_core;
base::Time last_access_time; // Last time shortcut was selected.
int number_of_hits; // How many times shortcut was selected.
};
typedef std::vector<std::string> ShortcutIDs;
typedef std::map<std::string, Shortcut> GuidToShortcutMap;
explicit ShortcutsDatabase(const base::FilePath& database_path);
bool Init();
// Adds the ShortcutsProvider::Shortcut to the database.
bool AddShortcut(const Shortcut& shortcut);
// Updates timing and selection count for the ShortcutsProvider::Shortcut.
bool UpdateShortcut(const Shortcut& shortcut);
// Deletes the ShortcutsProvider::Shortcuts with these IDs.
bool DeleteShortcutsWithIDs(const ShortcutIDs& shortcut_ids);
// Deletes the ShortcutsProvider::Shortcuts with the url.
bool DeleteShortcutsWithURL(const std::string& shortcut_url_spec);
// Deletes all of the ShortcutsProvider::Shortcuts.
bool DeleteAllShortcuts();
// Loads all of the shortcuts.
void LoadShortcuts(GuidToShortcutMap* shortcuts);
private:
friend class base::RefCountedThreadSafe<ShortcutsDatabase>;
friend class ShortcutsDatabaseTest;
FRIEND_TEST_ALL_PREFIXES(ShortcutsDatabaseTest, AddShortcut);
FRIEND_TEST_ALL_PREFIXES(ShortcutsDatabaseTest, UpdateShortcut);
FRIEND_TEST_ALL_PREFIXES(ShortcutsDatabaseTest, DeleteShortcutsWithIds);
FRIEND_TEST_ALL_PREFIXES(ShortcutsDatabaseTest, DeleteShortcutsWithURL);
FRIEND_TEST_ALL_PREFIXES(ShortcutsDatabaseTest, LoadShortcuts);
virtual ~ShortcutsDatabase();
// Ensures that the table is present.
bool EnsureTable();
// The sql database. Not valid until Init is called.
sql::Connection db_;
base::FilePath database_path_;
sql::MetaTable meta_table_;
DISALLOW_COPY_AND_ASSIGN(ShortcutsDatabase);
};
#endif // COMPONENTS_OMNIBOX_SHORTCUTS_DATABASE_H_
| [
"g4jc@github.com"
] | g4jc@github.com |
02752b591b6d97162772f815d6d959d48628b237 | 905b6a6aa9a9dce552541e98db753f71409f5c35 | /DigitalImagesProcessing/lab12.cpp | 87542ba53f0dcd9a75dfab5262d01958206ac054 | [] | no_license | sebastianpiascik/DigitalImagesProcessing | 8f61001a333780bb103a89054ba4a89d9d237162 | fa1369ea50152677cddad4cf01feafb6594922b7 | refs/heads/master | 2020-05-14T19:06:32.735956 | 2019-06-23T16:58:54 | 2019-06-23T16:58:54 | 181,922,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,305 | cpp | #include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <chrono>
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <wchar.h>
using namespace std;
using namespace cv;
int lab12()
{
VideoCapture vcap(0);
if (!vcap.isOpened())
return -1;
int threshNumber = 75;
namedWindow("Final window", 1);
createTrackbar("thresh", "Final window", &threshNumber, 255);
Mat firstFrame, frame, frame1, frame2, gray1, gray2, dst, thresh, gaussBlur;
Rect bounding_rect;
RNG rng(12345);
boolean paused = false, newFile = true;
int frame_width = vcap.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height = vcap.get(CV_CAP_PROP_FRAME_HEIGHT);
VideoWriter video("tmp.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);
SYSTEMTIME lt = { 0 };
std::clock_t start = std::clock();
double duration;
while (vcap.read(frame1)) {
GetLocalTime(<);
if (newFile) {
stringstream ss;
ss << lt.wHour;
ss << lt.wMinute;
ss << lt.wSecond;
ss << "_";
ss << lt.wYear;
ss << lt.wMonth;
ss << lt.wDay;
string time = ss.str();
string filename = "motion_" + time + ".avi";
cout << filename << endl;
video.release();
video.open(filename, CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);
newFile = false;
start = std::clock();
}
if (!paused) {
cvtColor(frame1, gray1, COLOR_BGR2GRAY);
vcap.read(frame2);
cvtColor(frame2, gray2, COLOR_BGR2GRAY);
absdiff(gray1, gray2, dst);
GaussianBlur(dst, gaussBlur, Size(5, 5), 0);
threshold(dst, thresh, threshNumber, 255, THRESH_BINARY);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(thresh, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
double largest_area = 0;
int largest_contour_index = 0;
for (int i = 0; i < contours.size(); i++)
{
double a = contourArea(contours[i], false);
if (a > largest_area) {
largest_area = a;
largest_contour_index = i;
}
}
if (contours.size() > 0 && contours.size() >= largest_contour_index) {
start = std::clock();
stringstream ss;
ss << lt.wHour;
ss << ":";
ss << lt.wMinute;
ss << ":";
ss << lt.wSecond;
ss << " ";
ss << lt.wYear;
ss << "/";
ss << lt.wMonth;
ss << "/";
ss << lt.wDay;
string str = ss.str();
cout << str << endl;
putText(frame1, str, Point(20, 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 0));
video.write(frame1);
}
else {
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
if (duration > 2) {
video.release();
newFile = true;
}
}
imshow("thresh", thresh);
imshow("frame1", frame1);
}
else {
start = std::clock();
}
char c = (char)waitKey(33);
if (c == 27) {
break;
}
if (c == 32) {
if (paused) {
paused = false;
}
else {
paused = true;
destroyWindow("thresh");
}
}
}
vcap.release();
video.release();
cvDestroyAllWindows();
return 0;
} | [
"sebastian.piascik97@gmail.com"
] | sebastian.piascik97@gmail.com |
1dfcb570838bd6c7ebcf6086778d1447a514178c | 1b859dc1462c325d5d2acdce863d0f71c7983d3b | /lab31/lab31.cpp | e34065f237dcebcc7c65bdd90e0a46525dbccd61 | [] | no_license | Crispin20/LeslieCrispin-CSCI20-Spr2017 | 96e6579d97c5da0f6265bd6be26d362365e511db | e9a7aa00baacac82281048bda58321886fbd086b | refs/heads/master | 2021-01-11T15:56:47.438789 | 2017-05-24T00:00:17 | 2017-05-24T00:00:17 | 79,965,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,924 | cpp | #include <iostream>
using namespace std;
int main(){
char deviceChoice;
cout << "What kind of device do you want? A) DumbPhone, B) Smart Phone, C) Tablet D) More than one kind" << endl;
cin >> deviceChoice;
if (deviceChoice == 'A'){
int dumbPhone = 0; //price
int deviceAmount = 0;
cout << "How many do you want? ";
cin >> deviceAmount;
int deviceTotal = 0;
deviceTotal = deviceAmount * dumbPhone;
cout << "Price for dumbphone(s) is $" << deviceTotal << endl;
if(deviceAmount >= 2){
cout << "Your familyplan discount is $" << deviceAmount * 3 << endl;
}
else {
cout << "Familyplan not needed." << endl;
}
}
else if (deviceChoice == 'B'){
int smartPhone = 5; //price
int deviceAmount = 0;
cout << "How many do you want?" << endl;
cin >> deviceAmount;
int deviceTotal = 0;
deviceTotal = deviceAmount * smartPhone;
cout << "Price for smartPhone(s) is $" << deviceTotal << endl;
if(deviceAmount >= 2){
cout << "Your familyplan discount is $" << deviceAmount * 3 << endl;
}
else {
cout << "Familyplan not needed." << endl;
}
}
else if(deviceChoice == 'C'){ //tablet
int tablet = 10; //price
int deviceAmount = 0;
cout << "How many do you want? " << endl;
cin >> deviceAmount;
int deviceTotal = 0;
deviceTotal = deviceAmount * tablet;
cout << "Price for tablet(s) is " << deviceTotal << endl;
if(deviceAmount >= 2){
cout << "Your familyplan discount is $" << deviceAmount * 3 << endl;
}
else {
cout << "Familyplan not needed." << endl;
}
}
else if(deviceChoice == 'D'){
int tablet = 10; //price
int smartPhone = 3;
int dumbPhone = 0;
int totalSPhone = 0;
int totalDPhone = 0;
int totalTablet = 0;
int deviceTotal = 0;
int deviceAmount = 0;
cout << "How many do you want? Smartphones: " ;
cin >> totalSPhone;
cout << "Dumb Phone: ";
cin >> totalDPhone;
cout << "Tablet: ";
cin >> totalTablet;
deviceTotal = (totalTablet * tablet) + (smartPhone * totalSPhone) + (totalDPhone * dumbPhone);
cout << "Device charge is $" << deviceTotal << endl;
if ((totalSPhone + dumbPhone) <= 2) {
int FamilyPlan = 3;
int familyTotal = 0;
familyTotal = (totalSPhone + dumbPhone) * 3;
cout << "Your have a familyplan discount for $" << familyTotal << endl;
}
else {
cout << "Famlilyplan not needed." << endl;
}
}
else{
cout << "No device selected.";
}
char planChoice;
cout << "Are you planing to use data? Y for yes and N for No" << endl;
cin >> planChoice;
if(planChoice == 'Y'){
char dataChoice;
cout << "What type of plan?" << endl << "A) Unlimited Data- with unlimited talk, text, and data up to 10GB" << endl << "B) Pay per Data" << endl;
cin >> dataChoice;
if(dataChoice == 'A'){
int dataUse = 0;
cout << "How much data will you use? " << endl;
cin >> dataUse;
if( dataUse > 10){
double overDue = 0.0;
overDue = ((dataUse - 10) * 1.50);
cout << "The price of the unlimited data is $75 and the price of data after 10GB is $" << overDue << ", totaling to $" << overDue + 75 << endl;
}
else{
cout << "Price for this plan is $75" << endl;
}
}
else if (dataChoice == 'B'){
int dataUse = 0;
cout << "How much data will you use? " << endl;
cin >> dataUse;
if (dataUse <= 1 ){
double totalPrice = 0.0;
totalPrice = 5;
cout << "Your price is $" << totalPrice << " for the first GB" << endl;
}
else if((dataUse <= 5) & (dataUse >= 1)) {
double totalPrice = 0.0;
double extraGB = .75;
totalPrice = ((((dataUse - 1) ) * extraGB) + 5);
cout << "The price total for the plan is $" << totalPrice << " up to $0.75 til 5GB" <<endl;
}
else if((dataUse <= 15) & (dataUse >= 5)){
double totalPrice = 0.0;
double extraGB = 1.50;
totalPrice = ((dataUse - 1) * 1.50) + 5;
cout << "The price total for the plan is $" << totalPrice << " up to $1.50 til 15GB" <<endl;
}
else if(dataUse >= 15){
double totalPrice = 0.0;
double extraGB = 3;
totalPrice = ((dataUse - 1) *3) +5 ;
}
else{
cout << "No plan selected";
}
}
}
else if (planChoice == 'N'){
cout << "A Monthly Charge plan of $30, for unlimted talk and text, would be a good fit.";
}
else{
cout << "No answer selected";
}
char corpMember;
cout << "Are you a Corporate Member? A) yes or B) No" << endl;
cin >> corpMember;
if ( corpMember == 'A'){
cout << "you get a 10 percent discount" << endl;
}
else if (corpMember == 'B' ){
cout << "You dont get a discount." <<endl;
}
else {
cout << "None Selected" <<endl;
}
return 0;
} | [
"lcrispin001@student.butte.edu"
] | lcrispin001@student.butte.edu |
1547789a2b1a3aba28b8bbd47b7b3b96265bcf5b | 6f874ccb136d411c8ec7f4faf806a108ffc76837 | /code/VCSamples/VC2008Samples/Language/General/TilePuzzle/TileDriver/Board.cpp | ac8bed5c1d4724269d944cb3213471ee137909a0 | [
"MIT"
] | permissive | JetAr/ZDoc | c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435 | e81a3adc354ec33345e9a3303f381dcb1b02c19d | refs/heads/master | 2022-07-26T23:06:12.021611 | 2021-07-11T13:45:57 | 2021-07-11T13:45:57 | 33,112,803 | 8 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 6,145 | cpp | //Copyright (c) Microsoft Corporation. All rights reserved.
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation. See these other
//materials for detailed information regarding Microsoft code samples.
//THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//Board.cpp
#include "stdafx.h"
#include "Board.h"
#using <TilePuzzle.dll>
using namespace TileDriver;
Board::Board(unsigned int sizeCol, unsigned int sizeRow) : m_boardSize(sizeCol * sizeRow), m_sizeRow(sizeRow), m_sizeCol(sizeCol)
{
//initialize the array
m_rgBoard = new unsigned int[m_boardSize];
unsigned int sizeBoardMinusOne = m_boardSize -1;
for(unsigned int c=0; c<sizeBoardMinusOne; c++)
{
m_rgBoard[c] = c+1;
}
m_rgBoard[sizeBoardMinusOne] = 0;
m_iBlank = sizeBoardMinusOne;//The last piece is assumed to be the blank one.
}
Board::~Board()
{
}
bool Board::Randomize(int Difficulty)
{
array<int> ^rgnGoalBoard = gcnew array<int> (m_boardSize);
for(unsigned int c=0; c<m_boardSize; c++)
{
rgnGoalBoard[c] = c+1;
}
rgnGoalBoard[m_boardSize-1]=0;
//note in the next call, that the number of columns is the 'size' of the row.
array<int> ^rgnRandomBoard = TilePuzzle::Engine::GenerateRandomBoard( (int)(DateTime::Now.Second), m_boardSize * Difficulty, GetRowSize(), GetColSize(), rgnGoalBoard);
unsigned int c;
for(c=0; c<m_boardSize; c++)
{
m_rgBoard[c] = rgnRandomBoard[c];
}
//find blank
c = 0;
while(m_rgBoard[c++] != 0);
m_iBlank = c-1;
Debug::Assert( m_iBlank < m_boardSize, L"m_iBlank < m_boardSize", L"TileDriver::Board::Randomize() - Blank tile not found from TilePuzzle::Engine::GenerateRandomBoard()");
return true;
}
bool Board::SetStringBoard(String ^ strBoardstate, int nCols, int nRows)
{
Debug::Assert(strBoardstate->Length == nCols * nRows, L"strBoardstate->Length == nCols * nRows", L"Bad input string, or col row data");
Debug::Assert(nCols > 0, L"valid number of columns", L"Invalid Number of columns");
Debug::Assert(nRows > 0, L"valid number of rows", L"Invalid Number of rows");
return true;
}
String ^ Board::GetStringBoard()
{
return "";
}
unsigned int * Board::GetBoard()
{
return m_rgBoard;
}
unsigned int Board::GetSize()
{
return m_boardSize;
}
unsigned int Board::GetBlank()
{
return m_iBlank;
}
unsigned int Board::GetRowSize()
{
return m_sizeRow;
}
unsigned int Board::GetColSize()
{
return m_sizeCol;
}
bool Board::Move(unsigned int uPositionClicked, char * pchDirection, unsigned int * puPositionToMoveTo)
{
//Assert if uPositionClicked > m_sizeBoard;
Debug::Assert(uPositionClicked <= m_boardSize, L"uPositionClicked is within board", L"Clicked outside board");
unsigned int tempPosition = *puPositionToMoveTo;
*puPositionToMoveTo = m_iBlank;
if( (uPositionClicked == (m_iBlank + 1)) && //Checks for 'Left'
((uPositionClicked) % m_sizeRow) ) //if user didn't click first block on a row
{
*pchDirection = 'L';//Valid left move
return true;
}
if( (uPositionClicked == (m_iBlank -1)) &&//Checks for 'Right'
((m_iBlank) % m_sizeRow) ) //if blank space isn't first block on a row
{
*pchDirection = 'R';//Valid right move
return true;
}
if(uPositionClicked == (m_iBlank + m_sizeRow))//Checks for 'Up'
{
*pchDirection = 'U';
return true;
}
if(uPositionClicked == (m_iBlank - m_sizeRow))//Checks for 'Down'
{
*pchDirection = 'D';
return true;
}
*puPositionToMoveTo = tempPosition;//safety - we don't alter their outparam unless we fail.
return false;//only return true if the move is valid.
}
bool Board::Move(char chMoveDirection, unsigned int * puPositionClicked, unsigned int * puPositionToMoveTo)
{
unsigned int tempPosition = *puPositionToMoveTo;
*puPositionToMoveTo = m_iBlank;
switch(chMoveDirection)
{
case 'L':
//ok, so long as blank isn't last on a row
if(((m_iBlank + 1) % m_sizeRow) == 0)
break;
*puPositionClicked = m_iBlank + 1;
return true;
case 'R':
//ok, so long as blank isn't first on a row
if((!m_iBlank) || (!(m_iBlank % m_sizeRow)))
break;
*puPositionClicked = m_iBlank - 1;
return true;
case 'U':
//ok, so long as blank isn't in last row
if(m_iBlank >= (m_boardSize - m_sizeRow))
break;
*puPositionClicked = m_iBlank + m_sizeRow;
return true;
case 'D':
//ok, so long as blank isn't in top row
if(m_iBlank < m_sizeRow)
break;
*puPositionClicked = m_iBlank - m_sizeRow;
return true;
default:
Debug::Assert(false, L"Only 4 possible move directions", L"not an expected move direction");
;
}
//we return false now
*puPositionToMoveTo = tempPosition;//safety - we don't alter their outparam unless we succeed.
return false;//only return true if the move is valid.
}
//This function assumes the validity of the move has already been confirmed
bool Board::CommitMove(unsigned int uPositionClicked, bool * pfFinishesPuzzle)
{
unsigned int iPrevBlank = m_iBlank;
m_iBlank = uPositionClicked;
m_rgBoard[iPrevBlank] = m_rgBoard[uPositionClicked];
m_rgBoard[m_iBlank] = 0;
//now see if it finishes the puzzle, assuming the caller cares
if(pfFinishesPuzzle ==0)
return true;
*pfFinishesPuzzle = true;
//check everything but the blank piece, since by process of elimination it must be there.
unsigned int sizeBoardMinusOne = m_boardSize-1;
for(unsigned int c=0; c<(sizeBoardMinusOne); c++)
{
if(m_rgBoard[c] != c+1)
{
*pfFinishesPuzzle = false;
break;
}
}
return true;
}
| [
"126.org@gmail.com"
] | 126.org@gmail.com |
81e564a37932c6de137398f4c33fb245b28186dc | 04bc05d1140cfcdb2c42c371c61e3f70ec524d77 | /c++/C++编程实例100篇/实例24/INCLASS.CPP | c9276bd82065c7658d1883ee7eb2a50958113f2f | [] | no_license | lcong/vsSource | 52ad6fdffd5a0ad841215c0bd5ee6db1ea2d59ef | 7ec52c5cd63215e7dbd1c89a3421309aa695bc5b | refs/heads/master | 2021-06-23T05:12:17.588868 | 2017-08-11T05:57:40 | 2017-08-11T05:57:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | //THE PROGRAM IS TO INSERT ONE CLASS INTO ANOTHER
//FILE INCLASS.CPP
#define CONST1 78
#define CONST2 12
#define CONST3 23
#include <stdio.h>
#include <conio.h>
class INCLASS_1
{
private :
int DATA;
public :
INCLASS_1(int NUM)
{
DATA=NUM;
};
void OUTPUT()
{
printf("\n %d",DATA);
}
};
class INCLASS_2
{
private :
int DATA;
public :
INCLASS_2(int NUM)
{
DATA=NUM;
};
void OUTPUT()
{
printf("\n %d",DATA);
}
};
class OUTCLASS
{
private :
int DATA;
INCLASS_1 OB1;
INCLASS_2 OB2;
public :
OUTCLASS(int NUM);
void OUTPUT()
{
printf("\n %d",DATA);
}
void OUTPUTOB1()
{
OB1.INCLASS_1::OUTPUT();
}
void OUTPUTOB2()
{
OB2.INCLASS_2::OUTPUT();
}
};
OUTCLASS::OUTCLASS(int NUM):OB1(CONST1),OB2(CONST2)
{
DATA=NUM;
}
int main(void)
{
OUTCLASS TEST(CONST3);
clrscr();
TEST.OUTPUT();
TEST.OUTPUTOB1();
TEST.OUTPUTOB2();
getch();
return 0;
} | [
"rockcong@gmail.com"
] | rockcong@gmail.com |
b43c1fef781ad53021dc969f6e0186acdf073571 | 983f60b258028ccacd9d0637d430f6e39ca19f44 | /src/sfizz/effects/gen/disto_stage.hxx | ee112e87e62d066a08d32e6a52d5cabcbc5ea4f3 | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT-0",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"WTFPL",
"MIT"
] | permissive | sfztools/sfizz | 98a1136ffa0fea547aa3560c31309b0be42e2b10 | c2783f1853067af933cdc8cc6e523d12a296b59d | refs/heads/develop | 2023-08-28T14:13:44.790032 | 2023-08-26T13:29:49 | 2023-08-26T13:29:49 | 199,350,095 | 362 | 72 | BSD-2-Clause | 2023-08-30T02:33:41 | 2019-07-29T00:12:15 | C++ | UTF-8 | C++ | false | false | 5,220 | hxx | #if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
/* ------------------------------------------------------------
name: "disto_stage"
Code generated with Faust 2.30.5 (https://faust.grame.fr)
Compilation options: -lang cpp -inpl -es 1 -scal -ftz 0
------------------------------------------------------------ */
#ifndef __faustDisto_H__
#define __faustDisto_H__
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
#include <algorithm>
#include <cmath>
#include <math.h>
//[Before:class]
class faustDistoSIG0 {
//[Begin:class]
private:
int iRec3[2];
public:
int getNumInputsfaustDistoSIG0() {
return 0;
}
int getNumOutputsfaustDistoSIG0() {
return 1;
}
int getInputRatefaustDistoSIG0(int channel) {
int rate;
switch ((channel)) {
default: {
rate = -1;
break;
}
}
return rate;
}
int getOutputRatefaustDistoSIG0(int channel) {
int rate;
switch ((channel)) {
case 0: {
rate = 0;
break;
}
default: {
rate = -1;
break;
}
}
return rate;
}
void instanceInitfaustDistoSIG0(int sample_rate) {
for (int l3 = 0; (l3 < 2); l3 = (l3 + 1)) {
iRec3[l3] = 0;
}
}
void fillfaustDistoSIG0(int count, float* table) {
for (int i = 0; (i < count); i = (i + 1)) {
iRec3[0] = (iRec3[1] + 1);
float fTemp1 = std::exp(((0.078125f * float((iRec3[0] + -1))) + -10.0f));
table[i] = (fTemp1 / (fTemp1 + 1.0f));
iRec3[1] = iRec3[0];
}
}
};
static faustDistoSIG0* newfaustDistoSIG0() { return (faustDistoSIG0*)new faustDistoSIG0(); }
static void deletefaustDistoSIG0(faustDistoSIG0* dsp) { delete dsp; }
static float ftbl0faustDistoSIG0[256];
#ifndef FAUSTCLASS
#define FAUSTCLASS faustDisto
#endif
#ifdef __APPLE__
#define exp10f __exp10f
#define exp10 __exp10
#endif
class faustDisto {
private:
float fVec0[2];
int fSampleRate;
float fConst0;
float fConst1;
float fConst2;
float fConst3;
float fConst4;
float fConst5;
int iRec2[2];
float fRec1[2];
FAUSTFLOAT fHslider0;
float fVec1[2];
float fRec0[2];
public:
static constexpr int getNumInputs() {
return 1;
}
static constexpr int getNumOutputs() {
return 1;
}
static void classInit(int sample_rate) {
//[Begin:classInit]
faustDistoSIG0* sig0 = newfaustDistoSIG0();
sig0->instanceInitfaustDistoSIG0(sample_rate);
sig0->fillfaustDistoSIG0(256, ftbl0faustDistoSIG0);
deletefaustDistoSIG0(sig0);
//[End:classInit]
}
void instanceConstants(int sample_rate) {
//[Begin:instanceConstants]
fSampleRate = sample_rate;
fConst0 = float(fSampleRate);
fConst1 = (125.663704f / fConst0);
fConst2 = (1.0f / (fConst1 + 1.0f));
fConst3 = (1.0f - fConst1);
fConst4 = std::exp((0.0f - (100.0f / fConst0)));
fConst5 = (1.0f - fConst4);
//[End:instanceConstants]
}
void instanceResetUserInterface() {
//[Begin:instanceResetUserInterface]
fHslider0 = FAUSTFLOAT(100.0f);
//[End:instanceResetUserInterface]
}
void instanceClear() {
//[Begin:instanceClear]
for (int l0 = 0; (l0 < 2); l0 = (l0 + 1)) {
fVec0[l0] = 0.0f;
}
for (int l1 = 0; (l1 < 2); l1 = (l1 + 1)) {
iRec2[l1] = 0;
}
for (int l2 = 0; (l2 < 2); l2 = (l2 + 1)) {
fRec1[l2] = 0.0f;
}
for (int l4 = 0; (l4 < 2); l4 = (l4 + 1)) {
fVec1[l4] = 0.0f;
}
for (int l5 = 0; (l5 < 2); l5 = (l5 + 1)) {
fRec0[l5] = 0.0f;
}
//[End:instanceClear]
}
void init(int sample_rate) {
//[Begin:init]
classInit(sample_rate);
instanceInit(sample_rate);
//[End:init]
}
void instanceInit(int sample_rate) {
//[Begin:instanceInit]
instanceConstants(sample_rate);
instanceResetUserInterface();
instanceClear();
//[End:instanceInit]
}
int getSampleRate() {
return fSampleRate;
}
void compute(int count, FAUSTFLOAT const* const* inputs, FAUSTFLOAT* const* outputs) {
//[Begin:compute]
FAUSTFLOAT const* input0 = inputs[0];
FAUSTFLOAT* output0 = outputs[0];
float fSlow0 = ((0.200000003f * float(fHslider0)) + 2.0f);
for (int i = 0; (i < count); i = (i + 1)) {
float fTemp0 = float(input0[i]);
fVec0[0] = fTemp0;
iRec2[0] = (((fTemp0 < fVec0[1]) & (fTemp0 < -0.25f)) ? 1 : (((fTemp0 > fVec0[1]) & (fTemp0 > 0.25f)) ? 0 : iRec2[1]));
fRec1[0] = ((fConst4 * fRec1[1]) + (fConst5 * float(iRec2[0])));
float fTemp2 = std::max<float>(0.0f, (12.75f * ((fSlow0 * fTemp0) + 10.0f)));
int iTemp3 = int(fTemp2);
float fTemp4 = ftbl0faustDistoSIG0[std::min<int>(255, iTemp3)];
float fTemp5 = (fTemp4 + ((fTemp2 - float(iTemp3)) * (ftbl0faustDistoSIG0[std::min<int>(255, (iTemp3 + 1))] - fTemp4)));
float fTemp6 = ((fRec1[0] * (fTemp5 + -1.0f)) + ((1.0f - fRec1[0]) * fTemp5));
fVec1[0] = fTemp6;
fRec0[0] = (fConst2 * ((fConst3 * fRec0[1]) + (2.0f * (fTemp6 - fVec1[1]))));
output0[i] = FAUSTFLOAT(fRec0[0]);
fVec0[1] = fVec0[0];
iRec2[1] = iRec2[0];
fRec1[1] = fRec1[0];
fVec1[1] = fVec1[0];
fRec0[1] = fRec0[0];
}
//[End:compute]
}
FAUSTFLOAT getDepth() const { return fHslider0; }
void setDepth(FAUSTFLOAT value) { fHslider0 = value; }
//[End:class]
};
//[After:class]
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#undef FAUSTFLOAT
#undef FAUSTCLASS
| [
"jp-dev@inbox.ru"
] | jp-dev@inbox.ru |
affafbaf0db3d300ea7e39bdde637da494682c96 | 83964e7fb41ee62e3084eef5d3deef07eecdd93e | /llvm/unittests/ADT/HashingTest.cpp | b148f144513c2d967338146b11ed9018fec9be59 | [
"BSD-2-Clause",
"NCSA"
] | permissive | pbb59/ScaffCC | e0bee9e5b16a6f145224ad6b0b6eb32adb026f95 | 7d28d310063d147930ec4705aa5ebdf94ea8e924 | refs/heads/master | 2020-09-23T04:43:54.059923 | 2019-12-19T03:59:22 | 2019-12-19T03:59:22 | 225,405,289 | 0 | 1 | BSD-2-Clause | 2019-12-02T15:17:37 | 2019-12-02T15:17:36 | null | UTF-8 | C++ | false | false | 19,329 | cpp | //===- llvm/unittest/ADT/HashingTest.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Hashing.h unit tests.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/DataTypes.h"
#include <deque>
#include <list>
#include <map>
#include <vector>
namespace llvm {
// Helper for test code to print hash codes.
void PrintTo(const hash_code &code, std::ostream *os) {
*os << static_cast<size_t>(code);
}
// Fake an object that is recognized as hashable data to test super large
// objects.
struct LargeTestInteger { uint64_t arr[8]; };
struct NonPOD {
uint64_t x, y;
NonPOD(uint64_t x, uint64_t y) : x(x), y(y) {}
~NonPOD() {}
friend hash_code hash_value(const NonPOD &obj) {
return hash_combine(obj.x, obj.y);
}
};
namespace hashing {
namespace detail {
template <> struct is_hashable_data<LargeTestInteger> : true_type {};
} // namespace detail
} // namespace hashing
} // namespace llvm
using namespace llvm;
namespace {
enum TestEnumeration {
TE_Foo = 42,
TE_Bar = 43
};
TEST(HashingTest, HashValueBasicTest) {
int x = 42, y = 43, c = 'x';
void *p = 0;
uint64_t i = 71;
const unsigned ci = 71;
volatile int vi = 71;
const volatile int cvi = 71;
uintptr_t addr = reinterpret_cast<uintptr_t>(&y);
EXPECT_EQ(hash_value(42), hash_value(x));
EXPECT_EQ(hash_value(42), hash_value(TE_Foo));
EXPECT_NE(hash_value(42), hash_value(y));
EXPECT_NE(hash_value(42), hash_value(TE_Bar));
EXPECT_NE(hash_value(42), hash_value(p));
EXPECT_EQ(hash_value(71), hash_value(i));
EXPECT_EQ(hash_value(71), hash_value(ci));
EXPECT_EQ(hash_value(71), hash_value(vi));
EXPECT_EQ(hash_value(71), hash_value(cvi));
EXPECT_EQ(hash_value(c), hash_value('x'));
EXPECT_EQ(hash_value('4'), hash_value('0' + 4));
EXPECT_EQ(hash_value(addr), hash_value(&y));
}
TEST(HashingTest, HashValueStdPair) {
EXPECT_EQ(hash_combine(42, 43), hash_value(std::make_pair(42, 43)));
EXPECT_NE(hash_combine(43, 42), hash_value(std::make_pair(42, 43)));
EXPECT_NE(hash_combine(42, 43), hash_value(std::make_pair(42ull, 43ull)));
EXPECT_NE(hash_combine(42, 43), hash_value(std::make_pair(42, 43ull)));
EXPECT_NE(hash_combine(42, 43), hash_value(std::make_pair(42ull, 43)));
// Note that pairs are implicitly flattened to a direct sequence of data and
// hashed efficiently as a consequence.
EXPECT_EQ(hash_combine(42, 43, 44),
hash_value(std::make_pair(42, std::make_pair(43, 44))));
EXPECT_EQ(hash_value(std::make_pair(42, std::make_pair(43, 44))),
hash_value(std::make_pair(std::make_pair(42, 43), 44)));
// Ensure that pairs which have padding bytes *inside* them don't get treated
// this way.
EXPECT_EQ(hash_combine('0', hash_combine(1ull, '2')),
hash_value(std::make_pair('0', std::make_pair(1ull, '2'))));
// Ensure that non-POD pairs don't explode the traits used.
NonPOD obj1(1, 2), obj2(3, 4), obj3(5, 6);
EXPECT_EQ(hash_combine(obj1, hash_combine(obj2, obj3)),
hash_value(std::make_pair(obj1, std::make_pair(obj2, obj3))));
}
TEST(HashingTest, HashValueStdString) {
std::string s = "Hello World!";
EXPECT_EQ(hash_combine_range(s.c_str(), s.c_str() + s.size()), hash_value(s));
EXPECT_EQ(hash_combine_range(s.c_str(), s.c_str() + s.size() - 1),
hash_value(s.substr(0, s.size() - 1)));
EXPECT_EQ(hash_combine_range(s.c_str() + 1, s.c_str() + s.size() - 1),
hash_value(s.substr(1, s.size() - 2)));
std::wstring ws = L"Hello Wide World!";
EXPECT_EQ(hash_combine_range(ws.c_str(), ws.c_str() + ws.size()),
hash_value(ws));
EXPECT_EQ(hash_combine_range(ws.c_str(), ws.c_str() + ws.size() - 1),
hash_value(ws.substr(0, ws.size() - 1)));
EXPECT_EQ(hash_combine_range(ws.c_str() + 1, ws.c_str() + ws.size() - 1),
hash_value(ws.substr(1, ws.size() - 2)));
}
template <typename T, size_t N> T *begin(T (&arr)[N]) { return arr; }
template <typename T, size_t N> T *end(T (&arr)[N]) { return arr + N; }
// Provide a dummy, hashable type designed for easy verification: its hash is
// the same as its value.
struct HashableDummy { size_t value; };
hash_code hash_value(HashableDummy dummy) { return dummy.value; }
TEST(HashingTest, HashCombineRangeBasicTest) {
// Leave this uninitialized in the hope that valgrind will catch bad reads.
int dummy;
hash_code dummy_hash = hash_combine_range(&dummy, &dummy);
EXPECT_NE(hash_code(0), dummy_hash);
const int arr1[] = { 1, 2, 3 };
hash_code arr1_hash = hash_combine_range(begin(arr1), end(arr1));
EXPECT_NE(dummy_hash, arr1_hash);
EXPECT_EQ(arr1_hash, hash_combine_range(begin(arr1), end(arr1)));
const std::vector<int> vec(begin(arr1), end(arr1));
EXPECT_EQ(arr1_hash, hash_combine_range(vec.begin(), vec.end()));
const std::list<int> list(begin(arr1), end(arr1));
EXPECT_EQ(arr1_hash, hash_combine_range(list.begin(), list.end()));
const std::deque<int> deque(begin(arr1), end(arr1));
EXPECT_EQ(arr1_hash, hash_combine_range(deque.begin(), deque.end()));
const int arr2[] = { 3, 2, 1 };
hash_code arr2_hash = hash_combine_range(begin(arr2), end(arr2));
EXPECT_NE(dummy_hash, arr2_hash);
EXPECT_NE(arr1_hash, arr2_hash);
const int arr3[] = { 1, 1, 2, 3 };
hash_code arr3_hash = hash_combine_range(begin(arr3), end(arr3));
EXPECT_NE(dummy_hash, arr3_hash);
EXPECT_NE(arr1_hash, arr3_hash);
const int arr4[] = { 1, 2, 3, 3 };
hash_code arr4_hash = hash_combine_range(begin(arr4), end(arr4));
EXPECT_NE(dummy_hash, arr4_hash);
EXPECT_NE(arr1_hash, arr4_hash);
const size_t arr5[] = { 1, 2, 3 };
const HashableDummy d_arr5[] = { {1}, {2}, {3} };
hash_code arr5_hash = hash_combine_range(begin(arr5), end(arr5));
hash_code d_arr5_hash = hash_combine_range(begin(d_arr5), end(d_arr5));
EXPECT_EQ(arr5_hash, d_arr5_hash);
}
TEST(HashingTest, HashCombineRangeLengthDiff) {
// Test that as only the length varies, we compute different hash codes for
// sequences.
std::map<size_t, size_t> code_to_size;
std::vector<char> all_one_c(256, '\xff');
for (unsigned Idx = 1, Size = all_one_c.size(); Idx < Size; ++Idx) {
hash_code code = hash_combine_range(&all_one_c[0], &all_one_c[0] + Idx);
std::map<size_t, size_t>::iterator
I = code_to_size.insert(std::make_pair(code, Idx)).first;
EXPECT_EQ(Idx, I->second);
}
code_to_size.clear();
std::vector<char> all_zero_c(256, '\0');
for (unsigned Idx = 1, Size = all_zero_c.size(); Idx < Size; ++Idx) {
hash_code code = hash_combine_range(&all_zero_c[0], &all_zero_c[0] + Idx);
std::map<size_t, size_t>::iterator
I = code_to_size.insert(std::make_pair(code, Idx)).first;
EXPECT_EQ(Idx, I->second);
}
code_to_size.clear();
std::vector<unsigned> all_one_int(512, -1);
for (unsigned Idx = 1, Size = all_one_int.size(); Idx < Size; ++Idx) {
hash_code code = hash_combine_range(&all_one_int[0], &all_one_int[0] + Idx);
std::map<size_t, size_t>::iterator
I = code_to_size.insert(std::make_pair(code, Idx)).first;
EXPECT_EQ(Idx, I->second);
}
code_to_size.clear();
std::vector<unsigned> all_zero_int(512, 0);
for (unsigned Idx = 1, Size = all_zero_int.size(); Idx < Size; ++Idx) {
hash_code code = hash_combine_range(&all_zero_int[0], &all_zero_int[0] + Idx);
std::map<size_t, size_t>::iterator
I = code_to_size.insert(std::make_pair(code, Idx)).first;
EXPECT_EQ(Idx, I->second);
}
}
TEST(HashingTest, HashCombineRangeGoldenTest) {
struct { const char *s; uint64_t hash; } golden_data[] = {
#if SIZE_MAX == UINT64_MAX
{ "a", 0xaeb6f9d5517c61f8ULL },
{ "ab", 0x7ab1edb96be496b4ULL },
{ "abc", 0xe38e60bf19c71a3fULL },
{ "abcde", 0xd24461a66de97f6eULL },
{ "abcdefgh", 0x4ef872ec411dec9dULL },
{ "abcdefghijklm", 0xe8a865539f4eadfeULL },
{ "abcdefghijklmnopqrstu", 0x261cdf85faaf4e79ULL },
{ "abcdefghijklmnopqrstuvwxyzabcdef", 0x43ba70e4198e3b2aULL },
{ "abcdefghijklmnopqrstuvwxyzabcdef"
"abcdefghijklmnopqrstuvwxyzghijkl"
"abcdefghijklmnopqrstuvwxyzmnopqr"
"abcdefghijklmnopqrstuvwxyzstuvwx"
"abcdefghijklmnopqrstuvwxyzyzabcd", 0xdcd57fb2afdf72beULL },
{ "a", 0xaeb6f9d5517c61f8ULL },
{ "aa", 0xf2b3b69a9736a1ebULL },
{ "aaa", 0xf752eb6f07b1cafeULL },
{ "aaaaa", 0x812bd21e1236954cULL },
{ "aaaaaaaa", 0xff07a2cff08ac587ULL },
{ "aaaaaaaaaaaaa", 0x84ac949d54d704ecULL },
{ "aaaaaaaaaaaaaaaaaaaaa", 0xcb2c8fb6be8f5648ULL },
{ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0xcc40ab7f164091b6ULL },
{ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0xc58e174c1e78ffe9ULL },
{ "z", 0x1ba160d7e8f8785cULL },
{ "zz", 0x2c5c03172f1285d7ULL },
{ "zzz", 0x9d2c4f4b507a2ac3ULL },
{ "zzzzz", 0x0f03b9031735693aULL },
{ "zzzzzzzz", 0xe674147c8582c08eULL },
{ "zzzzzzzzzzzzz", 0x3162d9fa6938db83ULL },
{ "zzzzzzzzzzzzzzzzzzzzz", 0x37b9a549e013620cULL },
{ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0x8921470aff885016ULL },
{ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0xf60fdcd9beb08441ULL },
{ "a", 0xaeb6f9d5517c61f8ULL },
{ "ab", 0x7ab1edb96be496b4ULL },
{ "aba", 0x3edb049950884d0aULL },
{ "ababa", 0x8f2de9e73a97714bULL },
{ "abababab", 0xee14a29ddf0ce54cULL },
{ "ababababababa", 0x38b3ddaada2d52b4ULL },
{ "ababababababababababa", 0xd3665364219f2b85ULL },
{ "abababababababababababababababab", 0xa75cd6afbf1bc972ULL },
{ "abababababababababababababababab"
"abababababababababababababababab"
"abababababababababababababababab"
"abababababababababababababababab"
"abababababababababababababababab", 0x840192d129f7a22bULL }
#elif SIZE_MAX == UINT32_MAX
{ "a", 0x000000004605f745ULL },
{ "ab", 0x00000000d5f06301ULL },
{ "abc", 0x00000000559fe1eeULL },
{ "abcde", 0x00000000424028d7ULL },
{ "abcdefgh", 0x000000007bb119f8ULL },
{ "abcdefghijklm", 0x00000000edbca513ULL },
{ "abcdefghijklmnopqrstu", 0x000000007c15712eULL },
{ "abcdefghijklmnopqrstuvwxyzabcdef", 0x000000000b3aad66ULL },
{ "abcdefghijklmnopqrstuvwxyzabcdef"
"abcdefghijklmnopqrstuvwxyzghijkl"
"abcdefghijklmnopqrstuvwxyzmnopqr"
"abcdefghijklmnopqrstuvwxyzstuvwx"
"abcdefghijklmnopqrstuvwxyzyzabcd", 0x000000008c758c8bULL },
{ "a", 0x000000004605f745ULL },
{ "aa", 0x00000000dc0a52daULL },
{ "aaa", 0x00000000b309274fULL },
{ "aaaaa", 0x00000000203b5ef6ULL },
{ "aaaaaaaa", 0x00000000a429e18fULL },
{ "aaaaaaaaaaaaa", 0x000000008662070bULL },
{ "aaaaaaaaaaaaaaaaaaaaa", 0x000000003f11151cULL },
{ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0x000000008600fe20ULL },
{ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0x000000004e0e0804ULL },
{ "z", 0x00000000c5e405e9ULL },
{ "zz", 0x00000000a8d8a2c6ULL },
{ "zzz", 0x00000000fc2af672ULL },
{ "zzzzz", 0x0000000047d9efe6ULL },
{ "zzzzzzzz", 0x0000000080d77794ULL },
{ "zzzzzzzzzzzzz", 0x00000000405f93adULL },
{ "zzzzzzzzzzzzzzzzzzzzz", 0x00000000fc72838dULL },
{ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0x000000007ce160f1ULL },
{ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0x00000000aed9ed1bULL },
{ "a", 0x000000004605f745ULL },
{ "ab", 0x00000000d5f06301ULL },
{ "aba", 0x00000000a85cd91bULL },
{ "ababa", 0x000000009e3bb52eULL },
{ "abababab", 0x000000002709b3b9ULL },
{ "ababababababa", 0x000000003a234174ULL },
{ "ababababababababababa", 0x000000005c63e5ceULL },
{ "abababababababababababababababab", 0x0000000013f74334ULL },
{ "abababababababababababababababab"
"abababababababababababababababab"
"abababababababababababababababab"
"abababababababababababababababab"
"abababababababababababababababab", 0x00000000c1a6f135ULL },
#else
#error This test only supports 64-bit and 32-bit systems.
#endif
};
for (unsigned i = 0; i < sizeof(golden_data)/sizeof(*golden_data); ++i) {
StringRef str = golden_data[i].s;
hash_code hash = hash_combine_range(str.begin(), str.end());
#if 0 // Enable this to generate paste-able text for the above structure.
std::string member_str = "\"" + str.str() + "\",";
fprintf(stderr, " { %-35s 0x%016llxULL },\n",
member_str.c_str(), static_cast<uint64_t>(hash));
#endif
EXPECT_EQ(static_cast<size_t>(golden_data[i].hash),
static_cast<size_t>(hash));
}
}
TEST(HashingTest, HashCombineBasicTest) {
// Hashing a sequence of homogenous types matches range hashing.
const int i1 = 42, i2 = 43, i3 = 123, i4 = 999, i5 = 0, i6 = 79;
const int arr1[] = { i1, i2, i3, i4, i5, i6 };
EXPECT_EQ(hash_combine_range(arr1, arr1 + 1), hash_combine(i1));
EXPECT_EQ(hash_combine_range(arr1, arr1 + 2), hash_combine(i1, i2));
EXPECT_EQ(hash_combine_range(arr1, arr1 + 3), hash_combine(i1, i2, i3));
EXPECT_EQ(hash_combine_range(arr1, arr1 + 4), hash_combine(i1, i2, i3, i4));
EXPECT_EQ(hash_combine_range(arr1, arr1 + 5),
hash_combine(i1, i2, i3, i4, i5));
EXPECT_EQ(hash_combine_range(arr1, arr1 + 6),
hash_combine(i1, i2, i3, i4, i5, i6));
// Hashing a sequence of heterogenous types which *happen* to all produce the
// same data for hashing produces the same as a range-based hash of the
// fundamental values.
const size_t s1 = 1024, s2 = 8888, s3 = 9000000;
const HashableDummy d1 = { 1024 }, d2 = { 8888 }, d3 = { 9000000 };
const size_t arr2[] = { s1, s2, s3 };
EXPECT_EQ(hash_combine_range(begin(arr2), end(arr2)),
hash_combine(s1, s2, s3));
EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(s1, s2, d3));
EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(s1, d2, s3));
EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(d1, s2, s3));
EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(d1, d2, s3));
EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(d1, d2, d3));
// Permuting values causes hashes to change.
EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i1, i1, i2));
EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i1, i2, i1));
EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i2, i1, i1));
EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i2, i2, i1));
EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i2, i2, i2));
EXPECT_NE(hash_combine(i2, i1, i1), hash_combine(i1, i1, i2));
EXPECT_NE(hash_combine(i1, i1, i2), hash_combine(i1, i2, i1));
EXPECT_NE(hash_combine(i1, i2, i1), hash_combine(i2, i1, i1));
// Changing type w/o changing value causes hashes to change.
EXPECT_NE(hash_combine(i1, i2, i3), hash_combine((char)i1, i2, i3));
EXPECT_NE(hash_combine(i1, i2, i3), hash_combine(i1, (char)i2, i3));
EXPECT_NE(hash_combine(i1, i2, i3), hash_combine(i1, i2, (char)i3));
// This is array of uint64, but it should have the exact same byte pattern as
// an array of LargeTestIntegers.
const uint64_t bigarr[] = {
0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL,
0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL,
0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL,
0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL,
0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL,
0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL,
0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL,
0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL,
0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL
};
// Hash a preposterously large integer, both aligned with the buffer and
// misaligned.
const LargeTestInteger li = { {
0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL,
0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL,
0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL
} };
// Rotate the storage from 'li'.
const LargeTestInteger l2 = { {
0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL,
0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL,
0xaaaacbcbffffababULL, 0xaaaaaaaaababababULL
} };
const LargeTestInteger l3 = { {
0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL,
0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL,
0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL
} };
EXPECT_EQ(hash_combine_range(begin(bigarr), end(bigarr)),
hash_combine(li, li, li));
EXPECT_EQ(hash_combine_range(bigarr, bigarr + 9),
hash_combine(bigarr[0], l2));
EXPECT_EQ(hash_combine_range(bigarr, bigarr + 10),
hash_combine(bigarr[0], bigarr[1], l3));
EXPECT_EQ(hash_combine_range(bigarr, bigarr + 17),
hash_combine(li, bigarr[0], l2));
EXPECT_EQ(hash_combine_range(bigarr, bigarr + 18),
hash_combine(li, bigarr[0], bigarr[1], l3));
EXPECT_EQ(hash_combine_range(bigarr, bigarr + 18),
hash_combine(bigarr[0], l2, bigarr[9], l3));
EXPECT_EQ(hash_combine_range(bigarr, bigarr + 20),
hash_combine(bigarr[0], l2, bigarr[9], l3, bigarr[18], bigarr[19]));
}
}
| [
"ajavadia@princeton.edu"
] | ajavadia@princeton.edu |
bc2bd4f385b439d469858fe6536b6da1ccf352f7 | 6226d6aed3629aa4069c46971ffe764bb6c743f6 | /ThirdParty/SpeedTree/Common Source/Transform.cpp | 0b2ba1e7eb170b4442edcd9f9eaa415aa8a89bfd | [] | no_license | Myway3D/Myway3D | 83c30258f1e3eae90e619269406acd0ddeac7887 | 39cf569993f62fc648cbba49ebf74b3f8a64e46a | refs/heads/master | 2020-04-22T20:24:15.817427 | 2014-03-09T14:25:23 | 2014-03-09T14:25:23 | 170,640,096 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,224 | cpp | // Name: Transform.cpp
//
// *** INTERACTIVE DATA VISUALIZATION (IDV) PROPRIETARY INFORMATION ***
//
// Copyright (c) 2001-2002 IDV, Inc.
// All Rights Reserved.
//
// IDV, Inc.
// 1233 Washington St. Suite 610
// Columbia, SC 29201
// Voice: (803) 799-1699
// Fax: (803) 931-0320
// Web: http://www.idvinc.com
//
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Interactive Data Visualization and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
#include "Transform.h"
#include <cmath>
#include <vector>
using namespace std;
///////////////////////////////////////////////////////////////////////
// CTransform::CTransform definition
CTransform::CTransform( )
{
LoadIdentity( );
}
///////////////////////////////////////////////////////////////////////
// CTransform::Set definition
void CTransform::Set(float afData[4][4])
{
memcpy(&m_afData[0][0], &afData[0][0], 16 * sizeof(float));
}
///////////////////////////////////////////////////////////////////////
// CTransform::LoadIdentity definition
void CTransform::LoadIdentity( )
{
m_afData[0][0] = 1.0f;
m_afData[0][1] = 0.0f;
m_afData[0][2] = 0.0f;
m_afData[0][3] = 0.0f;
m_afData[1][0] = 0.0f;
m_afData[1][1] = 1.0f;
m_afData[1][2] = 0.0f;
m_afData[1][3] = 0.0f;
m_afData[2][0] = 0.0f;
m_afData[2][1] = 0.0f;
m_afData[2][2] = 1.0f;
m_afData[2][3] = 0.0f;
m_afData[3][0] = 0.0f;
m_afData[3][1] = 0.0f;
m_afData[3][2] = 0.0f;
m_afData[3][3] = 1.0f;
}
///////////////////////////////////////////////////////////////////////
// CTransform::Translate definition
void CTransform::Translate(float fX, float fY, float fZ)
{
CTransform cTemp;
cTemp.m_afData[3][0] = fX;
cTemp.m_afData[3][1] = fY;
cTemp.m_afData[3][2] = fZ;
*this = cTemp * *this;
}
///////////////////////////////////////////////////////////////////////
// CTransform::Rotate definition
void CTransform::Rotate(float fAngle, char chAxis)
{
CTransform cRotMatrix;
float fCosine = cosf(fAngle);
float fSine = sinf(fAngle);
switch (chAxis)
{
case 'x': case 'X':
cRotMatrix.m_afData[1][1] = fCosine;
cRotMatrix.m_afData[1][2] = fSine;
cRotMatrix.m_afData[2][1] = -fSine;
cRotMatrix.m_afData[2][2] = fCosine;
break;
case 'y': case 'Y':
cRotMatrix.m_afData[0][0] = fCosine;
cRotMatrix.m_afData[0][2] = -fSine;
cRotMatrix.m_afData[2][0] = fSine;
cRotMatrix.m_afData[2][2] = fCosine;
break;
case 'z': case 'Z':
cRotMatrix.m_afData[0][0] = fCosine;
cRotMatrix.m_afData[1][0] = -fSine;
cRotMatrix.m_afData[0][1] = fSine;
cRotMatrix.m_afData[1][1] = fCosine;
break;
default:
return;
}
*this = cRotMatrix * *this;
}
///////////////////////////////////////////////////////////////////////
// CTransform::IsIdentity definition
bool CTransform::IsIdentity(void) const
{
CTransform cId;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
if (cId.m_afData[i][j] != m_afData[i][j])
return false;
return true;
}
///////////////////////////////////////////////////////////////////////
// CTransform::Scale definition
void CTransform::Scale(float fX)
{
CTransform cTemp;
cTemp.m_afData[0][0] = fX;
cTemp.m_afData[1][1] = fX;
cTemp.m_afData[2][2] = fX;
*this = cTemp * *this;
}
///////////////////////////////////////////////////////////////////////
// CTransform::Scale definition
void CTransform::Scale(float fX, float fY, float fZ)
{
CTransform cTemp;
cTemp.m_afData[0][0] = fX;
cTemp.m_afData[1][1] = fY;
cTemp.m_afData[2][2] = fZ;
*this = cTemp * *this;
}
///////////////////////////////////////////////////////////////////////
// CTransform::operator* definition
CTransform CTransform::operator*(const CTransform& cTransform) const
{
CTransform cTemp;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
cTemp.m_afData[i][j] = 0.0f;
for (int k = 0; k < 4; ++k)
cTemp.m_afData[i][j] += m_afData[i][k] * cTransform.m_afData[k][j];
}
return cTemp;
}
/*
///////////////////////////////////////////////////////////////////////
// CTransform::operator* definition
CVec CTransform::operator*(const CVec& cVec) const
{
int nSize = cVec.GetSize( );
CVec cTemp(nSize);
for (int i = 0; i < nSize; ++i)
{
cTemp.m_afData[i] = 0.0f;
for (int j = 0; j < 4; ++j)
if (j < nSize)
cTemp.m_afData[i] += m_afData[i][j] * cVec.m_afData[j];
else if (j == 3)
cTemp.m_afData[i] += m_afData[i][j];
}
return cTemp;
}
///////////////////////////////////////////////////////////////////////
// CTransform::operator* definition
CVec3 CTransform::operator*(const CVec3& cVec3) const
{
CVec3 cTemp;
for (int i = 0; i < 3; ++i)
{
cTemp.m_afData[i] = 0.0f;
for (int j = 0; j < 4; ++j)
if (j < 3)
cTemp.m_afData[i] += m_afData[i][j] * cVec3.m_afData[j];
else if (j == 3)
cTemp.m_afData[i] += m_afData[i][j];
}
return cTemp;
}
///////////////////////////////////////////////////////////////////////
// CTransform::operator* definition
CRegion CTransform::operator*(const CRegion& cRegion) const
{
CRegion cTemp;
cTemp.m_cMin = *this * cRegion.m_cMin;
cTemp.m_cMax = *this * cRegion.m_cMax;
return cTemp;
}
///////////////////////////////////////////////////////////////////////
// CTransform::operator+ definition
CTransform CTransform::operator+(const CTransform& cTransform) const
{
CTransform cTemp;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
cTemp.m_afData[i][j] = cTransform.m_afData[i][j] + m_afData[i][j];
return cTemp;
}
///////////////////////////////////////////////////////////////////////
// CTransform::operator- definition
CTransform CTransform::operator-(const CTransform& cTransform) const
{
CTransform cTemp;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
cTemp.m_afData[i][j] = m_afData[i][j] - cTransform.m_afData[i][j];
return cTemp;
}
///////////////////////////////////////////////////////////////////////
// CTransform::LookAt definition
void CTransform::LookAt(const CVec& cEye, const CVec& cCenter, const CVec& cUp)
{
CVec cF = cCenter - cEye;
cF.Normalize( );
CVec cUpPrime = cUp;
cUpPrime.Normalize( );
CVec cS = cF * cUpPrime;
CVec cU = cS * cF;
CTransform cTemp;
cTemp.m_afData[0][0] = cS[0];
cTemp.m_afData[1][0] = cS[1];
cTemp.m_afData[2][0] = cS[2];
cTemp.m_afData[0][1] = cU[0];
cTemp.m_afData[1][1] = cU[1];
cTemp.m_afData[2][1] = cU[2];
cTemp.m_afData[0][2] = -cF[0];
cTemp.m_afData[1][2] = -cF[1];
cTemp.m_afData[2][2] = -cF[2];
*this = cTemp * *this;
Translate(-cEye.m_afData[0], -cEye.m_afData[1], -cEye.m_afData[2]);
}
///////////////////////////////////////////////////////////////////////
// CTransform::ludcmp definition
CTransform::EInversionCodeType CTransform::ludcmp(float a[5][5], int n, int *indx, float *d)
{
// code was taken from Numerical Recipes in C
const double c_dTiny = 1.0e-20;
int i,imax,j,k;
float big,dum,sum,cTemp;
float vv[5];
*d = 1.0;
for (i = 1; i <= n; i++)
{
big = 0.0;
for (j = 1; j <= n; j++)
if ((cTemp = fabs(a[i][j])) > big)
big = cTemp;
if (big == 0.0)
{
return SINGULAR;
}
vv[i] = 1.0 / big;
}
for (j = 1; j <= n; j++)
{
for (i = 1; i < j; i++)
{
sum = a[i][j];
for (k = 1; k < i; k++)
sum -= a[i][k] * a[k][j];
a[i][j] = sum;
}
big=0.0;
for (i = j; i <= n; i++)
{
sum = a[i][j];
for (k = 1; k < j; k++)
sum -= a[i][k] * a[k][j];
a[i][j] = sum;
if ((dum = vv[i] * fabs(sum)) >= big)
{
big = dum;
imax = i;
}
}
if (j != imax)
{
for (k = 1; k <= n; k++)
{
dum = a[imax][k];
a[imax][k] = a[j][k];
a[j][k] = dum;
}
*d = -(*d);
vv[imax] = vv[j];
}
indx[j] = imax;
if (a[j][j] == 0.0)
a[j][j] = c_dTiny;
if (j != n)
{
dum = 1.0 / (a[j][j]);
for (i = j + 1; i <= n; i++)
a[i][j] *= dum;
}
}
return OK;
}
///////////////////////////////////////////////////////////////////////
// CTransform::lubksb definition
void CTransform::lubksb(float a[5][5], int n, int *indx, float b[ ])
{
// code was taken from Numerical Recipes in C
int i, ii = 0, ip, j;
float sum;
for (i = 1; i <= n; i++)
{
ip = indx[i];
sum = b[ip];
b[ip] = b[i];
if (ii)
for (j = ii; j <= i - 1; j++)
sum -= a[i][j] * b[j];
else if (sum)
ii=i;
b[i] = sum;
}
for (i = n; i >= 1 ; i--)
{
sum = b[i];
for (j = i + 1; j <= n; j++)
sum -= a[i][j] * b[j];
b[i] = sum / a[i][i];
}
}
*/
| [
"Myway3D@Gmail.com@ff49bfeb-f889-bd78-9ae6-4dc862721fa0"
] | Myway3D@Gmail.com@ff49bfeb-f889-bd78-9ae6-4dc862721fa0 |
8b9558325c9b370af03d3d841c73e537856255c3 | bd0f9f9e7d0256dcad2b618c4443f62b5484bf73 | /src/Google/OAuth2.cpp | 9434fe44446d5f010bb1fb9a19ac5f1c5a17e78f | [] | no_license | ufft47/QingfengCalendar | 694a1be2a4b049dd02b7538dcf6a047e5a68657a | f0f485b23ced31acbbed1108d764dab234e7ac0a | refs/heads/master | 2021-05-31T08:57:37.283136 | 2015-10-14T14:46:30 | 2015-10-14T14:46:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | cpp | #include "OAuth2.h"
#include <QApplication>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include "LoginDialog.h"
OAuth2::OAuth2(QWidget *parent)
{
m_end_point = "https://accounts.google.com/o/oauth2/auth";
m_scope = "https://www.googleapis.com/auth/calendar";
m_client_id = "135859676517-padra6sp9cd3ahqs0rs1j5l508e05nu1.apps.googleusercontent.com";
m_redirect_uri = "http://localhost";
m_response_type = "code";
m_login_dialog = new LoginDialog(parent);
m_parent = parent;
connect(m_login_dialog, SIGNAL(accessTokenObtained()), this,
SLOT(accessTokenObtained()));
}
void OAuth2::accessTokenObtained()
{
QSettings settings("Daizhe", "Qingfeng Calendar");
m_access_token = m_login_dialog->accessToken();
settings.setValue("access_token", m_access_token);
m_login_dialog->setLoginUrl("");
emit loginDone();
}
QString OAuth2::loginUrl()
{
QString str = QString(
"%1?client_id=%2&redirect_uri=%3&response_type=%4&scope=%5")
.arg(m_end_point).arg(m_client_id).arg(m_redirect_uri)
.arg(m_response_type).arg(m_scope);
qDebug() << "Login URL " << str;
return str;
}
QString OAuth2::accessToken()
{
return m_access_token;
}
bool OAuth2::isAuthorized()
{
return m_access_token != "";
}
void OAuth2::startLogin(bool force)
{
qDebug() << "OAuth2::startLogin";
QSettings settings("Daizhe", "Qingfeng Calendar");
QString str = settings.value("access_token", "").toString();
qDebug() << "OAuth2::startLogin, token from Settings: " << str;
if (str.isEmpty() || force) {
m_login_dialog->setLoginUrl(loginUrl());
m_login_dialog->show();
} else {
m_access_token = str;
emit loginDone();
}
}
| [
"qidaizhe11@gmail.com"
] | qidaizhe11@gmail.com |
42913771a15b814a5b10c1c92eb99e1d2668c677 | 00d092106cf24e95fdccd349d433170a21073eeb | /Region.cpp | 057e1e2aece229726c06cabf1f02659689b9ce8f | [] | no_license | 7Nate9/CS1440-HW5 | f9535a91d3160572b443e27eb6fc1f614e210005 | 5c21d83ed9093fbf2954c7a4579065652fbf54c9 | refs/heads/master | 2021-01-23T04:29:45.816084 | 2017-03-26T03:58:17 | 2017-03-26T03:58:17 | 86,205,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,841 | cpp | //
// Created by Stephen Clyde on 3/4/17.
//
#include "Region.h"
#include "Utils.h"
#include "World.h"
#include "Nation.h"
#include "State.h"
#include "County.h"
#include "City.h"
#include <iomanip>
const std::string regionDelimiter = "^^^";
const int TAB_SIZE = 4;
unsigned int Region::m_nextId = 0;
Region* Region::create(std::istream &in)
{
Region* region = nullptr;
std::string line;
std::getline(in, line);
if (line!="")
{
region = create(line);
if (region!= nullptr)
region->loadChildren(in);
}
return region;
}
Region* Region::create(const std::string& data)
{
Region* region = nullptr;
std::string regionData;
unsigned long commaPos = (int) data.find(",");
if (commaPos != std::string::npos)
{
std::string regionTypeStr = data.substr(0,commaPos);
regionData = data.substr(commaPos+1);
bool isValid;
RegionType regionType = (RegionType) convertStringToInt(regionTypeStr, &isValid);
if (isValid)
{
region = create(regionType, regionData);
}
}
return region;
}
Region* Region::create(RegionType regionType, const std::string& data)
{
Region* region = nullptr;
std::string fields[3];
if (split(data, ',', fields, 3)) {
// Create the region based on type
switch (regionType) {
case WorldType:
region = new World();
break;
case NationType:
region = new Nation(fields);
break;
// TODO: Add cases for State, County, and City
//Done
case StateType:
region = new State(fields);
break;
case CountyType:
region = new County(fields);
break;
case CityType:
region = new City(fields);
break;
// End of To Do
default:
break;
}
// If the region isn't valid, git ride of it
if (region != nullptr && !region->getIsValid()) {
delete region;
region = nullptr;
}
}
return region;
}
std::string Region::regionLabel(RegionType regionType)
{
std::string label = "Unknown";
switch (regionType)
{
case Region::WorldType:
label = "World";
break;
case Region::NationType:
label = "Nation";
break;
case Region::StateType:
label = "State";
break;
case Region::CountyType:
label = "County";
break;
case Region::CityType:
label = "City";
break;
default:
break;
}
return label;
}
Region::Region() { }
Region::Region(RegionType type, const std::string data[]) :
m_id(getNextId()), m_regionType(type), m_isValid(true)
{
m_name = data[0];
m_population = convertStringToUnsignedInt(data[1], &m_isValid);
if (m_isValid)
m_area = convertStringToDouble(data[2], &m_isValid);
}
Region::~Region()
{
// TODO: cleanup any dynamically allocated objects
for (Region* child : m_children)
{
delete child;
child = nullptr;
}
//End of To Do
}
std::string Region::getRegionLabel() const
{
return regionLabel(getType());
}
//Methods for managing subregions
void Region::appendSubRegion(Region* subRegion)
{
m_children.push_back(subRegion);
}
Region* Region::findId(unsigned int id)
{
if (m_id != id)
{
Region* foundRegion = nullptr;
for (Region* child : m_children)
{
foundRegion = child->findId(id);
if (foundRegion != nullptr)
break;
}
return foundRegion;
}
else
{
return this;
}
}
Region* Region::findSubRegionByIndex(unsigned int index)
{
if (index >= 0 && index < m_children.size())
return m_children[index];
else
return nullptr;
}
Region* Region::findParentByChildId(unsigned int id)
{
Region* parent = nullptr;
for (Region* child : m_children)
{
if (child->getId() == id)
parent = this;
}
if (!parent)
{
for (Region* child : m_children)
{
parent = child->findParentByChildId(id);
}
}
return parent;
}
void Region::removeSubRegion(Region *subRegion)
{
std::vector<Region*> childrenPostDelete;
for (Region* child : m_children)
{
if (child != subRegion)
{
childrenPostDelete.push_back(child);
}
else
{
delete child;
}
}
m_children = childrenPostDelete;
}
int Region::getSubRegionCount()
{
return m_children.size();
}
//End
unsigned int Region::computeTotalPopulation()
{
// TODO: implement computeTotalPopulation, such that the result is m_population + the total population for all sub-regions
//Done
unsigned int population = m_population;
for (Region* child : m_children)
{
population += child->computeTotalPopulation();
}
return population;
//End of To Do
}
void Region::list(std::ostream& out)
{
out << std::endl;
out << getName() << ":" << std::endl;
// TODO: implement the loop in the list method
//Done
// foreach subregion, print out
// id name
for (Region* child : m_children)
{
out << child->getId() << " : " << child->getName() << std::endl;
}
//End of To Do
}
void Region::display(std::ostream& out, unsigned int displayLevel, bool showChild)
{
if (displayLevel>0)
{
out << std::setw(displayLevel * TAB_SIZE) << " ";
}
unsigned totalPopulation = computeTotalPopulation();
double area = getArea();
double density = (double) totalPopulation / area;
// TODO: compute the totalPopulation using a method
//Done
out << std::setw(6) << getId() << " "
<< getName() << ", population="
<< totalPopulation
<< ", area=" << area
<< ", density=" << density << std::endl;
if (showChild)
{
// TODO: implement loop in display method
// foreach subregion
// display that subregion at displayLevel+1 with the same showChild value
//Done
for (Region* child : m_children)
{
child->display(out, displayLevel + 1, showChild);
}
//End of To Do
}
}
void Region::save(std::ostream& out)
{
out << getType()
<< "," << getName()
<< "," << getPopulation()
<< "," << getArea()
<< std::endl;
// TODO: implement loop in save method to save each sub-region
// foreach subregion,
// save that region
//Done
for (Region* child : m_children)
{
child->save(out);
}
//End of To Do
out << regionDelimiter << std::endl;
}
void Region::validate()
{
//m_isValid = (m_area!=UnknownRegionType && m_name!="" && m_area>=0);
m_isValid = (m_regionType!=UnknownRegionType && m_name!="" && m_area>=0);
}
void Region::loadChildren(std::istream& in)
{
std::string line;
bool done = false;
while (!in.eof() && !done)
{
std::getline(in, line);
if (line==regionDelimiter)
{
done = true;
}
else
{
Region* child = create(line);
if (child!= nullptr)
{
// TODO: Add the new sub-region to this region
//Done
m_children.push_back(child);
//End of To Do
child->loadChildren(in);
}
}
}
}
unsigned int Region::getNextId()
{
if (m_nextId==UINT32_MAX)
m_nextId=1;
return m_nextId++;
} | [
"Nate Lovell"
] | Nate Lovell |
5da705ad0c20ecb76ea3d81056d5ddef681a6fe1 | 63b82a1d4e645f5a1c2363f18e37a7d03be8cd4b | /Intermedios/Secuencia 2/Prueba.cpp | 771ceb5983bf69fa97ebef1b4e31f95481013aff | [] | no_license | Codedemons/Programing-C | bb4bae0fc6a756be5797a7b74ee360eab1108e0a | 3d2ec0ce4ff6b6c20199d3fc6a7dfcb32ec1ff55 | refs/heads/master | 2023-06-23T02:54:23.034555 | 2023-06-13T06:22:43 | 2023-06-13T06:22:43 | 290,343,123 | 1 | 0 | null | 2023-06-13T06:22:44 | 2020-08-25T23:09:07 | C | UTF-8 | C++ | false | false | 450 | cpp | #include<stdio.h>
#include<conio.h>
const int max = 1000;
int i,j,aux,cn,n[max];
int main()
{
printf("Dimension del Vector: ");
scanf("%d",&cn);
for(i=0;i<cn;i++)
{
printf("Ingrese el elemento %i: ",i+1);
scanf("%d",&n[i]);
}
for(i=1; i<cn; i++)
{
for(j=0; j<cn-i; j++)
{
if(n[j]>n[j+1])
{
aux = n[j+1];
n[j+1] = n[j];
n[j] = aux;
}
}
}
for(i=0;i<cn;i++)
{
printf("\n%d",n[i]);
}
return 0;
}
| [
"58617892+Codedemons@users.noreply.github.com"
] | 58617892+Codedemons@users.noreply.github.com |
8d19fbb277624d6b2a82e539c47b5b53533657fe | f298165c28590e5fa8643241424f385c38940d2e | /SDK/PUBG_ItemToolTipWidgetv3_parameters.hpp | 0cc95c70f4a3fdbddef47239aaccb35d3c5aaf73 | [] | no_license | ZoondEngine/Core | 2d35cc0121c7eb37b3744609e69f02a07fa36ac1 | 03cce9e7939c9654dc4da16e753eb62cbd9b1450 | refs/heads/master | 2020-03-14T01:16:16.972475 | 2018-04-28T04:49:50 | 2018-04-28T04:49:50 | 131,373,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,323 | hpp | #pragma once
// PLAYERUNKNOWN'S BATTLEGROUNDS (3.7.27.27) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetItemDetailedName
struct UItemToolTipWidgetv3_C_GetItemDetailedName_Params
{
class UEquipableItem* NewParam; // (Parm, ZeroConstructor, IsPlainOldData)
struct FText Name; // (Parm, OutParm)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.On_MagazineIcon_Prepass_1
struct UItemToolTipWidgetv3_C_On_MagazineIcon_Prepass_1_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetFiringRate
struct UItemToolTipWidgetv3_C_GetFiringRate_Params
{
class ATslWeapon_Trajectory* ShooterWeapon_Trajectory; // (Parm, ZeroConstructor, IsPlainOldData)
int AmmoClip; // (Parm, ZeroConstructor, IsPlainOldData)
float FullReloadingTime; // (Parm, ZeroConstructor, IsPlainOldData)
float FringRate; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetShooterWeapon
struct UItemToolTipWidgetv3_C_GetShooterWeapon_Params
{
class UEquipableItem* EquipableItem; // (Parm, ZeroConstructor, IsPlainOldData)
class ATslWeapon* ShooterWeapon; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
class ATslWeapon_Trajectory* ShooterWeapon_Trajectory; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.Clear
struct UItemToolTipWidgetv3_C_Clear_Params
{
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetAttachedAmmo
struct UItemToolTipWidgetv3_C_GetAttachedAmmo_Params
{
class UWeaponItem* WeaponItem; // (Parm, ZeroConstructor, IsPlainOldData)
int AmmoClip; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetAmmo
struct UItemToolTipWidgetv3_C_GetAmmo_Params
{
class UWeaponItem* WeaponItem; // (Parm, ZeroConstructor, IsPlainOldData)
int AmmoClip; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetAttachedStability
struct UItemToolTipWidgetv3_C_GetAttachedStability_Params
{
class ATslWeapon_Trajectory* ShooterWeapon_Trajectory; // (Parm, ZeroConstructor, IsPlainOldData)
float Accuracy; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetStability
struct UItemToolTipWidgetv3_C_GetStability_Params
{
class ATslWeapon_Trajectory* ShooterWeapon_Trajectory; // (Parm, ZeroConstructor, IsPlainOldData)
float Accuracy; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetWeaponEffectiveRange
struct UItemToolTipWidgetv3_C_GetWeaponEffectiveRange_Params
{
class ATslWeapon_Trajectory* ShooterWeapon_Trajectory; // (Parm, ZeroConstructor, IsPlainOldData)
float EffectRange; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.GetWeaponPower
struct UItemToolTipWidgetv3_C_GetWeaponPower_Params
{
class ATslWeapon* ShooterWeapon; // (Parm, ZeroConstructor, IsPlainOldData)
float Damage; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.FadeIn
struct UItemToolTipWidgetv3_C_FadeIn_Params
{
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.UpdateDefaultInfo
struct UItemToolTipWidgetv3_C_UpdateDefaultInfo_Params
{
TScriptInterface<class USlotInterface> Item; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.SetItemByInterface
struct UItemToolTipWidgetv3_C_SetItemByInterface_Params
{
TScriptInterface<class USlotInterface> Item; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.UpdateItemDetailInfo
struct UItemToolTipWidgetv3_C_UpdateItemDetailInfo_Params
{
class UItem* Item; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.Construct
struct UItemToolTipWidgetv3_C_Construct_Params
{
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.UpdateSlotInfo
struct UItemToolTipWidgetv3_C_UpdateSlotInfo_Params
{
TScriptInterface<class USlotInterface>* SlotInterface; // (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData)
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.SetToolTipOn
struct UItemToolTipWidgetv3_C_SetToolTipOn_Params
{
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.SetToolTipOff
struct UItemToolTipWidgetv3_C_SetToolTipOff_Params
{
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.StartFadeIn
struct UItemToolTipWidgetv3_C_StartFadeIn_Params
{
};
// Function ItemToolTipWidgetv3.ItemToolTipWidgetv3_C.ExecuteUbergraph_ItemToolTipWidgetv3
struct UItemToolTipWidgetv3_C_ExecuteUbergraph_ItemToolTipWidgetv3_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"mango.kamchatka.1997@gmail.com"
] | mango.kamchatka.1997@gmail.com |
4e9c9eb3f2cc8b4359e7a59b89c29478ccecb772 | 65a948570b3ef32d7b031fd5f2dd0944fe933336 | /test/test_first.cpp | b128664be3dabb7c9281ac789e2af6bc49216423 | [] | no_license | ner0-m/cxx-template | 0561cfc17889e3da82e82d7c84ec73bea3934b51 | 8ae70a71b6d930b1c9340fdad9ee500e0846c870 | refs/heads/master | 2021-05-19T07:21:18.480052 | 2021-04-04T10:39:18 | 2021-04-04T10:39:18 | 251,583,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | #include "doctest.h"
int factorial(int number)
{
return number <= 1 ? number : factorial(number - 1) * number;
}
TEST_CASE("testing the factorial function")
{
CHECK(factorial(1) == 1);
CHECK(factorial(2) == 2);
CHECK(factorial(3) == 6);
CHECK(factorial(10) == 3628800);
} | [
"frankd@in.tum.de"
] | frankd@in.tum.de |
0b66f0b7736618b698e16cbc51ca0ddbf1580753 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Codes/AC/2297.cpp | afea3eb49eb1139630569a853028f1bca3dee7e8 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | cpp | #include<bits/stdc++.h>
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define ll long long
#define ld long double
#define all(a) a.begin(),a.end()
#define endl '\n'
#define int long long
using namespace std;
const int N=1e7+1;
const int M=1e7+15;
int used[M];
vector<bool>p(M,true);
int pref[M];
main ()
{
ios_base :: sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
for (int i=1;i<=n;++i){
int x;
cin>>x;
used[x]++;
}
p[0]=false;
p[1]=false;
for (int i=2;i<=N-1;++i){
if (p[i]){
for (int j=i;j<=N-1;j+=i){
pref[i]+=used[j];
p[j]=false;
}
}
}
for (int i=2;i<=N-1;++i){
pref[i]+=pref[i-1];
}
int m;
cin>>m;
for (int i=1;i<=m;++i){
int l,r;
cin>>l>>r;
l=min(l,N-1);
r=min(r,N-1);
cout<<pref[r]-pref[l-1]<<endl;
}
}
| [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
aa41f670dc8fdd4f7b97e5dc4637b4903a8ed5ea | 4d8ecf28131be87ed76f5269a1462fa691af2b1b | /Bitmap.cpp | e39f26a399198e2a96f38f8fd8bc9a85eaee9d9b | [] | no_license | 0201jin/BedLam | 4e7cbae7f7714d88672c0c917cb8c5d1b0f0487e | 15c97bd43faedc07c7e30fc581f11998a173a6f7 | refs/heads/master | 2022-12-17T17:10:18.786339 | 2020-09-16T23:30:49 | 2020-09-16T23:30:49 | 296,167,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | #include "Bitmap.h"
#include "Define.h"
Bitmap::Bitmap(void)
{
}
Bitmap::~Bitmap(void)
{
}
Bitmap* Bitmap::LoadBmp(PTCHAR pFileName)
{
m_hdc = GetDC(g_hWnd);
m_MemDC = CreateCompatibleDC(m_hdc);
m_bitmap = (HBITMAP)LoadImage(NULL,pFileName, IMAGE_BITMAP
,0,0,LR_LOADFROMFILE | LR_CREATEDIBSECTION);
m_oldbitmap = (HBITMAP)SelectObject(m_MemDC, m_bitmap);
ReleaseDC(g_hWnd,m_hdc);
return this;
}
void Bitmap::Release()
{
SelectObject(m_MemDC,m_oldbitmap);
DeleteObject(m_bitmap);
DeleteDC(m_MemDC);
}
| [
"53131813+0201jin@users.noreply.github.com"
] | 53131813+0201jin@users.noreply.github.com |
3a75b67498063a27c43f92f168629f7147bdc545 | 8a70d60c9d279cc5895e63b638873ffff385c553 | /Unalyze/backup/analyze_20110405-0031.cxx | b92418f5e3b4740174b90500cf8534e1b26d38eb | [] | no_license | belmonrj/Run8dAu | 46394dfe84695bc489036ef2bc985105926099b9 | 60c0ed10841169db1c2a734a0dae9a15a1f93363 | refs/heads/master | 2021-01-19T15:11:59.517645 | 2017-02-16T21:31:16 | 2017-02-16T21:31:16 | 88,204,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 148,001 | cxx | // Author: Ron Belmont
// Date: 2010-05-17
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <map>
#include <sys/time.h>
#include "hadrontree.h"
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
using namespace std;
const float phbeta = 29.9792458;
const float mpion = 0.13957;
const float mkaon = 0.493677;
const float mproton = 0.938270;
map<string,int> myMap;
void GetRunIndex();
bool goodStrip(int i);
void fetchRunOffset();
void fetchStripOffset();
void fetchSlewingOffset();
void fetchMatching();
float stripoffset[512]; // 512 = number of strips
float runoffset[848]; // 848 = number of runs
//float slewingoffset(float qtofw);
float slewingoffset(int strip, float adc);
float Slewing_A[512];
float Slewing_B[512];
float mean_dz_pos_plusplus[512];
float mean_dz_neg_plusplus[512];
float mean_dphi_pos_plusplus[512];
float mean_dphi_neg_plusplus[512];
float mean_dz_pos_minusminus[512];
float mean_dz_neg_minusminus[512];
float mean_dphi_pos_minusminus[512];
float mean_dphi_neg_minusminus[512];
Long64_t nevents = 0;
Long64_t ntracks = 0;
Long64_t ngoodtofwevents = 0;
Long64_t ngoodtofwtracks = 0;
Long64_t ngoodtofwtracks_snglevent = 0;
float sigma_tofwdz(int charge, float mom, float tofwdz);
float sigma_tofwdphi(int charge, float mom, float tofwdphi);
float sigma_tofwdz_before(float mom, float tofwdz);
float sigma_tofwdphi_before(float mom, float tofwdphi);
float caltofwsdz(int run, int striptofw, int charge, float zed, float mom, float tofwdz);
float caltofwsdphi(int run, int striptofw, int charge, float zed, float mom, float tofwdphi);
//float recaltofwsdz(int run, int striptofw, int charge, float zed, float mom, float tofwsdz);
//float recaltofwsdphi(int run, int striptofw, int charge, float zed, float mom, float tofwsdphi);
float tunetofwsdz(int run, int charge, float mom, float cent, float tofwsdz);
float tunetofwsdphi(int run, int charge, float mom, float cent, float tofwsdphi);
//PID functions
float isPion(float pT, float m2tofw);
float isKaon(float pT, float m2tofw);
float isProton(float pT, float m2tofw);
bool GoodDCH(int run, float zed, float alpha, float phi);
bool GoodEdgeDCH(int run, float zed, float alpha, float phi);
bool GoodInnerDCH(int run, float zed, float alpha, float phi);
bool GoodPC1(float ppc1z, float ppc1phi);
bool GoodPC2(float pc2z, float pc2phi);
bool GoodPC3(float pc3z, float pc3phi);
// Main part of program
int main()
{
Char_t inFile[100];
Char_t outFile[100];
cout<<"Now beginning program"<<endl;
cout<<"Please enter input file name"<<endl;
cin>>inFile;
cout<<"Input file is "<<inFile<<endl;
cout<<"Please enter output file name"<<endl;
cin>>outFile;
cout<<"Output file is "<<outFile<<endl;
// ----------------------------
struct timeval Time;
gettimeofday(&Time,0);
int begintime = Time.tv_sec;
//cout<<"begintime is "<<begintime<<endl;
// ----------------------------
TFile *mData = new TFile(outFile,"recreate"); // declare output file
GetRunIndex(); // get runindex from data file
fetchRunOffset(); // get the run-by-run timing offsets
fetchStripOffset(); // get the strip-by-strip timing offsets
fetchSlewingOffset(); // get the slewing correction
fetchMatching(); // get the strip-by-strip matching correction
// -------------------------- //
// --- Declare histograms --- //
// -------------------------- //
TH1F *deltatdis = new TH1F("deltatdis","deltatdis",800, -2, 2);
TH1F *qtofwdis = new TH1F("qtofwdis","qtofwdis",1000,0,1000);
TH1F *tofwadcupdis = new TH1F("tofwadcupdis","tofwadcupdis",1000,0,1000);
TH1F *tofwadcdwdis = new TH1F("tofwadcdwdis","tofwadcdwdis",1000,0,1000);
TH2F *deltatrundis = new TH2F("deltatrundis","deltatrundis", 850,0,850, 800, -2, 2);
TH2F *deltatstriptofwdis = new TH2F("deltatstriptofwdis","deltatstriptofwdis", 512, 0, 512, 800, -2, 2);
TH2F *deltatslewingdis_q = new TH2F("deltatslewingdis_q","slewing (qtofw) distribution", 1000, 0, 1000, 800, -2, 2);
TH2F *deltatslewingdis_u = new TH2F("deltatslewingdis_u","slewing (adcup) distribution", 1000, 0, 1000, 800, -2, 2);
TH2F *deltatslewingdis_d = new TH2F("deltatslewingdis_d","slewing (adcdw) distribution", 1000, 0, 1000, 800, -2, 2);
// from run7 analysis
//TH2F *m2pTdis_pos = new TH2F("m2pTdis_pos","m2 vs pT", 100, 0.0, 10.0, 300, -1.0, 2.0);
//TH2F *m2pTdis_neg = new TH2F("m2pTdis_neg","m2 vs pT", 100, 0.0, 10.0, 300, -1.0, 2.0);
TH2F *m2mom_dis = new TH2F("m2mom_dis", "mom vs m2", 160, -8.0, 8.0, 300, -1.0, 2.0);
TH2F *m2mompos_dis = new TH2F("m2mompos_dis", "mom vs m2", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2momneg_dis = new TH2F("m2momneg_dis", "mom vs m2", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *ttofwmom_dis = new TH2F("ttofwmom_dis", "mom vs ttofw", 160, -8.0, 8.0, 500, -2.0, 4.0);
TH2F *ttofwmompos_dis = new TH2F("ttofwmompos_dis", "mom vs ttofw", 80, 0.0, 8.0, 500, -2.0, 4.0);
TH2F *ttofwmomneg_dis = new TH2F("ttofwmomneg_dis", "mom vs ttofw", 80, 0.0, 8.0, 500, -2.0, 4.0);
TH2F *m2mom_w1_dis = new TH2F("m2mom_w1_dis", "mom vs m2 sector 1 west", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2mom_w2_dis = new TH2F("m2mom_w2_dis", "mom vs m2 sector 2 west", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2mompos_w1_dis = new TH2F("m2mompos_w1_dis", "mom vs m2 sector 1 west", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2momneg_w1_dis = new TH2F("m2momneg_w1_dis", "mom vs m2 sector 1 west", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2mompos_w2_dis = new TH2F("m2mompos_w2_dis", "mom vs m2 sector 2 west", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2momneg_w2_dis = new TH2F("m2momneg_w2_dis", "mom vs m2 sector 2 west", 80, 0.0, 8.0, 300, -1.0, 2.0);
TH2F *m2pos_strip_dis = new TH2F("m2pos_strip_dis", "m2 vs strip ", 512, 0, 511, 300, -1.0, 2.0);
TH2F *m2neg_strip_dis = new TH2F("m2neg_strip_dis", "m2 vs strip ", 512, 0, 511, 300, -1.0, 2.0);
TH2F *m2pos_run_dis = new TH2F("m2pos_run_dis", "m2 vs run ", 512, 0, 511, 300, -1.0, 2.0);
TH2F *m2neg_run_dis = new TH2F("m2neg_run_dis", "m2 vs run ", 512, 0, 511, 300, -1.0, 2.0);
// -------------------------- //
// --- now pid histograms --- //
// -------------------------- //
TH1F *ptpid_tofw_pos_0_dis = new TH1F("ptpid_tofw_pos_0_dis", "tofw 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_1_dis = new TH1F("ptpid_tofw_pos_1_dis", "tofw 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_2_dis = new TH1F("ptpid_tofw_pos_2_dis", "tofw 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_3_dis = new TH1F("ptpid_tofw_pos_3_dis", "tofw 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_4_dis = new TH1F("ptpid_tofw_pos_4_dis", "tofw 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_5_dis = new TH1F("ptpid_tofw_pos_5_dis", "tofw 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_0_dis = new TH1F("ptpid_tofw_neg_0_dis", "tofw 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_1_dis = new TH1F("ptpid_tofw_neg_1_dis", "tofw 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_2_dis = new TH1F("ptpid_tofw_neg_2_dis", "tofw 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_3_dis = new TH1F("ptpid_tofw_neg_3_dis", "tofw 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_4_dis = new TH1F("ptpid_tofw_neg_4_dis", "tofw 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_5_dis = new TH1F("ptpid_tofw_neg_5_dis", "tofw 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_0_dis = new TH1F("ptpid_tofw_w1_pos_0_dis", "tofw_w1 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_1_dis = new TH1F("ptpid_tofw_w1_pos_1_dis", "tofw_w1 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_2_dis = new TH1F("ptpid_tofw_w1_pos_2_dis", "tofw_w1 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_3_dis = new TH1F("ptpid_tofw_w1_pos_3_dis", "tofw_w1 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_4_dis = new TH1F("ptpid_tofw_w1_pos_4_dis", "tofw_w1 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_5_dis = new TH1F("ptpid_tofw_w1_pos_5_dis", "tofw_w1 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_0_dis = new TH1F("ptpid_tofw_w1_neg_0_dis", "tofw_w1 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_1_dis = new TH1F("ptpid_tofw_w1_neg_1_dis", "tofw_w1 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_2_dis = new TH1F("ptpid_tofw_w1_neg_2_dis", "tofw_w1 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_3_dis = new TH1F("ptpid_tofw_w1_neg_3_dis", "tofw_w1 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_4_dis = new TH1F("ptpid_tofw_w1_neg_4_dis", "tofw_w1 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_5_dis = new TH1F("ptpid_tofw_w1_neg_5_dis", "tofw_w1 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_0_dis = new TH1F("ptpid_tofw_w2_pos_0_dis", "tofw_w2 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_1_dis = new TH1F("ptpid_tofw_w2_pos_1_dis", "tofw_w2 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_2_dis = new TH1F("ptpid_tofw_w2_pos_2_dis", "tofw_w2 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_3_dis = new TH1F("ptpid_tofw_w2_pos_3_dis", "tofw_w2 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_4_dis = new TH1F("ptpid_tofw_w2_pos_4_dis", "tofw_w2 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_5_dis = new TH1F("ptpid_tofw_w2_pos_5_dis", "tofw_w2 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_0_dis = new TH1F("ptpid_tofw_w2_neg_0_dis", "tofw_w2 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_1_dis = new TH1F("ptpid_tofw_w2_neg_1_dis", "tofw_w2 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_2_dis = new TH1F("ptpid_tofw_w2_neg_2_dis", "tofw_w2 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_3_dis = new TH1F("ptpid_tofw_w2_neg_3_dis", "tofw_w2 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_4_dis = new TH1F("ptpid_tofw_w2_neg_4_dis", "tofw_w2 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_5_dis = new TH1F("ptpid_tofw_w2_neg_5_dis", "tofw_w2 5 neg pr asym", 100, 0.0, 10.0);
// ---
// ---
// ---
TH1F *ptpid_tofw_pos_0_dis_cent0088 = new TH1F("ptpid_tofw_pos_0_dis_cent0088", "tofw 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_1_dis_cent0088 = new TH1F("ptpid_tofw_pos_1_dis_cent0088", "tofw 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_2_dis_cent0088 = new TH1F("ptpid_tofw_pos_2_dis_cent0088", "tofw 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_3_dis_cent0088 = new TH1F("ptpid_tofw_pos_3_dis_cent0088", "tofw 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_4_dis_cent0088 = new TH1F("ptpid_tofw_pos_4_dis_cent0088", "tofw 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_5_dis_cent0088 = new TH1F("ptpid_tofw_pos_5_dis_cent0088", "tofw 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_0_dis_cent0088 = new TH1F("ptpid_tofw_neg_0_dis_cent0088", "tofw 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_1_dis_cent0088 = new TH1F("ptpid_tofw_neg_1_dis_cent0088", "tofw 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_2_dis_cent0088 = new TH1F("ptpid_tofw_neg_2_dis_cent0088", "tofw 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_3_dis_cent0088 = new TH1F("ptpid_tofw_neg_3_dis_cent0088", "tofw 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_4_dis_cent0088 = new TH1F("ptpid_tofw_neg_4_dis_cent0088", "tofw 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_5_dis_cent0088 = new TH1F("ptpid_tofw_neg_5_dis_cent0088", "tofw 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_0_dis_cent0020 = new TH1F("ptpid_tofw_pos_0_dis_cent0020", "tofw 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_1_dis_cent0020 = new TH1F("ptpid_tofw_pos_1_dis_cent0020", "tofw 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_2_dis_cent0020 = new TH1F("ptpid_tofw_pos_2_dis_cent0020", "tofw 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_3_dis_cent0020 = new TH1F("ptpid_tofw_pos_3_dis_cent0020", "tofw 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_4_dis_cent0020 = new TH1F("ptpid_tofw_pos_4_dis_cent0020", "tofw 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_5_dis_cent0020 = new TH1F("ptpid_tofw_pos_5_dis_cent0020", "tofw 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_0_dis_cent0020 = new TH1F("ptpid_tofw_neg_0_dis_cent0020", "tofw 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_1_dis_cent0020 = new TH1F("ptpid_tofw_neg_1_dis_cent0020", "tofw 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_2_dis_cent0020 = new TH1F("ptpid_tofw_neg_2_dis_cent0020", "tofw 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_3_dis_cent0020 = new TH1F("ptpid_tofw_neg_3_dis_cent0020", "tofw 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_4_dis_cent0020 = new TH1F("ptpid_tofw_neg_4_dis_cent0020", "tofw 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_5_dis_cent0020 = new TH1F("ptpid_tofw_neg_5_dis_cent0020", "tofw 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_0_dis_cent2040 = new TH1F("ptpid_tofw_pos_0_dis_cent2040", "tofw 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_1_dis_cent2040 = new TH1F("ptpid_tofw_pos_1_dis_cent2040", "tofw 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_2_dis_cent2040 = new TH1F("ptpid_tofw_pos_2_dis_cent2040", "tofw 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_3_dis_cent2040 = new TH1F("ptpid_tofw_pos_3_dis_cent2040", "tofw 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_4_dis_cent2040 = new TH1F("ptpid_tofw_pos_4_dis_cent2040", "tofw 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_5_dis_cent2040 = new TH1F("ptpid_tofw_pos_5_dis_cent2040", "tofw 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_0_dis_cent2040 = new TH1F("ptpid_tofw_neg_0_dis_cent2040", "tofw 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_1_dis_cent2040 = new TH1F("ptpid_tofw_neg_1_dis_cent2040", "tofw 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_2_dis_cent2040 = new TH1F("ptpid_tofw_neg_2_dis_cent2040", "tofw 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_3_dis_cent2040 = new TH1F("ptpid_tofw_neg_3_dis_cent2040", "tofw 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_4_dis_cent2040 = new TH1F("ptpid_tofw_neg_4_dis_cent2040", "tofw 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_5_dis_cent2040 = new TH1F("ptpid_tofw_neg_5_dis_cent2040", "tofw 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_0_dis_cent4060 = new TH1F("ptpid_tofw_pos_0_dis_cent4060", "tofw 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_1_dis_cent4060 = new TH1F("ptpid_tofw_pos_1_dis_cent4060", "tofw 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_2_dis_cent4060 = new TH1F("ptpid_tofw_pos_2_dis_cent4060", "tofw 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_3_dis_cent4060 = new TH1F("ptpid_tofw_pos_3_dis_cent4060", "tofw 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_4_dis_cent4060 = new TH1F("ptpid_tofw_pos_4_dis_cent4060", "tofw 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_5_dis_cent4060 = new TH1F("ptpid_tofw_pos_5_dis_cent4060", "tofw 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_0_dis_cent4060 = new TH1F("ptpid_tofw_neg_0_dis_cent4060", "tofw 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_1_dis_cent4060 = new TH1F("ptpid_tofw_neg_1_dis_cent4060", "tofw 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_2_dis_cent4060 = new TH1F("ptpid_tofw_neg_2_dis_cent4060", "tofw 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_3_dis_cent4060 = new TH1F("ptpid_tofw_neg_3_dis_cent4060", "tofw 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_4_dis_cent4060 = new TH1F("ptpid_tofw_neg_4_dis_cent4060", "tofw 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_5_dis_cent4060 = new TH1F("ptpid_tofw_neg_5_dis_cent4060", "tofw 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_0_dis_cent6088 = new TH1F("ptpid_tofw_pos_0_dis_cent6088", "tofw 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_1_dis_cent6088 = new TH1F("ptpid_tofw_pos_1_dis_cent6088", "tofw 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_2_dis_cent6088 = new TH1F("ptpid_tofw_pos_2_dis_cent6088", "tofw 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_3_dis_cent6088 = new TH1F("ptpid_tofw_pos_3_dis_cent6088", "tofw 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_4_dis_cent6088 = new TH1F("ptpid_tofw_pos_4_dis_cent6088", "tofw 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_pos_5_dis_cent6088 = new TH1F("ptpid_tofw_pos_5_dis_cent6088", "tofw 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_0_dis_cent6088 = new TH1F("ptpid_tofw_neg_0_dis_cent6088", "tofw 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_1_dis_cent6088 = new TH1F("ptpid_tofw_neg_1_dis_cent6088", "tofw 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_2_dis_cent6088 = new TH1F("ptpid_tofw_neg_2_dis_cent6088", "tofw 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_3_dis_cent6088 = new TH1F("ptpid_tofw_neg_3_dis_cent6088", "tofw 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_4_dis_cent6088 = new TH1F("ptpid_tofw_neg_4_dis_cent6088", "tofw 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_neg_5_dis_cent6088 = new TH1F("ptpid_tofw_neg_5_dis_cent6088", "tofw 5 neg pr asym", 100, 0.0, 10.0);
// ---
// ---
// ---
TH1F *ptpid_tofw_w1_pos_0_dis_cent0088 = new TH1F("ptpid_tofw_w1_pos_0_dis_cent0088", "tofw_w1 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_1_dis_cent0088 = new TH1F("ptpid_tofw_w1_pos_1_dis_cent0088", "tofw_w1 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_2_dis_cent0088 = new TH1F("ptpid_tofw_w1_pos_2_dis_cent0088", "tofw_w1 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_3_dis_cent0088 = new TH1F("ptpid_tofw_w1_pos_3_dis_cent0088", "tofw_w1 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_4_dis_cent0088 = new TH1F("ptpid_tofw_w1_pos_4_dis_cent0088", "tofw_w1 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_5_dis_cent0088 = new TH1F("ptpid_tofw_w1_pos_5_dis_cent0088", "tofw_w1 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_0_dis_cent0088 = new TH1F("ptpid_tofw_w1_neg_0_dis_cent0088", "tofw_w1 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_1_dis_cent0088 = new TH1F("ptpid_tofw_w1_neg_1_dis_cent0088", "tofw_w1 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_2_dis_cent0088 = new TH1F("ptpid_tofw_w1_neg_2_dis_cent0088", "tofw_w1 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_3_dis_cent0088 = new TH1F("ptpid_tofw_w1_neg_3_dis_cent0088", "tofw_w1 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_4_dis_cent0088 = new TH1F("ptpid_tofw_w1_neg_4_dis_cent0088", "tofw_w1 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_5_dis_cent0088 = new TH1F("ptpid_tofw_w1_neg_5_dis_cent0088", "tofw_w1 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_0_dis_cent0020 = new TH1F("ptpid_tofw_w1_pos_0_dis_cent0020", "tofw_w1 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_1_dis_cent0020 = new TH1F("ptpid_tofw_w1_pos_1_dis_cent0020", "tofw_w1 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_2_dis_cent0020 = new TH1F("ptpid_tofw_w1_pos_2_dis_cent0020", "tofw_w1 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_3_dis_cent0020 = new TH1F("ptpid_tofw_w1_pos_3_dis_cent0020", "tofw_w1 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_4_dis_cent0020 = new TH1F("ptpid_tofw_w1_pos_4_dis_cent0020", "tofw_w1 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_5_dis_cent0020 = new TH1F("ptpid_tofw_w1_pos_5_dis_cent0020", "tofw_w1 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_0_dis_cent0020 = new TH1F("ptpid_tofw_w1_neg_0_dis_cent0020", "tofw_w1 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_1_dis_cent0020 = new TH1F("ptpid_tofw_w1_neg_1_dis_cent0020", "tofw_w1 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_2_dis_cent0020 = new TH1F("ptpid_tofw_w1_neg_2_dis_cent0020", "tofw_w1 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_3_dis_cent0020 = new TH1F("ptpid_tofw_w1_neg_3_dis_cent0020", "tofw_w1 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_4_dis_cent0020 = new TH1F("ptpid_tofw_w1_neg_4_dis_cent0020", "tofw_w1 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_5_dis_cent0020 = new TH1F("ptpid_tofw_w1_neg_5_dis_cent0020", "tofw_w1 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_0_dis_cent2040 = new TH1F("ptpid_tofw_w1_pos_0_dis_cent2040", "tofw_w1 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_1_dis_cent2040 = new TH1F("ptpid_tofw_w1_pos_1_dis_cent2040", "tofw_w1 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_2_dis_cent2040 = new TH1F("ptpid_tofw_w1_pos_2_dis_cent2040", "tofw_w1 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_3_dis_cent2040 = new TH1F("ptpid_tofw_w1_pos_3_dis_cent2040", "tofw_w1 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_4_dis_cent2040 = new TH1F("ptpid_tofw_w1_pos_4_dis_cent2040", "tofw_w1 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_5_dis_cent2040 = new TH1F("ptpid_tofw_w1_pos_5_dis_cent2040", "tofw_w1 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_0_dis_cent2040 = new TH1F("ptpid_tofw_w1_neg_0_dis_cent2040", "tofw_w1 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_1_dis_cent2040 = new TH1F("ptpid_tofw_w1_neg_1_dis_cent2040", "tofw_w1 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_2_dis_cent2040 = new TH1F("ptpid_tofw_w1_neg_2_dis_cent2040", "tofw_w1 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_3_dis_cent2040 = new TH1F("ptpid_tofw_w1_neg_3_dis_cent2040", "tofw_w1 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_4_dis_cent2040 = new TH1F("ptpid_tofw_w1_neg_4_dis_cent2040", "tofw_w1 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_5_dis_cent2040 = new TH1F("ptpid_tofw_w1_neg_5_dis_cent2040", "tofw_w1 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_0_dis_cent4060 = new TH1F("ptpid_tofw_w1_pos_0_dis_cent4060", "tofw_w1 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_1_dis_cent4060 = new TH1F("ptpid_tofw_w1_pos_1_dis_cent4060", "tofw_w1 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_2_dis_cent4060 = new TH1F("ptpid_tofw_w1_pos_2_dis_cent4060", "tofw_w1 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_3_dis_cent4060 = new TH1F("ptpid_tofw_w1_pos_3_dis_cent4060", "tofw_w1 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_4_dis_cent4060 = new TH1F("ptpid_tofw_w1_pos_4_dis_cent4060", "tofw_w1 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_5_dis_cent4060 = new TH1F("ptpid_tofw_w1_pos_5_dis_cent4060", "tofw_w1 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_0_dis_cent4060 = new TH1F("ptpid_tofw_w1_neg_0_dis_cent4060", "tofw_w1 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_1_dis_cent4060 = new TH1F("ptpid_tofw_w1_neg_1_dis_cent4060", "tofw_w1 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_2_dis_cent4060 = new TH1F("ptpid_tofw_w1_neg_2_dis_cent4060", "tofw_w1 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_3_dis_cent4060 = new TH1F("ptpid_tofw_w1_neg_3_dis_cent4060", "tofw_w1 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_4_dis_cent4060 = new TH1F("ptpid_tofw_w1_neg_4_dis_cent4060", "tofw_w1 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_5_dis_cent4060 = new TH1F("ptpid_tofw_w1_neg_5_dis_cent4060", "tofw_w1 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_0_dis_cent6088 = new TH1F("ptpid_tofw_w1_pos_0_dis_cent6088", "tofw_w1 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_1_dis_cent6088 = new TH1F("ptpid_tofw_w1_pos_1_dis_cent6088", "tofw_w1 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_2_dis_cent6088 = new TH1F("ptpid_tofw_w1_pos_2_dis_cent6088", "tofw_w1 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_3_dis_cent6088 = new TH1F("ptpid_tofw_w1_pos_3_dis_cent6088", "tofw_w1 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_4_dis_cent6088 = new TH1F("ptpid_tofw_w1_pos_4_dis_cent6088", "tofw_w1 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_pos_5_dis_cent6088 = new TH1F("ptpid_tofw_w1_pos_5_dis_cent6088", "tofw_w1 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_0_dis_cent6088 = new TH1F("ptpid_tofw_w1_neg_0_dis_cent6088", "tofw_w1 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_1_dis_cent6088 = new TH1F("ptpid_tofw_w1_neg_1_dis_cent6088", "tofw_w1 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_2_dis_cent6088 = new TH1F("ptpid_tofw_w1_neg_2_dis_cent6088", "tofw_w1 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_3_dis_cent6088 = new TH1F("ptpid_tofw_w1_neg_3_dis_cent6088", "tofw_w1 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_4_dis_cent6088 = new TH1F("ptpid_tofw_w1_neg_4_dis_cent6088", "tofw_w1 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w1_neg_5_dis_cent6088 = new TH1F("ptpid_tofw_w1_neg_5_dis_cent6088", "tofw_w1 5 neg pr asym", 100, 0.0, 10.0);
// ---
// ---
// ---
TH1F *ptpid_tofw_w2_pos_0_dis_cent0088 = new TH1F("ptpid_tofw_w2_pos_0_dis_cent0088", "tofw_w2 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_1_dis_cent0088 = new TH1F("ptpid_tofw_w2_pos_1_dis_cent0088", "tofw_w2 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_2_dis_cent0088 = new TH1F("ptpid_tofw_w2_pos_2_dis_cent0088", "tofw_w2 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_3_dis_cent0088 = new TH1F("ptpid_tofw_w2_pos_3_dis_cent0088", "tofw_w2 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_4_dis_cent0088 = new TH1F("ptpid_tofw_w2_pos_4_dis_cent0088", "tofw_w2 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_5_dis_cent0088 = new TH1F("ptpid_tofw_w2_pos_5_dis_cent0088", "tofw_w2 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_0_dis_cent0088 = new TH1F("ptpid_tofw_w2_neg_0_dis_cent0088", "tofw_w2 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_1_dis_cent0088 = new TH1F("ptpid_tofw_w2_neg_1_dis_cent0088", "tofw_w2 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_2_dis_cent0088 = new TH1F("ptpid_tofw_w2_neg_2_dis_cent0088", "tofw_w2 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_3_dis_cent0088 = new TH1F("ptpid_tofw_w2_neg_3_dis_cent0088", "tofw_w2 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_4_dis_cent0088 = new TH1F("ptpid_tofw_w2_neg_4_dis_cent0088", "tofw_w2 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_5_dis_cent0088 = new TH1F("ptpid_tofw_w2_neg_5_dis_cent0088", "tofw_w2 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_0_dis_cent0020 = new TH1F("ptpid_tofw_w2_pos_0_dis_cent0020", "tofw_w2 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_1_dis_cent0020 = new TH1F("ptpid_tofw_w2_pos_1_dis_cent0020", "tofw_w2 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_2_dis_cent0020 = new TH1F("ptpid_tofw_w2_pos_2_dis_cent0020", "tofw_w2 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_3_dis_cent0020 = new TH1F("ptpid_tofw_w2_pos_3_dis_cent0020", "tofw_w2 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_4_dis_cent0020 = new TH1F("ptpid_tofw_w2_pos_4_dis_cent0020", "tofw_w2 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_5_dis_cent0020 = new TH1F("ptpid_tofw_w2_pos_5_dis_cent0020", "tofw_w2 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_0_dis_cent0020 = new TH1F("ptpid_tofw_w2_neg_0_dis_cent0020", "tofw_w2 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_1_dis_cent0020 = new TH1F("ptpid_tofw_w2_neg_1_dis_cent0020", "tofw_w2 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_2_dis_cent0020 = new TH1F("ptpid_tofw_w2_neg_2_dis_cent0020", "tofw_w2 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_3_dis_cent0020 = new TH1F("ptpid_tofw_w2_neg_3_dis_cent0020", "tofw_w2 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_4_dis_cent0020 = new TH1F("ptpid_tofw_w2_neg_4_dis_cent0020", "tofw_w2 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_5_dis_cent0020 = new TH1F("ptpid_tofw_w2_neg_5_dis_cent0020", "tofw_w2 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_0_dis_cent2040 = new TH1F("ptpid_tofw_w2_pos_0_dis_cent2040", "tofw_w2 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_1_dis_cent2040 = new TH1F("ptpid_tofw_w2_pos_1_dis_cent2040", "tofw_w2 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_2_dis_cent2040 = new TH1F("ptpid_tofw_w2_pos_2_dis_cent2040", "tofw_w2 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_3_dis_cent2040 = new TH1F("ptpid_tofw_w2_pos_3_dis_cent2040", "tofw_w2 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_4_dis_cent2040 = new TH1F("ptpid_tofw_w2_pos_4_dis_cent2040", "tofw_w2 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_5_dis_cent2040 = new TH1F("ptpid_tofw_w2_pos_5_dis_cent2040", "tofw_w2 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_0_dis_cent2040 = new TH1F("ptpid_tofw_w2_neg_0_dis_cent2040", "tofw_w2 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_1_dis_cent2040 = new TH1F("ptpid_tofw_w2_neg_1_dis_cent2040", "tofw_w2 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_2_dis_cent2040 = new TH1F("ptpid_tofw_w2_neg_2_dis_cent2040", "tofw_w2 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_3_dis_cent2040 = new TH1F("ptpid_tofw_w2_neg_3_dis_cent2040", "tofw_w2 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_4_dis_cent2040 = new TH1F("ptpid_tofw_w2_neg_4_dis_cent2040", "tofw_w2 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_5_dis_cent2040 = new TH1F("ptpid_tofw_w2_neg_5_dis_cent2040", "tofw_w2 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_0_dis_cent4060 = new TH1F("ptpid_tofw_w2_pos_0_dis_cent4060", "tofw_w2 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_1_dis_cent4060 = new TH1F("ptpid_tofw_w2_pos_1_dis_cent4060", "tofw_w2 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_2_dis_cent4060 = new TH1F("ptpid_tofw_w2_pos_2_dis_cent4060", "tofw_w2 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_3_dis_cent4060 = new TH1F("ptpid_tofw_w2_pos_3_dis_cent4060", "tofw_w2 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_4_dis_cent4060 = new TH1F("ptpid_tofw_w2_pos_4_dis_cent4060", "tofw_w2 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_5_dis_cent4060 = new TH1F("ptpid_tofw_w2_pos_5_dis_cent4060", "tofw_w2 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_0_dis_cent4060 = new TH1F("ptpid_tofw_w2_neg_0_dis_cent4060", "tofw_w2 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_1_dis_cent4060 = new TH1F("ptpid_tofw_w2_neg_1_dis_cent4060", "tofw_w2 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_2_dis_cent4060 = new TH1F("ptpid_tofw_w2_neg_2_dis_cent4060", "tofw_w2 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_3_dis_cent4060 = new TH1F("ptpid_tofw_w2_neg_3_dis_cent4060", "tofw_w2 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_4_dis_cent4060 = new TH1F("ptpid_tofw_w2_neg_4_dis_cent4060", "tofw_w2 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_5_dis_cent4060 = new TH1F("ptpid_tofw_w2_neg_5_dis_cent4060", "tofw_w2 5 neg pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_0_dis_cent6088 = new TH1F("ptpid_tofw_w2_pos_0_dis_cent6088", "tofw_w2 0 pos pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_1_dis_cent6088 = new TH1F("ptpid_tofw_w2_pos_1_dis_cent6088", "tofw_w2 1 pos pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_2_dis_cent6088 = new TH1F("ptpid_tofw_w2_pos_2_dis_cent6088", "tofw_w2 2 pos ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_3_dis_cent6088 = new TH1F("ptpid_tofw_w2_pos_3_dis_cent6088", "tofw_w2 3 pos ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_4_dis_cent6088 = new TH1F("ptpid_tofw_w2_pos_4_dis_cent6088", "tofw_w2 4 pos pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_pos_5_dis_cent6088 = new TH1F("ptpid_tofw_w2_pos_5_dis_cent6088", "tofw_w2 5 pos pr asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_0_dis_cent6088 = new TH1F("ptpid_tofw_w2_neg_0_dis_cent6088", "tofw_w2 0 neg pi sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_1_dis_cent6088 = new TH1F("ptpid_tofw_w2_neg_1_dis_cent6088", "tofw_w2 1 neg pi asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_2_dis_cent6088 = new TH1F("ptpid_tofw_w2_neg_2_dis_cent6088", "tofw_w2 2 neg ka sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_3_dis_cent6088 = new TH1F("ptpid_tofw_w2_neg_3_dis_cent6088", "tofw_w2 3 neg ka asym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_4_dis_cent6088 = new TH1F("ptpid_tofw_w2_neg_4_dis_cent6088", "tofw_w2 4 neg pr sym", 100, 0.0, 10.0);
TH1F *ptpid_tofw_w2_neg_5_dis_cent6088 = new TH1F("ptpid_tofw_w2_neg_5_dis_cent6088", "tofw_w2 5 neg pr asym", 100, 0.0, 10.0);
// ---
// ---
// ---
// DC fiducial maps
TH2F *hh_alphaphi_poszed_nc_FW = new TH2F("hh_alphaphi_poszed_nc_FW","alpha vs phi zed>0 no cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_negzed_nc_FW = new TH2F("hh_alphaphi_negzed_nc_FW","alpha vs phi zed<0 no cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_poszed_mc_FW = new TH2F("hh_alphaphi_poszed_mc_FW","alpha vs phi zed>0 matching cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_negzed_mc_FW = new TH2F("hh_alphaphi_negzed_mc_FW","alpha vs phi zed<0 matching cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_poszed_ec_FW = new TH2F("hh_alphaphi_poszed_ec_FW","alpha vs phi zed>0 edge cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_negzed_ec_FW = new TH2F("hh_alphaphi_negzed_ec_FW","alpha vs phi zed<0 edge cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_poszed_ac_FW = new TH2F("hh_alphaphi_poszed_ac_FW","alpha vs phi zed>0 all cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
TH2F *hh_alphaphi_negzed_ac_FW = new TH2F("hh_alphaphi_negzed_ac_FW","alpha vs phi zed<0 all cuts", 920, -0.22, 0.7, 420, -0.21, 0.21);
// no cuts
// zed>0
TH2F *hh_alphaphi_poszed_nc = new TH2F("hh_alphaphi_poszed_nc","alpha vs phi zed>0 no cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_poszed_nc = new TH2F("hh_pos_momphi_poszed_nc","pT vs phi zed>0 no cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_poszed_nc = new TH2F("hh_neg_momphi_poszed_nc","pT vs phi zed>0 no cuts", 1500, -0.5, 1.0, 100, 0, 10);
// zed<0
TH2F *hh_alphaphi_negzed_nc = new TH2F("hh_alphaphi_negzed_nc","alpha vs phi zed<0 no cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_negzed_nc = new TH2F("hh_pos_momphi_negzed_nc","pT vs phi zed<0 no cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_negzed_nc = new TH2F("hh_neg_momphi_negzed_nc","pT vs phi zed<0 no cuts", 1500, -0.5, 1.0, 100, 0, 10);
// matching cuts
// zed>0
TH2F *hh_alphaphi_poszed_mc = new TH2F("hh_alphaphi_poszed_mc","alpha vs phi zed>0 matching cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_poszed_mc = new TH2F("hh_pos_momphi_poszed_mc","pT vs phi zed>0 matching cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_poszed_mc = new TH2F("hh_neg_momphi_poszed_mc","pT vs phi zed>0 matching cuts", 1500, -0.5, 1.0, 100, 0, 10);
// zed<0
TH2F *hh_alphaphi_negzed_mc = new TH2F("hh_alphaphi_negzed_mc","alpha vs phi zed<0 matching cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_negzed_mc = new TH2F("hh_pos_momphi_negzed_mc","pT vs phi zed<0 matching cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_negzed_mc = new TH2F("hh_neg_momphi_negzed_mc","pT vs phi zed<0 matching cuts", 1500, -0.5, 1.0, 100, 0, 10);
// edge cuts
// zed>0
TH2F *hh_alphaphi_poszed_ec = new TH2F("hh_alphaphi_poszed_ec","alpha vs phi zed>0 edge cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_poszed_ec = new TH2F("hh_pos_momphi_poszed_ec","pT vs phi zed>0 edge cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_poszed_ec = new TH2F("hh_neg_momphi_poszed_ec","pT vs phi zed>0 edge cuts", 1500, -0.5, 1.0, 100, 0, 10);
// zed<0
TH2F *hh_alphaphi_negzed_ec = new TH2F("hh_alphaphi_negzed_ec","alpha vs phi zed<0 edge cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_negzed_ec = new TH2F("hh_pos_momphi_negzed_ec","pT vs phi zed<0 edge cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_negzed_ec = new TH2F("hh_neg_momphi_negzed_ec","pT vs phi zed<0 edge cuts", 1500, -0.5, 1.0, 100, 0, 10);
// all cuts
// zed>0
TH2F *hh_alphaphi_poszed_ac = new TH2F("hh_alphaphi_poszed_ac","alpha vs phi zed>0 all cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_poszed_ac = new TH2F("hh_pos_momphi_poszed_ac","pT vs phi zed>0 all cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_poszed_ac = new TH2F("hh_neg_momphi_poszed_ac","pT vs phi zed>0 all cuts", 1500, -0.5, 1.0, 100, 0, 10);
// zed<0
TH2F *hh_alphaphi_negzed_ac = new TH2F("hh_alphaphi_negzed_ac","alpha vs phi zed<0 all cuts", 1500, -0.5, 1.0, 1200, -0.6, 0.6);
TH2F *hh_pos_momphi_negzed_ac = new TH2F("hh_pos_momphi_negzed_ac","pT vs phi zed<0 all cuts", 1500, -0.5, 1.0, 100, 0, 10);
TH2F *hh_neg_momphi_negzed_ac = new TH2F("hh_neg_momphi_negzed_ac","pT vs phi zed<0 all cuts", 1500, -0.5, 1.0, 100, 0, 10);
// dc zed vs phi
TH2F *hh_zedphi_nc = new TH2F("hh_zedphi_nc","phi vs zed no cuts", 160, -80, 80, 1300, -0.4, 0.9);
TH2F *hh_zedphi_mc = new TH2F("hh_zedphi_mc","phi vs zed matching cuts", 160, -80, 80, 1300, -0.4, 0.9);
TH2F *hh_zedphi_ec = new TH2F("hh_zedphi_ec","phi vs zed edge cuts", 160, -80, 80, 1300, -0.4, 0.9);
TH2F *hh_zedphi_ac = new TH2F("hh_zedphi_ac","phi vs zed all cuts", 160, -80, 80, 1300, -0.4, 0.9);
//Pad Chamber Fiducial Cut Histograms
TH2F *PC1ZedPhiDis = new TH2F("PC1ZedPhiDis", "PC1 phi vs zed w/o FC", 400, -200, 200, 500, -0.3, 0.7);
TH2F *PC1ZedPhiNewDis = new TH2F("PC1ZedPhiNewDis", "PC1 phi vs zed w/ FC", 400, -200, 200, 500, -0.3, 0.7);
TH2F *PC2ZedPhiDis = new TH2F("PC2ZedPhiDis", "PC2 phi vs zed w/o FC", 400, -200, 200, 500, -0.3, 0.7);
TH2F *PC2ZedPhiNewDis = new TH2F("PC2ZedPhiNewDis", "PC2 phi vs zed w/ FC",400, -200, 200, 500, -0.3, 0.7);
TH2F *PC3ZedPhiDis = new TH2F("PC3ZedPhiDis", "PC3 phi vs zed w/o FC", 400, -200, 200, 500, -0.3, 0.7);
TH2F *PC3ZedPhiNewDis = new TH2F("PC3ZedPhiNewDis", "PC3 phi vs zed w/ FC", 400, -200, 200, 500, -0.3, 0.7);
// tofw fiducial histograms
TH2F *TOFWZedPhiDis = new TH2F("TOFWZedPhiDis", "TOFW phi vs zed w/o FC", 400, -200, 200, 500, -0.3, 0.7);
TH2F *TOFWZedPhiNewDis = new TH2F("TOFWZedPhiNewDis", "TOFW phi vs zed w/ FC", 400, -200, 200, 500, -0.3, 0.7);
TH2F *TOFWZedPhiNewNewDis = new TH2F("TOFWZedPhiNewNewDis", "TOFW phi vs zed w/ all FC", 400, -200, 200, 500, -0.3, 0.7);
// --- Done with Histograms ---------------------
//Now read in the pDSTs listed in the input files
int ifile=0;
char filename[100];
ifstream fin(inFile);
if(!fin)
{
cout<<"list input error: file does not exist "<<endl;
exit(1);
}
while(fin.getline(filename,100))
{
ifile++;
cout<<ifile<<" "<<filename<<endl;
TFile *f = TFile::Open(filename);
if(!f)
{
cout<<"pDST input error: file does not exist "<<endl;
continue;
//exit(0);
}
nevents += (Long64_t)((TH1F *)f->Get("hcent"))->GetEntries();
TTree *t=(TTree *)f->Get("hadrontree");
if(!t)
{
cout<<"pDST input error: cannot find tree "<<endl;
continue;
//exit(0);
}
int n=(int)t->GetEntries(); // number of events in tree
hadrontree *ktree = new hadrontree(t); // pointer to tree
for(int i=0;i<n;i++) // loop over events
{
//reset to 0 for every event
ngoodtofwtracks_snglevent = 0;
ktree->GetEntry(i);
int run = ktree->run;
//if(run>250484) continue; // ++ only
//if(run<250593) continue; // -- only
stringstream ss;
ss<<run;
int runindex = myMap[ss.str()];
float bbcz = ktree->bbcz;
float cent = ktree->cent;
//if(fabs(bbcz)>30) continue;
//if(cent<0||cent>=100) continue;
int icent=-1;
if (cent>0 && cent<=20) icent=0;
else if (cent>20 && cent<=40) icent=1;
else if (cent>40 && cent<=60) icent=2;
else if (cent>60 && cent<=90) icent=3;
for(int itrk=0; itrk<ktree->mNtrack; itrk++)
{
ntracks++; // count total number of tracks
int charge = ktree->HadronTracks_charge[itrk];
float alpha = ktree->HadronTracks_alpha[itrk];
float phi = ktree->HadronTracks_phi[itrk];
float phi0 = ktree->HadronTracks_phi0[itrk];
float the0 = ktree->HadronTracks_the0[itrk];
float mom = ktree->HadronTracks_mom[itrk];
float zed = ktree->HadronTracks_zed[itrk];
float pc3sdz = ktree->HadronTracks_pc3sdz[itrk];
float pc3sdphi = ktree->HadronTracks_pc3sdphi[itrk];
float tofwdz = ktree->HadronTracks_tofwdz[itrk];
float tofwdphi = ktree->HadronTracks_tofwdphi[itrk];
int striptofw = (int)ktree->HadronTracks_striptofw[itrk];
float tofwadcup = ktree->HadronTracks_tofwadcup[itrk];
float tofwadcdw = ktree->HadronTracks_tofwadcdw[itrk];
float pltofw = ktree->HadronTracks_pltofw[itrk];
float ttofw = ktree->HadronTracks_ttofw[itrk];
if(fabs(zed)<3.0||fabs(zed)>75.0) continue;
if(!goodStrip(striptofw)) continue;
float pt = mom*sin(the0);
float pT = pt;
if(pT<0.2) continue;
hh_zedphi_nc->Fill(zed,phi);
if(zed>0)
{
hh_alphaphi_poszed_nc->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_poszed_nc_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_poszed_nc->Fill(phi,pT);
if(charge<0) hh_neg_momphi_poszed_nc->Fill(phi,pT);
}
if(zed<0)
{
hh_alphaphi_negzed_nc->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_negzed_nc->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_negzed_nc->Fill(phi,pT);
if(charge<0) hh_neg_momphi_negzed_nc->Fill(phi,pT);
}
float beta = pltofw/ttofw/phbeta;
float qtofw = (tofwadcup+tofwadcdw)/2.0;
if(striptofw<0||striptofw>511)
{
cout<<"BAD STRIP NUMBER!!! WTF!!! "<<striptofw<<endl;
continue;
}
if(qtofw<60||qtofw>600)
{
//cout<<"BAD ADC VALUE!!!"<<endl;
continue;
}
if(runindex<0||runindex>848)
{
cout<<"BAD RUNINDEX VALUE!!! WTF!!! "<<runindex<<endl;
continue;
}
float tofwsdz_before = sigma_tofwdz_before(mom,tofwdz);
float tofwsdphi_before = sigma_tofwdphi_before(mom,tofwdphi);
ttofw = ttofw - slewingoffset(striptofw,qtofw) - stripoffset[striptofw] - runoffset[runindex];
float deltat = ttofw - pltofw/phbeta*sqrt(mpion*mpion/mom/mom+1);
if(run<250593) // ++ only
{
if(charge>0) tofwdz = tofwdz - mean_dz_pos_plusplus[striptofw];
if(charge<0) tofwdz = tofwdz - mean_dz_neg_plusplus[striptofw];
if(charge>0) tofwdphi = tofwdphi - mean_dphi_pos_plusplus[striptofw];
if(charge<0) tofwdphi = tofwdphi - mean_dphi_neg_plusplus[striptofw];
}
if(run>250484) // -- field
{
if(charge>0) tofwdz = tofwdz - mean_dz_pos_minusminus[striptofw];
if(charge<0) tofwdz = tofwdz - mean_dz_neg_minusminus[striptofw];
if(charge>0) tofwdphi = tofwdphi - mean_dphi_pos_minusminus[striptofw];
if(charge<0) tofwdphi = tofwdphi - mean_dphi_neg_minusminus[striptofw];
}
float tofwsdz;
float tofwsdphi;
// first do main calibration
tofwsdz = caltofwsdz(run,striptofw,charge,zed,mom,tofwdz);
tofwsdphi = caltofwsdphi(run,striptofw,charge,zed,mom,tofwdphi);
// then do recalculation with zed dependence
//tofwsdz = recaltofwsdz(run,striptofw,charge,zed,mom,tofwsdz);
//tofwsdphi = recaltofwsdphi(run,striptofw,charge,zed,mom,tofwsdphi);
// then to small retuning
tofwsdz = tunetofwsdz(run,charge,mom,cent,tofwsdz);
tofwsdphi = tunetofwsdphi(run,charge,mom,cent,tofwsdphi);
float pc3_matching = fabs(pc3sdz)<2.0 && fabs(pc3sdphi)<2.0;
float tfw_matching = fabs(tofwsdz)<2.0 && fabs(tofwsdphi)<2.0;
//if(!pc3_matching||!tfw_matching) continue;
//if(!tfw_matching) continue;
// float ppc1x = ktree->HadronTracks_ppc1x[itrk];
// float ppc1y = ktree->HadronTracks_ppc1y[itrk];
// float ppc1z = ktree->HadronTracks_ppc1z[itrk];
// float pc1z = ppc1z;
// float pc1phi = atan2(ppc1y,ppc1x);
// bool good_pc1 = GoodPC1(pc1z,pc1phi);
// PC1ZedPhiDis->Fill(pc1z,pc1phi);
// if(good_pc1&&pT>0.4) PC1ZedPhiNewDis->Fill(pc1z,pc1phi);
// float ppc2x = ktree->HadronTracks_ppc2x[itrk];
// float ppc2y = ktree->HadronTracks_ppc2y[itrk];
// float ppc2z = ktree->HadronTracks_ppc2z[itrk];
// float pc2dz = ktree->HadronTracks_pc2dz[itrk];
// float pc2dphi = ktree->HadronTracks_pc2dphi[itrk];
// float pc2z = ppc2z -pc2dz;
// float pc2phi = atan2(ppc2y,ppc2x) - pc2dphi;
// bool good_pc2 = GoodPC2(pc2z,pc2phi);
// if(pc2_matching) PC2ZedPhiDis->Fill(pc2z,pc2phi);
// if(pc2_matching&&good_pc2) PC2ZedPhiNewDis->Fill(pc2z,pc2phi);
// float ppc3x = ktree->HadronTracks_ppc3x[itrk];
// float ppc3y = ktree->HadronTracks_ppc3y[itrk];
// float ppc3z = ktree->HadronTracks_ppc3z[itrk];
// float pc3dz = ktree->HadronTracks_pc3dz[itrk];
// float pc3dphi = ktree->HadronTracks_pc3dphi[itrk];
// float pc3z = ppc3z - pc3dz;
// float pc3phi = atan2(ppc3y,ppc3x) - pc3dphi;
// bool good_pc3 = GoodPC3(pc3z,pc3phi);
// if(pc3_matching) PC3ZedPhiDis->Fill(pc3z,pc3phi);
// if(pc3_matching&&good_pc3) PC3ZedPhiNewDis->Fill(pc3z,pc3phi);
ngoodtofwtracks++;
ngoodtofwtracks_snglevent++;
// -------------- //
// --- NORMAL --- //
// -------------- //
// ------------------------------ //
// --- END OF MATCHING HISTOS --- //
// ------------------------------ //
// ------------------------------ //
// --- NOW DOING TIMING CALIB --- //
// ------------------------------ //
if(mom>1.1&&mom<1.5&&tfw_matching)
{
qtofwdis->Fill(qtofw);
tofwadcupdis->Fill(tofwadcup);
tofwadcdwdis->Fill(tofwadcdw);
deltatslewingdis_q->Fill(qtofw,deltat);
deltatslewingdis_u->Fill(tofwadcup,deltat);
deltatslewingdis_d->Fill(tofwadcdw,deltat);
deltatdis->Fill(deltat);
deltatrundis->Fill(runindex,deltat);
deltatstriptofwdis->Fill(striptofw,deltat);
}
float m2tofw = mom*mom*(ttofw*ttofw*phbeta*phbeta/(pltofw*pltofw)-1);
if(striptofw<256) m2mom_w1_dis->Fill(pT,m2tofw);
if(striptofw>255) m2mom_w2_dis->Fill(pT,m2tofw);
m2mom_dis->Fill(charge*pT,m2tofw);
ttofwmom_dis->Fill(charge*mom,deltat);
if(charge>0)
{
m2mompos_dis->Fill(pT,m2tofw);
ttofwmompos_dis->Fill(mom,deltat);
if(mom>1.1&&mom<1.5) m2pos_strip_dis->Fill(striptofw,m2tofw);
if(mom>1.1&&mom<1.5) m2pos_run_dis->Fill(runindex,m2tofw);
if(striptofw<256) m2mompos_w1_dis->Fill(pT,m2tofw);
else m2mompos_w2_dis->Fill(pT,m2tofw);
}
else
{
m2momneg_dis->Fill(pT,m2tofw);
ttofwmomneg_dis->Fill(mom,deltat);
if(mom>1.1&&mom<1.5) m2neg_strip_dis->Fill(striptofw,m2tofw);
if(mom>1.1&&mom<1.5) m2neg_run_dis->Fill(runindex,m2tofw);
if(striptofw<256) m2momneg_w1_dis->Fill(pT,m2tofw);
else m2momneg_w2_dis->Fill(pT,m2tofw);
}
// --------------------------- //
// --- end of timing calib --- //
// --------------------------- //
// matching cut
if(!pc3_matching||!tfw_matching) continue;
// ----------------------- //
// --- dcfc histograms --- //
// ----------------------- //
hh_zedphi_mc->Fill(zed,phi);
if(zed>0)
{
hh_alphaphi_poszed_mc->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_poszed_mc_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_poszed_mc->Fill(phi,pT);
if(charge<0) hh_neg_momphi_poszed_mc->Fill(phi,pT);
}
if(zed<0)
{
hh_alphaphi_negzed_mc->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_negzed_mc_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_negzed_mc->Fill(phi,pT);
if(charge<0) hh_neg_momphi_negzed_mc->Fill(phi,pT);
}
// ----------------------- //
// ----------------------- //
// ----------------------- //
if(!GoodEdgeDCH(run,zed,alpha,phi)) continue;
// ----------------------- //
// --- dcfc histograms --- //
// ----------------------- //
hh_zedphi_ec->Fill(zed,phi);
if(zed>0)
{
hh_alphaphi_poszed_ec->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_poszed_ec_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_poszed_ec->Fill(phi,pT);
if(charge<0) hh_neg_momphi_poszed_ec->Fill(phi,pT);
}
if(zed<0)
{
hh_alphaphi_negzed_ec->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_negzed_ec_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_negzed_ec->Fill(phi,pT);
if(charge<0) hh_neg_momphi_negzed_ec->Fill(phi,pT);
}
// ----------------------- //
// ----------------------- //
// ----------------------- //
if(!GoodInnerDCH(run,zed,alpha,phi)) continue;
hh_zedphi_ac->Fill(zed,phi);
if(zed>0)
{
hh_alphaphi_poszed_ac->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_poszed_ac_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_poszed_ac->Fill(phi,pT);
if(charge<0) hh_neg_momphi_poszed_ac->Fill(phi,pT);
}
if(zed<0)
{
hh_alphaphi_negzed_ac->Fill(phi,alpha);
if(pT>0.55) hh_alphaphi_negzed_ac_FW->Fill(phi,alpha);
if(charge>0) hh_pos_momphi_negzed_ac->Fill(phi,pT);
if(charge<0) hh_neg_momphi_negzed_ac->Fill(phi,pT);
}
// ----------------------- //
// ----------------------- //
// ----------------------- //
// --------------------- //
// --- now to do pid --- //
// --------------------- //
// adc cut already done
// if(!goodadc) continue;
float isPi = isPion(pT,m2tofw);
float isK = isKaon(pT,m2tofw);
float isP = isProton(pT,m2tofw);
// pid distributions
bool dis0 = isPi>=-2 && isPi<=2;
bool dis1 = isPi>=-2 && isPi<=2 && isK<=-2;
bool dis2 = isK>=-2 && isK<=2;
bool dis3 = isK>=-2 && isK<=2 && isPi>=2 && isP<=-2;
bool dis4 = isP>=-2 && isP<=2;
bool dis5 = isP>=-2 && isP<=2 && isK>=2;
// sector and charge
bool w1pos = charge>0 && striptofw>=0 && striptofw<=255;
bool w1neg = charge<0 && striptofw>=0 && striptofw<=255;
bool w2pos = charge>0 && striptofw>=256 && striptofw<=511;
bool w2neg = charge<0 && striptofw>=256 && striptofw<=511;
// both sectors together
if(charge>0)
{
if(dis0) ptpid_tofw_pos_0_dis->Fill(pT);
if(dis1) ptpid_tofw_pos_1_dis->Fill(pT);
if(dis2) ptpid_tofw_pos_2_dis->Fill(pT);
if(dis3) ptpid_tofw_pos_3_dis->Fill(pT);
if(dis4) ptpid_tofw_pos_4_dis->Fill(pT);
if(dis5) ptpid_tofw_pos_5_dis->Fill(pT);
}
if(charge<0)
{
//1-d
if(dis0) ptpid_tofw_neg_0_dis->Fill(pT);
if(dis1) ptpid_tofw_neg_1_dis->Fill(pT);
if(dis2) ptpid_tofw_neg_2_dis->Fill(pT);
if(dis3) ptpid_tofw_neg_3_dis->Fill(pT);
if(dis4) ptpid_tofw_neg_4_dis->Fill(pT);
if(dis5) ptpid_tofw_neg_5_dis->Fill(pT);
}
// centrality, both sectors together
if(cent>0&¢<=88)
{
if(charge>0)
{
if(dis0) ptpid_tofw_pos_0_dis_cent0088->Fill(pT);
if(dis1) ptpid_tofw_pos_1_dis_cent0088->Fill(pT);
if(dis2) ptpid_tofw_pos_2_dis_cent0088->Fill(pT);
if(dis3) ptpid_tofw_pos_3_dis_cent0088->Fill(pT);
if(dis4) ptpid_tofw_pos_4_dis_cent0088->Fill(pT);
if(dis5) ptpid_tofw_pos_5_dis_cent0088->Fill(pT);
}
if(charge<0)
{
//1-d
if(dis0) ptpid_tofw_neg_0_dis_cent0088->Fill(pT);
if(dis1) ptpid_tofw_neg_1_dis_cent0088->Fill(pT);
if(dis2) ptpid_tofw_neg_2_dis_cent0088->Fill(pT);
if(dis3) ptpid_tofw_neg_3_dis_cent0088->Fill(pT);
if(dis4) ptpid_tofw_neg_4_dis_cent0088->Fill(pT);
if(dis5) ptpid_tofw_neg_5_dis_cent0088->Fill(pT);
}
}
if(cent>0&¢<=20)
{
if(charge>0)
{
if(dis0) ptpid_tofw_pos_0_dis_cent0020->Fill(pT);
if(dis1) ptpid_tofw_pos_1_dis_cent0020->Fill(pT);
if(dis2) ptpid_tofw_pos_2_dis_cent0020->Fill(pT);
if(dis3) ptpid_tofw_pos_3_dis_cent0020->Fill(pT);
if(dis4) ptpid_tofw_pos_4_dis_cent0020->Fill(pT);
if(dis5) ptpid_tofw_pos_5_dis_cent0020->Fill(pT);
}
if(charge<0)
{
//1-d
if(dis0) ptpid_tofw_neg_0_dis_cent0020->Fill(pT);
if(dis1) ptpid_tofw_neg_1_dis_cent0020->Fill(pT);
if(dis2) ptpid_tofw_neg_2_dis_cent0020->Fill(pT);
if(dis3) ptpid_tofw_neg_3_dis_cent0020->Fill(pT);
if(dis4) ptpid_tofw_neg_4_dis_cent0020->Fill(pT);
if(dis5) ptpid_tofw_neg_5_dis_cent0020->Fill(pT);
}
}
if(cent>20&¢<=40)
{
if(charge>0)
{
if(dis0) ptpid_tofw_pos_0_dis_cent2040->Fill(pT);
if(dis1) ptpid_tofw_pos_1_dis_cent2040->Fill(pT);
if(dis2) ptpid_tofw_pos_2_dis_cent2040->Fill(pT);
if(dis3) ptpid_tofw_pos_3_dis_cent2040->Fill(pT);
if(dis4) ptpid_tofw_pos_4_dis_cent2040->Fill(pT);
if(dis5) ptpid_tofw_pos_5_dis_cent2040->Fill(pT);
}
if(charge<0)
{
//1-d
if(dis0) ptpid_tofw_neg_0_dis_cent2040->Fill(pT);
if(dis1) ptpid_tofw_neg_1_dis_cent2040->Fill(pT);
if(dis2) ptpid_tofw_neg_2_dis_cent2040->Fill(pT);
if(dis3) ptpid_tofw_neg_3_dis_cent2040->Fill(pT);
if(dis4) ptpid_tofw_neg_4_dis_cent2040->Fill(pT);
if(dis5) ptpid_tofw_neg_5_dis_cent2040->Fill(pT);
}
}
if(cent>40&¢<=60)
{
if(charge>0)
{
if(dis0) ptpid_tofw_pos_0_dis_cent4060->Fill(pT);
if(dis1) ptpid_tofw_pos_1_dis_cent4060->Fill(pT);
if(dis2) ptpid_tofw_pos_2_dis_cent4060->Fill(pT);
if(dis3) ptpid_tofw_pos_3_dis_cent4060->Fill(pT);
if(dis4) ptpid_tofw_pos_4_dis_cent4060->Fill(pT);
if(dis5) ptpid_tofw_pos_5_dis_cent4060->Fill(pT);
}
if(charge<0)
{
//1-d
if(dis0) ptpid_tofw_neg_0_dis_cent4060->Fill(pT);
if(dis1) ptpid_tofw_neg_1_dis_cent4060->Fill(pT);
if(dis2) ptpid_tofw_neg_2_dis_cent4060->Fill(pT);
if(dis3) ptpid_tofw_neg_3_dis_cent4060->Fill(pT);
if(dis4) ptpid_tofw_neg_4_dis_cent4060->Fill(pT);
if(dis5) ptpid_tofw_neg_5_dis_cent4060->Fill(pT);
}
}
if(cent>60&¢<=88)
{
if(charge>0)
{
if(dis0) ptpid_tofw_pos_0_dis_cent6088->Fill(pT);
if(dis1) ptpid_tofw_pos_1_dis_cent6088->Fill(pT);
if(dis2) ptpid_tofw_pos_2_dis_cent6088->Fill(pT);
if(dis3) ptpid_tofw_pos_3_dis_cent6088->Fill(pT);
if(dis4) ptpid_tofw_pos_4_dis_cent6088->Fill(pT);
if(dis5) ptpid_tofw_pos_5_dis_cent6088->Fill(pT);
}
if(charge<0)
{
//1-d
if(dis0) ptpid_tofw_neg_0_dis_cent6088->Fill(pT);
if(dis1) ptpid_tofw_neg_1_dis_cent6088->Fill(pT);
if(dis2) ptpid_tofw_neg_2_dis_cent6088->Fill(pT);
if(dis3) ptpid_tofw_neg_3_dis_cent6088->Fill(pT);
if(dis4) ptpid_tofw_neg_4_dis_cent6088->Fill(pT);
if(dis5) ptpid_tofw_neg_5_dis_cent6088->Fill(pT);
}
}
// ---
// now do sectors separately
if(w1pos)
{
//1-d
if(dis0) ptpid_tofw_w1_pos_0_dis->Fill(pT);
if(dis1) ptpid_tofw_w1_pos_1_dis->Fill(pT);
if(dis2) ptpid_tofw_w1_pos_2_dis->Fill(pT);
if(dis3) ptpid_tofw_w1_pos_3_dis->Fill(pT);
if(dis4) ptpid_tofw_w1_pos_4_dis->Fill(pT);
if(dis5) ptpid_tofw_w1_pos_5_dis->Fill(pT);
}
if(w1neg)
{
//1-d
if(dis0) ptpid_tofw_w1_neg_0_dis->Fill(pT);
if(dis1) ptpid_tofw_w1_neg_1_dis->Fill(pT);
if(dis2) ptpid_tofw_w1_neg_2_dis->Fill(pT);
if(dis3) ptpid_tofw_w1_neg_3_dis->Fill(pT);
if(dis4) ptpid_tofw_w1_neg_4_dis->Fill(pT);
if(dis5) ptpid_tofw_w1_neg_5_dis->Fill(pT);
}
if(w2pos)
{
//1-d
if(dis0) ptpid_tofw_w2_pos_0_dis->Fill(pT);
if(dis1) ptpid_tofw_w2_pos_1_dis->Fill(pT);
if(dis2) ptpid_tofw_w2_pos_2_dis->Fill(pT);
if(dis3) ptpid_tofw_w2_pos_3_dis->Fill(pT);
if(dis4) ptpid_tofw_w2_pos_4_dis->Fill(pT);
if(dis5) ptpid_tofw_w2_pos_5_dis->Fill(pT);
}
if(w2neg)
{
//1-d
if(dis0) ptpid_tofw_w2_neg_0_dis->Fill(pT);
if(dis1) ptpid_tofw_w2_neg_1_dis->Fill(pT);
if(dis2) ptpid_tofw_w2_neg_2_dis->Fill(pT);
if(dis3) ptpid_tofw_w2_neg_3_dis->Fill(pT);
if(dis4) ptpid_tofw_w2_neg_4_dis->Fill(pT);
if(dis5) ptpid_tofw_w2_neg_5_dis->Fill(pT);
}
// centrality
if(cent>0&¢<=88)
{
if(w1pos)
{
//1-d
if(dis0) ptpid_tofw_w1_pos_0_dis_cent0088->Fill(pT);
if(dis1) ptpid_tofw_w1_pos_1_dis_cent0088->Fill(pT);
if(dis2) ptpid_tofw_w1_pos_2_dis_cent0088->Fill(pT);
if(dis3) ptpid_tofw_w1_pos_3_dis_cent0088->Fill(pT);
if(dis4) ptpid_tofw_w1_pos_4_dis_cent0088->Fill(pT);
if(dis5) ptpid_tofw_w1_pos_5_dis_cent0088->Fill(pT);
}
if(w1neg)
{
//1-d
if(dis0) ptpid_tofw_w1_neg_0_dis_cent0088->Fill(pT);
if(dis1) ptpid_tofw_w1_neg_1_dis_cent0088->Fill(pT);
if(dis2) ptpid_tofw_w1_neg_2_dis_cent0088->Fill(pT);
if(dis3) ptpid_tofw_w1_neg_3_dis_cent0088->Fill(pT);
if(dis4) ptpid_tofw_w1_neg_4_dis_cent0088->Fill(pT);
if(dis5) ptpid_tofw_w1_neg_5_dis_cent0088->Fill(pT);
}
if(w2pos)
{
//1-d
if(dis0) ptpid_tofw_w2_pos_0_dis_cent0088->Fill(pT);
if(dis1) ptpid_tofw_w2_pos_1_dis_cent0088->Fill(pT);
if(dis2) ptpid_tofw_w2_pos_2_dis_cent0088->Fill(pT);
if(dis3) ptpid_tofw_w2_pos_3_dis_cent0088->Fill(pT);
if(dis4) ptpid_tofw_w2_pos_4_dis_cent0088->Fill(pT);
if(dis5) ptpid_tofw_w2_pos_5_dis_cent0088->Fill(pT);
}
if(w2neg)
{
//1-d
if(dis0) ptpid_tofw_w2_neg_0_dis_cent0088->Fill(pT);
if(dis1) ptpid_tofw_w2_neg_1_dis_cent0088->Fill(pT);
if(dis2) ptpid_tofw_w2_neg_2_dis_cent0088->Fill(pT);
if(dis3) ptpid_tofw_w2_neg_3_dis_cent0088->Fill(pT);
if(dis4) ptpid_tofw_w2_neg_4_dis_cent0088->Fill(pT);
if(dis5) ptpid_tofw_w2_neg_5_dis_cent0088->Fill(pT);
}
}
if(cent>0&¢<=20)
{
if(w1pos)
{
//1-d
if(dis0) ptpid_tofw_w1_pos_0_dis_cent0020->Fill(pT);
if(dis1) ptpid_tofw_w1_pos_1_dis_cent0020->Fill(pT);
if(dis2) ptpid_tofw_w1_pos_2_dis_cent0020->Fill(pT);
if(dis3) ptpid_tofw_w1_pos_3_dis_cent0020->Fill(pT);
if(dis4) ptpid_tofw_w1_pos_4_dis_cent0020->Fill(pT);
if(dis5) ptpid_tofw_w1_pos_5_dis_cent0020->Fill(pT);
}
if(w1neg)
{
//1-d
if(dis0) ptpid_tofw_w1_neg_0_dis_cent0020->Fill(pT);
if(dis1) ptpid_tofw_w1_neg_1_dis_cent0020->Fill(pT);
if(dis2) ptpid_tofw_w1_neg_2_dis_cent0020->Fill(pT);
if(dis3) ptpid_tofw_w1_neg_3_dis_cent0020->Fill(pT);
if(dis4) ptpid_tofw_w1_neg_4_dis_cent0020->Fill(pT);
if(dis5) ptpid_tofw_w1_neg_5_dis_cent0020->Fill(pT);
}
if(w2pos)
{
//1-d
if(dis0) ptpid_tofw_w2_pos_0_dis_cent0020->Fill(pT);
if(dis1) ptpid_tofw_w2_pos_1_dis_cent0020->Fill(pT);
if(dis2) ptpid_tofw_w2_pos_2_dis_cent0020->Fill(pT);
if(dis3) ptpid_tofw_w2_pos_3_dis_cent0020->Fill(pT);
if(dis4) ptpid_tofw_w2_pos_4_dis_cent0020->Fill(pT);
if(dis5) ptpid_tofw_w2_pos_5_dis_cent0020->Fill(pT);
}
if(w2neg)
{
//1-d
if(dis0) ptpid_tofw_w2_neg_0_dis_cent0020->Fill(pT);
if(dis1) ptpid_tofw_w2_neg_1_dis_cent0020->Fill(pT);
if(dis2) ptpid_tofw_w2_neg_2_dis_cent0020->Fill(pT);
if(dis3) ptpid_tofw_w2_neg_3_dis_cent0020->Fill(pT);
if(dis4) ptpid_tofw_w2_neg_4_dis_cent0020->Fill(pT);
if(dis5) ptpid_tofw_w2_neg_5_dis_cent0020->Fill(pT);
}
}
if(cent>20&¢<=40)
{
if(w1pos)
{
//1-d
if(dis0) ptpid_tofw_w1_pos_0_dis_cent2040->Fill(pT);
if(dis1) ptpid_tofw_w1_pos_1_dis_cent2040->Fill(pT);
if(dis2) ptpid_tofw_w1_pos_2_dis_cent2040->Fill(pT);
if(dis3) ptpid_tofw_w1_pos_3_dis_cent2040->Fill(pT);
if(dis4) ptpid_tofw_w1_pos_4_dis_cent2040->Fill(pT);
if(dis5) ptpid_tofw_w1_pos_5_dis_cent2040->Fill(pT);
}
if(w1neg)
{
//1-d
if(dis0) ptpid_tofw_w1_neg_0_dis_cent2040->Fill(pT);
if(dis1) ptpid_tofw_w1_neg_1_dis_cent2040->Fill(pT);
if(dis2) ptpid_tofw_w1_neg_2_dis_cent2040->Fill(pT);
if(dis3) ptpid_tofw_w1_neg_3_dis_cent2040->Fill(pT);
if(dis4) ptpid_tofw_w1_neg_4_dis_cent2040->Fill(pT);
if(dis5) ptpid_tofw_w1_neg_5_dis_cent2040->Fill(pT);
}
if(w2pos)
{
//1-d
if(dis0) ptpid_tofw_w2_pos_0_dis_cent2040->Fill(pT);
if(dis1) ptpid_tofw_w2_pos_1_dis_cent2040->Fill(pT);
if(dis2) ptpid_tofw_w2_pos_2_dis_cent2040->Fill(pT);
if(dis3) ptpid_tofw_w2_pos_3_dis_cent2040->Fill(pT);
if(dis4) ptpid_tofw_w2_pos_4_dis_cent2040->Fill(pT);
if(dis5) ptpid_tofw_w2_pos_5_dis_cent2040->Fill(pT);
}
if(w2neg)
{
//1-d
if(dis0) ptpid_tofw_w2_neg_0_dis_cent2040->Fill(pT);
if(dis1) ptpid_tofw_w2_neg_1_dis_cent2040->Fill(pT);
if(dis2) ptpid_tofw_w2_neg_2_dis_cent2040->Fill(pT);
if(dis3) ptpid_tofw_w2_neg_3_dis_cent2040->Fill(pT);
if(dis4) ptpid_tofw_w2_neg_4_dis_cent2040->Fill(pT);
if(dis5) ptpid_tofw_w2_neg_5_dis_cent2040->Fill(pT);
}
}
if(cent>40&¢<=60)
{
if(w1pos)
{
//1-d
if(dis0) ptpid_tofw_w1_pos_0_dis_cent4060->Fill(pT);
if(dis1) ptpid_tofw_w1_pos_1_dis_cent4060->Fill(pT);
if(dis2) ptpid_tofw_w1_pos_2_dis_cent4060->Fill(pT);
if(dis3) ptpid_tofw_w1_pos_3_dis_cent4060->Fill(pT);
if(dis4) ptpid_tofw_w1_pos_4_dis_cent4060->Fill(pT);
if(dis5) ptpid_tofw_w1_pos_5_dis_cent4060->Fill(pT);
}
if(w1neg)
{
//1-d
if(dis0) ptpid_tofw_w1_neg_0_dis_cent4060->Fill(pT);
if(dis1) ptpid_tofw_w1_neg_1_dis_cent4060->Fill(pT);
if(dis2) ptpid_tofw_w1_neg_2_dis_cent4060->Fill(pT);
if(dis3) ptpid_tofw_w1_neg_3_dis_cent4060->Fill(pT);
if(dis4) ptpid_tofw_w1_neg_4_dis_cent4060->Fill(pT);
if(dis5) ptpid_tofw_w1_neg_5_dis_cent4060->Fill(pT);
}
if(w2pos)
{
//1-d
if(dis0) ptpid_tofw_w2_pos_0_dis_cent4060->Fill(pT);
if(dis1) ptpid_tofw_w2_pos_1_dis_cent4060->Fill(pT);
if(dis2) ptpid_tofw_w2_pos_2_dis_cent4060->Fill(pT);
if(dis3) ptpid_tofw_w2_pos_3_dis_cent4060->Fill(pT);
if(dis4) ptpid_tofw_w2_pos_4_dis_cent4060->Fill(pT);
if(dis5) ptpid_tofw_w2_pos_5_dis_cent4060->Fill(pT);
}
if(w2neg)
{
//1-d
if(dis0) ptpid_tofw_w2_neg_0_dis_cent4060->Fill(pT);
if(dis1) ptpid_tofw_w2_neg_1_dis_cent4060->Fill(pT);
if(dis2) ptpid_tofw_w2_neg_2_dis_cent4060->Fill(pT);
if(dis3) ptpid_tofw_w2_neg_3_dis_cent4060->Fill(pT);
if(dis4) ptpid_tofw_w2_neg_4_dis_cent4060->Fill(pT);
if(dis5) ptpid_tofw_w2_neg_5_dis_cent4060->Fill(pT);
}
}
if(cent>60&¢<=88)
{
if(w1pos)
{
//1-d
if(dis0) ptpid_tofw_w1_pos_0_dis_cent6088->Fill(pT);
if(dis1) ptpid_tofw_w1_pos_1_dis_cent6088->Fill(pT);
if(dis2) ptpid_tofw_w1_pos_2_dis_cent6088->Fill(pT);
if(dis3) ptpid_tofw_w1_pos_3_dis_cent6088->Fill(pT);
if(dis4) ptpid_tofw_w1_pos_4_dis_cent6088->Fill(pT);
if(dis5) ptpid_tofw_w1_pos_5_dis_cent6088->Fill(pT);
}
if(w1neg)
{
//1-d
if(dis0) ptpid_tofw_w1_neg_0_dis_cent6088->Fill(pT);
if(dis1) ptpid_tofw_w1_neg_1_dis_cent6088->Fill(pT);
if(dis2) ptpid_tofw_w1_neg_2_dis_cent6088->Fill(pT);
if(dis3) ptpid_tofw_w1_neg_3_dis_cent6088->Fill(pT);
if(dis4) ptpid_tofw_w1_neg_4_dis_cent6088->Fill(pT);
if(dis5) ptpid_tofw_w1_neg_5_dis_cent6088->Fill(pT);
}
if(w2pos)
{
//1-d
if(dis0) ptpid_tofw_w2_pos_0_dis_cent6088->Fill(pT);
if(dis1) ptpid_tofw_w2_pos_1_dis_cent6088->Fill(pT);
if(dis2) ptpid_tofw_w2_pos_2_dis_cent6088->Fill(pT);
if(dis3) ptpid_tofw_w2_pos_3_dis_cent6088->Fill(pT);
if(dis4) ptpid_tofw_w2_pos_4_dis_cent6088->Fill(pT);
if(dis5) ptpid_tofw_w2_pos_5_dis_cent6088->Fill(pT);
}
if(w2neg)
{
//1-d
if(dis0) ptpid_tofw_w2_neg_0_dis_cent6088->Fill(pT);
if(dis1) ptpid_tofw_w2_neg_1_dis_cent6088->Fill(pT);
if(dis2) ptpid_tofw_w2_neg_2_dis_cent6088->Fill(pT);
if(dis3) ptpid_tofw_w2_neg_3_dis_cent6088->Fill(pT);
if(dis4) ptpid_tofw_w2_neg_4_dis_cent6088->Fill(pT);
if(dis5) ptpid_tofw_w2_neg_5_dis_cent6088->Fill(pT);
}
}
// ---------------------------- //
// --- end of tofw only pid --- //
// ---------------------------- //
// ---------------------------- //
// --- Done with track loop --- //
// ---------------------------- //
} // End of track loop
// only count as good event if at least one track is used
if(ngoodtofwtracks_snglevent>0) ngoodtofwevents++;
} // End of event loop
t->Delete();
delete ktree;
f->Close();
delete f;
} // End of pDST loop
mData->Write();
mData->Close();
cout<<"Number of events: "<<nevents<<endl;
cout<<"Number of good TOFW events: "<<ngoodtofwevents<<endl;
cout<<"Number of tracks: "<<ntracks<<endl;
cout<<"Number of good TOFW tracks: "<<ngoodtofwtracks<<endl;
gettimeofday(&Time,0);
int endtime = Time.tv_sec;
//cout<<"endtime is "<<endtime<<endl;
int tdiff = endtime-begintime;
cout<<"End of program."<<endl;
cout<<"Execution time: "<<tdiff<<" seconds"<<endl;
exit(0);
}
void GetRunIndex()
{
string s;
ifstream f("runs.list");
if(!f)
{
cerr << "Couldn't open file\n";
exit(1);
}
int j=0;
while(getline(f,s))
{
//cout << s << '\n';
myMap.insert(make_pair(s,j));
j++;
}
return;
}
bool goodStrip(int i)
{
if((i>=0 &&i<= 7)||
(i>=12&&i<=15)||
(i>=20&&i<=23)||
(i>=28&&i<=31)||
(i>=36&&i<=39)||
(i>=44&&i<=47)||
(i>=52&&i<=55)||
(i>=60&&i<=63)||
//i==19||i==161||i==372||i==394||i==460) // from shengli
i==19||i==79||i==161||i==372||i==394||i==460) // my revision
//i==176||i==288||i==308||i==316||i==320||i==360) // commented out by shengli, agrees with my results
return false;//need reproduction
else return true;
}
void fetchRunOffset()
{
ifstream fin("run-by-run-pass4.dat");
if(!fin)
{
cout<<"Warning! Cannot open run-by-run offset file"<<endl;
return;
}
float tmp=-9999;
int runnum=-9999;
for(int i=0; i<848; i++)
{
fin>>runnum;
fin>>tmp;
fin>>runoffset[i];
fin>>tmp>>tmp>>tmp;
}
fin.close();
return;
}
void fetchStripOffset()
{
ifstream fin("strip-by-strip-pass4.dat");
if(!fin)
{
cout<<"Warning! Cannot open strip-by-strip offset file"<<endl;
return;
}
for(int i=0; i<512; i++)
{
float tmp=-9999;
int striptofw=-9999;
fin>>striptofw>>tmp>>stripoffset[i]>>tmp>>tmp>>tmp;
if(striptofw!=i)
{
cout<<"SERIOUS ERROR! stripid in strip-by-strip offset file does not match index"<<endl;
cout<<"stripid is "<<striptofw<<" but index is "<<i<<endl;
exit(1);
}
}
fin.close();
return;
}
void fetchSlewingOffset()
{
ifstream file("shengli_slewing.dat");
if(!file)
{
cout<<"Warning! Cannot open slewing correction file"<<endl;
return;
}
int istrip;
float tmp;
while(!file.eof())
{
file>>istrip>>tmp>>Slewing_A[istrip]>>Slewing_B[istrip]>>tmp>>tmp>>tmp>>tmp;
}
file.close();
return ;
}
void fetchMatching()
{
int stripid;
ifstream fin_plusplus("residuals-plusplus-pass2.dat");
if(!fin_plusplus)
{
cout<<"Warning! Cannot find residual matching file"<<endl;
return;
}
for(int i=0; i<512; i++)
{
fin_plusplus>>stripid;
//there needs to be a break here for some reason...........
fin_plusplus>>mean_dz_pos_plusplus[stripid]>>mean_dz_neg_plusplus[stripid]>>mean_dphi_pos_plusplus[stripid]>>mean_dphi_neg_plusplus[stripid];
if(stripid!=i)
{
cout<<"SERIOUS ERROR! stripid in residual matching file does not match index"<<endl;
cout<<"strip is is "<<stripid<<" but index is "<<i<<endl;
exit(1);
}
}
fin_plusplus.close();
ifstream fin_minusminus("residuals-minusminus-pass2.dat");
if(!fin_minusminus)
{
cout<<"Warning! Cannot find residual matching file"<<endl;
return;
}
for(int i=0; i<512; i++)
{
fin_minusminus>>stripid;
//there needs to be a break here for some reason...........
fin_minusminus>>mean_dz_pos_minusminus[stripid]>>mean_dz_neg_minusminus[stripid]>>mean_dphi_pos_minusminus[stripid]>>mean_dphi_neg_minusminus[stripid];
if(stripid!=i)
{
cout<<"SERIOUS ERROR! stripid in residual matching file does not match index"<<endl;
cout<<"strip is is "<<stripid<<" but index is "<<i<<endl;
exit(1);
}
}
fin_minusminus.close();
return;
}
float slewingoffset(int strip, float adc)
{
float par = 0.4;
float offset = Slewing_A[strip]+Slewing_B[strip]/pow(adc,par);
return offset;
}
float sigma_tofwdz(int charge, float mom, float tofwdz)
{
float mean = -9999;
float sigma = -9999;
float value = -9999;
if(mom<1.1||mom>1.5) return -9999;
if(charge>0){mean=-2.974e-03; sigma=1.674e+00;}
if(charge<0){mean=-1.671e-02; sigma=1.678e+00;}
value = (tofwdz-mean)/sigma;
return value;
}
float sigma_tofwdphi(int charge, float mom, float tofwdphi)
{
float mean = -9999;
float sigma = -9999;
float value = -9999;
if(mom<1.1||mom>1.5) return -9999;
if(charge>0){mean=1.289e-04; sigma=2.095e-03;}
if(charge<0){mean=-1.568e-03; sigma=2.165e-03;}
value = (tofwdphi-mean)/sigma;
return value;
}
float sigma_tofwdz_before(float mom, float tofwdz)
{
if(mom<1.1||mom>1.5) return -9999;
float mean = 5.35412e-01;
float sigma = 1.85677e+00;
float value = (tofwdz-mean)/sigma;
return value;
}
float sigma_tofwdphi_before(float mom, float tofwdphi)
{
if(mom<1.1||mom>1.5) return -9999;
float mean = -3.82415e-04;
float sigma = 2.79629e-03;
float value = (tofwdphi-mean)/sigma;
return value;
}
// float slewingoffset(float qtofw)
// {
// float offset = -0.9388 + 11.64/pow(qtofw,0.5);
// return offset;
// }
float caltofwsdz(int run, int striptofw, int charge, float zed, float mom, float tofwdz)
{
float mean = -9999;
float sigma = -9999;
float value = -9999;
if(run>250484&&striptofw<256&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -2.01264 + -2.22923/mom + 0.198624/mom/mom + 4.05608/sqrt(mom);
else if(mom>=1.0) mean = -4.20534 + -12.962/mom + 3.21798/mom/mom + 13.9799/sqrt(mom);
sigma = 1.8858 + 0.462482/mom + 0.104371/mom/mom + -0.717956/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.201275 + 0.281806/mom + -0.0311368/mom/mom + -0.430883/sqrt(mom);
else if(mom>=1.0) mean = 1.84526 + 7.65751/mom + -2.25727/mom/mom + -7.25833/sqrt(mom);
sigma = 2.05773 + 1.02525/mom + -0.000881981/mom/mom + -1.31723/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.125341 + 0.281109/mom + -0.0103479/mom/mom + -0.391107/sqrt(mom);
else if(mom>=1.0) mean = 1.30427 + 5.90121/mom + -1.61843/mom/mom + -5.6123/sqrt(mom);
sigma = 1.76621 + 0.216232/mom + 0.140618/mom/mom + -0.373179/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 2.98021 + 3.86248/mom + -0.381395/mom/mom + -6.4654/sqrt(mom);
else if(mom>=1.0) mean = 0.606218 + 4.12766/mom + -1.36135/mom/mom + -3.38873/sqrt(mom);
sigma = 2.06437 + 0.943117/mom + 0.0173967/mom/mom + -1.25726/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -0.0633981 + 0.318759/mom + -0.0238596/mom/mom + -0.23343/sqrt(mom);
else if(mom>=1.0) mean = 3.54814 + 15.7326/mom + -4.52858/mom/mom + -14.8112/sqrt(mom);
sigma = 2.02621 + 0.68814/mom + 0.0901361/mom/mom + -1.07381/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.900445 + 1.21436/mom + -0.13086/mom/mom + -1.95768/sqrt(mom);
else if(mom>=1.0) mean = 0.668389 + 5.60594/mom + -1.92836/mom/mom + -4.36143/sqrt(mom);
sigma = 1.80564 + 0.375056/mom + 0.105184/mom/mom + -0.527921/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = -0.210075 + 0.578088/mom + -0.0917194/mom/mom + -0.274022/sqrt(mom);
else if(mom>=1.0) mean = 0.963274 + 9.6754/mom + -3.31536/mom/mom + -7.34767/sqrt(mom);
sigma = 2.07744 + 0.813355/mom + 0.0804633/mom/mom + -1.22711/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 1.34188 + 2.41121/mom + -0.324979/mom/mom + -3.39357/sqrt(mom);
else if(mom>=1.0) mean = 1.98578 + 11.6526/mom + -3.71143/mom/mom + -9.93703/sqrt(mom);
sigma = 1.95425 + 0.647739/mom + 0.0697672/mom/mom + -0.904098/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 2.61191 + 4.50081/mom + -0.578052/mom/mom + -6.4041/sqrt(mom);
else if(mom>=1.0) mean = 1.07424 + 12.8927/mom + -4.50748/mom/mom + -9.38109/sqrt(mom);
sigma = 1.64426 + 0.18596/mom + 0.179195/mom/mom + -0.239326/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 2.93192 + 5.10844/mom + -0.743913/mom/mom + -7.15891/sqrt(mom);
else if(mom>=1.0) mean = 1.85826 + 14.0976/mom + -4.86004/mom/mom + -11.0233/sqrt(mom);
sigma = 1.79728 + 0.383494/mom + 0.121521/mom/mom + -0.51804/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -0.984296 + -1.26376/mom + 0.117613/mom/mom + 2.09283/sqrt(mom);
else if(mom>=1.0) mean = -2.67559 + -10.0934/mom + 2.80997/mom/mom + 9.95667/sqrt(mom);
sigma = 1.49385 + -0.112198/mom + 0.159713/mom/mom + 0.213054/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -1.11653 + -1.54128/mom + 0.1579/mom/mom + 2.49549/sqrt(mom);
else if(mom>=1.0) mean = 1.10518 + 2.80511/mom + -0.568315/mom/mom + -3.32427/sqrt(mom);
sigma = 2.06495 + 1.06655/mom + -0.00623102/mom/mom + -1.37327/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -1.25027 + -1.68319/mom + 0.15361/mom/mom + 2.77088/sqrt(mom);
else if(mom>=1.0) mean = -0.899186 + -5.57989/mom + 1.8125/mom/mom + 4.70074/sqrt(mom);
sigma = 1.84228 + 0.462316/mom + 0.0885473/mom/mom + -0.63806/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 0.295173 + 0.211965/mom + -0.00731029/mom/mom + -0.506842/sqrt(mom);
else if(mom>=1.0) mean = -0.989844 + -4.64626/mom + 1.31855/mom/mom + 4.31434/sqrt(mom);
sigma = 2.09877 + 1.00515/mom + 0.0140272/mom/mom + -1.36857/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -1.98492 + -3.21829/mom + 0.33586/mom/mom + 4.89143/sqrt(mom);
else if(mom>=1.0) mean = -1.03187 + -7.27482/mom + 2.28507/mom/mom + 6.06266/sqrt(mom);
sigma = 1.72473 + 0.215516/mom + 0.127946/mom/mom + -0.316989/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 0.356433 + 0.08037/mom + 0.0259917/mom/mom + -0.469411/sqrt(mom);
else if(mom>=1.0) mean = -2.51385 + -12.8006/mom + 3.99336/mom/mom + 11.3597/sqrt(mom);
sigma = 2.18518 + 1.07847/mom + 0.01511/mom/mom + -1.53668/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -2.6141 + -4.02929/mom + 0.42801/mom/mom + 6.20533/sqrt(mom);
else if(mom>=1.0) mean = -1.75443 + -12.1993/mom + 3.89681/mom/mom + 10.0736/sqrt(mom);
sigma = 1.61384 + -0.0895259/mom + 0.176818/mom/mom + 0.0666991/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -3.87415 + -5.20754/mom + 0.568591/mom/mom + 8.44181/sqrt(mom);
else if(mom>=1.0) mean = -1.9436 + -11.1138/mom + 3.47018/mom/mom + 9.54135/sqrt(mom);
sigma = 2.31828 + 1.37733/mom + -0.0242923/mom/mom + -1.91525/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -1.6169 + -3.17935/mom + 0.447276/mom/mom + 4.24246/sqrt(mom);
else if(mom>=1.0) mean = -3.75017 + -22.2417/mom + 7.05895/mom/mom + 18.8999/sqrt(mom);
sigma = 1.47007 + -0.229602/mom + 0.210489/mom/mom + 0.316812/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -0.294532 + -1.16014/mom + 0.294548/mom/mom + 1.01132/sqrt(mom);
else if(mom>=1.0) mean = -0.8557 + -11.2929/mom + 4.23867/mom/mom + 7.81223/sqrt(mom);
sigma = 1.85904 + 0.461763/mom + 0.126445/mom/mom + -0.68716/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.0919229 + 0.00941828/mom + -0.0094649/mom/mom + 0.127198/sqrt(mom);
else if(mom>=1.0) mean = 2.166 + 6.27738/mom + -1.38601/mom/mom + -6.98305/sqrt(mom);
sigma = 1.56162 + 0.206245/mom + 0.0984638/mom/mom + -0.0683332/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.299561 + 0.467542/mom + -0.0362706/mom/mom + -0.728446/sqrt(mom);
else if(mom>=1.0) mean = 1.35228 + 5.04917/mom + -1.36045/mom/mom + -5.05525/sqrt(mom);
sigma = 1.98632 + 0.671964/mom + 0.0864345/mom/mom + -1.01984/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 2.12027 + 3.01523/mom + -0.320226/mom/mom + -4.8179/sqrt(mom);
else if(mom>=1.0) mean = 2.73786 + 11.5286/mom + -3.34584/mom/mom + -10.9466/sqrt(mom);
sigma = 2.12161 + 1.0951/mom + 0.00263339/mom/mom + -1.43535/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = -1.23111 + -1.15415/mom + 0.110677/mom/mom + 2.25362/sqrt(mom);
else if(mom>=1.0) mean = 0.035215 + 2.42444/mom + -0.862371/mom/mom + -1.61862/sqrt(mom);
sigma = 2.03289 + 0.792285/mom + 0.0697749/mom/mom + -1.16223/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -1.48654 + -1.45191/mom + 0.10455/mom/mom + 2.81985/sqrt(mom);
else if(mom>=1.0) mean = 1.48313 + 7.7362/mom + -2.37972/mom/mom + -6.84741/sqrt(mom);
sigma = 1.92171 + 0.760257/mom + 0.0497491/mom/mom + -0.94872/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.414626 + 0.822979/mom + -0.0667727/mom/mom + -1.15387/sqrt(mom);
else if(mom>=1.0) mean = 0.80112 + 6.92233/mom + -2.24199/mom/mom + -5.49689/sqrt(mom);
sigma = 2.09263 + 0.95895/mom + 0.0506358/mom/mom + -1.3754/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 1.55399 + 2.87794/mom + -0.388745/mom/mom + -4.02725/sqrt(mom);
else if(mom>=1.0) mean = 0.384593 + 5.99497/mom + -2.18899/mom/mom + -4.2022/sqrt(mom);
sigma = 1.99257 + 0.842343/mom + 0.0447718/mom/mom + -1.09415/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 1.78345 + 2.68829/mom + -0.272149/mom/mom + -4.15272/sqrt(mom);
else if(mom>=1.0) mean = 2.76149 + 16.4511/mom + -5.16168/mom/mom + -14.0782/sqrt(mom);
sigma = 1.94065 + 0.687271/mom + 0.0867374/mom/mom + -0.976231/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = -1.35122 + 0.149169/mom + -0.288561/mom/mom + 1.55083/sqrt(mom);
else if(mom>=1.0) mean = 3.19757 + 18.4137/mom + -5.8794/mom/mom + -15.6724/sqrt(mom);
sigma = 1.23925 + -0.487187/mom + 0.23234/mom/mom + 0.83731/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 1.44226 + 3.09605/mom + -0.450693/mom/mom + -3.92814/sqrt(mom);
else if(mom>=1.0) mean = 3.91614 + 22.603/mom + -7.14364/mom/mom + -19.2925/sqrt(mom);
sigma = 1.99568 + 0.685269/mom + 0.128296/mom/mom + -1.05883/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 2.42597 + 2.48386/mom + -0.19825/mom/mom + -4.7197/sqrt(mom);
else if(mom>=1.0) mean = -1.74229 + -7.23282/mom + 2.11802/mom/mom + 6.83557/sqrt(mom);
sigma = 1.8592 + 0.575/mom + 0.0801405/mom/mom + -0.745418/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -1.75228 + -2.185/mom + 0.197892/mom/mom + 3.75025/sqrt(mom);
else if(mom>=1.0) mean = -0.75157 + -3.38307/mom + 0.970865/mom/mom + 3.18414/sqrt(mom);
sigma = 1.74648 + 0.490736/mom + 0.0729525/mom/mom + -0.564248/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.446741 + -0.795589/mom + 0.09732/mom/mom + 1.14971/sqrt(mom);
else if(mom>=1.0) mean = -0.708683 + -3.55498/mom + 1.02082/mom/mom + 3.24161/sqrt(mom);
sigma = 2.26652 + 1.35997/mom + -0.0242315/mom/mom + -1.83573/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.937332 + -1.33603/mom + 0.122776/mom/mom + 2.16557/sqrt(mom);
else if(mom>=1.0) mean = -0.161653 + -2.49384/mom + 0.809332/mom/mom + 1.86052/sqrt(mom);
sigma = 2.13866 + 1.04174/mom + 0.0231952/mom/mom + -1.4645/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -1.38383 + -1.91602/mom + 0.208927/mom/mom + 3.08538/sqrt(mom);
else if(mom>=1.0) mean = -1.43927 + -8.00562/mom + 2.43174/mom/mom + 7.01715/sqrt(mom);
sigma = 2.32916 + 1.44588/mom + -0.0347687/mom/mom + -1.98099/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -0.944205 + -1.82612/mom + 0.195769/mom/mom + 2.5884/sqrt(mom);
else if(mom>=1.0) mean = -1.71019 + -9.78175/mom + 2.98334/mom/mom + 8.55365/sqrt(mom);
sigma = 1.94061 + 0.693698/mom + 0.0640307/mom/mom + -0.958252/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.392707 + -1.08489/mom + 0.194746/mom/mom + 1.22933/sqrt(mom);
else if(mom>=1.0) mean = -1.59604 + -10.7313/mom + 3.57967/mom/mom + 8.74002/sqrt(mom);
sigma = 1.92456 + 0.776863/mom + 0.0487216/mom/mom + -0.971358/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.906115 + -2.12973/mom + 0.269804/mom/mom + 2.75566/sqrt(mom);
else if(mom>=1.0) mean = -0.545772 + -8.19807/mom + 2.83576/mom/mom + 5.91303/sqrt(mom);
sigma = 1.9675 + 0.706943/mom + 0.0686683/mom/mom + -0.990997/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -1.38642 + -2.66637/mom + 0.445851/mom/mom + 3.49318/sqrt(mom);
else if(mom>=1.0) mean = -2.44319 + -16.8239/mom + 5.71626/mom/mom + 13.4948/sqrt(mom);
sigma = 1.99755 + 0.73992/mom + 0.105423/mom/mom + -1.06993/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -1.73286 + -3.3409/mom + 0.475252/mom/mom + 4.45117/sqrt(mom);
else if(mom>=1.0) mean = -3.81481 + -21.661/mom + 6.79021/mom/mom + 18.6124/sqrt(mom);
sigma = 1.77706 + 0.332007/mom + 0.142964/mom/mom + -0.496762/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.541892 + -0.812558/mom + 0.0816186/mom/mom + 1.28308/sqrt(mom);
else if(mom>=1.0) mean = -0.954051 + -3.80387/mom + 1.12444/mom/mom + 3.66547/sqrt(mom);
sigma = 1.67562 + 0.300812/mom + 0.0784305/mom/mom + -0.316802/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 1.0942 + 1.29652/mom + -0.108497/mom/mom + -2.26513/sqrt(mom);
else if(mom>=1.0) mean = -0.884651 + -2.06092/mom + 0.456672/mom/mom + 2.49223/sqrt(mom);
sigma = 1.93983 + 0.729402/mom + 0.0213795/mom/mom + -0.96863/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.673401 + 0.7472/mom + -0.0580085/mom/mom + -1.33381/sqrt(mom);
else if(mom>=1.0) mean = 0.18287 + 2.79189/mom + -1.14067/mom/mom + -1.85208/sqrt(mom);
sigma = 1.97346 + 0.74301/mom + 0.0416474/mom/mom + -1.0184/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 1.72163 + 2.41046/mom + -0.24049/mom/mom + -3.91417/sqrt(mom);
else if(mom>=1.0) mean = -0.0471491 + 2.2174/mom + -0.966346/mom/mom + -1.255/sqrt(mom);
sigma = 1.93399 + 0.729875/mom + 0.0315069/mom/mom + -0.977921/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -1.219 + -1.05821/mom + 0.0705652/mom/mom + 2.20626/sqrt(mom);
else if(mom>=1.0) mean = 1.36458 + 8.17568/mom + -2.59687/mom/mom + -6.96877/sqrt(mom);
sigma = 1.91599 + 0.776162/mom + 0.0294565/mom/mom + -1.00557/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 2.34645 + 3.21152/mom + -0.335475/mom/mom + -5.19886/sqrt(mom);
else if(mom>=1.0) mean = 0.348417 + 4.33744/mom + -1.48867/mom/mom + -3.18548/sqrt(mom);
sigma = 1.79695 + 0.545148/mom + 0.0526217/mom/mom + -0.69413/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 1.8148 + 2.84335/mom + -0.333896/mom/mom + -4.28863/sqrt(mom);
else if(mom>=1.0) mean = 3.48989 + 17.3358/mom + -5.21716/mom/mom + -15.6354/sqrt(mom);
sigma = 1.9951 + 0.842776/mom + 0.0344874/mom/mom + -1.16012/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 4.51233 + 6.01986/mom + -0.659352/mom/mom + -9.8031/sqrt(mom);
else if(mom>=1.0) mean = 0.520017 + 6.80763/mom + -2.43378/mom/mom + -4.8567/sqrt(mom);
sigma = 1.83018 + 0.606135/mom + 0.0520331/mom/mom + -0.783439/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 0.880248 + 2.48967/mom + -0.415289/mom/mom + -2.87673/sqrt(mom);
else if(mom>=1.0) mean = 2.21923 + 15.942/mom + -5.24349/mom/mom + -12.8802/sqrt(mom);
sigma = 2.05587 + 0.975946/mom + 0.0384069/mom/mom + -1.34651/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 4.71358 + 6.66297/mom + -0.84591/mom/mom + -10.367/sqrt(mom);
else if(mom>=1.0) mean = 1.62692 + 13.7291/mom + -4.81663/mom/mom + -10.4483/sqrt(mom);
sigma = 1.82965 + 0.530109/mom + 0.0917188/mom/mom + -0.738725/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 2.49232 + 2.67819/mom + -0.239944/mom/mom + -4.95554/sqrt(mom);
else if(mom>=1.0) mean = -1.52329 + -5.97027/mom + 1.54306/mom/mom + 5.92159/sqrt(mom);
sigma = 2.03301 + 0.939431/mom + 0.00991868/mom/mom + -1.26076/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 1.9401 + 2.29346/mom + -0.198128/mom/mom + -4.0523/sqrt(mom);
else if(mom>=1.0) mean = -0.752947 + -2.57678/mom + 0.632423/mom/mom + 2.65635/sqrt(mom);
sigma = 2.00484 + 0.891807/mom + 0.00448395/mom/mom + -1.1744/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 1.0114 + 0.786054/mom + -0.0626547/mom/mom + -1.72174/sqrt(mom);
else if(mom>=1.0) mean = -1.4926 + -7.0609/mom + 1.95907/mom/mom + 6.60743/sqrt(mom);
sigma = 1.56446 + 0.147636/mom + 0.104077/mom/mom + -0.0901279/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.803005 + -1.07736/mom + 0.128519/mom/mom + 1.73175/sqrt(mom);
else if(mom>=1.0) mean = -1.0967 + -5.05832/mom + 1.5255/mom/mom + 4.62059/sqrt(mom);
sigma = 1.92881 + 0.741317/mom + 0.02987/mom/mom + -0.992277/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 1.15935 + 0.806861/mom + -0.0548248/mom/mom + -1.90047/sqrt(mom);
else if(mom>=1.0) mean = 0.627723 + -1.85741/mom + 0.904581/mom/mom + 0.360266/sqrt(mom);
sigma = 1.93533 + 0.781957/mom + 0.027623/mom/mom + -1.02733/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -0.578266 + -0.877581/mom + 0.134722/mom/mom + 1.27999/sqrt(mom);
else if(mom>=1.0) mean = -2.09135 + -10.5544/mom + 3.33467/mom/mom + 9.32838/sqrt(mom);
sigma = 1.77157 + 0.516464/mom + 0.0576763/mom/mom + -0.64555/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -1.78961 + -3.04845/mom + 0.352865/mom/mom + 4.44657/sqrt(mom);
else if(mom>=1.0) mean = -1.45018 + -11.4666/mom + 3.65871/mom/mom + 9.26592/sqrt(mom);
sigma = 1.98359 + 0.788154/mom + 0.0405084/mom/mom + -1.09906/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -1.26011 + -1.86239/mom + 0.279609/mom/mom + 2.76902/sqrt(mom);
else if(mom>=1.0) mean = -1.42904 + -9.4595/mom + 3.15569/mom/mom + 7.69049/sqrt(mom);
sigma = 1.62816 + 0.268514/mom + 0.100472/mom/mom + -0.302425/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = 1.33297 + 0.135116/mom + 0.170156/mom/mom + -1.76236/sqrt(mom);
else if(mom>=1.0) mean = -1.99156 + -16.1317/mom + 5.37007/mom/mom + 12.6741/sqrt(mom);
sigma = 1.75497 + 0.378449/mom + 0.108098/mom/mom + -0.490607/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -2.06035 + -3.31739/mom + 0.544676/mom/mom + 4.67947/sqrt(mom);
else if(mom>=1.0) mean = -2.32279 + -15.0474/mom + 5.0848/mom/mom + 12.1939/sqrt(mom);
sigma = 1.70199 + 0.165244/mom + 0.169647/mom/mom + -0.340919/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.617972 + 0.509209/mom + -0.0200808/mom/mom + -1.05911/sqrt(mom);
else if(mom>=1.0) mean = -1.41479 + -4.46073/mom + 1.20103/mom/mom + 4.73255/sqrt(mom);
sigma = 2.20411 + 1.20838/mom + -0.0267258/mom/mom + -1.65368/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.861156 + 0.874603/mom + -0.0731827/mom/mom + -1.65762/sqrt(mom);
else if(mom>=1.0) mean = -0.062007 + 0.280841/mom + -0.174998/mom/mom + -0.0611629/sqrt(mom);
sigma = 2.21696 + 1.30024/mom + -0.0420797/mom/mom + -1.75279/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.871573 + 1.58638/mom + -0.182786/mom/mom + -2.30229/sqrt(mom);
else if(mom>=1.0) mean = 0.285797 + 2.29882/mom + -0.720694/mom/mom + -1.86547/sqrt(mom);
sigma = 2.09773 + 1.04292/mom + -0.00635903/mom/mom + -1.39424/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 1.25226 + 1.37997/mom + -0.114068/mom/mom + -2.48281/sqrt(mom);
else if(mom>=1.0) mean = 0.101966 + 1.92509/mom + -0.721933/mom/mom + -1.28112/sqrt(mom);
sigma = 2.37243 + 1.61028/mom + -0.0750087/mom/mom + -2.19358/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 2.62302 + 3.51336/mom + -0.362695/mom/mom + -5.74431/sqrt(mom);
else if(mom>=1.0) mean = -1.15637 + -0.34549/mom + -0.375083/mom/mom + 1.89814/sqrt(mom);
sigma = 1.9603 + 0.797152/mom + 0.0268146/mom/mom + -1.05801/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.750666 + 1.35552/mom + -0.159444/mom/mom + -1.94538/sqrt(mom);
else if(mom>=1.0) mean = 1.9128 + 9.85667/mom + -2.95683/mom/mom + -8.83369/sqrt(mom);
sigma = 2.07362 + 1.12081/mom + -0.0177659/mom/mom + -1.48312/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 2.80365 + 4.02459/mom + -0.48236/mom/mom + -6.2956/sqrt(mom);
else if(mom>=1.0) mean = 1.04117 + 9.5854/mom + -3.41551/mom/mom + -7.22264/sqrt(mom);
sigma = 1.87949 + 0.772704/mom + 0.0274194/mom/mom + -0.950965/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 1.98176 + 3.17721/mom + -0.376891/mom/mom + -4.74421/sqrt(mom);
else if(mom>=1.0) mean = 2.895 + 15.8951/mom + -4.96969/mom/mom + -13.8517/sqrt(mom);
sigma = 2.02135 + 1.02632/mom + -0.000818548/mom/mom + -1.34543/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 5.31797 + 7.34429/mom + -0.901989/mom/mom + -11.6168/sqrt(mom);
else if(mom>=1.0) mean = 0.891271 + 11.1655/mom + -4.14171/mom/mom + -7.84374/sqrt(mom);
sigma = 1.73315 + 0.358343/mom + 0.12339/mom/mom + -0.474741/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 1.67162 + 3.2025/mom + -0.478006/mom/mom + -4.25661/sqrt(mom);
else if(mom>=1.0) mean = 3.15481 + 19.7988/mom + -6.39026/mom/mom + -16.4965/sqrt(mom);
sigma = 1.96597 + 0.859286/mom + 0.0498139/mom/mom + -1.16671/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 1.32175 + 1.68365/mom + -0.151181/mom/mom + -2.91003/sqrt(mom);
else if(mom>=1.0) mean = -0.314603 + -1.67456/mom + 0.592112/mom/mom + 1.34399/sqrt(mom);
sigma = 1.79525 + 0.779027/mom + 0.00333022/mom/mom + -0.820459/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 0.0832334 + 0.00976643/mom + -0.013692/mom/mom + -0.0919365/sqrt(mom);
else if(mom>=1.0) mean = -0.376745 + -2.19215/mom + 0.641949/mom/mom + 1.94215/sqrt(mom);
sigma = 2.14108 + 1.13005/mom + -0.0122511/mom/mom + -1.53911/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -1.6151 + -2.1408/mom + 0.236926/mom/mom + 3.48708/sqrt(mom);
else if(mom>=1.0) mean = -1.03215 + -5.42958/mom + 1.70165/mom/mom + 4.73327/sqrt(mom);
sigma = 2.05207 + 1.0335/mom + -0.00876587/mom/mom + -1.34564/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 0.886043 + 0.561448/mom + -0.0352962/mom/mom + -1.38518/sqrt(mom);
else if(mom>=1.0) mean = -0.678945 + -5.13034/mom + 1.66718/mom/mom + 4.19236/sqrt(mom);
sigma = 2.17876 + 1.13813/mom + -0.00683737/mom/mom + -1.60295/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -4.31743 + -5.18596/mom + 0.51676/mom/mom + 8.92739/sqrt(mom);
else if(mom>=1.0) mean = -1.15101 + -7.11444/mom + 2.3709/mom/mom + 5.89955/sqrt(mom);
sigma = 1.77999 + 0.627806/mom + 0.0451238/mom/mom + -0.729082/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 1.31406 + 0.729107/mom + -0.0284899/mom/mom + -1.98847/sqrt(mom);
else if(mom>=1.0) mean = -0.476882 + -5.72849/mom + 1.8797/mom/mom + 4.35448/sqrt(mom);
sigma = 2.10651 + 1.07632/mom + -0.00314085/mom/mom + -1.48516/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -1.1556 + -1.85716/mom + 0.278838/mom/mom + 2.69102/sqrt(mom);
else if(mom>=1.0) mean = -1.74602 + -11.7183/mom + 4.03617/mom/mom + 9.43867/sqrt(mom);
sigma = 1.76217 + 0.572065/mom + 0.062289/mom/mom + -0.676939/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.565115 + -1.8374/mom + 0.256077/mom/mom + 2.13428/sqrt(mom);
else if(mom>=1.0) mean = -3.51874 + -18.7395/mom + 5.70531/mom/mom + 16.6102/sqrt(mom);
sigma = 1.8924 + 0.659082/mom + 0.0572412/mom/mom + -0.91036/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -3.35195 + -4.95559/mom + 0.699575/mom/mom + 7.47805/sqrt(mom);
else if(mom>=1.0) mean = -1.99697 + -14.712/mom + 5.15328/mom/mom + 11.5164/sqrt(mom);
sigma = 1.74893 + 0.329297/mom + 0.14871/mom/mom + -0.500394/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -0.801332 + -2.47601/mom + 0.426166/mom/mom + 2.68073/sqrt(mom);
else if(mom>=1.0) mean = -3.3436 + -20.7108/mom + 6.60627/mom/mom + 17.3687/sqrt(mom);
sigma = 1.72343 + 0.509166/mom + 0.081141/mom/mom + -0.58115/sqrt(mom);
}
else
{
cout<<"significant issue in caltofwsdz"<<endl;
return -9999;
}
value = (tofwdz - mean)/sigma;
return value;
}
float caltofwsdphi(int run, int striptofw, int charge, float zed, float mom, float tofwdphi)
{
float mean = -9999;
float sigma = -9999;
float value = -9999;
if(run>250484&&striptofw<256&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.0111693 + -0.0179804/mom + 0.00222222/mom/mom + 0.0270516/sqrt(mom);
else if(mom>=1.0) mean = 0.00183304 + 0.00492135/mom + -0.00137131/mom/mom + -0.00524524/sqrt(mom);
sigma = 0.00191169 + 0.00135976/mom + 0.000109287/mom/mom + -0.00130868/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.000919912 + 0.0001305/mom + -0.000223512/mom/mom + 0.00086823/sqrt(mom);
else if(mom>=1.0) mean = -0.00129849 + -0.00972102/mom + 0.00252642/mom/mom + 0.00819793/sqrt(mom);
sigma = 0.00212381 + 0.000325305/mom + 0.00032085/mom/mom + -0.000531452/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = -0.015294 + -0.023321/mom + 0.00271271/mom/mom + 0.0360358/sqrt(mom);
else if(mom>=1.0) mean = 0.0019924 + 0.00667001/mom + -0.00231375/mom/mom + -0.0062737/sqrt(mom);
sigma = 0.00104359 + -0.000946742/mom + 0.00054678/mom/mom + 0.00144582/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.00534339 + 0.00588622/mom + -0.000439138/mom/mom + -0.0109084/sqrt(mom);
else if(mom>=1.0) mean = -0.00602378 + -0.0237317/mom + 0.00594976/mom/mom + 0.0235211/sqrt(mom);
sigma = 0.00110779 + -0.00188478/mom + 0.000692939/mom/mom + 0.00232669/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -0.0130766 + -0.020681/mom + 0.00223909/mom/mom + 0.0316848/sqrt(mom);
else if(mom>=1.0) mean = 0.0016696 + 0.00558525/mom + -0.0023808/mom/mom + -0.0048049/sqrt(mom);
sigma = 0.000974563 + -0.00146289/mom + 0.000717284/mom/mom + 0.00187132/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.0216755 + 0.0273646/mom + -0.00237462/mom/mom + -0.0468154/sqrt(mom);
else if(mom>=1.0) mean = -0.00447619 + -0.0192878/mom + 0.00547137/mom/mom + 0.0180053/sqrt(mom);
sigma = 0.00154772 + -0.00142054/mom + 0.000722499/mom/mom + 0.00137071/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = -0.0104444 + -0.0178846/mom + 0.00173669/mom/mom + 0.0266979/sqrt(mom);
else if(mom>=1.0) mean = 0.00106208 + 0.0017845/mom + -0.00150766/mom/mom + -0.00128626/sqrt(mom);
sigma = 0.000183525 + -0.00410421/mom + 0.00128057/mom/mom + 0.00473443/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 0.0135249 + 0.0135683/mom + -0.000249168/mom/mom + -0.0269242/sqrt(mom);
else if(mom>=1.0) mean = -0.00466344 + -0.0192779/mom + 0.00574216/mom/mom + 0.0179905/sqrt(mom);
sigma = 0.000713911 + -0.00386405/mom + 0.00128707/mom/mom + 0.00412818/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 0.000584012 + -0.00391181/mom + -0.000105035/mom/mom + 0.00327875/sqrt(mom);
else if(mom>=1.0) mean = 0.00407464 + 0.0121303/mom + -0.00474243/mom/mom + -0.0118154/sqrt(mom);
sigma = 0.00104946 + -0.00286793/mom + 0.00119321/mom/mom + 0.00272217/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 0.0133224 + 0.0102497/mom + 0.000941732/mom/mom + -0.0242771/sqrt(mom);
else if(mom>=1.0) mean = -0.00586296 + -0.0231923/mom + 0.00709393/mom/mom + 0.0221364/sqrt(mom);
sigma = 0.000806618 + -0.00413324/mom + 0.00149992/mom/mom + 0.00415258/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 0.0195677 + 0.0296051/mom + -0.00312579/mom/mom + -0.0462729/sqrt(mom);
else if(mom>=1.0) mean = 0.0016173 + 0.0066212/mom + -0.00232467/mom/mom + -0.00604846/sqrt(mom);
sigma = 0.00309977 + 0.00430701/mom + -0.000321822/mom/mom + -0.00487254/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -0.00465823 + -0.00190454/mom + -0.000223039/mom/mom + 0.00642224/sqrt(mom);
else if(mom>=1.0) mean = 0.00193268 + 0.00582236/mom + -0.00258719/mom/mom + -0.00564887/sqrt(mom);
sigma = 0.00100654 + -0.0018007/mom + 0.000621958/mom/mom + 0.00241433/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 0.0146175 + 0.0236627/mom + -0.0027167/mom/mom + -0.0357543/sqrt(mom);
else if(mom>=1.0) mean = 0.00159524 + 0.00523706/mom + -0.00186079/mom/mom + -0.00503391/sqrt(mom);
sigma = 0.00325753 + 0.00480982/mom + -0.00041734/mom/mom + -0.00542232/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.00492154 + -0.00334746/mom + 0.000168475/mom/mom + 0.00778783/sqrt(mom);
else if(mom>=1.0) mean = 0.000478822 + 0.000597555/mom + -0.000763624/mom/mom + -0.000738741/sqrt(mom);
sigma = 0.0010575 + -0.00185852/mom + 0.000688697/mom/mom + 0.00233713/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 0.0174326 + 0.0273568/mom + -0.00340357/mom/mom + -0.0414791/sqrt(mom);
else if(mom>=1.0) mean = 0.000440835 + 0.000210714/mom + -0.000714988/mom/mom + 4.56835e-05/sqrt(mom);
sigma = 0.00386167 + 0.00581463/mom + -0.000503255/mom/mom + -0.00694218/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -0.00939194 + -0.00967108/mom + 0.0011311/mom/mom + 0.0176254/sqrt(mom);
else if(mom>=1.0) mean = 0.000103603 + -0.000331632/mom + -0.000157332/mom/mom + -5.03372e-05/sqrt(mom);
sigma = 0.0010201 + -0.00292075/mom + 0.00102372/mom/mom + 0.00308206/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = 0.00887053 + 0.01669/mom + -0.00274246/mom/mom + -0.0228844/sqrt(mom);
else if(mom>=1.0) mean = -0.000282363 + -0.00276853/mom + -0.000289164/mom/mom + 0.00333343/sqrt(mom);
sigma = 0.00437885 + 0.00645232/mom + -0.000508818/mom/mom + -0.00808212/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.0137176 + -0.0159055/mom + 0.00219178/mom/mom + 0.0271417/sqrt(mom);
else if(mom>=1.0) mean = 0.00175411 + 0.00521533/mom + -0.000584753/mom/mom + -0.00677979/sqrt(mom);
sigma = 0.00168475 + -0.00194291/mom + 0.00106099/mom/mom + 0.00137252/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = 0.00286314 + 0.00989804/mom + -0.00256251/mom/mom + -0.0106085/sqrt(mom);
else if(mom>=1.0) mean = -0.000129154 + -0.00201676/mom + -0.000793747/mom/mom + 0.00257634/sqrt(mom);
sigma = 0.00386224 + 0.00494676/mom + -0.000200333/mom/mom + -0.006409/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -0.0133634 + -0.0173316/mom + 0.00295682/mom/mom + 0.0277825/sqrt(mom);
else if(mom>=1.0) mean = -0.00404202 + -0.0134408/mom + 0.0040691/mom/mom + 0.0133807/sqrt(mom);
sigma = -0.000240179 + -0.00685185/mom + 0.00191014/mom/mom + 0.00738224/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.00497067 + 0.00504253/mom + -0.000397867/mom/mom + -0.0096885/sqrt(mom);
else if(mom>=1.0) mean = -0.00686102 + -0.0257015/mom + 0.00645914/mom/mom + 0.0259457/sqrt(mom);
sigma = 0.000391535 + -0.00314856/mom + 0.00088079/mom/mom + 0.00409002/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.00658244 + -0.0132434/mom + 0.00184724/mom/mom + 0.018177/sqrt(mom);
else if(mom>=1.0) mean = 0.00336873 + 0.00882874/mom + -0.00227332/mom/mom + -0.00981799/sqrt(mom);
sigma = 0.00260359 + 0.00173333/mom + 0.000198245/mom/mom + -0.00242864/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.0118383 + 0.0116558/mom + -0.000731536/mom/mom + -0.0227902/sqrt(mom);
else if(mom>=1.0) mean = -0.00646069 + -0.0240832/mom + 0.00614939/mom/mom + 0.0242385/sqrt(mom);
sigma = 0.000988982 + -0.00162494/mom + 0.000638322/mom/mom + 0.0022495/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = -0.0153786 + -0.0235636/mom + 0.00270747/mom/mom + 0.0363761/sqrt(mom);
else if(mom>=1.0) mean = 0.00556701 + 0.0165567/mom + -0.00445607/mom/mom + -0.0175503/sqrt(mom);
sigma = 0.00246597 + 0.00136651/mom + 0.000259801/mom/mom + -0.00195345/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.0277379 + 0.032566/mom + -0.00260573/mom/mom + -0.0577676/sqrt(mom);
else if(mom>=1.0) mean = -0.00586375 + -0.0214244/mom + 0.00562504/mom/mom + 0.0214211/sqrt(mom);
sigma = 0.00159138 + -0.00169025/mom + 0.000866726/mom/mom + 0.00145931/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -0.0160061 + -0.0256034/mom + 0.00284247/mom/mom + 0.0389646/sqrt(mom);
else if(mom>=1.0) mean = 0.00654846 + 0.0192498/mom + -0.00536735/mom/mom + -0.0203165/sqrt(mom);
sigma = 0.00179042 + -0.000254583/mom + 0.00056777/mom/mom + 1.71917e-05/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 0.015944 + 0.0149373/mom + -0.000199132/mom/mom + -0.0307251/sqrt(mom);
else if(mom>=1.0) mean = -0.00420032 + -0.0141359/mom + 0.00380043/mom/mom + 0.0143589/sqrt(mom);
sigma = 0.000196024 + -0.00509817/mom + 0.00157324/mom/mom + 0.00557836/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = -0.0155145 + -0.0241601/mom + 0.00226057/mom/mom + 0.0375435/sqrt(mom);
else if(mom>=1.0) mean = 0.00237876 + 0.00529648/mom + -0.00224988/mom/mom + -0.00535953/sqrt(mom);
sigma = 0.00143368 + -0.00185358/mom + 0.000968618/mom/mom + 0.00159879/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 0.00644759 + 0.000963176/mom + 0.00193926/mom/mom + -0.00912479/sqrt(mom);
else if(mom>=1.0) mean = -0.0030578 + -0.012929/mom + 0.00397234/mom/mom + 0.0121364/sqrt(mom);
sigma = 0.000789651 + -0.00382715/mom + 0.00144045/mom/mom + 0.00390959/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = -0.0197629 + -0.0317104/mom + 0.00292317/mom/mom + 0.0483129/sqrt(mom);
else if(mom>=1.0) mean = 0.000134067 + -0.00115549/mom + -0.00119301/mom/mom + 0.00188604/sqrt(mom);
sigma = 0.00134475 + -0.00215417/mom + 0.00105832/mom/mom + 0.00192813/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -0.00334595 + -0.00257423/mom + 9.42772e-05/mom/mom + 0.00556476/sqrt(mom);
else if(mom>=1.0) mean = -0.00212209 + -0.0061724/mom + 0.00049983/mom/mom + 0.00744338/sqrt(mom);
sigma = 0.00146502 + -0.000973019/mom + 0.000550749/mom/mom + 0.00118402/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 0.0112664 + 0.0181233/mom + -0.00192965/mom/mom + -0.027632/sqrt(mom);
else if(mom>=1.0) mean = 0.00508141 + 0.0168378/mom + -0.0048183/mom/mom + -0.0172226/sqrt(mom);
sigma = 0.00372493 + 0.00521081/mom + -0.000407918/mom/mom + -0.0063168/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.00316202 + -0.00221388/mom + 0.00017731/mom/mom + 0.00493534/sqrt(mom);
else if(mom>=1.0) mean = -0.00117097 + -0.00311082/mom + -0.000162393/mom/mom + 0.00403029/sqrt(mom);
sigma = 0.00100455 + -0.00211671/mom + 0.000769257/mom/mom + 0.00253085/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 0.0124325 + 0.0195136/mom + -0.00218234/mom/mom + -0.0298942/sqrt(mom);
else if(mom>=1.0) mean = 0.00378734 + 0.0113938/mom + -0.00330086/mom/mom + -0.0119498/sqrt(mom);
sigma = 0.00413372 + 0.00586509/mom + -0.000470723/mom/mom + -0.00731797/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -0.00950612 + -0.0110111/mom + 0.00146137/mom/mom + 0.0187512/sqrt(mom);
else if(mom>=1.0) mean = -0.00680386 + -0.0219407/mom + 0.0052146/mom/mom + 0.0231411/sqrt(mom);
sigma = 0.00118249 + -0.00283605/mom + 0.00108526/mom/mom + 0.00270569/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 0.0119743 + 0.0198206/mom + -0.00258994/mom/mom + -0.029287/sqrt(mom);
else if(mom>=1.0) mean = 0.00520967 + 0.0151219/mom + -0.00447717/mom/mom + -0.0159136/sqrt(mom);
sigma = 0.00452915 + 0.00656287/mom + -0.000533057/mom/mom + -0.00834097/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.00805064 + -0.009515/mom + 0.00166024/mom/mom + 0.0156881/sqrt(mom);
else if(mom>=1.0) mean = -0.000731162 + -0.00112739/mom + 0.000704835/mom/mom + 0.000779115/sqrt(mom);
sigma = 0.00137405 + -0.00282142/mom + 0.00126289/mom/mom + 0.00233208/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = 0.0054322 + 0.0118652/mom + -0.00221914/mom/mom + -0.0151661/sqrt(mom);
else if(mom>=1.0) mean = 0.000128165 + -0.00300757/mom + 8.70517e-05/mom/mom + 0.00279913/sqrt(mom);
sigma = 0.00480329 + 0.00701564/mom + -0.000548736/mom/mom + -0.00900075/sqrt(mom);
}
else if(run>250484&&striptofw<256&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -0.0106116 + -0.0143839/mom + 0.00275205/mom/mom + 0.0223392/sqrt(mom);
else if(mom>=1.0) mean = -0.00131478 + -0.00542669/mom + 0.00210068/mom/mom + 0.00461257/sqrt(mom);
sigma = 0.000417882 + -0.00542497/mom + 0.00173107/mom/mom + 0.00545199/sqrt(mom);
}
else if(run<250593&&striptofw<256&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = 0.00229806 + 0.00883081/mom + -0.00241183/mom/mom + -0.00915319/sqrt(mom);
else if(mom>=1.0) mean = -0.000744112 + -0.00327571/mom + -0.000597993/mom/mom + 0.00421884/sqrt(mom);
sigma = 0.00428314 + 0.00582874/mom + -0.000362426/mom/mom + -0.00748534/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.0150518 + 0.019115/mom + -0.00181246/mom/mom + -0.0322523/sqrt(mom);
else if(mom>=1.0) mean = 0.00168405 + 0.00500783/mom + -0.00118996/mom/mom + -0.00538902/sqrt(mom);
sigma = 0.000934249 + -0.000297245/mom + 0.000183313/mom/mom + 0.0013952/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.0245686 + -0.028583/mom + 0.00249109/mom/mom + 0.0504303/sqrt(mom);
else if(mom>=1.0) mean = -0.00378089 + -0.0115843/mom + 0.00266955/mom/mom + 0.0125527/sqrt(mom);
sigma = 0.00160332 + 0.000275894/mom + 0.000182243/mom/mom + 1.13411e-05/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.00293425 + 0.00488742/mom + -0.00060633/mom/mom + -0.00712365/sqrt(mom);
else if(mom>=1.0) mean = -0.000397719 + -0.00646269/mom + 0.00261868/mom/mom + 0.00428986/sqrt(mom);
sigma = -0.000315782 + -0.00277596/mom + 0.00055071/mom/mom + 0.00483398/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.00208679 + 0.00464515/mom + -0.000524755/mom/mom + -0.00651239/sqrt(mom);
else if(mom>=1.0) mean = -0.00439634 + -0.0124428/mom + 0.00232458/mom/mom + 0.0142139/sqrt(mom);
sigma = -0.000941359 + -0.00529102/mom + 0.000976552/mom/mom + 0.00741683/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.00863763 + 0.0110055/mom + -0.00137707/mom/mom + -0.0179944/sqrt(mom);
else if(mom>=1.0) mean = 0.00269171 + 0.00424032/mom + -0.000639582/mom/mom + -0.00600465/sqrt(mom);
sigma = 0.00019161 + -0.00264161/mom + 0.000685036/mom/mom + 0.00397294/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -0.0244563 + -0.027964/mom + 0.0027828/mom/mom + 0.0492034/sqrt(mom);
else if(mom>=1.0) mean = -0.0040733 + -0.0121524/mom + 0.00310502/mom/mom + 0.0128271/sqrt(mom);
sigma = 0.000565877 + -0.00308507/mom + 0.000902665/mom/mom + 0.00369277/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 0.00807054 + 0.01059/mom + -0.00172233/mom/mom + -0.0167201/sqrt(mom);
else if(mom>=1.0) mean = -0.00152662 + -0.0104726/mom + 0.00288963/mom/mom + 0.00936782/sqrt(mom);
sigma = -8.79339e-05 + -0.0036825/mom + 0.000976747/mom/mom + 0.00499278/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = -0.0127216 + -0.0140849/mom + 0.0018727/mom/mom + 0.0245996/sqrt(mom);
else if(mom>=1.0) mean = -0.00201549 + -0.00477047/mom + 0.00154286/mom/mom + 0.00494989/sqrt(mom);
sigma = 0.000348629 + -0.00454768/mom + 0.00136758/mom/mom + 0.00489214/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = -0.000527628 + 0.0008419/mom + -0.00128823/mom/mom + 0.000814781/sqrt(mom);
else if(mom>=1.0) mean = 0.00210107 + 0.00200451/mom + -0.000926133/mom/mom + -0.00332982/sqrt(mom);
sigma = 0.000616358 + -0.00264165/mom + 0.000927417/mom/mom + 0.00327186/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = -0.0180575 + -0.0215866/mom + 0.003169/mom/mom + 0.0364398/sqrt(mom);
else if(mom>=1.0) mean = -0.00316988 + -0.00827443/mom + 0.00281248/mom/mom + 0.00867462/sqrt(mom);
sigma = -0.00043605 + -0.00698349/mom + 0.00189348/mom/mom + 0.00759933/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 0.0229129 + 0.021823/mom + -0.00158183/mom/mom + -0.0425446/sqrt(mom);
else if(mom>=1.0) mean = 0.00619534 + 0.0250281/mom + -0.00654733/mom/mom + -0.0242121/sqrt(mom);
sigma = -0.00103989 + -0.00554054/mom + 0.000985785/mom/mom + 0.00788904/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -0.0265797 + -0.0307563/mom + 0.00268573/mom/mom + 0.0543832/sqrt(mom);
else if(mom>=1.0) mean = -0.00697722 + -0.0203184/mom + 0.00453138/mom/mom + 0.0225178/sqrt(mom);
sigma = 0.00158346 + 0.000309575/mom + 0.000156873/mom/mom + 0.000117302/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 0.0158875 + 0.0136284/mom + -0.000977841/mom/mom + -0.027939/sqrt(mom);
else if(mom>=1.0) mean = 0.003921 + 0.0188411/mom + -0.00557224/mom/mom + -0.0168326/sqrt(mom);
sigma = -0.00112818 + -0.00597026/mom + 0.00110392/mom/mom + 0.00827921/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.0138975 + -0.0160326/mom + 0.00151023/mom/mom + 0.0281766/sqrt(mom);
else if(mom>=1.0) mean = -0.00693999 + -0.0196232/mom + 0.00450151/mom/mom + 0.0218498/sqrt(mom);
sigma = 0.000463528 + -0.00214549/mom + 0.000548826/mom/mom + 0.00333483/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 0.0122775 + 0.0101563/mom + -0.00100993/mom/mom + -0.020815/sqrt(mom);
else if(mom>=1.0) mean = 0.00170264 + 0.0058075/mom + -0.00141918/mom/mom + -0.00558536/sqrt(mom);
sigma = -0.00157399 + -0.00765202/mom + 0.00150265/mom/mom + 0.0100118/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -0.00617191 + -0.00776933/mom + 0.00112159/mom/mom + 0.0125769/sqrt(mom);
else if(mom>=1.0) mean = -0.00623092 + -0.0175247/mom + 0.00436918/mom/mom + 0.019116/sqrt(mom);
sigma = -0.000332252 + -0.00442572/mom + 0.00101768/mom/mom + 0.00594409/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = 0.0136757 + 0.0131587/mom + -0.00178179/mom/mom + -0.0245288/sqrt(mom);
else if(mom>=1.0) mean = 0.00115421 + 0.00454635/mom + -0.00177914/mom/mom + -0.00353489/sqrt(mom);
sigma = -0.000892073 + -0.00645965/mom + 0.0014467/mom/mom + 0.00815186/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.00239261 + -0.0042506/mom + 0.00130935/mom/mom + 0.0051162/sqrt(mom);
else if(mom>=1.0) mean = -0.004718 + -0.0111943/mom + 0.00293121/mom/mom + 0.0126972/sqrt(mom);
sigma = -0.0010567 + -0.00667119/mom + 0.00153094/mom/mom + 0.00840046/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = 0.0279204 + 0.0343174/mom + -0.00453105/mom/mom + -0.0576967/sqrt(mom);
else if(mom>=1.0) mean = -0.00175497 + -0.0102372/mom + 0.0028026/mom/mom + 0.00919784/sqrt(mom);
sigma = 0.000730295 + -0.00300285/mom + 0.00102019/mom/mom + 0.00348338/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==-1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -0.000422815 + -0.00386144/mom + 0.00191616/mom/mom + 0.00253134/sqrt(mom);
else if(mom>=1.0) mean = -0.00742087 + -0.0198281/mom + 0.00547491/mom/mom + 0.0218903/sqrt(mom);
sigma = -0.000450233 + -0.00559022/mom + 0.00144669/mom/mom + 0.00679286/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = -0.0192455 + -0.0225693/mom + 0.0019896/mom/mom + 0.039623/sqrt(mom);
else if(mom>=1.0) mean = -0.00726099 + -0.0219162/mom + 0.00521991/mom/mom + 0.0238511/sqrt(mom);
sigma = 0.00178016 + 0.000534475/mom + 0.000181486/mom/mom + -0.000418003/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-15&&zed<0))
{
if(mom<1.0) mean = 0.00796952 + 0.0107908/mom + -0.00108552/mom/mom + -0.017587/sqrt(mom);
else if(mom>=1.0) mean = 0.0049583 + 0.0142444/mom + -0.00333584/mom/mom + -0.015798/sqrt(mom);
sigma = 0.00250988 + 0.00246705/mom + -0.000137394/mom/mom + -0.00268295/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = 0.00282511 + 0.00531444/mom + -0.000555582/mom/mom + -0.00785994/sqrt(mom);
else if(mom>=1.0) mean = -0.0100941 + -0.0307787/mom + 0.00711995/mom/mom + 0.0335103/sqrt(mom);
sigma = -0.000886689 + -0.00501879/mom + 0.000978759/mom/mom + 0.0070667/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-30&&zed<=-15))
{
if(mom<1.0) mean = -0.0033627 + -0.00189407/mom + -7.5255e-05/mom/mom + 0.00539209/sqrt(mom);
else if(mom>=1.0) mean = 0.00522032 + 0.011838/mom + -0.00212/mom/mom + -0.014945/sqrt(mom);
sigma = 0.00138682 + 0.000402657/mom + 0.000160806/mom/mom + 0.000282295/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = -0.0236892 + -0.0275781/mom + 0.00279082/mom/mom + 0.0480828/sqrt(mom);
else if(mom>=1.0) mean = -0.00785671 + -0.0218373/mom + 0.00513933/mom/mom + 0.024266/sqrt(mom);
sigma = 0.000874412 + -0.00241567/mom + 0.000839411/mom/mom + 0.00277019/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-45&&zed<=-30))
{
if(mom<1.0) mean = 0.00356937 + 0.00548438/mom + -0.000952027/mom/mom + -0.00783958/sqrt(mom);
else if(mom>=1.0) mean = 0.00470801 + 0.00977546/mom + -0.00198162/mom/mom + -0.0122641/sqrt(mom);
sigma = 0.00138923 + -0.000357262/mom + 0.000396536/mom/mom + 0.00075861/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = -0.0153723 + -0.0172962/mom + 0.00218312/mom/mom + 0.030158/sqrt(mom);
else if(mom>=1.0) mean = -0.00597598 + -0.017135/mom + 0.00468087/mom/mom + 0.0182038/sqrt(mom);
sigma = -0.000148274 + -0.00543036/mom + 0.0015111/mom/mom + 0.00614371/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-60&&zed<=-45))
{
if(mom<1.0) mean = 0.000438052 + 0.00174869/mom + -0.000938639/mom/mom + -0.00107016/sqrt(mom);
else if(mom>=1.0) mean = 0.00146945 + -0.000776049/mom + 0.000349083/mom/mom + -0.000843265/sqrt(mom);
sigma = 0.00138028 + -0.000633222/mom + 0.000549582/mom/mom + 0.000899618/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = -0.0207332 + -0.0245253/mom + 0.00340292/mom/mom + 0.0418194/sqrt(mom);
else if(mom>=1.0) mean = -0.00321394 + -0.00963409/mom + 0.00338963/mom/mom + 0.00955568/sqrt(mom);
sigma = -0.000381408 + -0.00678677/mom + 0.00186752/mom/mom + 0.00737771/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>-75&&zed<=-60))
{
if(mom<1.0) mean = 0.00235525 + 0.00531669/mom + -0.00185515/mom/mom + -0.00599814/sqrt(mom);
else if(mom>=1.0) mean = -0.00269547 + -0.0134437/mom + 0.00313092/mom/mom + 0.0128704/sqrt(mom);
sigma = 0.000827205 + -0.00219639/mom + 0.000879618/mom/mom + 0.00269047/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = -0.0259888 + -0.0302742/mom + 0.00269081/mom/mom + 0.0532961/sqrt(mom);
else if(mom>=1.0) mean = -0.00808909 + -0.0217068/mom + 0.00453431/mom/mom + 0.0250489/sqrt(mom);
sigma = 0.00146462 + 0.000380385/mom + 0.000154586/mom/mom + 0.000172139/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=0&&zed<15))
{
if(mom<1.0) mean = 0.0149774 + 0.0126916/mom + -0.000788262/mom/mom + -0.0263278/sqrt(mom);
else if(mom>=1.0) mean = 0.0112894 + 0.0402018/mom + -0.0102535/mom/mom + -0.0408511/sqrt(mom);
sigma = 0.00126593 + -0.00160634/mom + 0.00053463/mom/mom + 0.00201931/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = -0.00947534 + -0.011962/mom + 0.0012709/mom/mom + 0.0199843/sqrt(mom);
else if(mom>=1.0) mean = -0.00876473 + -0.0237449/mom + 0.00528444/mom/mom + 0.0270477/sqrt(mom);
sigma = 0.0013381 + -0.000504025/mom + 0.00038554/mom/mom + 0.000968167/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=15&&zed<30))
{
if(mom<1.0) mean = 0.00767852 + 0.00416046/mom + -0.00014392/mom/mom + -0.0111481/sqrt(mom);
else if(mom>=1.0) mean = 0.0107129 + 0.0377651/mom + -0.00975121/mom/mom + -0.0383664/sqrt(mom);
sigma = 0.000218044 + -0.00413124/mom + 0.000959441/mom/mom + 0.0051898/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = -0.00444575 + -0.00615191/mom + 0.00102972/mom/mom + 0.00935856/sqrt(mom);
else if(mom>=1.0) mean = -0.0104358 + -0.027825/mom + 0.00639597/mom/mom + 0.0316207/sqrt(mom);
sigma = 0.000194868 + -0.00331273/mom + 0.000902405/mom/mom + 0.00440426/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=30&&zed<45))
{
if(mom<1.0) mean = 0.0114909 + 0.00913036/mom + -0.000922316/mom/mom + -0.0190636/sqrt(mom);
else if(mom>=1.0) mean = 0.00936342 + 0.0313681/mom + -0.00808637/mom/mom + -0.0322231/sqrt(mom);
sigma = -0.000488869 + -0.00581663/mom + 0.00131574/mom/mom + 0.00721865/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = -0.00228134 + -0.0049997/mom + 0.00149358/mom/mom + 0.00561084/sqrt(mom);
else if(mom>=1.0) mean = -0.00513401 + -0.0118049/mom + 0.00297391/mom/mom + 0.0137058/sqrt(mom);
sigma = -0.000460288 + -0.00519419/mom + 0.00131399/mom/mom + 0.00655468/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=45&&zed<60))
{
if(mom<1.0) mean = 0.00627704 + 0.00395804/mom + -0.000912967/mom/mom + -0.00880627/sqrt(mom);
else if(mom>=1.0) mean = 0.00416215 + 0.0126033/mom + -0.0034174/mom/mom + -0.0129492/sqrt(mom);
sigma = -0.000538445 + -0.00598059/mom + 0.00142679/mom/mom + 0.00735372/sqrt(mom);
}
else if(run>250484&&striptofw>255&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = -0.00287085 + -0.00781433/mom + 0.0024171/mom/mom + 0.0084786/sqrt(mom);
else if(mom>=1.0) mean = -0.00664132 + -0.0174918/mom + 0.00486693/mom/mom + 0.019421/sqrt(mom);
sigma = -0.000818906 + -0.00639409/mom + 0.00162316/mom/mom + 0.00781553/sqrt(mom);
}
else if(run<250593&&striptofw>255&&charge==1&&(zed>=60&&zed<75))
{
if(mom<1.0) mean = 0.0254615 + 0.0314769/mom + -0.00426499/mom/mom + -0.0526869/sqrt(mom);
else if(mom>=1.0) mean = -0.00250221 + -0.0123778/mom + 0.00341901/mom/mom + 0.0114449/sqrt(mom);
sigma = 0.001134 + -0.00178234/mom + 0.00079769/mom/mom + 0.00214561/sqrt(mom);
}
else
{
cout<<"significant issue in caltofwsdphi"<<endl;
return -9999;
}
value = (tofwdphi - mean)/sigma;
return value;
}
float tunetofwsdz(int run, int charge, float mom, float cent, float tofwsdz)
{
float mean = -9999;
float sigma = -9999;
float value = -9999;
if(run>250484&&charge==-1)
{
mean = -0.00565153 + -0.0170638/mom + 0.00335309/mom/mom + 0.0166101/sqrt(mom);
sigma = 0.916739 + -0.0706207/mom + 0.0111088/mom/mom + 0.125801/sqrt(mom);
}
if(run<250593&&charge==-1)
{
mean = -0.016311 + -0.0278699/mom + 0.00352864/mom/mom + 0.0386405/sqrt(mom);
sigma = 0.83138 + -0.212727/mom + 0.0294335/mom/mom + 0.333165/sqrt(mom);
}
if(run>250484&&charge==1)
{
mean = 0.00968331 + 0.00842975/mom + -4.97472e-05/mom/mom + -0.0219147/sqrt(mom);
sigma = 0.764554 + -0.331884/mom + 0.0388235/mom/mom + 0.527434/sqrt(mom);
}
if(run<250593&&charge==1)
{
mean = -0.0141964 + -0.0222397/mom + 0.00321578/mom/mom + 0.0302044/sqrt(mom);
sigma = 0.797409 + -0.250537/mom + 0.0278151/mom/mom + 0.42065/sqrt(mom);
}
if(run>250484&&charge==-1)
{
mean += -0.209883 + -1.27492/cent + 0.447868/cent/cent + 1.22479/sqrt(cent);
sigma *= 0.931064 + 0.00213625*cent;
}
if(run<250593&&charge==-1)
{
mean += -0.183573 + -1.06332/cent + 0.358501/cent/cent + 1.05742/sqrt(cent);
sigma *= 0.935782 + 0.0020964*cent;
}
if(run>250484&&charge==1)
{
mean += -0.204872 + -1.21461/cent + 0.414129/cent/cent + 1.18977/sqrt(cent);
sigma *= 0.928696 + 0.00229116*cent;
}
if(run<250593&&charge==1)
{
mean += -0.184366 + -1.07374/cent + 0.364514/cent/cent + 1.05733/sqrt(cent);
sigma *= 0.930854 + 0.00224951*cent;
}
value = (tofwsdz - mean)/sigma;
return value;
}
float tunetofwsdphi(int run, int charge, float mom, float cent, float tofwsdphi)
{
float mean = -9999;
float sigma = -9999;
float value = -9999;
if(run>250484&&charge==-1)
{
mean = 0.175144 + 0.550273/mom + -0.0999333/mom/mom + -0.606328/sqrt(mom);
sigma = 0.513865 + -0.90656/mom + 0.133787/mom/mom + 1.2629/sqrt(mom);
}
if(run<250593&&charge==-1)
{
mean = -0.578024 + -1.29717/mom + 0.184724/mom/mom + 1.72076/sqrt(mom);
sigma = 0.813399 + -0.15248/mom + 0.00753161/mom/mom + 0.34745/sqrt(mom);
}
if(run>250484&&charge==1)
{
mean = -0.385368 + -0.970492/mom + 0.143773/mom/mom + 1.23642/sqrt(mom);
sigma = 0.814729 + -0.132461/mom + 0.00318168/mom/mom + 0.318003/sqrt(mom);
}
if(run<250593&&charge==1)
{
mean = 0.100131 + 0.474586/mom + -0.0924466/mom/mom + -0.466119/sqrt(mom);
sigma = 0.410412 + -1.05308/mom + 0.150811/mom/mom + 1.48642/sqrt(mom);
}
if(run>250484&&charge==-1)
{
mean += 0.00590256;
sigma *= 0.999172;
}
if(run<250593&&charge==-1)
{
mean += -0.00945991;
sigma *= 1.00515;
}
if(run>250484&&charge==1)
{
mean += -0.00929133;
sigma *= 1.00342;
}
if(run<250593&&charge==1)
{
mean += 0.00588407;
sigma *= 0.999539;
}
value = (tofwsdphi - mean)/sigma;
return value;
}
float isPion(float x, float m2tofw)
{
if(x<0.2) return -9999;
float mean = mpion*mpion;
float p0 = -5.20841e-02;
float p1 = 4.62591e-03;
float p2 = -6.07273e-04;
float p3 = 6.15347e-02;
float p4 = -1.03104e-01;
float sigma = p0+p1/x+p2/x/x+p3*exp(sqrt(x))+p4*sqrt(x);
return (m2tofw - mean)/sigma;
}
float isKaon(float x, float m2tofw)
{
if(x<0.3) return -9999;
float mean = mkaon*mkaon;
float p0 = 1.10981e-01;
float p1 = -6.74987e-02;
float p2 = 1.31111e-02;
float p3 = 1.03992e-01;
float p4 = -3.17107e-01;
float sigma = p0+p1/x+p2/x/x+p3*exp(sqrt(x))+p4*sqrt(x);
return (m2tofw - mean)/sigma;
}
float isProton(float x, float m2tofw)
{
if(x<0.4) return -9999;
float mean = mproton*mproton;
float p0 = 1.50217e-01;
float p1 = -1.13316e-01;
float p2 = 3.67417e-02;
float p3 = 1.06479e-01;
float p4 = -3.26890e-01;
float sigma = p0+p1/x+p2/x/x+p3*exp(sqrt(x))+p4*sqrt(x);
return (m2tofw - mean)/sigma;
}
bool GoodPC1(float ppc1z, float ppc1phi)
{
float zed = ppc1z;
float phi = ppc1phi;
if(zed>0&&zed<13&&phi>0.9&&phi<0.95) return false;
if(zed>61&&zed<65&&phi>0.9&&phi<0.95) return false;
if(zed>-55&&zed<-48&&phi>0.81&&phi<0.88) return false;
if(zed>-70&&zed<-57&&phi>0.78&&phi<0.83) return false;
if(zed>-30&&zed<-18&&phi>0.55&&phi<0.6) return false;
if(zed>-30&&zed<-18&&phi>0.35&&phi<0.45) return false;
if(zed>-3&&zed<0&&phi>0.4&&phi<0.45) return false;
if(zed>70&&zed<82&&phi>0.35&&phi<0.45) return false;
if(zed>28&&zed<41&&phi>0.16&&phi<0.2) return false;
if(zed>-52&&zed<-39&&phi>0.12&&phi<0.16) return false;
//if(zed>0&&zed<11&&phi>-0.26&&phi<-0.22) return false;
if(zed>0&&zed<8&&phi>-0.27&&phi<-0.22) return false;
if(zed>-30&&zed<-18&&phi>-0.4&&phi<-0.35) return false;
// These holes are probably DC holes since they don't appear on a pc1phi vs pc1z plot
// But it seems you can cut on these holes using the PC1 anyway
//if(zed<0&&phi<-0.075&&phi>-0.095) return false; // modified
if(zed<0&&phi<-0.065&&phi>-0.105) return false; // modified
if(zed>49&&zed<60&&phi>0.008&&phi<0.05) return false;
if(zed>-71&&zed<-59&&phi>0.398&&phi<0.44) return false;
return true;
}
bool GoodPC2(float pc2z, float pc2phi)
{
float zed = pc2z;
float phi = pc2phi;
//if(zed>-70&&zed<-50&&phi>0.51&&phi<0.55) return false; // modified
//if(zed>-25&&zed<0&&phi>0.46&&phi<0.516) return false; // modified
//if(zed>20&&zed<42&&phi>0.46&&phi<0.516) return false; // modified
//if(zed>-70&&zed<-50&&phi>0.4&&phi<0.44) return false; // modified
//if(zed>73&&zed<94&&phi>-0.076&&phi<0.02) return false; // modified
if(zed>-73&&zed<-53&&phi>0.508&&phi<0.552) return false;
if(zed>-23&&zed<0&&phi>0.472&&phi<0.520) return false;
if(zed>22&&zed<41&&phi>0.472&&phi<0.520) return false;
if(zed>-100&&zed<-87&&phi>0.370&&phi<0.438) return false;
if(zed>-73&&zed<-53&&phi>0.370&&phi<0.438) return false;
if(zed>61&&zed<72&&phi>0.370&&phi<0.438) return false;
if(zed>73&&zed<93&&phi>-0.076&&phi<-0.022) return false;
if(zed>81&&zed<93&&phi>-0.022&&phi<0.012) return false;
if(zed>81&&zed<93&&phi>-0.150&&phi<-0.076) return false;
if(zed>-85&&zed<-70&&phi>-0.060&&phi<-0.018) return false;
// holes in simulation that don't exist in real data
if(zed>-74&&zed<-52&&phi>-0.080&&phi<-0.030) return false;
if(zed>71&&zed<90&&phi>0.032&&phi<0.070) return false;
return true;
}
bool GoodPC3(float pc3z, float pc3phi)
{
// --- these are the pc3 fiducial cuts, similar to the old
// --- this is a pc3 fiducial map of the whole west arm
float zed = pc3z;
float phi = pc3phi;
//if(zed>-125&&zed<-90&&phi>0.45&&phi<0.5) return false;
//if(zed>63&&zed<90&&phi>0.45&&phi<0.52) return false; // modified
//if(zed>-105&&zed<-80&&phi>0.4&&phi<0.45) return false;
//if(zed>-65&&zed<0&&phi>0.4&&phi<0.45) return false;
//if(zed>66&&zed<84&&phi>0.04&&phi<0.1) return false;
//if(zed>-86&&zed<-73&&phi>0&&phi<0.1) return false; // modified
//if(zed>-86&&zed<-60&&phi>0.038&&phi<0.1) return false; // modified
//if(zed>85&&zed<115&&phi>-0.02&&phi<0.01) return false;
//if(zed>-126&&zed<-100&&phi>0.476&&phi<0.508) return false;
if(zed>-126&&zed<-90&&phi>0.470&&phi<0.512) return false;
if(zed>62&&zed<88&&phi>0.472&&phi<0.516) return false;
if(zed>-104&&zed<-84&&phi>0.370&&phi<0.444) return false;
if(zed>-64&&zed<0&&phi>0.370&&phi<0.444) return false;
if(zed>67&&zed<80&&phi>0.040&&phi<0.100) return false;
if(zed>-86&&zed<-74&&phi>0.006&&phi<0.100) return false;
if(zed>-86&&zed<-61&&phi>0.036&&phi<0.100) return false;
if(zed>84&&zed<112&&phi>-0.034&&phi<0.012) return false;
if(zed>148&&zed<154&&phi>0.014&&phi<0.048) return false;
if(zed>155&&zed<161&&phi>-0.100&&phi<-0.076) return false;
if(zed>14&&zed<28&&phi>0.488&&phi<0.508) return false;
//if(zed>94&&zed<105&&phi>0.492&&phi<0.506) return false;
if(zed>94&&zed<105&&phi>0.476&&phi<0.510) return false;
if(zed>-45&&zed<-30&&phi>0.498&&phi<0.600) return false;
return true;
}
bool GoodEdgeDCH(int run, float zed, float alpha, float phi)
{
float slope = 1.72; // 1.72 is latest and greatest, Monday 10/25/1010
float sline = 25.0;
float slire = 8.1;
// === W1 === //
if(alpha<slope*phi-slope*-0.200 && alpha>slope*phi-slope*-0.103) return false; // w1 below box
if(alpha<slope*phi-slope*-0.021 && alpha>slope*phi-slope*-0.014) return false; // w1 center of box
if(alpha<slope*phi-slope*0.060 && alpha>slope*phi-slope*0.200) return false; // w1 above box
// both w1 wires are much less pronounced than w2
//if(alpha<slire*phi-slire*-0.191 && alpha>slire*phi-slire*-0.188) return false; // w1 wire // not straight
//if(alpha<slire*phi-slire*0.006 && alpha>slire*phi-slire*0.009) return false; // w1 wire // leaving out for now
// === W2 === //
if(alpha<slope*phi-slope*0.300 && alpha>slope*phi-slope*0.415) return false; // w2 below box
if(alpha<slope*phi-slope*0.494 && alpha>slope*phi-slope*0.501) return false; // w2 center of box
if(alpha<slope*phi-slope*0.577 && alpha>slope*phi-slope*0.700) return false; // w2 above box
if(alpha<slire*phi-slire*0.397 && alpha>slire*phi-slire*0.400) return false; // w2 wire, low
if(alpha<slire*phi-slire*0.543 && alpha>slire*phi-slire*0.547) return false; // w2 wire, middle
if(alpha<slire*phi-slire*0.593 && alpha>slire*phi-slire*0.596) return false; // w2 wire, high
return true;
}
bool GoodInnerDCH(int run, float zed, float alpha, float phi)
{
float slope = 1.72; // 1.72 is latest and greatest, Monday 10/25/1010
float sline = 25.0;
float slire = 8.1;
// large stripe covering far upper alpha of w1 and far lower alpha of w2
if(alpha<22.0*phi-22.0*0.175 && alpha>22.0*phi-22.0*0.276) return false; // checked
if(zed>0)
{
// === W1 === //
// left-most corner
if(phi<-0.373) return false; // checked
// small stripe, lower alpha, lower phi
if(alpha>23.7666*phi-23.7666*-0.225933 && alpha<14.5819*phi-14.5819*-0.227896) return false; // checked
// parellel hole with negative slope for upper alpha, higher phi
if(alpha<-14.8469*phi+14.8469*0.199158 && alpha>-13.1329*phi+13.1329*0.181353) return false; // checked
// patchy region, upper alpha
if(alpha>22.3703*phi-22.3703*0.118409 && alpha>-21.3095*phi+21.3095*0.0383544 && alpha>0) return false; // checked // preferred for now
//if(alpha<-14.8469*phi+14.8469*0.199158 && alpha>-21.3095*phi+21.3095*0.0383544 && alpha>0) return false; // checked alternative
//if(alpha>22.3703*phi-22.3703*0.118409 && alpha<50.7591*phi-50.7591*0.0413847 && alpha>0) return false; // checked // alternative
//if(alpha<-14.8469*phi+14.8469*0.199158 && alpha<50.7591*phi-50.7591*0.0413847 && alpha>0) return false; // checked // alternative
// === W2 === //
// triangular hole, lower alpha
if(alpha<26.4147*phi-26.4147*0.393654 && alpha<-23.0095*phi+23.0095*0.435974) return false; // checked
}
if(zed<0)
{
// === W1 === //
// triangular hole for lower alpha, higher phi
if(alpha<25.5628*phi-25.5628*-0.115491 && alpha<-19.9631*phi+19.9631*-0.092522) return false; // checked
// triangular hole for lower alpha, lower phi
//if(alpha<-17.3768*phi+17.3768*-0.191001 && alpha<18.8489*phi-18.8489*-0.200406) return false; // checked
// triangular hole for lower alpha, lower phi, right side
if(alpha<-17.3768*phi+17.3768*-0.191001 && alpha>-14.9259*phi+14.9259*-0.213603) return false; // a // checked
// triangular hole for lower alpha, lower phi, left side
if(alpha<18.8489*phi-18.8489*-0.205 && alpha>22.1084*phi-22.1084*-0.197) return false; // b // checked
// parellel hole with negative slope for upper alpha, higher phi
if(alpha<-14.8469*phi+14.8469*0.199158 && alpha>-13.1329*phi+13.1329*0.181353) return false; // checked
// patchy region, upper alpha
if(alpha>22.3703*phi-22.3703*0.118409 && alpha>-21.3095*phi+21.3095*0.0383544 && alpha>0) return false; // checked // preferred for now
//if(alpha<-14.8469*phi+14.8469*0.199158 && alpha>-21.3095*phi+21.3095*0.0383544 && alpha>0) return false; // checked alternative
//if(alpha>22.3703*phi-22.3703*0.118409 && alpha<50.7591*phi-50.7591*0.0413847 && alpha>0) return false; // checked // alternative
//if(alpha<-14.8469*phi+14.8469*0.199158 && alpha<50.7591*phi-50.7591*0.0413847 && alpha>0) return false; // checked // alternative
// === W2 === //
// small stripe, upper alpha, higher phi
if(alpha<22.0*phi-22.0*0.725 && alpha>22.0*phi-22.0*0.745) return false; // checked
// inverted triangular shape, upper alpha, lower phi
if(alpha>13.7928*phi-13.7928*0.666602 && alpha>-48.9766*phi+48.9766*0.653529) return false; // checked
}
return true;
}
bool GoodDCH(int run, float zed, float alpha, float phi)
{
return true; // disabling this function for now
float slope = 1.72; // 1.72 is latest and greatest, Monday 10/25/1010
float sline = 25.0;
float slire = 8.1;
//if(zed>0) return false; // look at south only
//if(zed<0) return false; // look at north only
//if(alpha<slope*phi-slope*-0.021 && alpha>slope*phi-slope*0.200 && alpha > 0.00) return false; // pos alpha, w1, worst section // temp out
//return true; // temp testing
if(zed>0)
{
// === W1 === //
if(alpha<slope*phi-slope*-0.200 && alpha>slope*phi-slope*-0.103) return false; // w1 below box
if(alpha<slope*phi-slope*-0.021 && alpha>slope*phi-slope*-0.014) return false; // w1 center of box
if(alpha<slope*phi-slope*0.060 && alpha>slope*phi-slope*0.200) return false; // w1 above box
if(alpha<slire*phi-slire*0.006 && alpha>slire*phi-slire*0.009) return false; // w1 wire, only one
// straight
//if(alpha<slope*phi-slope*-0.021 && phi<-0.083) return false; // NEW
//if(alpha>slope*phi-slope*-0.014 && phi>0.064) return false; // NEW
//if(alpha>slope*phi-slope*-0.014 && phi>0.047 && phi<0.054) return false; // NEW // removing corner cuts now
if(phi>-0.223&&phi<-0.184) return false; // NEW // removing corner cuts now
if(phi>-0.105&&phi<-0.089) return false; // widened // temp out
if(phi>-0.058&&phi<-0.052) return false;
if(phi>-0.039&&phi<-0.032) return false;
if(phi>-0.021&&phi<-0.013) return false;
if(phi>0.020&&phi<0.026) return false;
if(phi>0.145&&phi<0.200) return false; // new
// === W2 === //
if(alpha<slope*phi-slope*0.300 && alpha>slope*phi-slope*0.415) return false; // w2 below box
if(alpha<slope*phi-slope*0.494 && alpha>slope*phi-slope*0.501) return false; // w2 center of box
if(alpha<slope*phi-slope*0.577 && alpha>slope*phi-slope*0.700) return false; // w2 above box
if(alpha<slire*phi-slire*0.397 && alpha>slire*phi-slire*0.400) return false; // w2 wire, low
if(alpha<slire*phi-slire*0.543 && alpha>slire*phi-slire*0.547) return false; // w2 wire, middle
if(alpha<slire*phi-slire*0.593 && alpha>slire*phi-slire*0.596) return false; // w2 wire, high
// temp out
//if(alpha>slope*phi-slope*0.501&&phi>0.428&&phi<0.438) return false; // 2 // widened // above
//if(alpha>slope*phi-slope*0.501&&phi>0.469&&phi<0.475) return false; // 3 above
//if(alpha>slope*phi-slope*0.501&&phi>0.516&&phi<0.524) return false; // new // north only
//if(alpha<slope*phi-slope*0.494&&phi>0.382&&phi<0.428) return false; // new below
//if(alpha<slope*phi-slope*0.494&&phi>0.526&&phi<0.533) return false; // 6 below
////if(phi>0.635&&phi<0.700) return false; // cut the corner // no more corner cutting...
}
if(zed<0)
{
// === W1 === //
//if(alpha < 7.14*phi-7.14*-0.186 && alpha < -16.00*phi+16.00*-0.190 && alpha < 0) return false; // low, south only
if(alpha < 7.14*phi-7.14*-0.105 && alpha < -16.00*phi+16.00*-0.095 && alpha < 0) return false; // low, south only
if(alpha<slope*phi-slope*-0.200 && alpha>slope*phi-slope*-0.105) return false; // w1 below box
if(alpha<slope*phi-slope*-0.021 && alpha>slope*phi-slope*-0.014) return false; // w1 center of box
if(alpha<slope*phi-slope*0.060 && alpha>slope*phi-slope*0.200) return false; // w1 above box
if(alpha<slire*phi-slire*0.006 && alpha>slire*phi-slire*0.009) return false; // w1 wire, only one
//if(alpha<slope*phi-slope*-0.021 && phi<-0.083) return false; // NEW
//if(alpha>slope*phi-slope*-0.014 && phi>0.044) return false; // NEW
// straight
if(phi>-0.225&&phi<-0.200) return false; // not present in north
if(phi>-0.118&&phi<-0.089) return false; // wider than poszed // widened // temp out
if(phi>-0.058&&phi<-0.052) return false;
if(phi>-0.039&&phi<-0.032) return false; // not needed in south
if(phi>-0.021&&phi<-0.013) return false;
if(phi>0.020&&phi<0.026) return false;
if(phi>0.145&&phi<0.200) return false; // new
// === W2 === //
if(alpha<slope*phi-slope*0.300 && alpha>slope*phi-slope*0.415) return false; // w2 below box
if(alpha<slope*phi-slope*0.494 && alpha>slope*phi-slope*0.501) return false; // w2 center of box
if(alpha<slope*phi-slope*0.577 && alpha>slope*phi-slope*0.700) return false; // w2 above box
if(alpha<slire*phi-slire*0.397 && alpha>slire*phi-slire*0.400) return false; // w2 wire, low
if(alpha<slire*phi-slire*0.543 && alpha>slire*phi-slire*0.547) return false; // w2 wire, middle
if(alpha<slire*phi-slire*0.593 && alpha>slire*phi-slire*0.596) return false; // w2 wire, high
// temp out
//if(alpha>slope*phi-slope*0.501&&phi>0.428&&phi<0.438) return false; // 2 // widened // above
//if(alpha>slope*phi-slope*0.501&&phi>0.469&&phi<0.475) return false; // 3 above
//if(alpha>slope*phi-slope*0.501&&phi>0.516&&phi<0.524) return false; // new // north only
//if(alpha<slope*phi-slope*0.494&&phi>0.382&&phi<0.428) return false; // new below
//if(alpha<slope*phi-slope*0.494&&phi>0.526&&phi<0.533) return false; // 6 below
////if(phi>0.635&&phi<0.700) return false; // cut the corner // no more corner cutting
}
return true;
}
| [
"belmonrj@gmail.com"
] | belmonrj@gmail.com |
295544e68144392083b7baabc34d3aa01c2f0a4c | fe4cc9cda77fe27fd8fa7d11fe57a42f01362ef0 | /CodeChef/GOODPROB.cpp | fc831da1787d892c90e9e8dfe6a80d570692a094 | [] | no_license | mysterious-29/cp | 3c3c05ab4d0be985c13bf61dfc8d1f20282e8b5a | f9a5689a142122cc97d56007be3499a3a597c104 | refs/heads/master | 2021-04-26T23:41:43.277538 | 2018-10-01T19:44:05 | 2018-10-01T19:44:05 | 72,021,257 | 0 | 3 | null | 2016-10-28T06:29:23 | 2016-10-26T16:14:14 | C++ | UTF-8 | C++ | false | false | 611 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
int main(){
int n, i, j, x;
scanf("%d", &n);
int arr[n], temp1, temp2, temp3;
long long int ans;
vector<int> maxs[n];
ans = 0;
for(i = 0; i < n; i++){
scanf("%d", &x);
arr[i] = x;
for(j = 0; j < i; j++){
if(maxs[j][i - j - 1] > x)
maxs[j].push_back(maxs[j][i - j - 1]);
else
maxs[j].push_back(x);
temp1 = arr[i];
temp2 = arr[j];
temp3 = temp1&temp2;
if(temp3 == temp1 || temp3 == temp2){
ans += maxs[j][i - j];
}
}
maxs[j].push_back(x);
}
printf("%lld\n", ans);
return 0;
} | [
"saurabh.k0402@gmail.com"
] | saurabh.k0402@gmail.com |
5eba1d91f14d9102de803bb9ece6091680a0fb07 | dd30cfdbae5e919d94a3b2c0a2172043971fe2bb | /C++/Strategy/DuckSimulator/client/Duck.cpp | 85e726da5ab9d8c4e95e789a53d12bfe001702c1 | [] | no_license | mustafaelghrib/DesignPatterns | fb19a03b2a537098220f9b95eb2d427a074b9bf5 | b24f081df3e4dca0c56fce4dbc1322d9ceae6298 | refs/heads/main | 2023-07-09T01:06:30.994918 | 2020-12-15T12:57:56 | 2020-12-15T12:57:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include "../behavior/FlyBehavior.cpp"
#include "../behavior/QuackBehavior.cpp"
#include "iostream"
#include <string>
#include <utility>
using namespace std;
class FlyBehavior;
class QuackBehavior;
class Duck {
public:
explicit Duck(string duckName) : duckName(move(duckName)) {}
void display() { cout << "I am a " << duckName << endl; }
void swim() { cout << duckName << " is swimming" << endl; }
void performFly() { flyBehavior->fly(); }
void performQuack() { quackBehavior->quack(); }
protected:
FlyBehavior *flyBehavior{};
QuackBehavior *quackBehavior{};
private:
string duckName;
}; | [
"mustafaabdo468@gmail.com"
] | mustafaabdo468@gmail.com |
49a70a9669d8db4e111a167b48cc727e5c195e4f | d2788ebe40c2a265bdb3bb02bc4c5bb7a0da9c3d | /libraries/chain/include/VACio/chain/contract_table_objects.hpp | 22c25f48e2f3fc3de79e338c45d4954497665e13 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | vaccoin/vac | b68df3dac0841990ee7b8947584253974c0b926c | 146ba68ab94e249416e644d3df39715b948c948c | refs/heads/master | 2020-03-23T21:34:29.456786 | 2018-07-24T05:05:40 | 2018-07-24T06:38:31 | 142,096,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,460 | hpp | /**
* @file
* @copyright defined in VAC/LICENSE.txt
*/
#pragma once
#include <VACio/chain/contract_types.hpp>
#include <VACio/chain/multi_index_includes.hpp>
#include <softfloat.hpp>
#include <chainbase/chainbase.hpp>
#include <array>
#include <type_traits>
namespace VACio { namespace chain {
/**
* @brief The table_id_object class tracks the mapping of (scope, code, table) to an opaque identifier
*/
class table_id_object : public chainbase::object<table_id_object_type, table_id_object> {
OBJECT_CTOR(table_id_object)
id_type id;
account_name code;
scope_name scope;
table_name table;
account_name payer;
uint32_t count = 0; /// the number of elements in the table
};
struct by_code_scope_table;
using table_id_multi_index = chainbase::shared_multi_index_container<
table_id_object,
indexed_by<
ordered_unique<tag<by_id>,
member<table_id_object, table_id_object::id_type, &table_id_object::id>
>,
ordered_unique<tag<by_code_scope_table>,
composite_key< table_id_object,
member<table_id_object, account_name, &table_id_object::code>,
member<table_id_object, scope_name, &table_id_object::scope>,
member<table_id_object, table_name, &table_id_object::table>
>
>
>
>;
using table_id = table_id_object::id_type;
struct by_scope_primary;
struct by_scope_secondary;
struct by_scope_tertiary;
struct key_value_object : public chainbase::object<key_value_object_type, key_value_object> {
OBJECT_CTOR(key_value_object, (value))
typedef uint64_t key_type;
static const int number_of_keys = 1;
id_type id;
table_id t_id;
uint64_t primary_key;
account_name payer = 0;
shared_string value;
};
using key_value_index = chainbase::shared_multi_index_container<
key_value_object,
indexed_by<
ordered_unique<tag<by_id>, member<key_value_object, key_value_object::id_type, &key_value_object::id>>,
ordered_unique<tag<by_scope_primary>,
composite_key< key_value_object,
member<key_value_object, table_id, &key_value_object::t_id>,
member<key_value_object, uint64_t, &key_value_object::primary_key>
>,
composite_key_compare< std::less<table_id>, std::less<uint64_t> >
>
>
>;
struct by_primary;
struct by_secondary;
template<typename SecondaryKey, uint64_t ObjectTypeId, typename SecondaryKeyLess = std::less<SecondaryKey> >
struct secondary_index
{
struct index_object : public chainbase::object<ObjectTypeId,index_object> {
OBJECT_CTOR(index_object)
typedef SecondaryKey secondary_key_type;
typename chainbase::object<ObjectTypeId,index_object>::id_type id;
table_id t_id;
uint64_t primary_key;
account_name payer = 0;
SecondaryKey secondary_key;
};
typedef chainbase::shared_multi_index_container<
index_object,
indexed_by<
ordered_unique<tag<by_id>, member<index_object, typename index_object::id_type, &index_object::id>>,
ordered_unique<tag<by_primary>,
composite_key< index_object,
member<index_object, table_id, &index_object::t_id>,
member<index_object, uint64_t, &index_object::primary_key>
>,
composite_key_compare< std::less<table_id>, std::less<uint64_t> >
>,
ordered_unique<tag<by_secondary>,
composite_key< index_object,
member<index_object, table_id, &index_object::t_id>,
member<index_object, SecondaryKey, &index_object::secondary_key>,
member<index_object, uint64_t, &index_object::primary_key>
>,
composite_key_compare< std::less<table_id>, SecondaryKeyLess, std::less<uint64_t> >
>
>
> index_index;
};
typedef secondary_index<uint64_t,index64_object_type>::index_object index64_object;
typedef secondary_index<uint64_t,index64_object_type>::index_index index64_index;
typedef secondary_index<uint128_t,index128_object_type>::index_object index128_object;
typedef secondary_index<uint128_t,index128_object_type>::index_index index128_index;
typedef std::array<uint128_t, 2> key256_t;
typedef secondary_index<key256_t,index256_object_type>::index_object index256_object;
typedef secondary_index<key256_t,index256_object_type>::index_index index256_index;
struct soft_double_less {
bool operator()( const float64_t& lhs, const float64_t& rhs )const {
return f64_lt(lhs, rhs);
}
};
struct soft_long_double_less {
bool operator()( const float128_t lhs, const float128_t& rhs )const {
return f128_lt(lhs, rhs);
}
};
/**
* This index supports a deterministic software implementation of double as the secondary key.
*
* The software double implementation is using the Berkeley softfloat library (release 3).
*/
typedef secondary_index<float64_t,index_double_object_type,soft_double_less>::index_object index_double_object;
typedef secondary_index<float64_t,index_double_object_type,soft_double_less>::index_index index_double_index;
/**
* This index supports a deterministic software implementation of long double as the secondary key.
*
* The software long double implementation is using the Berkeley softfloat library (release 3).
*/
typedef secondary_index<float128_t,index_long_double_object_type,soft_long_double_less>::index_object index_long_double_object;
typedef secondary_index<float128_t,index_long_double_object_type,soft_long_double_less>::index_index index_long_double_index;
namespace config {
template<>
struct billable_size<table_id_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 2; ///< overhead for 2x indices internal-key and code,scope,table
static const uint64_t value = 44 + overhead; ///< 36 bytes for constant size fields + overhead
};
template<>
struct billable_size<key_value_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 2; ///< overhead for potentially single-row table, 2x indices internal-key and primary key
static const uint64_t value = 32 + 8 + 4 + overhead; ///< 32 bytes for our constant size fields, 8 for pointer to vector data, 4 bytes for a size of vector + overhead
};
template<>
struct billable_size<index64_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 3; ///< overhead for potentially single-row table, 3x indices internal-key, primary key and primary+secondary key
static const uint64_t value = 24 + 8 + overhead; ///< 24 bytes for fixed fields + 8 bytes key + overhead
};
template<>
struct billable_size<index128_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 3; ///< overhead for potentially single-row table, 3x indices internal-key, primary key and primary+secondary key
static const uint64_t value = 24 + 16 + overhead; ///< 24 bytes for fixed fields + 16 bytes key + overhead
};
template<>
struct billable_size<index256_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 3; ///< overhead for potentially single-row table, 3x indices internal-key, primary key and primary+secondary key
static const uint64_t value = 24 + 32 + overhead; ///< 24 bytes for fixed fields + 32 bytes key + overhead
};
template<>
struct billable_size<index_double_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 3; ///< overhead for potentially single-row table, 3x indices internal-key, primary key and primary+secondary key
static const uint64_t value = 24 + 8 + overhead; ///< 24 bytes for fixed fields + 8 bytes key + overhead
};
template<>
struct billable_size<index_long_double_object> {
static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 3; ///< overhead for potentially single-row table, 3x indices internal-key, primary key and primary+secondary key
static const uint64_t value = 24 + 16 + overhead; ///< 24 bytes for fixed fields + 16 bytes key + overhead
};
} // namespace config
} } // namespace VACio::chain
CHAINBASE_SET_INDEX_TYPE(VACio::chain::table_id_object, VACio::chain::table_id_multi_index)
CHAINBASE_SET_INDEX_TYPE(VACio::chain::key_value_object, VACio::chain::key_value_index)
CHAINBASE_SET_INDEX_TYPE(VACio::chain::index64_object, VACio::chain::index64_index)
CHAINBASE_SET_INDEX_TYPE(VACio::chain::index128_object, VACio::chain::index128_index)
CHAINBASE_SET_INDEX_TYPE(VACio::chain::index256_object, VACio::chain::index256_index)
CHAINBASE_SET_INDEX_TYPE(VACio::chain::index_double_object, VACio::chain::index_double_index)
CHAINBASE_SET_INDEX_TYPE(VACio::chain::index_long_double_object, VACio::chain::index_long_double_index)
FC_REFLECT(VACio::chain::table_id_object, (id)(code)(scope)(table) )
FC_REFLECT(VACio::chain::key_value_object, (id)(t_id)(primary_key)(value)(payer) )
| [
"vaccoin@mail.com"
] | vaccoin@mail.com |
77be593356607ccdf2343b5b2930ebe405bf00e1 | 9dc6cb93169af80ffc1e055eaea2a7cbd2b139ec | /o2engine_render_debug/src/util/image/image.cpp | e311634ec379c5ffedd7e5af3edb4e8ec632b2c0 | [] | no_license | zenkovich/anphys-engine-svn | 2b745f8341f1cebde1863404e8cc55a0eaeb4c91 | 4fac80c014a0e0c39e1f0d821be1a062c626499c | refs/heads/master | 2020-06-09T16:58:33.065922 | 2015-01-15T17:37:05 | 2015-01-15T17:37:05 | 53,565,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,853 | cpp | #include "image.h"
#include "png_image_format.h"
#include "util\log.h"
OPEN_O2_NAMESPACE
cImage::cImage():
mFormat(FMT_NONE), mData(NULL)
{
}
cImage::cImage( Format format, const vec2i& size ):
mFormat(format), mSize(size)
{
create(format, size);
}
cImage::~cImage()
{
safe_release_arr(mData);
}
void cImage::create( Format format, const vec2i& size )
{
if (mData)
safe_release_arr(mData);
short bpp[] = { 0, 4 };
mFormat = format;
mSize = size;
mData = mnew unsigned char[ size.x*size.y*bpp[format] ];
}
bool cImage::load( const string& fileName, ImageType type, shared(cLogStream) clog /*= NULL*/ )
{
shared(cLogStream) log = clog ? clog:gLog;
mFilename = fileName;
if (type == IT_PNG)
return loadPngImage(fileName, this, true, log);
else
{
if (loadPngImage(fileName, this, false, log))
return true;
log->error("Can't load image '%s': unknown format", fileName.c_str());
}
mFilename = "";
return false;
}
bool cImage::save( const string& fileName, ImageType type, shared(cLogStream) clog /*= NULL*/ ) const
{
shared(cLogStream) log = clog ? clog:gLog;
if (type == IT_PNG || type == IT_AUTO)
{
return savePngImage(fileName, this, log);
}
log->error("Can't save image to '%s': unknown format specified", fileName.c_str());
return false;
}
void cImage::clear( const color4& color )
{
short bpp[] = { 0, 4 };
memset(mData, color.ARGB(), bpp[mFormat]*mSize.x*mSize.y);
}
unsigned char* cImage::getData()
{
return mData;
}
vec2i cImage::getSize() const
{
return mSize;
}
cImage::Format cImage::getFormat() const
{
return mFormat;
}
const unsigned char* cImage::getDataConst() const
{
return mData;
}
const string& cImage::getFilename() const
{
return mFilename;
}
CLOSE_O2_NAMESPACE | [
"zenkovichan@gmail.com"
] | zenkovichan@gmail.com |
9fbb68262a02e51929b23b0815e408b8fe24947d | 8153de6526a9ac2880f200ebe4ccab2a2aee5b89 | /VoxelEngine/Classes/ScaleTo.cpp | 4d13a818fc8aea9d857abd67fa5dfa350272254b | [] | no_license | bsy6766/VoxelEngine | b0ca9d849f935d2688dda461b24bfd1e2404ce88 | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | refs/heads/master | 2023-02-20T01:10:44.053563 | 2021-01-21T08:36:56 | 2021-01-21T08:36:56 | 215,790,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | cpp | #include "ScaleTo.h"
// voxel
#include "TransformNode.h"
Voxel::UI::ScaleTo::ScaleTo()
: Action()
, scale(0.0f)
, target(nullptr)
{}
bool Voxel::UI::ScaleTo::init(const float duration, const glm::vec2 & scale)
{
if (duration < 0.0f)
{
return false;
}
this->duration = duration;
this->scale = scale;
return true;
}
Voxel::UI::ScaleTo * Voxel::UI::ScaleTo::create(const float duration, const glm::vec2 & scale)
{
auto newScaleTo = new ScaleTo();
if (newScaleTo->init(duration, scale))
{
return newScaleTo;
}
else
{
delete newScaleTo;
return nullptr;
}
}
void Voxel::UI::ScaleTo::setTarget(TransformNode * target)
{
if (target)
{
this->target = target;
}
}
void Voxel::UI::ScaleTo::update(const float delta)
{
elapsedTime += delta;
if (elapsedTime >= duration)
{
target->setScale(scale);
}
else
{
auto curScale = target->getScale();
target->setScale(curScale + ((scale - curScale) * (delta / (duration - (elapsedTime - delta)))));
}
}
| [
"bsy6766@gmail.com"
] | bsy6766@gmail.com |
44a89aa719809c55592cd1673dd608459c13a1f5 | 56a4cb943d085a672f8b0d08a8c047f772e6a45e | /code/Johnson_Engine/Runtime/server/src/s_client.cpp | d35cc3b305545ff109b285d525d93839b098ec19 | [] | no_license | robertveloso/suddenattack_legacy | 2016fa21640d9a97227337ac8b2513af7b0ce00b | 05ff49cced2ba651c25c18379fed156c58a577d7 | refs/heads/master | 2022-06-20T05:00:10.375695 | 2020-05-08T01:46:02 | 2020-05-08T01:46:02 | 262,199,345 | 3 | 1 | null | null | null | null | UHC | C++ | false | false | 49,668 | cpp | #include "bdefs.h"
#include "s_client.h"
#include "ftserv.h"
#include "servermgr.h"
#include "s_net.h"
#include "dhashtable.h"
#include "sounddata.h"
#include "impl_common.h"
#include "s_object.h"
#include "soundtrack.h"
#include "serverevent.h"
#include "sysstreamsim.h"
#include "iltphysics.h"
#include "Limits.h"
#include "ltmessage_server.h"
#include "netmgr.h"
#include "clienthack.h"
// 광식
//---------------------------------------
#include "animtracker.h"
#ifndef DE_SERVER_COMPILE
#include "clientmgr.h"
#endif // DE_SERVER_COMPILE
//---------------------------------------
#include <queue>
//------------------------------------------------------------------
//------------------------------------------------------------------
// Holders and their headers.
//------------------------------------------------------------------
//------------------------------------------------------------------
//server file mgr.
#include "server_filemgr.h"
static IServerFileMgr *server_filemgr;
define_holder(IServerFileMgr, server_filemgr);
//server console state
#include "server_consolestate.h"
#include "concommand.h"
static IServerConsoleState *console_state;
define_holder(IServerConsoleState, console_state);
//IWorld holder
#include "world_server_bsp.h"
#include "de_mainworld.h"
static IWorldServerBSP *world_bsp_server;
define_holder(IWorldServerBSP, world_bsp_server);
//the ILTServer game interface
#include "iltserver.h"
static ILTServer *ilt_server;
define_holder(ILTServer, ilt_server);
//IServerShell game server shell object.
#include "iservershell.h"
static IServerShell *i_server_shell;
define_holder(IServerShell, i_server_shell);
struct UpdateInfo {
Client *m_pClient;
CPacket_Write m_cPacket;
CPacket_Write m_cUnguaranteed;
uint32 m_nTargetUpdateSize;
uint32 m_nUpdateTime;
};
SentList *g_pCurSentList;
uint32 g_Ticks_ClientVis;
extern int32 g_CV_STracePackets, g_CV_DelimitPackets;
extern int32 g_bForceRemote;
extern int32 g_CV_BandwidthTargetServer;
#ifndef _FINAL
extern uint32 g_CV_TestG;
extern uint32 g_CV_TestUG;
#endif
ILTStream* sm_FTOpenFn(FTServ *hServ, char *pFilename)
{
return server_filemgr->OpenFile(pFilename);
}
void sm_FTCloseFn(FTServ *hServ, ILTStream *pStream)
{
pStream->Release();
}
int sm_FTCantOpenFileFn(FTServ *hServ, char *pFilename)
{
return TODO_REMOVEFILE;
}
//------------------------------------------------------------------
// Client structure implementation
//------------------------------------------------------------------
Client::Client() :
m_Link(LTLink_Init),
m_pClientData(0),
m_ClientDataLen(0),
m_nDesiredReceiveBandwidth(0),
m_AttachmentLink(LTLink_Init),
m_pAttachmentParent(0),
m_ViewPos(0.0f, 0.0f, 0.0f),
m_Attachments(LTLink_Init),
m_hFTServ(0),
m_ObjInfos(0),
m_iPrevSentList(0),
m_pObject(0),
m_pPluginUserData(0),
m_ClientID(0),
m_State(0),
m_PuttingIntoWorldStage(0),
m_ClientFlags(0),
m_Name(0),
m_ConnectionID(0),
m_Events(LTLink_Init),
m_hFileIDTable(0)
{
}
bool Client::Init( CBaseConn *pBaseConn, bool bIsLocal )
{
m_ClientFlags |= CFLAG_WANTALLFILES | CFLAG_SENDGLOBALLIGHT;
m_ClientFlags |= CFLAG_SENDCOBJROTATION;
m_State = CLIENT_WAITINGTOENTERWORLD;
LT_MEM_TRACK_ALLOC(m_Name = (char*)dalloc(1),LT_MEM_TYPE_MISC);
m_Name[0] = 0;
m_AttachmentLink.m_pData = this;
if( bIsLocal )
{
m_ClientFlags |= CFLAG_LOCAL;
g_pServerMgr->m_InternalFlags |= SFLAG_LOCAL;
}
uint32 flags = 0;
if (bIsLocal)
{
flags |= FTSFLAG_LOCAL;
}
FTSInitStruct initStruct;
initStruct.m_OpenFn = sm_FTOpenFn;
initStruct.m_CloseFn = sm_FTCloseFn;
initStruct.m_CantOpenFileFn = sm_FTCantOpenFileFn;
initStruct.m_pNetMgr = &g_pServerMgr->m_NetMgr;
initStruct.m_ConnID = pBaseConn;
m_hFTServ = fts_Init(&initStruct, flags);
LT_MEM_TRACK_ALLOC(m_ObjInfos = (ObjInfo*)dalloc(sizeof(ObjInfo) * g_pServerMgr->m_nObjInfos),LT_MEM_TYPE_OBJECT);
memset(m_ObjInfos, 0, sizeof(ObjInfo)*g_pServerMgr->m_nObjInfos);
m_ConnectionID = pBaseConn;
m_pObject = LTNULL;
// Find a free ID.
m_ClientID = 0;
uint16 testID;
for (testID=0; testID < 30000; testID++)
{
bool bUnique = true;
LTLink *pCur, *pListHead;
pListHead = &g_pServerMgr->m_Clients.m_Head;
for (pCur=pListHead->m_pNext; pCur != pListHead; pCur=pCur->m_pNext)
{
if (((Client*)pCur->m_pData)->m_ClientID == testID)
{
bUnique = false;
break;
}
}
if (bUnique)
{
break;
}
}
m_ClientID = testID;
// Initialize the fileid info list. Some information sent to the client doesn't change based on fileid.
// This is used to reduce the amount of info sent to the client, but just comparing the new info to what
// was sent last. As an example, sound radii is typically the same for one particular file, so the server
// only needs to send this info once. Other info can be added to the FileIDInfo structure as needed.
m_hFileIDTable = hs_CreateHashTable(500, HASH_2BYTENUMBER);
// Add us to the list of clients.
dl_AddHead(&g_pServerMgr->m_Clients, &m_Link, this);
// Tell the server shell they're in.
i_server_shell->OnAddClient((HCLIENT)this);
// Don't let them send anything yet..
pBaseConn->SetBandwidth(0);
//[MURSUM]
/*
// MUST BE FIRST. Send them the protocol version.
cPacket.Writeuint8(SMSG_NETPROTOCOLVERSION);
cPacket.Writeuint32(LT_NET_PROTOCOL_VERSION);
cPacket.Writeuint32(g_CV_BandwidthTargetServer);
SendToClient(this, CPacket_Read(cPacket), false);
*/
// Send them their ID.
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_YOURID);
cPacket.Writeuint16(m_ClientID);
cPacket.Writeuint8((uint8)bIsLocal);
SendToClient(this, CPacket_Read(cPacket), false);
// Setup their file transfer.
HHashIterator *hIterator = hs_GetFirstElement(server_filemgr->m_hFileTable);
while (hIterator)
{
HHashElement *hElement = hs_GetNextElement(hIterator);
UsedFile *pUsedFile = (UsedFile*)hs_GetElementUserData(hElement);
if( !(pUsedFile->m_Flags & FFLAG_DONTSEND) )
{
fts_AddFile(m_hFTServ,
pUsedFile->GetFilename(), pUsedFile->m_FileSize, pUsedFile->m_FileID,
(uint16)(pUsedFile->m_Flags | FFLAG_SENDWAIT));
}
}
fts_FlushAddedFiles(m_hFTServ);
// Now set them up to try to get into the world, after their file transfer
// has completed.
sm_SetClientState(this, CLIENT_WAITINGTOENTERWORLD);
dsi_ConsolePrint("New client, id %d, for a total of %d.", m_ClientID, g_pServerMgr->m_Clients.m_nElements);
g_pServerMgr->ResetFlowControl();
return true;
}
Client::~Client( )
{
// Free up everything.
fts_Term(m_hFTServ);
m_hFTServ = NULL;
LTLink *pCur;
pCur = m_Events.m_Head.m_pNext;
while( pCur != &m_Events.m_Head )
{
LTLink *pNext = pCur->m_pNext;
CServerEvent *pEvent = (CServerEvent*)pCur->m_pData;
pEvent->DecrementRefCount();
pCur = pNext;
}
dfree(m_ObjInfos);
dfree(m_SentLists[0].m_ObjectIDs);
dfree(m_SentLists[1].m_ObjectIDs);
dfree(m_Name);
// Free the fileid info structures...
HHashIterator *hIterator = hs_GetFirstElement(m_hFileIDTable);
while( hIterator )
{
HHashElement *hElement = hs_GetNextElement(hIterator);
if (hElement)
{
sb_Free(&g_pServerMgr->m_FileIDInfoBank, hs_GetElementUserData(hElement));
}
}
hs_DestroyHashTable(m_hFileIDTable);
if (m_pClientData)
{
delete[] m_pClientData;
m_pClientData = NULL;
}
if( !m_Link.IsTiedOff( ))
dl_RemoveAt(&g_pServerMgr->m_Clients, &m_Link);
}
//------------------------------------------------------------------
// ServerMgr client-related function implementation
//------------------------------------------------------------------
void sm_UpdateClientFileTransfer(Client *pClient)
{
fts_Update(pClient->m_hFTServ, g_pServerMgr->m_nTrueFrameTimeMS / 1000.0f);
}
bool sm_CanClientEnterWorld(Client *pClient)
{
if (g_pServerMgr->m_State != SERV_RUNNINGWORLD)
return false;
if (!(pClient->m_ClientFlags & CFLAG_GOT_HELLO))
return false;
if (pClient->m_ClientFlags & CFLAG_LOCAL)
{
return true;
}
else
{
if (pClient->m_ClientFlags & CFLAG_WANTALLFILES)
{
return (fts_GetNumNeededFiles(pClient->m_hFTServ) == 0) &&
(fts_GetNumTotalFiles(pClient->m_hFTServ) == 0);
}
else
{
return fts_GetNumNeededFiles(pClient->m_hFTServ) == 0;
}
}
}
LTRESULT sm_SendCacheListSection(Client *pClient,
uint32 nStartIndex,
uint8 nPacketID,
uint16 nFileType)
{
bool bPacketEmpty = true;
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_PRELOADLIST);
cPacket.Writeuint8(nPacketID);
for (uint32 i = nStartIndex; i < g_pServerMgr->m_CacheListSize; ++i)
{
if (g_pServerMgr->m_CacheList[i].m_FileType == nFileType)
{
bPacketEmpty = false;
cPacket.Writeuint16((uint16)g_pServerMgr->m_CacheList[i].m_FileID);
}
}
// Send it to the client if it's not empty
if (!bPacketEmpty)
{
SendToClient(pClient, CPacket_Read(cPacket), false);
}
return LT_OK;
}
// Sends the cached file list to the client
LTRESULT sm_SendCacheListToClient(Client *pClient, uint32 nStartIndex)
{
// Add models
//sm_SendCacheListSection(pClient, nStartIndex, PRELOADTYPE_MODEL_CACHED, FT_MODEL);
// Add sprites.
sm_SendCacheListSection(pClient, nStartIndex, PRELOADTYPE_SPRITE, FT_SPRITE);
// Add textures.
sm_SendCacheListSection(pClient, nStartIndex, PRELOADTYPE_TEXTURE, FT_TEXTURE);
// Add sounds.
sm_SendCacheListSection(pClient, nStartIndex, PRELOADTYPE_SOUND, FT_SOUND);
return LT_OK;
}
// Goes thru the current level and tells the client about everything it should preload.
LTRESULT sm_TellClientToPreloadStuff(Client *pClient)
{
// t.f
g_pServerMgr->SendPreloadModelMsgToClient( pClient );
// Send all the other files in the cache list
sm_SendCacheListToClient(pClient, 0);
// Send the sounds that weren't in the cache list
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_PRELOADLIST);
cPacket.Writeuint8(PRELOADTYPE_SOUND);
bool bPacketEmpty = true;
LTLink *pCur = g_pServerMgr->m_SoundDataList.m_Head.m_pNext;
while (pCur != &g_pServerMgr->m_SoundDataList.m_Head)
{
CSoundData *pSoundData = (CSoundData *)pCur->m_pData;
pCur = pCur->m_pNext;
if (!pSoundData) continue;
if (pSoundData->IsTouched())
{
if (pSoundData->GetFile())
{
bPacketEmpty = false;
cPacket.Writeuint16((uint16)pSoundData->GetFile()->m_FileID);
}
}
}
if (!bPacketEmpty)
SendToClient(pClient, CPacket_Read(cPacket), false);
else
cPacket.Reset();
// Mark the end and send away.
cPacket.Writeuint8(SMSG_PRELOADLIST);
cPacket.Writeuint8(PRELOADTYPE_END);
SendToClient(pClient, CPacket_Read(cPacket), false);
return LT_OK;
}
LTRESULT sm_UpdatePuttingInWorld(Client *pClient)
{
if (pClient->m_PuttingIntoWorldStage == PUTTINGINTOWORLD_LOADEDWORLD ||
(pClient->m_ClientFlags & CFLAG_LOCAL))
{
// Tell them all the stuff they need to preload.
sm_TellClientToPreloadStuff(pClient);
// Tell them about the sky.
sm_TellClientAboutSky(pClient);
pClient->m_PuttingIntoWorldStage = PUTTINGINTOWORLD_PRELOADING;
}
if (pClient->m_PuttingIntoWorldStage == PUTTINGINTOWORLD_PRELOADED ||
(pClient->m_ClientFlags & CFLAG_LOCAL))
{
// Call OnClientEnterWorld and setup the client's object.
LPBASECLASS pObject = i_server_shell->OnClientEnterWorld((HCLIENT)pClient);
if (!pObject)
{
dsi_PrintToConsole("Error: ServerShell::OnClientEnterWorld returned LTNULL!");
return LT_ERROR;
}
pClient->m_pObject = GetObjectServerObj(pObject);
pClient->m_pObject->sd->m_pClient = pClient;
ASSERT(g_pServerMgr->m_pWorldFile);
// If they used a ClientRef's object, remove the ClientRef.
LTLink *pCur, *pListHead;
pListHead = &g_pServerMgr->m_ClientReferences.m_Head;
for (pCur=pListHead->m_pNext; pCur != pListHead; pCur=pCur->m_pNext)
{
ClientRef *pRef = (ClientRef*)pCur->m_pData;
if (pRef->m_ObjectID == pClient->m_pObject->m_ObjectID)
{
pClient->m_pObject->m_InternalFlags &= ~IFLAG_HASCLIENTREF;
dl_RemoveAt(&g_pServerMgr->m_ClientReferences, &pRef->m_Link);
dfree(pRef);
break;
}
}
// Tell this client (and its attachments) to use the object ID if it
// doesn't have an attachment parent.
if (!pClient->m_pAttachmentParent)
{
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_CLIENTOBJECTID);
cPacket.Writeuint16(pClient->m_pObject->m_ObjectID);
SendToClient(pClient, CPacket_Read(cPacket), true);
}
// Reset their sent lists.
pClient->m_SentLists[0].m_nObjectIDs = pClient->m_SentLists[1].m_nObjectIDs = 0;
// Mark all the objects as new and find out what the client needs to be sent.
pListHead = &g_pServerMgr->m_Objects.m_Head;
for (pCur=pListHead->m_pNext; pCur != pListHead; pCur=pCur->m_pNext)
{
LTObject *pObj = (LTObject*)pCur->m_pData;
ObjInfo *pInfo = &pClient->m_ObjInfos[pObj->m_ObjectID];
pInfo->m_ChangeFlags = (uint16)sm_GetNewObjectChangeFlags(pObj);
}
// Mark all the soundtracks as new and find out what the client needs to be sent.
for (pCur=g_pServerMgr->m_SoundTrackList.m_Head.m_pNext; pCur != &g_pServerMgr->m_SoundTrackList.m_Head; pCur = pCur->m_pNext)
{
CSoundTrack *pSoundTrack = (CSoundTrack *)pCur->m_pData;
ObjInfo *pInfo = &pClient->m_ObjInfos[GetLinkID(pSoundTrack->m_pIDLink)];
pInfo->m_ChangeFlags = (uint16)sm_GetNewSoundTrackChangeFlags(pSoundTrack);
pInfo->m_nSoundFlags = 0;
}
pClient->m_State = CLIENT_INWORLD;
}
return LT_OK;
}
LTRESULT sm_ConnectClientToWorld(Client *pClient)
{
if (g_pServerMgr->m_State != SERV_RUNNINGWORLD)
{
return LT_OK;
}
ASSERT(pClient->m_State != CLIENT_INWORLD);
// Send the client the console state...
// 광식
#ifdef DE_SERVER_COMPILE
HHashIterator *hIterator = hs_GetFirstElement(console_state->State()->m_VarHash);
while (hIterator)
{
HHashElement *hElement = hs_GetNextElement(hIterator);
if (!hElement)
continue;
LTCommandVar *pCurVar = (LTCommandVar *)hs_GetElementUserData( hElement );
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_CONSOLEVAR);
cPacket.WriteString(pCurVar->pVarName);
cPacket.WriteString(pCurVar->pStringVal);
SendToClient(pClient, CPacket_Read(cPacket), false);
}
#endif // DE_SERVER_COMPILE
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_LOADWORLD);
cPacket.Writefloat(g_pServerMgr->m_GameTime);
cPacket.Writeuint16((uint16)g_pServerMgr->m_pWorldFile->m_FileID);
SendToClient(pClient, CPacket_Read(cPacket), false);
// Alrighty.. wait till we get the acknowledgement back.
pClient->m_State = CLIENT_PUTTINGINWORLD;
pClient->m_PuttingIntoWorldStage = PUTTINGINTOWORLD_LOADINGWORLD;
// Get them in right away if they're local.
if (pClient->m_ClientFlags & CFLAG_LOCAL)
{
sm_UpdatePuttingInWorld(pClient);
}
return LT_OK;
}
void sm_GetClientOutOfWorld(Client *pClient)
{
i_server_shell->OnClientExitWorld((HCLIENT)pClient);
if (pClient->m_pObject) {
pClient->m_pObject->sd->m_pClient = LTNULL;
}
pClient->m_pObject = LTNULL;
//[MURSUM]
/*
// Send them an UNLOADWORLD packet.
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_UNLOADWORLD);
SendToClient(pClient, CPacket_Read(cPacket), false);
// If they're local, call the function to get them out of the world
// so the local client removes its objects.
if (pClient->m_ClientFlags & CFLAG_LOCAL) {
clienthack_UnloadWorld();
}
*/
}
// ----------------------------------------------------------------------- //
// Interface functions.
// ----------------------------------------------------------------------- //
Client* sm_OnNewConnection(CBaseConn *id, bool bIsLocal)
{
// Clear the local flag if remote is forced.
if (g_bForceRemote)
{
bIsLocal = false;
}
// Add the client to the internal structures.
Client *pClient;
LT_MEM_TRACK_ALLOC(( pClient = new Client( )),LT_MEM_TYPE_MISC);
if( !pClient )
return NULL;
if( !pClient->Init( id, bIsLocal ))
{
delete pClient;
pClient = NULL;
return NULL;
}
return pClient;
}
void sm_OnBrokenConnection(CBaseConn *id)
{
Client *pClient = sm_FindClient(id);
if (pClient)
{
sm_RemoveClient(pClient);
}
}
LTRESULT sm_AttachClient(Client *pParent, Client *pChild)
{
if (pParent == pChild)
{
RETURN_ERROR(1, sm_AttachClient, LT_INVALIDPARAMS);
}
sm_DetachClient(pChild);
pChild->m_pAttachmentParent = pParent;
dl_Insert(&pParent->m_Attachments, &pChild->m_AttachmentLink);
// Tell the client to use the new object ID.
if (pParent->m_pObject)
{
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_CLIENTOBJECTID);
cPacket.Writeuint16(pParent->m_pObject->m_ObjectID);
SendToClient(pChild, CPacket_Read(cPacket), true);
}
return LT_OK;
}
LTRESULT sm_DetachClient(Client *pClient)
{
if (pClient->m_pAttachmentParent == 0)
return LT_OK;
dl_Remove(&pClient->m_AttachmentLink);
pClient->m_pAttachmentParent = LTNULL;
// Tell the client to use its normal object.
if (pClient->m_pObject)
{
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_CLIENTOBJECTID);
cPacket.Writeuint16(pClient->m_pObject->m_ObjectID);
SendToClient(pClient, CPacket_Read(cPacket), true);
}
return LT_OK;
}
LTRESULT sm_DetachClientChildren(Client *pClient)
{
LTLink *pCur, *pNext;
pCur = pClient->m_Attachments.m_pNext;
while (pCur != &pClient->m_Attachments)
{
pNext = pCur->m_pNext;
sm_DetachClient((Client*)pCur->m_pData);
pCur = pNext;
}
return LT_OK;
}
void sm_RemoveClient(Client *pClient)
{
// Undo all attachments.
sm_DetachClient(pClient);
sm_DetachClientChildren(pClient);
// Remove the client reference in any sound tracks...
for (LTLink *pCur = g_pServerMgr->m_SoundTrackList.m_Head.m_pNext;
pCur != &g_pServerMgr->m_SoundTrackList.m_Head;
pCur = pCur->m_pNext)
{
CSoundTrack *pSoundTrack = (CSoundTrack *)pCur->m_pData;
ObjInfo *pInfo = &pClient->m_ObjInfos[GetLinkID(pSoundTrack->m_pIDLink)];
if (!(pInfo->m_nSoundFlags & OBJINFOSOUNDF_CLIENTDONE))
{
pSoundTrack->Release(&pInfo->m_nSoundFlags);
}
}
// If they had a local connection, clear the server's local flag.
if (pClient->m_ClientFlags & CFLAG_LOCAL)
{
g_pServerMgr->m_InternalFlags &= ~SFLAG_LOCAL;
}
// Get them out of the world..
sm_SetClientState(pClient, CLIENT_CONNECTED);
// Notify the shell.
i_server_shell->OnRemoveClient((HCLIENT)pClient);
// Remove the client.
delete pClient;
pClient = NULL;
// The flow control needs re-balancing now...
g_pServerMgr->ResetFlowControl();
}
bool sm_SetClientState(Client *pClient, int state)
{
if (pClient->m_State == state)
return true;
if (state == CLIENT_INWORLD)
{
if (sm_CanClientEnterWorld(pClient))
{
sm_ConnectClientToWorld(pClient);
return true;
}
else
{
return false;
}
}
else
{
// If they're in the world, remove them from the world.
if (pClient->m_State == CLIENT_INWORLD)
{
sm_GetClientOutOfWorld(pClient);
}
}
pClient->m_State = state;
return true;
}
void sm_UpdateClientState(Client *pClient)
{
// Try to put them in the world.
if (pClient->m_State == CLIENT_WAITINGTOENTERWORLD)
{
sm_SetClientState(pClient, CLIENT_INWORLD);
}
else if (pClient->m_State == CLIENT_PUTTINGINWORLD)
{
sm_UpdatePuttingInWorld(pClient);
}
// Update any files they're transferring.
sm_UpdateClientFileTransfer(pClient);
}
// Prints all the packet data into the packet.trc file.
void sm_TracePacket(const CPacket_Read &cPacket)
{
if (g_CV_STracePackets == 0)
return;
if (!g_pServerMgr->m_pTracePacketFile)
{
g_pServerMgr->m_pTracePacketFile = streamsim_Open("packet.trc", "wb");
if (!g_pServerMgr->m_pTracePacketFile)
return;
}
ILTStream *pStream = g_pServerMgr->m_pTracePacketFile;
uint32 nPacketSize = cPacket.Size();
*pStream << nPacketSize;
CPacket_Read cDumpPacket(cPacket);
cDumpPacket.SeekTo(0);
while (!cDumpPacket.EOP())
{
uint32 nTemp = (uint32)cDumpPacket.Readuint32();
*pStream << nTemp;
}
if (g_CV_DelimitPackets)
{
char end[6] = "*END*";
pStream->WriteString(end);
}
}
// Returns true if it sent the packet.
// Set roomNeeded to FU_FORCEFLUSH to force it to send.
bool sm_FlushUpdate(UpdateInfo *pInfo, const CPacket_Read &cPacket, uint32 nPacketFlags)
{
if (cPacket.Size() <= 8)
return false;
sm_TracePacket(cPacket);
SendToClient(pInfo->m_pClient, cPacket, false, nPacketFlags);
return true;
}
void WriteUnguaranteedInfo(LTObject *pObject, CPacket_Write &cPacket, bool bLastClient = false)
{
uint32 flags = 0;
if (pObject->sd->m_NetFlags & NETFLAG_POSUNGUARANTEED)
{
flags |= UUF_POS;
}
if (pObject->sd->m_NetFlags & NETFLAG_ROTUNGUARANTEED)
{
if (pObject->m_Flags & FLAG_YROTATION)
{
flags |= UUF_YROTATION;
}
else
{
flags |= UUF_ROT;
}
}
if (pObject->sd->m_NetFlags & NETFLAG_ANIMUNGUARANTEED)
{
// They shouldn't be able to set this flag unless it's a model.
ASSERT(pObject->m_ObjectType == OT_MODEL);
flags |= UUF_ANIMINFO;
}
//////////////////////////////////////////////////////////////////////////
if ( pObject->DoesNeedPitchUpdate() )
{
flags |= UUF_PITCH;
}
//////////////////////////////////////////////////////////////////////////
ASSERT(flags); // You shouldn't get into this function without being unguaranteed-info friendly
// ANI 정보는 Packet으로 날리지 않기.
//flags &= ~UUF_ANIMINFO;
/*
// 광식
//------------------------------------------------------------------
if( pObject->m_UserFlags & (1<<1) )
{
flags &= ~UUF_POS;
flags &= ~UUF_PITCH;
flags &= ~UUF_YROTATION;
flags &= ~UUF_ANIMINFO;
}
//------------------------------------------------------------------
*/
cPacket.Writeuint16(pObject->m_ObjectID);
cPacket.WriteBits(flags, UUF_FLAGCOUNT);
// Write position/rotation.
if (flags & UUF_POS)
{
CLTMessage_Write_Server::WriteCompPos(cPacket, pObject->GetPos());
bool bWriteVelocity = pObject->m_Velocity.MagSqr() > 0.00001f;
cPacket.Writebool(bWriteVelocity);
if (bWriteVelocity)
{
//CLTMessage_Write_Server::WriteCompLTVector(cPacket, pObject->m_Velocity);
CLTMessage_Write_Server::WriteCompPos(cPacket, pObject->m_Velocity);
}
}
if (flags & UUF_YROTATION)
{
CLTMessage_Write_Server::WriteYRotation(cPacket, pObject->m_Rotation);
}
else if (flags & UUF_ROT)
{
CLTMessage_Write_Server::WriteCompLTRotation(cPacket, pObject->m_Rotation);
}
// Write pitch.
//////////////////////////////////////////////////////////////////////////
if ( flags & UUF_PITCH )
{
CLTMessage_Write_Server::WriteCompPitch( cPacket, pObject->GetPitch() );
if ( bLastClient )
{
pObject->FinishPitchUpdate();
}
}
//////////////////////////////////////////////////////////////////////////
// 광식 : Ani 수정.
if (flags & UUF_ANIMINFO)
{
ModelInstance* pModel = ToModel(pObject);
LTAnimTracker* pTracker = pModel->GetTracker(1);
uint8 nAnimIndex;
if(pTracker)
{
nAnimIndex = (uint8)trk_GetCurAnimIndex(pTracker);
cPacket.Writeint8(nAnimIndex);
bool bLoop = !!(pTracker->m_Flags&AT_LOOPING);
//----------------------------------------------------------
cPacket.Writebool((pTracker->m_Flags & AT_LOOPING) != 0);
//----------------------------------------------------------
}
pTracker = pModel->GetTracker(2);
if(pTracker)
{
nAnimIndex = (uint8)trk_GetCurAnimIndex(pTracker);
cPacket.Writeint8(nAnimIndex);
bool bLoop = !!(pTracker->m_Flags&AT_LOOPING);
//----------------------------------------------------------
cPacket.Writebool((pTracker->m_Flags & AT_LOOPING) != 0);
//----------------------------------------------------------
}
// 여기부터 추가
pTracker = pModel->GetTracker(44); // Recoil Tracker
if(pTracker)
{
nAnimIndex = (uint8)trk_GetCurAnimIndex(pTracker);
if( nAnimIndex != 0 )
{
cPacket.Writebool(true);
cPacket.Writeint8(nAnimIndex);
}
else
{
cPacket.Writebool(false);
}
}
else
{
cPacket.Writebool(false);
}
}
/*
// Write anim info.
if (flags & UUF_ANIMINFO)
{
WriteAnimInfo(ToModel(pObject), cPacket);
}
*/
}
void ExpandObjectIdList(SentList *pSentList)
{
uint16* pNewIDs = NULL;
int nNewSize = pSentList->m_nObjectIDs + 256;
LT_MEM_TRACK_ALLOC(pNewIDs = (uint16*)dalloc(sizeof(uint16) * (nNewSize)),LT_MEM_TYPE_OBJECT);
memcpy(pNewIDs, pSentList->m_ObjectIDs, sizeof(uint16) * pSentList->m_nObjectIDs);
dfree(pSentList->m_ObjectIDs);
pSentList->m_ObjectIDs = pNewIDs;
pSentList->m_AllocatedSize = nNewSize;
}
void AddObjectIdToSentList(SentList* pSentList, uint16 id)
{
// Mark the object as changed.
if (pSentList->m_nObjectIDs >= pSentList->m_AllocatedSize)
{
ExpandObjectIdList( pSentList );
}
pSentList->m_ObjectIDs[pSentList->m_nObjectIDs] = id;
pSentList->m_nObjectIDs++;
//since all the object ID's are 16 bit we'll have other problems before this, but
//we should assert just to make sure
assert(pSentList->m_nObjectIDs < USHRT_MAX);
}
// Marks the object with CF_SENTINFO and sends any change info it has.
void sm_AddObjectChangeInfo(UpdateInfo *pInfo, LTObject *pObject, ObjInfo *pObjInfo)
{
// Check if we already sent this.
if (pObjInfo->m_ChangeFlags & CF_SENTINFO)
return;
// Update the send time
pObjInfo->m_nLastSentG = pInfo->m_nUpdateTime;
AddObjectIdToSentList(g_pCurSentList, pObject->m_ObjectID);
// Setup the packet with update info.
CPacket_Write cSubPacket;
#ifdef _DEBUG
if( pObject->m_ObjectType == OT_NORMAL )
{
int a=0;
++a;
}
#endif
if( FillPacketFromInfo(pInfo->m_pClient, pObject, pObjInfo, cSubPacket))
{
if (!cSubPacket.Empty())
{
pInfo->m_cPacket.Writeuint32(cSubPacket.Size());
pInfo->m_cPacket.WritePacket(CPacket_Read(cSubPacket));
}
}
// Clear 'em.
ASSERT(!(pObjInfo->m_ChangeFlags & CF_SENTINFO));
pObjInfo->m_ChangeFlags = (uint16)((pObjInfo->m_ChangeFlags & CF_CLEARMASK) | CF_SENTINFO);
}
inline bool ShouldSendToClient(const Client *pClient, LTObject *pObject)
{
//we should always have an associated client and object
assert(pClient && pObject);
//flags that indicate that the client can have an interaction with the object
static const uint32 k_nInteractionFlags = FLAG_VISIBLE | FLAG_SOLID | FLAG_RAYHIT;
if (!(pObject->m_Flags & FLAG_FORCECLIENTUPDATE))
{
// 광식
//--------------------------------------------
if( pObject->m_UserFlags & (1<<1) )
return false;
//--------------------------------------------
//if it is a normal object type, only inform the client about it if it has a special
//effect message
if((pObject->m_ObjectType == OT_NORMAL) && (pObject->sd->m_cSpecialEffectMsg.Size() == 0))
return false;
// See if this object can't be interacted with and hasn't changed
if (!(pObject->m_Flags & k_nInteractionFlags) &&
!(pClient->m_ObjInfos[pObject->m_ObjectID].m_ChangeFlags & CF_FLAGS))
return false;
}
// This happens sometimes when an object removes another object in its
// destructor.. not a big deal.
if (!(pObject->m_InternalFlags & IFLAG_INWORLD))
{
return false;
}
if( pObject->m_InternalFlags & IFLAG_DONTSEND )
{
return false;
}
// Don't tell them about null models.
if ( (pObject->m_ObjectType == OT_MODEL) &&
(pObject->ToModel()->GetModelDB() == NULL) )
{
return false;
}
return true;
}
inline void UpdateSendToClientState(LTObject *pObject, UpdateInfo *pInfo)
{
sm_AddObjectChangeInfo(pInfo,
pObject, &pInfo->m_pClient->m_ObjInfos[pObject->m_ObjectID]);
for (Attachment *pAttachment=pObject->m_Attachments; pAttachment; pAttachment=pAttachment->m_pNext)
{
LTObject *pAttachedObj = sm_FindObject(pAttachment->m_nChildID);
if (!pAttachedObj)
continue;
if (!ShouldSendToClient(pInfo->m_pClient, pAttachedObj))
continue;
sm_AddObjectChangeInfo(pInfo, pAttachedObj, &pInfo->m_pClient->m_ObjInfos[pAttachedObj->m_ObjectID]);
}
}
void sm_SendSoundTracks(UpdateInfo *pInfo, CPacket_Write &cPacket)
{
ObjInfo *pObjInfo;
LTLink *pCur;
CSoundTrack *pSoundTrack;
// float fMaxDistSqr;
for (pCur = g_pServerMgr->m_SoundTrackList.m_Head.m_pNext; pCur != &g_pServerMgr->m_SoundTrackList.m_Head; pCur = pCur->m_pNext)
{
pSoundTrack = (CSoundTrack *)pCur->m_pData;
pObjInfo = &pInfo->m_pClient->m_ObjInfos[GetLinkID(pSoundTrack->m_pIDLink)];
if( pSoundTrack->m_dwFlags & PLAYSOUND_AMBIENT )
continue;
// Check if the sound was removed but not sending a end loop change.
if (pSoundTrack->GetRemove() && !(pObjInfo->m_ChangeFlags & CF_SOUNDINFO))
continue;
// Check if the sound is done...
if ((pSoundTrack->IsTrackTime() && pSoundTrack->GetTimeLeft() <= 0.0f))
continue;
// [RP] 1/11/02 - This range check introduces a bug where upon leaving the range
// the sound gets removed and never re-added when coming back into the range.
// The range check is simply a network optimization for the SoundTrack data.
// Since the SoundTrack data isn't that big to begin with and sending all the sounds really
// *shouldn't* be a problem... don't do the range check.
// Check if sound is in range...
/* if (pSoundTrack->m_dwFlags & (PLAYSOUND_3D | PLAYSOUND_AMBIENT))
{
// Check if sound is within 2x its outer radius from the client or the viewer pos...
fMaxDistSqr = 4.0f * pSoundTrack->m_fOuterRadius * pSoundTrack->m_fOuterRadius;
if ((pSoundTrack->m_vPosition.DistSqr(pInfo->m_pClient->m_pObject->GetPos()) < fMaxDistSqr) ||
(pSoundTrack->m_vPosition.DistSqr(pInfo->m_pClient->m_ViewPos) < fMaxDistSqr))
{
}
else
{
continue;
}
}
*/
pObjInfo = &pInfo->m_pClient->m_ObjInfos[GetLinkID(pSoundTrack->m_pIDLink)];
uint16 nNewId = (uint16)GetLinkID(pSoundTrack->m_pIDLink);
AddObjectIdToSentList( g_pCurSentList, nNewId );
// Setup the packet with update info. If the client already told us the sound is done, then don't
// send it again...
if (pObjInfo->m_ChangeFlags && !(pObjInfo->m_nSoundFlags & OBJINFOSOUNDF_CLIENTDONE))
{
FillSoundTrackPacketFromInfo(pSoundTrack, pObjInfo, pInfo->m_pClient, cPacket);
}
// Clear 'em.
pObjInfo->m_ChangeFlags = CF_SENTINFO;
}
}
void ClearSoundChangeFlags(UpdateInfo *pInfo)
{
ObjInfo *pObjInfo;
LTLink *pCur;
CSoundTrack *pSoundTrack;
for (pCur = g_pServerMgr->m_SoundTrackList.m_Head.m_pNext; pCur != &g_pServerMgr->m_SoundTrackList.m_Head; pCur = pCur->m_pNext)
{
pSoundTrack = (CSoundTrack *)pCur->m_pData;
pObjInfo = &pInfo->m_pClient->m_ObjInfos[GetLinkID(pSoundTrack->m_pIDLink)];
pObjInfo->m_ChangeFlags = 0;
}
}
void WriteEndUpdateInfo(Client *pClient, CPacket_Write &cPacket)
{
// Mark the end-update info.
cPacket.Writeuint16(ID_TIMESTAMP);
cPacket.WriteBits(0, UUF_FLAGCOUNT);
cPacket.Writefloat(g_pServerMgr->m_GameTime);
}
bool IsClientInTrouble(Client *pClient)
{
if(pClient->m_ConnectionID)
{
if(pClient->m_ConnectionID->IsInTrouble())
{
return true;
}
}
return false;
}
void WriteObjectRemoves(UpdateInfo *pInfo, SentList *pPrevList)
{
uint32 counter, nRemoves;
LTRecord *pRecord;
uint16 *pCurID;
CSoundTrack *pSoundTrack;
CPacket_Write cSubPacket;
nRemoves = 0;
counter = pPrevList->m_nObjectIDs;
pCurID = pPrevList->m_ObjectIDs;
while (counter--)
{
if (!(pInfo->m_pClient->m_ObjInfos[*pCurID].m_ChangeFlags & CF_SENTINFO))
{
// Write the UDPATESUB_OBJECTREMOVES if necessary.
if (nRemoves == 0)
{
cSubPacket.Writeuint8(0);
cSubPacket.Writeuint8(UPDATESUB_OBJECTREMOVES);
}
cSubPacket.Writeuint16(*pCurID);
++nRemoves;
// Find this record...
pRecord = sm_FindRecord(*pCurID);
if( pRecord && pRecord->m_pRecordData )
{
if (pRecord->m_nRecordType == RECORDTYPE_LTOBJECT)
{
pInfo->m_pClient->m_ObjInfos[*pCurID].m_ChangeFlags =
(uint16)sm_GetNewObjectChangeFlags((LTObject *)pRecord->m_pRecordData);
}
else
{
pSoundTrack = (CSoundTrack *)pRecord->m_pRecordData;
// If the client hasn't already told us the sound is done, then remove the reference...
if (!(pInfo->m_pClient->m_ObjInfos[ *pCurID ].m_nSoundFlags & OBJINFOSOUNDF_CLIENTDONE))
{
pSoundTrack->Release(&pInfo->m_pClient->m_ObjInfos[ *pCurID ].m_nSoundFlags);
}
pInfo->m_pClient->m_ObjInfos[*pCurID].m_ChangeFlags =
(uint16)sm_GetNewSoundTrackChangeFlags(pSoundTrack);
}
}
}
++pCurID;
}
if (!cSubPacket.Empty())
{
pInfo->m_cPacket.Writeuint32(cSubPacket.Size());
pInfo->m_cPacket.WritePacket(CPacket_Read(cSubPacket));
}
}
struct CGuaranteedObjTrack
{
bool operator<(const CGuaranteedObjTrack &sOther) const { return m_fPriority < sOther.m_fPriority; }
LTObject *m_pObject;
ObjInfo *m_pObjInfo;
float m_fPriority;
};
typedef std::priority_queue<CGuaranteedObjTrack> TGuaranteedObjQueue;
void SendAllObjectsGuaranteed(ObjectMgr *pObjectMgr, UpdateInfo *pInfo)
{
//determine if we are dealing with a local client.
bool bLocalClient = !!(pInfo->m_pClient->m_ClientFlags & CFLAG_LOCAL);
uint32 i;
LTLink *pListHead, *pCur;
LTObject *pObject;
if(bLocalClient)
{
//we have a local client, so we can bypass queueing up, sorting, bandwidth checking
//and other tasks and just send all objects
for (i=0; i < NUM_OBJECTTYPES; i++)
{
// 광식
//---------------------------------
//if( i != OT_MODEL ) continue;
//---------------------------------
pListHead = &pObjectMgr->m_ObjectLists[i].m_Head;
for (pCur=pListHead->m_pNext; pCur != pListHead; pCur=pCur->m_pNext)
{
pObject = (LTObject*)pCur->m_pData;
// Gotta check here too for objects not in the BSP.
if (!ShouldSendToClient(pInfo->m_pClient, pObject))
{
continue;
}
// Don't send over the main world model
if (pObject->IsMainWorldModel())
{
continue;
}
UpdateSendToClientState(pObject, pInfo);
}
}
}
else
{
// Do this in priority order...
static TGuaranteedObjQueue aObjects;
// Try not to use up the whole update...
uint32 nUpdateSizeRemaining = pInfo->m_nTargetUpdateSize / 2;
for (i=0; i < NUM_OBJECTTYPES; i++)
{
// 광식
//---------------------------------
//if( i != OT_MODEL ) continue;
//---------------------------------
pListHead = &pObjectMgr->m_ObjectLists[i].m_Head;
for (pCur=pListHead->m_pNext; pCur != pListHead; pCur=pCur->m_pNext)
{
pObject = (LTObject*)pCur->m_pData;
// Gotta check here too for objects not in the BSP.
if (!ShouldSendToClient(pInfo->m_pClient, pObject))
continue;
// Don't send over the main world model
if (pObject->IsMainWorldModel())
continue;
CGuaranteedObjTrack cCurObj;
cCurObj.m_pObject = pObject;
cCurObj.m_pObjInfo = &pInfo->m_pClient->m_ObjInfos[pObject->m_ObjectID];
cCurObj.m_fPriority = (float)(pInfo->m_nUpdateTime - cCurObj.m_pObjInfo->m_nLastSentG);
aObjects.push(cCurObj);
}
}
while (!aObjects.empty())
{
const CGuaranteedObjTrack &cCurObj = aObjects.top();
UpdateSendToClientState(cCurObj.m_pObject, pInfo);
// Jump out if we're sending too much...
if (pInfo->m_cPacket.Size() >= nUpdateSizeRemaining)
{
break;
}
aObjects.pop();
}
// Act like we sent the left-overs so they don't look like they got removed...
while (!aObjects.empty())
{
const CGuaranteedObjTrack &cCurObj = aObjects.top();
cCurObj.m_pObjInfo->m_ChangeFlags |= CF_SENTINFO;
AddObjectIdToSentList(g_pCurSentList, cCurObj.m_pObject->m_ObjectID);
aObjects.pop();
}
}
}
//Handles writing out the unguaranteed data of an object as well as all of its attachments
static void WriteUnguaranteedDataWithAttachments(LTObject* pObject, CPacket_Write& cUnguaranteed, const uint32 k_nUnguaranteedMask, bool bLastClient = false)
{
//write out the unguaranteed data for the object itself
WriteUnguaranteedInfo(pObject, cUnguaranteed, bLastClient);
//now do the same for all the attached objects
for (Attachment *pAttachment = pObject->m_Attachments; pAttachment; pAttachment = pAttachment->m_pNext)
{
LTObject *pAttachedObj = sm_FindObject(pAttachment->m_nChildID);
if (!pAttachedObj)
continue;
if ((pAttachedObj->sd->m_NetFlags & k_nUnguaranteedMask) == 0)
continue;
WriteUnguaranteedInfo(pAttachedObj, cUnguaranteed, bLastClient);
}
}
//Handles updating the send time of the specified object and all of its attachments
static void UpdateSendTimeWithAttachments(LTObject* pObject, UpdateInfo *pInfo, const uint32 k_nUnguaranteedMask)
{
// Update the send time
pInfo->m_pClient->m_ObjInfos[pObject->m_ObjectID].m_nLastSentU = pInfo->m_nUpdateTime;
// Update the send time of the attachments
for (Attachment *pAttachment = pObject->m_Attachments; pAttachment; pAttachment = pAttachment->m_pNext)
{
LTObject *pAttachedObj = sm_FindObject(pAttachment->m_nChildID);
if (!pAttachedObj)
continue;
if ((pAttachedObj->sd->m_NetFlags & k_nUnguaranteedMask) == 0)
continue;
pInfo->m_pClient->m_ObjInfos[pAttachedObj->m_ObjectID].m_nLastSentU = pInfo->m_nUpdateTime;
}
}
struct CUnguaranteedObjTrack
{
bool operator<(const CUnguaranteedObjTrack &sOther) const { return m_fPriority < sOther.m_fPriority; }
LTObject *m_pObject;
float m_fPriority;
};
typedef std::priority_queue<CUnguaranteedObjTrack> TUnguaranteedObjQueue;
void SendAllObjectsUnguaranteed(ObjectMgr *pObjectMgr, UpdateInfo *pInfo, bool bLastClient = false)
{
//determine if we are dealing with a local client.
bool bLocalClient = !!(pInfo->m_pClient->m_ClientFlags & CFLAG_LOCAL);
//mask representing all the flags that would indicate an object needing to be included
//in an unguaranteed packet
const uint32 k_nUnguaranteedMask = (NETFLAG_POSUNGUARANTEED|NETFLAG_ROTUNGUARANTEED|NETFLAG_ANIMUNGUARANTEED);
if(bLocalClient)
{
//we are on a local client, we don't need to do queuing, weighting, or anything, everything
//can just be sent down
for (uint32 i = 0; i < NUM_OBJECTTYPES; i++)
{
LTLink *pListHead = &pObjectMgr->m_ObjectLists[i].m_Head;
for (LTLink *pCur = pListHead->m_pNext; pCur != pListHead; pCur = pCur->m_pNext)
{
LTObject *pObject = (LTObject*)pCur->m_pData;
if ((pObject->sd->m_NetFlags & k_nUnguaranteedMask) == 0)
continue;
// 광식 : Player 가 죽었으면 Ungaranteed Packet은 무조건 안날리도록 수정
//------------------------------------------------------------------------
if( pObject->m_UserFlags & (1<<1) )
continue;
//------------------------------------------------------------------------
//write out all the unguaranteed data
WriteUnguaranteedDataWithAttachments(pObject, pInfo->m_cUnguaranteed, k_nUnguaranteedMask, bLastClient);
// Update the send time
UpdateSendTimeWithAttachments(pObject, pInfo, k_nUnguaranteedMask);
}
}
}
else
{
// Don't even bother if we're already over the limit
if (pInfo->m_cPacket.Size() >= pInfo->m_nTargetUpdateSize )
{
return;
}
uint32 nUpdateSizeRemaining = pInfo->m_nTargetUpdateSize - pInfo->m_cPacket.Size();
// Do this in priority order...
static TUnguaranteedObjQueue aObjects;
uint32 nUnguaranteedLength = 0;
const float k_fDistPriorityScale = 1.0f / 128.0f;
for (uint32 i = 0; i < NUM_OBJECTTYPES; i++)
{
LTLink *pListHead = &pObjectMgr->m_ObjectLists[i].m_Head;
for (LTLink *pCur = pListHead->m_pNext; pCur != pListHead; pCur = pCur->m_pNext)
{
LTObject *pObject = (LTObject*)pCur->m_pData;
if ((pObject->sd->m_NetFlags & k_nUnguaranteedMask) == 0)
continue;
// 광식 : Player 가 죽었으면 Ungaranteed Packet은 무조건 안날리도록 수정
//------------------------------------------------------------------------
if( pObject->m_UserFlags & (1<<1) )
continue;
//------------------------------------------------------------------------
//[MURSUM] 내정보는 내가 받지말자!
if( pInfo->m_pClient->m_pObject == pObject )
{
continue;
}
CUnguaranteedObjTrack cCurObj;
cCurObj.m_pObject = pObject;
//Determine the weight of this message based upon some rules
ObjInfo* pObjInfo = &pInfo->m_pClient->m_ObjInfos[pObject->m_ObjectID];
float fDistToClient = LTMAX(pObject->m_Pos.Dist(pInfo->m_pClient->m_ViewPos) * k_fDistPriorityScale, 1.0f);
float fTime = (float)(pInfo->m_nUpdateTime - pObjInfo->m_nLastSentU) + 1.0f;
float fSize = pObject->m_Dims.MagSqr();
float fSpeed = (pObject->m_Velocity.Mag() * k_fDistPriorityScale) + 1.0f;
cCurObj.m_fPriority = (fTime * fSize * fSpeed) / fDistToClient;
aObjects.push(cCurObj);
}
}
while (!aObjects.empty())
{
const CUnguaranteedObjTrack &cCurObj = aObjects.top();
//write out all the unguaranteed data
WriteUnguaranteedDataWithAttachments(cCurObj.m_pObject, pInfo->m_cUnguaranteed, k_nUnguaranteedMask);
// Jump out if we're sending too much...
if (pInfo->m_cUnguaranteed.Size() >= nUpdateSizeRemaining)
{
break;
}
else
nUnguaranteedLength = pInfo->m_cUnguaranteed.Size();
// Update the send time
UpdateSendTimeWithAttachments(cCurObj.m_pObject, pInfo, k_nUnguaranteedMask);
// Next!
aObjects.pop();
}
// Forget the left-overs
while (!aObjects.empty())
aObjects.pop();
// Strip the end of the packet
if (nUnguaranteedLength != pInfo->m_cUnguaranteed.Size())
{
CPacket_Read cStripUnguaranteed(CPacket_Read(pInfo->m_cUnguaranteed), 0, nUnguaranteedLength);
pInfo->m_cUnguaranteed.WritePacket(cStripUnguaranteed);
}
}
}
void sm_UpdateClientInWorld( Client *pClient, bool bLastClient, bool bUpdateUnguaranteed )
{
// If the client's queue is backed up, wait until it's ok.
if (IsClientInTrouble(pClient))
{
return;
}
// If they're not in the world, they don't need to be updated...
if (pClient->m_State != CLIENT_INWORLD)
return;
// Init the update info
UpdateInfo updateInfo;
updateInfo.m_cPacket.Writeuint8(SMSG_UPDATE);
updateInfo.m_cUnguaranteed.Writeuint8(SMSG_UNGUARANTEEDUPDATE);
updateInfo.m_pClient = pClient;
// Keep track of time
updateInfo.m_nUpdateTime = timeGetTime();
uint32 nTimeSinceUpdate = updateInfo.m_nUpdateTime - pClient->m_nLastUpdateTime;
pClient->m_nLastUpdateTime = updateInfo.m_nUpdateTime;
// Get the available bandwidth
// Note : We're more interested in multi-frame bandwidth usage.
// Further note : We also over-estimate how much we will use. Otherwise it will use less than it can.
int32 nAvailableBandwidth = pClient->m_ConnectionID->GetAvailableBandwidth(nTimeSinceUpdate * 3.0f / 1000.0f) / 3;
if (nAvailableBandwidth <= 0)
{
// Don't update them if we're choking
return;
}
updateInfo.m_nTargetUpdateSize = (uint32)nAvailableBandwidth;
SentList *pPrevList = &pClient->m_SentLists[pClient->m_iPrevSentList];
SentList *pCurList = &pClient->m_SentLists[!pClient->m_iPrevSentList];
g_pCurSentList = pCurList;
// Clear the CF_SENTINFO flag on all the objects we sent info on earlier.
for (uint32 i = 0; i < pPrevList->m_nObjectIDs; i++)
{
pClient->m_ObjInfos[pPrevList->m_ObjectIDs[i]].m_ChangeFlags &= ~CF_SENTINFO;
}
// Build the new SentInfo list.
pCurList->m_nObjectIDs = 0;
#ifdef USE_LOCAL_STUFF
if (!(pClient->m_ClientFlags & CFLAG_LOCAL))
#endif
{
// Activate everything they can see.
{
CountAdder cTicks_ClientVis(&g_Ticks_ClientVis);
// Send all the alive objects to the client
SendAllObjectsGuaranteed(&g_pServerMgr->m_ObjectMgr, &updateInfo);
}
}
// Add all the event subpackets.
LTLink *pCur = pClient->m_Events.m_Head.m_pNext;
while (pCur != &pClient->m_Events.m_Head)
{
LTLink *pNext = pCur->m_pNext;
CServerEvent *pEvent = (CServerEvent*)pCur->m_pData;
WriteEventToPacket(pEvent, pClient, updateInfo.m_cPacket);
dl_RemoveAt(&pClient->m_Events, pCur);
pEvent->DecrementRefCount();
pCur = pNext;
}
// Send sound tracking data.
sm_SendSoundTracks(&updateInfo, updateInfo.m_cPacket);
// Write the list of objects to remove (objects we didn't send info on).
WriteObjectRemoves(&updateInfo, pPrevList);
// Clear out the change status on all the sound objects
ClearSoundChangeFlags(&updateInfo);
// 광식 : 만약 맵을 로딩 중이면 Unguaranteed Packet 은 날리지 않도록 수정
if( bUpdateUnguaranteed && !(g_pServerMgr->m_ServerFlags & SS_PAUSED) )
{
SendAllObjectsUnguaranteed(&g_pServerMgr->m_ObjectMgr, &updateInfo, bLastClient);
}
// Write unguaranteed stuff.
//SendAllObjectsUnguaranteed(&g_pServerMgr->m_ObjectMgr, &updateInfo, bLastClient);
// Mark the end of the unguaranteed info
//[MURSUM] 시간 보내지 마!
//WriteEndUpdateInfo(pClient, updateInfo.m_cUnguaranteed);
// 광식
//------------------------------------------------------------------------
/*
char szTemp[256] = {0, };
OutputDebugString("\n===================================================================\n");
sprintf( szTemp, "\r\n============ Packet Size [%d] \r\n", updateInfo.m_cPacket.Size() );
OutputDebugString( szTemp );
OutputDebugString("\n===================================================================\n");
*/
//------------------------------------------------------------------------
#ifndef _FINAL
if( g_CV_TestG > 0 )
{
char* pTempData = new char[g_CV_TestG*256];
CPacket_Write cTempPacket;
cTempPacket.Writeuint8(SMSG_MESSAGE);
cTempPacket.Writeuint8(110);
cTempPacket.WriteData( pTempData, g_CV_TestG*256 );
delete pTempData;
sm_FlushUpdate(&updateInfo, CPacket_Read(cTempPacket), MESSAGE_GUARANTEED);
}
if( g_CV_TestUG > 0 )
{
char* pTempData = new char[g_CV_TestUG*256];
CPacket_Write cTempPacket;
cTempPacket.Writeuint8(SMSG_MESSAGE);
cTempPacket.Writeuint8(110);
cTempPacket.WriteData( pTempData, g_CV_TestUG*256 );
delete pTempData;
sm_FlushUpdate(&updateInfo, CPacket_Read(cTempPacket), 0);
}
#endif
// Send them..
sm_FlushUpdate(&updateInfo, CPacket_Read(updateInfo.m_cPacket), MESSAGE_GUARANTEED);
sm_FlushUpdate(&updateInfo, CPacket_Read(updateInfo.m_cUnguaranteed), 0);
pClient->m_iPrevSentList = !pClient->m_iPrevSentList; // Swap this..
// Send the sky definition if need be.
if (pClient->m_ClientFlags & CFLAG_SENDSKYDEF)
{
pClient->m_ClientFlags &= ~CFLAG_SENDSKYDEF;
sm_TellClientAboutSky(pClient);
}
// Send the global light object if need be.
if (pClient->m_ClientFlags & CFLAG_SENDGLOBALLIGHT)
{
pClient->m_ClientFlags &= ~CFLAG_SENDGLOBALLIGHT;
sm_TellClientAboutGlobalLight(pClient);
}
}
Client* sm_FindClient(CBaseConn *connID)
{
// otherwise, search for the corresponding client in the client list
LTLink* pListHead = &g_pServerMgr->m_Clients.m_Head;
for (LTLink* pCur=pListHead->m_pNext; pCur != pListHead; pCur = pCur->m_pNext)
{
Client* pClient = (Client*)pCur->m_pData;
if (pClient->m_ConnectionID == connID)
{
return pClient;
}
}
return LTNULL;
}
void sm_SetSendSkyDef()
{
LTLink *pCur;
for (pCur = g_pServerMgr->m_Clients.m_Head.m_pNext; pCur != &g_pServerMgr->m_Clients.m_Head; pCur=pCur->m_pNext)
{
((Client*)pCur->m_pData)->m_ClientFlags |= CFLAG_SENDSKYDEF;
}
}
void sm_TellClientAboutSky(Client *pClient)
{
// 광식
#ifdef DE_SERVER_COMPILE
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_SKYDEF);
cPacket.WriteType(g_pServerMgr->m_SkyDef);
cPacket.Writeuint16(MAX_SKYOBJECTS);
for (uint32 i = 0; i < MAX_SKYOBJECTS; i++)
{
cPacket.Writeuint16(g_pServerMgr->m_SkyObjects[i]);
}
SendToClient(pClient, CPacket_Read(cPacket), false);
#endif // DE_SERVER_COMPILE
}
void sm_TellClientAboutGlobalLight(Client *pClient)
{
StaticSunLight *pSun = (StaticSunLight *)ilt_server->HandleToObject(g_pServerMgr->GetGlobalLightObject());
// If we don't have a sun yet, we can't tell the client, now can we?
// (They'll get told as soon as we get told...)
if (!pSun)
return;
CPacket_Write cPacket;
cPacket.Writeuint8(SMSG_GLOBALLIGHT);
LTRotation rRotation;
ilt_server->GetObjectRotation(g_pServerMgr->GetGlobalLightObject(), &rRotation);
// 광식
//cPacket.WriteLTVector(rRotation.Forward());
CLTMessage_Write::WriteCompLTVector(cPacket, rRotation.Forward());
//the brightness scale of the sunlight
float fBrightness = pSun->m_BrightScale * pSun->m_ObjectBrightScale;
// 광식
//cPacket.WriteLTVector(pSun->m_InnerColor * fBrightness);
CLTMessage_Write::WriteCompLTVector(cPacket, pSun->m_InnerColor * fBrightness);
cPacket.Writefloat(pSun->m_fConvertToAmbient);
SendToClient(pClient, CPacket_Read(cPacket), false);
}
LTRESULT sm_RemoveObjectFromSky(LTObject *pObject)
{
uint32 i;
// Is it even in the sky?
if (~pObject->m_InternalFlags & IFLAG_INSKY)
{
return LT_OK;
}
pObject->m_InternalFlags &= ~IFLAG_INSKY;
sm_SetSendSkyDef();
for (i=0; i < MAX_SKYOBJECTS; i++)
{
if (g_pServerMgr->m_SkyObjects[i] == pObject->m_ObjectID)
{
g_pServerMgr->m_SkyObjects[i] = 0xFFFF;
sm_SetSendSkyDef();
return LT_OK;
}
}
return LT_OK;
}
// Get the FileIDInfo for this file id.
FileIDInfo *sm_GetClientFileIDInfo(Client *pClient, uint16 wFileID)
{
HHashElement *hElement;
FileIDInfo *pFileIDInfo = LTNULL;
// See if it's in the hash table.
hElement = hs_FindElement(pClient->m_hFileIDTable, &wFileID, 2);
if (hElement)
{
pFileIDInfo = (FileIDInfo *)hs_GetElementUserData(hElement);
if (pFileIDInfo)
{
return pFileIDInfo;
}
}
// Create a new fileidinfo...
pFileIDInfo = (FileIDInfo *)sb_Allocate_z(&g_pServerMgr->m_FileIDInfoBank);
if (!pFileIDInfo)
return LTNULL;
pFileIDInfo->m_nChangeFlags = FILEIDINFOF_NEWMASK;
// Make a new one...
hElement = hs_AddElement(pClient->m_hFileIDTable, &wFileID, 2);
if (!hElement)
{
dfree(pFileIDInfo);
return LTNULL;
}
// Have the hash table own the pointer...
hs_SetElementUserData(hElement, (void *)pFileIDInfo);
return pFileIDInfo;
}
| [
"robert@velosodigital.com"
] | robert@velosodigital.com |
fbd505969c4ad2581aec7a6a21f6f714d5e57af7 | 1a902df42c2c22c6e66152044e2c75f5549aa399 | /210925 Kakao 2.cpp | c32260823a1ee756420d63160e982e2bf335f680 | [] | no_license | Garrrruii/CodingTests | 8e32ca294c86fd745ca5191cdc91a0330e569ed5 | 6984c4791637e5621600d201a5598545e5e1aea5 | refs/heads/master | 2023-08-13T13:20:23.316669 | 2021-10-17T07:35:12 | 2021-10-17T07:35:12 | 417,817,523 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,753 | cpp | #include <cmath>
#include <vector>
#include <iostream>
using namespace std;
//3^13>1000000 => r(10^13) => 3333333
bool notp[3333334];
vector<long long> prime;
int solution(int n, int k) {
int answer = 0;
long long MAX = 3333333;
notp[0] = notp[1] = true;
for (long long i = 2; i < MAX; ++i) {
if (!notp[i]) {
prime.push_back(i);
for (long long j = i * i; j <= MAX; j += i) notp[j] = true;
}
}
int K = 1;
while (K < n) K *= k;
K /= k;
long long num = 0;
while (K > 1) {
long long q = n / K; n %= K; K /= k;
if (!q) {
//몫 없음 => 소수인지 판정해야 함
cout << num << " ";
if (num <= MAX) {
if (!notp[num]) answer++;
}
else {
bool notprime = false;
long long r = sqrt(num) + 1;
for (int p : prime) {
if (p > r) break;
if (!(num % p)) { notprime = true; break; }
}
if (!notprime) answer++;
}
num = 0;
}
else num *= 10, num += q;
}
if (num) {
//num이 소수인가?
cout << num << " ";
if (num <= MAX) if (!notp[num]) answer++;
else {
bool notprime = false;
long long r = sqrt(num) + 1;
for (int p : prime) {
if (p > r) break;
if (!(num % p)) { notprime = true; break; }
}
if (!notprime) answer++;
}
}
return answer;
}
int main() {
cout << solution(437674, 3)<<"\n";
cout << solution(110011, 10) << "\n";
cout << solution(1679615, 3) << "\n";
} | [
"hishally012@gmail.com"
] | hishally012@gmail.com |
10db409bf306c6e56ce220c10863d185747a3182 | d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3 | /chromium/remoting/host/policy_watcher_unittest.cc | e4a9d30c634ecd20a59b5f518337af7f1d7558fb | [
"BSD-3-Clause"
] | permissive | Csineneo/Vivaldi | 4eaad20fc0ff306ca60b400cd5fad930a9082087 | d92465f71fb8e4345e27bd889532339204b26f1e | refs/heads/master | 2022-11-23T17:11:50.714160 | 2019-05-25T11:45:11 | 2019-05-25T11:45:11 | 144,489,531 | 5 | 4 | BSD-3-Clause | 2022-11-04T05:55:33 | 2018-08-12T18:04:37 | null | UTF-8 | C++ | false | false | 31,331 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/policy_watcher.h"
#include "base/bind.h"
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/mock_log.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "components/policy/core/common/fake_async_policy_loader.h"
#include "components/policy/policy_constants.h"
#include "remoting/host/dns_blackhole_checker.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
namespace key = ::policy::key;
MATCHER_P(IsPolicies, dict, "") {
bool equal = arg->Equals(dict);
if (!equal) {
std::string actual_value;
base::JSONWriter::WriteWithOptions(
*arg, base::JSONWriter::OPTIONS_PRETTY_PRINT, &actual_value);
std::string expected_value;
base::JSONWriter::WriteWithOptions(
*dict, base::JSONWriter::OPTIONS_PRETTY_PRINT, &expected_value);
*result_listener << "Policies are not equal. ";
*result_listener << "Expected policy: " << expected_value << ". ";
*result_listener << "Actual policy: " << actual_value << ".";
}
return equal;
}
class MockPolicyCallback {
public:
MockPolicyCallback() = default;
// TODO(lukasza): gmock cannot mock a method taking std::unique_ptr<T>...
MOCK_METHOD1(OnPolicyUpdatePtr, void(const base::DictionaryValue* policies));
void OnPolicyUpdate(std::unique_ptr<base::DictionaryValue> policies) {
OnPolicyUpdatePtr(policies.get());
}
MOCK_METHOD0(OnPolicyError, void());
private:
DISALLOW_COPY_AND_ASSIGN(MockPolicyCallback);
};
class PolicyWatcherTest : public testing::Test {
public:
PolicyWatcherTest() : message_loop_(base::MessageLoop::TYPE_IO) {}
void SetUp() override {
// We expect no callbacks unless explicitly specified by individual tests.
EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(testing::_)).Times(0);
EXPECT_CALL(mock_policy_callback_, OnPolicyError()).Times(0);
// Retaining a raw pointer to keep control over policy contents.
policy_loader_ =
new policy::FakeAsyncPolicyLoader(base::ThreadTaskRunnerHandle::Get());
policy_watcher_ = PolicyWatcher::CreateFromPolicyLoaderForTesting(
base::WrapUnique(policy_loader_));
base::ListValue host_domain;
host_domain.AppendString(kHostDomain);
base::ListValue client_domain;
client_domain.AppendString(kClientDomain);
base::ListValue multiple_host_domains;
multiple_host_domains.AppendString("a.com");
multiple_host_domains.AppendString("b.com");
multiple_host_domains.AppendString("c.com");
base::ListValue multiple_client_domains;
multiple_client_domains.AppendString("d.com");
multiple_client_domains.AppendString("e.com");
multiple_client_domains.AppendString("f.com");
nat_true_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true);
nat_false_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, false);
nat_one_.SetInteger(key::kRemoteAccessHostFirewallTraversal, 1);
nat_one_domain_full_.SetInteger(key::kRemoteAccessHostFirewallTraversal, 1);
nat_one_domain_full_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
domain_empty_.Set(key::kRemoteAccessHostDomainList,
std::make_unique<base::ListValue>());
domain_full_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
SetDefaults(nat_true_others_default_);
nat_true_others_default_.SetBoolean(key::kRemoteAccessHostFirewallTraversal,
true);
SetDefaults(nat_false_others_default_);
nat_false_others_default_.SetBoolean(
key::kRemoteAccessHostFirewallTraversal, false);
SetDefaults(domain_empty_others_default_);
domain_empty_others_default_.Set(key::kRemoteAccessHostDomainList,
std::make_unique<base::ListValue>());
SetDefaults(domain_full_others_default_);
domain_full_others_default_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
nat_true_domain_empty_.SetBoolean(key::kRemoteAccessHostFirewallTraversal,
true);
nat_true_domain_empty_.Set(key::kRemoteAccessHostDomainList,
std::make_unique<base::ListValue>());
nat_true_domain_full_.SetBoolean(key::kRemoteAccessHostFirewallTraversal,
true);
nat_true_domain_full_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
nat_false_domain_empty_.SetBoolean(key::kRemoteAccessHostFirewallTraversal,
false);
nat_false_domain_empty_.Set(key::kRemoteAccessHostDomainList,
std::make_unique<base::ListValue>());
nat_false_domain_full_.SetBoolean(key::kRemoteAccessHostFirewallTraversal,
false);
nat_false_domain_full_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
SetDefaults(nat_true_domain_empty_others_default_);
nat_true_domain_empty_others_default_.SetBoolean(
key::kRemoteAccessHostFirewallTraversal, true);
nat_true_domain_empty_others_default_.Set(
key::kRemoteAccessHostDomainList, std::make_unique<base::ListValue>());
unknown_policies_.SetString("UnknownPolicyOne", std::string());
unknown_policies_.SetString("UnknownPolicyTwo", std::string());
unknown_policies_.SetBoolean("RemoteAccessHostUnknownPolicyThree", true);
pairing_true_.SetBoolean(key::kRemoteAccessHostAllowClientPairing, true);
pairing_false_.SetBoolean(key::kRemoteAccessHostAllowClientPairing, false);
gnubby_auth_true_.SetBoolean(key::kRemoteAccessHostAllowGnubbyAuth, true);
gnubby_auth_false_.SetBoolean(key::kRemoteAccessHostAllowGnubbyAuth, false);
relay_true_.SetBoolean(key::kRemoteAccessHostAllowRelayedConnection, true);
relay_false_.SetBoolean(key::kRemoteAccessHostAllowRelayedConnection,
false);
port_range_full_.SetString(key::kRemoteAccessHostUdpPortRange, kPortRange);
port_range_empty_.SetString(key::kRemoteAccessHostUdpPortRange,
std::string());
port_range_malformed_.SetString(key::kRemoteAccessHostUdpPortRange,
"malformed");
port_range_malformed_domain_full_.MergeDictionary(&port_range_malformed_);
port_range_malformed_domain_full_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
curtain_true_.SetBoolean(key::kRemoteAccessHostRequireCurtain, true);
curtain_false_.SetBoolean(key::kRemoteAccessHostRequireCurtain, false);
username_true_.SetBoolean(key::kRemoteAccessHostMatchUsername, true);
username_false_.SetBoolean(key::kRemoteAccessHostMatchUsername, false);
talk_gadget_blah_.SetString(key::kRemoteAccessHostTalkGadgetPrefix, "blah");
third_party_auth_partial_.SetString(key::kRemoteAccessHostTokenUrl,
"https://token.com");
third_party_auth_partial_.SetString(
key::kRemoteAccessHostTokenValidationUrl, "https://validation.com");
third_party_auth_full_.MergeDictionary(&third_party_auth_partial_);
third_party_auth_full_.SetString(
key::kRemoteAccessHostTokenValidationCertificateIssuer,
"certificate subject");
third_party_auth_cert_empty_.MergeDictionary(&third_party_auth_partial_);
third_party_auth_cert_empty_.SetString(
key::kRemoteAccessHostTokenValidationCertificateIssuer, "");
remote_assistance_uiaccess_true_.SetBoolean(
key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, true);
remote_assistance_uiaccess_false_.SetBoolean(
key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, false);
deprecated_policies_.SetString(key::kRemoteAccessHostDomain, kHostDomain);
deprecated_policies_.SetString(key::kRemoteAccessHostClientDomain,
kClientDomain);
// Deprecated policies should get converted if new ones aren't present.
SetDefaults(deprecated_policies_expected_);
deprecated_policies_expected_.Set(key::kRemoteAccessHostDomainList,
host_domain.CreateDeepCopy());
deprecated_policies_expected_.Set(key::kRemoteAccessHostClientDomainList,
client_domain.CreateDeepCopy());
deprecated_and_new_policies_.SetString(key::kRemoteAccessHostDomain,
kHostDomain);
deprecated_and_new_policies_.SetString(key::kRemoteAccessHostClientDomain,
kClientDomain);
deprecated_and_new_policies_.Set(key::kRemoteAccessHostDomainList,
multiple_host_domains.CreateDeepCopy());
deprecated_and_new_policies_.Set(key::kRemoteAccessHostClientDomainList,
multiple_client_domains.CreateDeepCopy());
// Deprecated policies should just be dropped in new ones are present.
SetDefaults(deprecated_and_new_policies_expected_);
deprecated_and_new_policies_expected_.Set(
key::kRemoteAccessHostDomainList,
multiple_host_domains.CreateDeepCopy());
deprecated_and_new_policies_expected_.Set(
key::kRemoteAccessHostClientDomainList,
multiple_client_domains.CreateDeepCopy());
// Empty strings should be treated as not set.
deprecated_empty_strings_.SetString(key::kRemoteAccessHostDomain, "");
deprecated_empty_strings_.SetString(key::kRemoteAccessHostClientDomain, "");
}
void TearDown() override {
policy_watcher_.reset();
policy_loader_ = nullptr;
base::RunLoop().RunUntilIdle();
}
protected:
void StartWatching() {
policy_watcher_->StartWatching(
base::Bind(&MockPolicyCallback::OnPolicyUpdate,
base::Unretained(&mock_policy_callback_)),
base::Bind(&MockPolicyCallback::OnPolicyError,
base::Unretained(&mock_policy_callback_)));
base::RunLoop().RunUntilIdle();
}
void SetPolicies(const base::DictionaryValue& dict) {
// Copy |dict| into |policy_bundle|.
policy::PolicyNamespace policy_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string());
policy::PolicyBundle policy_bundle;
policy::PolicyMap& policy_map = policy_bundle.Get(policy_namespace);
policy_map.LoadFrom(&dict, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE,
policy::POLICY_SOURCE_CLOUD);
// Simulate a policy file/registry/preference update.
policy_loader_->SetPolicies(policy_bundle);
policy_loader_->PostReloadOnBackgroundThread(true /* force reload asap */);
base::RunLoop().RunUntilIdle();
}
const policy::Schema* GetPolicySchema() {
return policy_watcher_->GetPolicySchema();
}
// TODO(jamiewalch): Update this to use PolicyWatcher::GetDefaultValues()
const base::DictionaryValue& GetDefaultValues() {
return *(policy_watcher_->default_values_);
}
MOCK_METHOD0(PostPolicyWatcherShutdown, void());
static const char* kHostDomain;
static const char* kClientDomain;
static const char* kPortRange;
base::MessageLoop message_loop_;
MockPolicyCallback mock_policy_callback_;
// |policy_loader_| is owned by |policy_watcher_|. PolicyWatcherTest retains
// a raw pointer to |policy_loader_| in order to control the simulated / faked
// policy contents.
policy::FakeAsyncPolicyLoader* policy_loader_;
std::unique_ptr<PolicyWatcher> policy_watcher_;
base::DictionaryValue empty_;
base::DictionaryValue nat_true_;
base::DictionaryValue nat_false_;
base::DictionaryValue nat_one_;
base::DictionaryValue nat_one_domain_full_;
base::DictionaryValue domain_empty_;
base::DictionaryValue domain_full_;
base::DictionaryValue nat_true_others_default_;
base::DictionaryValue nat_false_others_default_;
base::DictionaryValue domain_empty_others_default_;
base::DictionaryValue domain_full_others_default_;
base::DictionaryValue nat_true_domain_empty_;
base::DictionaryValue nat_true_domain_full_;
base::DictionaryValue nat_false_domain_empty_;
base::DictionaryValue nat_false_domain_full_;
base::DictionaryValue nat_true_domain_empty_others_default_;
base::DictionaryValue unknown_policies_;
base::DictionaryValue pairing_true_;
base::DictionaryValue pairing_false_;
base::DictionaryValue gnubby_auth_true_;
base::DictionaryValue gnubby_auth_false_;
base::DictionaryValue relay_true_;
base::DictionaryValue relay_false_;
base::DictionaryValue port_range_full_;
base::DictionaryValue port_range_empty_;
base::DictionaryValue port_range_malformed_;
base::DictionaryValue port_range_malformed_domain_full_;
base::DictionaryValue curtain_true_;
base::DictionaryValue curtain_false_;
base::DictionaryValue username_true_;
base::DictionaryValue username_false_;
base::DictionaryValue talk_gadget_blah_;
base::DictionaryValue third_party_auth_full_;
base::DictionaryValue third_party_auth_partial_;
base::DictionaryValue third_party_auth_cert_empty_;
base::DictionaryValue remote_assistance_uiaccess_true_;
base::DictionaryValue remote_assistance_uiaccess_false_;
base::DictionaryValue deprecated_policies_;
base::DictionaryValue deprecated_policies_expected_;
base::DictionaryValue deprecated_and_new_policies_;
base::DictionaryValue deprecated_and_new_policies_expected_;
base::DictionaryValue deprecated_empty_strings_;
private:
void SetDefaults(base::DictionaryValue& dict) {
dict.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true);
dict.SetBoolean(key::kRemoteAccessHostAllowRelayedConnection, true);
dict.SetString(key::kRemoteAccessHostUdpPortRange, "");
dict.Set(key::kRemoteAccessHostClientDomainList,
std::make_unique<base::ListValue>());
dict.Set(key::kRemoteAccessHostDomainList,
std::make_unique<base::ListValue>());
dict.SetBoolean(key::kRemoteAccessHostMatchUsername, false);
dict.SetString(key::kRemoteAccessHostTalkGadgetPrefix,
kDefaultHostTalkGadgetPrefix);
dict.SetBoolean(key::kRemoteAccessHostRequireCurtain, false);
dict.SetString(key::kRemoteAccessHostTokenUrl, "");
dict.SetString(key::kRemoteAccessHostTokenValidationUrl, "");
dict.SetString(key::kRemoteAccessHostTokenValidationCertificateIssuer, "");
dict.SetBoolean(key::kRemoteAccessHostAllowClientPairing, true);
dict.SetBoolean(key::kRemoteAccessHostAllowGnubbyAuth, true);
dict.SetBoolean(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance,
false);
#if !defined(OS_CHROMEOS)
dict.SetBoolean(key::kRemoteAccessHostAllowFileTransfer, true);
#endif
ASSERT_THAT(&dict, IsPolicies(&GetDefaultValues()))
<< "Sanity check that defaults expected by the test code "
<< "match what is stored in PolicyWatcher::default_values_";
}
};
const char* PolicyWatcherTest::kHostDomain = "google.com";
const char* PolicyWatcherTest::kClientDomain = "client.com";
const char* PolicyWatcherTest::kPortRange = "12400-12409";
TEST_F(PolicyWatcherTest, None) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
SetPolicies(empty_);
StartWatching();
}
TEST_F(PolicyWatcherTest, NatTrue) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
SetPolicies(nat_true_);
StartWatching();
}
TEST_F(PolicyWatcherTest, NatFalse) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_false_others_default_)));
SetPolicies(nat_false_);
StartWatching();
}
TEST_F(PolicyWatcherTest, NatWrongType) {
EXPECT_CALL(mock_policy_callback_, OnPolicyError());
SetPolicies(nat_one_);
StartWatching();
}
// This test verifies that a mistyped policy value is still detected
// even though it doesn't change during the second SetPolicies call.
TEST_F(PolicyWatcherTest, NatWrongTypeThenIrrelevantChange) {
EXPECT_CALL(mock_policy_callback_, OnPolicyError()).Times(2);
SetPolicies(nat_one_);
StartWatching();
SetPolicies(nat_one_domain_full_);
}
// This test verifies that a malformed policy value is still detected
// even though it doesn't change during the second SetPolicies call.
TEST_F(PolicyWatcherTest, PortRangeMalformedThenIrrelevantChange) {
EXPECT_CALL(mock_policy_callback_, OnPolicyError()).Times(2);
SetPolicies(port_range_malformed_);
StartWatching();
SetPolicies(port_range_malformed_domain_full_);
}
TEST_F(PolicyWatcherTest, DomainEmpty) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&domain_empty_others_default_)));
SetPolicies(domain_empty_);
StartWatching();
}
TEST_F(PolicyWatcherTest, DomainFull) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&domain_full_others_default_)));
SetPolicies(domain_full_);
StartWatching();
}
TEST_F(PolicyWatcherTest, NatNoneThenTrue) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(nat_true_);
}
TEST_F(PolicyWatcherTest, NatNoneThenTrueThenTrue) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(nat_true_);
SetPolicies(nat_true_);
}
TEST_F(PolicyWatcherTest, NatNoneThenTrueThenTrueThenFalse) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_false_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(nat_true_);
SetPolicies(nat_true_);
SetPolicies(nat_false_);
}
TEST_F(PolicyWatcherTest, NatNoneThenFalse) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_false_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(nat_false_);
}
TEST_F(PolicyWatcherTest, NatNoneThenFalseThenTrue) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_false_)));
EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(nat_false_);
SetPolicies(nat_true_);
}
TEST_F(PolicyWatcherTest, ChangeOneRepeatedlyThenTwo) {
testing::InSequence sequence;
EXPECT_CALL(
mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_domain_empty_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&domain_full_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_false_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&domain_empty_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_domain_full_)));
SetPolicies(nat_true_domain_empty_);
StartWatching();
SetPolicies(nat_true_domain_full_);
SetPolicies(nat_false_domain_full_);
SetPolicies(nat_false_domain_empty_);
SetPolicies(nat_true_domain_full_);
}
TEST_F(PolicyWatcherTest, FilterUnknownPolicies) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(unknown_policies_);
SetPolicies(empty_);
}
class MisspelledPolicyTest : public PolicyWatcherTest,
public ::testing::WithParamInterface<const char*> {
};
// Verify that a misspelled policy causes a warning written to the log.
TEST_P(MisspelledPolicyTest, WarningLogged) {
const char* misspelled_policy_name = GetParam();
base::test::MockLog mock_log;
ON_CALL(mock_log, Log(testing::_, testing::_, testing::_, testing::_,
testing::_)).WillByDefault(testing::Return(true));
EXPECT_CALL(mock_log,
Log(logging::LOG_WARNING, testing::_, testing::_, testing::_,
testing::HasSubstr(misspelled_policy_name))).Times(1);
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
base::DictionaryValue misspelled_policies;
misspelled_policies.SetString(misspelled_policy_name, "some test value");
mock_log.StartCapturingLogs();
SetPolicies(misspelled_policies);
StartWatching();
mock_log.StopCapturingLogs();
}
INSTANTIATE_TEST_SUITE_P(
PolicyWatcherTest,
MisspelledPolicyTest,
::testing::Values("RemoteAccessHostDomainX",
"XRemoteAccessHostDomain",
"RemoteAccessHostdomain",
"RemoteAccessHostPolicyForFutureVersion"));
TEST_F(PolicyWatcherTest, PairingFalseThenTrue) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&pairing_false_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&pairing_true_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(pairing_false_);
SetPolicies(pairing_true_);
}
TEST_F(PolicyWatcherTest, GnubbyAuth) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&gnubby_auth_false_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&gnubby_auth_true_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(gnubby_auth_false_);
SetPolicies(gnubby_auth_true_);
}
TEST_F(PolicyWatcherTest, RemoteAssistanceUiAccess) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
#if defined(OS_WIN)
// This setting only affects Windows, it is ignored on other platforms so the
// 2 SetPolicies calls won't result in any calls to OnPolicyUpdate.
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&remote_assistance_uiaccess_true_)));
EXPECT_CALL(
mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&remote_assistance_uiaccess_false_)));
#endif // defined(OS_WIN)
SetPolicies(empty_);
StartWatching();
SetPolicies(remote_assistance_uiaccess_true_);
SetPolicies(remote_assistance_uiaccess_false_);
}
TEST_F(PolicyWatcherTest, Relay) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&relay_false_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&relay_true_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(relay_false_);
SetPolicies(relay_true_);
}
TEST_F(PolicyWatcherTest, Curtain) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&curtain_true_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&curtain_false_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(curtain_true_);
SetPolicies(curtain_false_);
}
TEST_F(PolicyWatcherTest, MatchUsername) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
#if !defined(OS_WIN)
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&username_true_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&username_false_)));
#else
// On Windows the MatchUsername policy is ignored and therefore the 2
// SetPolicies calls won't result in any calls to OnPolicyUpdate.
#endif
SetPolicies(empty_);
StartWatching();
SetPolicies(username_true_);
SetPolicies(username_false_);
}
TEST_F(PolicyWatcherTest, TalkGadgetPrefix) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&talk_gadget_blah_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(talk_gadget_blah_);
}
TEST_F(PolicyWatcherTest, ThirdPartyAuthFull) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&third_party_auth_full_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(third_party_auth_full_);
}
// This test verifies what happens when only 1 out of 3 third-party auth
// policies changes. Without the other 2 policy values such policy values
// combination is invalid (i.e. cannot have TokenUrl without
// TokenValidationUrl) and can trigger OnPolicyError unless PolicyWatcher
// implementation is careful around this scenario.
TEST_F(PolicyWatcherTest, ThirdPartyAuthPartialToFull) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&third_party_auth_cert_empty_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&third_party_auth_full_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(third_party_auth_partial_);
SetPolicies(third_party_auth_full_);
}
TEST_F(PolicyWatcherTest, UdpPortRange) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&port_range_full_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&port_range_empty_)));
SetPolicies(empty_);
StartWatching();
SetPolicies(port_range_full_);
SetPolicies(port_range_empty_);
}
TEST_F(PolicyWatcherTest, PolicySchemaAndPolicyWatcherShouldBeInSync) {
// This test verifies that
// 1) policy schema (generated out of policy_templates.json)
// and
// 2) PolicyWatcher's code (i.e. contents of the |default_values_| field)
// are kept in-sync.
std::map<std::string, base::Value::Type> expected_schema;
for (base::DictionaryValue::Iterator i(GetDefaultValues()); !i.IsAtEnd();
i.Advance()) {
expected_schema[i.key()] = i.value().type();
}
#if defined(OS_WIN)
// RemoteAccessHostMatchUsername is marked in policy_templates.json as not
// supported on Windows and therefore is (by design) excluded from the schema.
expected_schema.erase(key::kRemoteAccessHostMatchUsername);
#else // !defined(OS_WIN)
// RemoteAssistanceHostAllowUiAccess does not exist on non-Windows platforms.
expected_schema.erase(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance);
#endif
std::map<std::string, base::Value::Type> actual_schema;
const policy::Schema* schema = GetPolicySchema();
ASSERT_TRUE(schema->valid());
for (auto it = schema->GetPropertiesIterator(); !it.IsAtEnd(); it.Advance()) {
std::string key = it.key();
if (key.find("RemoteAccessHost") == std::string::npos) {
// For now PolicyWatcher::GetPolicySchema() mixes Chrome and Chromoting
// policies, so we have to skip them here.
continue;
}
if (key == policy::key::kRemoteAccessHostDomain ||
key == policy::key::kRemoteAccessHostClientDomain) {
// These policies are deprecated and get removed during normalization
continue;
}
actual_schema[key] = it.schema().type();
}
EXPECT_THAT(actual_schema, testing::ContainerEq(expected_schema));
}
TEST_F(PolicyWatcherTest, SchemaTypeCheck) {
const policy::Schema* schema = GetPolicySchema();
ASSERT_TRUE(schema->valid());
// Check one, random "string" policy to see if the type propagated correctly
// from policy_templates.json file.
const policy::Schema string_schema =
schema->GetKnownProperty("RemoteAccessHostDomain");
EXPECT_TRUE(string_schema.valid());
EXPECT_EQ(string_schema.type(), base::Value::Type::STRING);
// And check one, random "boolean" policy to see if the type propagated
// correctly from policy_templates.json file.
const policy::Schema boolean_schema =
schema->GetKnownProperty("RemoteAccessHostRequireCurtain");
EXPECT_TRUE(boolean_schema.valid());
EXPECT_EQ(boolean_schema.type(), base::Value::Type::BOOLEAN);
}
TEST_F(PolicyWatcherTest, DeprecatedOnly) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&deprecated_policies_expected_)));
SetPolicies(deprecated_policies_);
StartWatching();
}
TEST_F(PolicyWatcherTest, DeprecatedAndNew) {
EXPECT_CALL(
mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&deprecated_and_new_policies_expected_)));
SetPolicies(deprecated_and_new_policies_);
StartWatching();
}
TEST_F(PolicyWatcherTest, DeprecatedEmpty) {
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&GetDefaultValues())));
SetPolicies(deprecated_empty_strings_);
StartWatching();
}
TEST_F(PolicyWatcherTest, GetCurrentPolicies) {
testing::InSequence sequence;
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_)));
EXPECT_CALL(mock_policy_callback_,
OnPolicyUpdatePtr(IsPolicies(&nat_false_)));
StartWatching();
SetPolicies(nat_false_);
std::unique_ptr<base::DictionaryValue> current_policies =
policy_watcher_->GetCurrentPolicies();
ASSERT_TRUE(*current_policies == nat_false_others_default_);
}
TEST_F(PolicyWatcherTest, GetCurrentPoliciesError) {
EXPECT_CALL(mock_policy_callback_, OnPolicyError());
SetPolicies(nat_one_);
StartWatching();
std::unique_ptr<base::DictionaryValue> current_policies =
policy_watcher_->GetCurrentPolicies();
ASSERT_EQ(0u, current_policies->size());
}
} // namespace remoting
| [
"csineneo@gmail.com"
] | csineneo@gmail.com |
bd797e7e438c351160f1689f1f58a7548fcfea3b | 1d159b3f3f2706afd98a72682e67135f3fd5f04c | /Proj/com.cpp | 4dfb72d50b9947f8d9db812a10384070f0a51f59 | [] | no_license | RabbitChenc/reju_qss | f5d73e6e5f455995234e60fa225c69eb48084011 | ba7c473a7f92a1265166d282fd5a9ab573982d6f | refs/heads/master | 2022-08-30T01:58:14.298158 | 2020-05-22T09:35:54 | 2020-05-22T09:35:54 | 266,072,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 912 | cpp | #include "com.h"
#include <QFile>
#include <QApplication>
com::com()
{
}
void com::setStyle(const QString &style)
{
QFile qss(style);
qss.open(QFile::ReadOnly);
qApp->setStyleSheet(qss.readAll());
qss.close();
}
void com::whiteStyle(void)
{
qApp->setStyleSheet("QWidget#MainWindow {"
"border: 1px solid rgb(r, g, b);"
"background: rgb(232,241,252);"
"}"
"QPushButton{"
"border-image:url(://Image/btn2_normal.png) 10 10 10 10;"
"border: 10px transparent;"
"}"
"QPushButton:pressed{"
" border-image:url(://Image/btn2_pressed.png) 10 10 10 10;"
"border: 10px transparent;"
"}");
}
void com::blackStyle(void)
{
}
| [
"357778342@qq.com"
] | 357778342@qq.com |
97a7248e341caf9ddb5faf7c51930e8822f17199 | 8dc8a23d229897851523d397127cfdb788b60e40 | /serialcomm/fotokite_serialcom/src/CameraControl.h | 5dbc06261a27a793fed0765f7d8a3c268c6cf2a8 | [] | no_license | pranavvaidik/CSCE-635-USV-Track-Behavior | 7e8434f637f4ee95dbcf88c6d536b11b32606ece | 7615e1e1de8863f97b5d287b5ab83d2e6a9be35f | refs/heads/master | 2021-01-23T00:33:55.802201 | 2017-04-27T18:24:35 | 2017-04-27T18:24:35 | 85,738,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,310 | h | /*
Code to control the camera gimbal pitch and fotokite yaw motion.
It takes in 4 inputs. x,y coordinate position of EMILY and rx,ry major and minor axes lengths of the ellipse
The ellipse is assumed to have an origin at the centre (l/2,w/2);
The control used is a simple proportional controller.
*/
#include "serial_communication.h"
#include<math.h>
#include<iostream>
using namespace std;
class cameracontrol
{
int l = 1280; // enter length of the image
int h = 720; // enter height of the image
int x,y,rx,ry
serial_comm test2;
public :
void control(int,int,int,int);
};
void cameracontrol::control(int x, int y, int rx, int ry)
{
//first change coordinate axis to have (0,0) at center;
float r,theta;
x = x - l/2;
y = h/2 - y;
rx = rx - l/2;
ry = ry - h/2;
// get length value of EMILY from centre
r = pow((x*x + y*y),0.5);
theta = atan(y/x);
float k1 = 0.1;
float k2 = 0.1;
float tilt = 0f;
float pan=0f;
float val ;
val = (x*x)/(rx*rx) + (y*y)/(ry*ry);
if (val>1)
{
if (y<0)
{
r = -1*r;
}
if (theta<0)
{
theta = -1*theta;
}
//theta in degrees
float thetad = theta*180/3.14f;
if (thetad<=45 && thetad>=-45)
{
tilt = (1-k1)*theta*0.001;
test2.fotokite_yaw(tilt);
}
else
{
pan = (1-k2)*r*0.001;
test2.gimbal_pitch(pan);
}
}
}
| [
"haresh.miriyala@gmail.com"
] | haresh.miriyala@gmail.com |
7248dc1c60d4e6d3267838f1661251b3a2f4bdb6 | eb996a41bb5dc55e782a3996f50238e4ed7c6ef6 | /sessie_4/main.cpp | 3e6cae2d89fc5f97300506bd92c11643453eb0e4 | [] | no_license | WoutVerschaeren/2018_beeldinterpretatie_Verschaeren_Wout | c1c4034f02d25872291e2c70eefbaf72c717702e | c87f6831fab532c06d478e3138544592e9c7acea | refs/heads/master | 2020-04-02T06:53:40.837256 | 2019-03-31T22:42:14 | 2019-03-31T22:42:14 | 154,173,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,893 | cpp | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
///Detect keypoints in the image
/*
img: the image in which keypoints need to be detected
keypointType: keypoint type: ORB (1), BRISK (2), or AKAZE (3)
*/
vector<KeyPoint> KeyPointDetection(Mat img, int keypointType)
{
/// Detect features using ORB, BRISK, or AKAZE
Ptr<Feature2D> detector;
switch(keypointType)
{
case 1 :
{
Ptr<ORB> detector_ORB = ORB::create();
detector = detector_ORB;
}
break;
case 2 :
{
Ptr<BRISK> detector_BRISK = BRISK::create();
detector = detector_BRISK;
}
break;
case 3 :
{
Ptr<AKAZE> detector_AKAZE = AKAZE::create();
detector = detector_AKAZE;
}
break;
}
//Detect keypoints
vector<KeyPoint> keypointsImg;
detector->detect(img.clone(), keypointsImg);
return keypointsImg;
}
///Calculate descriptors for a given image and its keypoints
/*
img: the image for which descriptors need to be calculated
keypoints: the detected keypoints in the image
keypointType: keypoint type: ORB (1), BRISK (2), or AKAZE (3)
*/
Mat KeyPointDescription(Mat img, vector<KeyPoint> keypoints, int keyPointType)
{
/// Detect features using ORB, BRISK, or AKAZE
Ptr<Feature2D> descriptor;
switch(keyPointType)
{
case 1 :
{
Ptr<ORB> descriptor_ORB = ORB::create();
descriptor = descriptor_ORB;
}
break;
case 2 :
{
Ptr<BRISK> descriptor_BRISK = BRISK::create();
descriptor = descriptor_BRISK;
}
break;
case 3 :
{
Ptr<AKAZE> descriptor_AKAZE = AKAZE::create();
descriptor = descriptor_AKAZE;
}
break;
}
//Detect features and compute their descriptors
vector<KeyPoint> keypointsImg;
Mat descriptorsImg;
//descriptor->detectAndCompute(obj.clone(), Mat(), keypointsObj, descriptorsObj);
descriptor->compute(img.clone(), keypoints, descriptorsImg);
return descriptorsImg;
}
///Detect and draw features using ORB (1), BRISK (2), and AKAZE (3)
/*
obj_loc: location of the template image
img_loc: location of the image itself
keypointType: keypoint type: ORB (1), BRISK (2), or AKAZE (3)
*/
int detectKeypoints(string obj_loc, string img_loc, int keypointType)
{
///Read the object and image
Mat obj = imread(obj_loc);
Mat img = imread(img_loc);
//Check if the images can be found
if ( obj.empty() || img.empty() ){
cerr << "One or more images can't be found.";
return -1;
}
/// Detect features using ORB, BRISK, or AKAZE
string method;
switch(keypointType)
{
case 1 :
method = "ORB";
break;
case 2 :
method = "BRISK";
break;
case 3 :
method = "AKAZE";
break;
}
//Detect keypoints
vector<KeyPoint> keypointsObj, keypointsImg;
keypointsObj = KeyPointDetection(obj.clone(), keypointType);
keypointsImg = KeyPointDetection(img.clone(), keypointType);
//Draw keypoints
Mat img_keypointsObj, img_keypointsImg;
drawKeypoints(obj.clone(), keypointsObj, img_keypointsObj, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
drawKeypoints(img.clone(), keypointsImg, img_keypointsImg, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
/*
string titleT = "Template with keypoints: " + method;
string titleI = "Image with keypoints: " + method;
imshow(titleT, img_keypointsObj); waitKey(0);
imshow(titleI, img_keypointsImg); waitKey(0);
*/
return 0;
}
///Detect features, compute the descriptors and match using ORB (1), BRISK (2), or AKAZE (3)
/*
obj_loc: location of the template image
img_loc: location of the image itself
keypointType: keypoint type: ORB (1), BRISK (2), or AKAZE (3)
homogr: whether or not the function is being used for a homography
name: name of the object (used for titles)
*/
int detectAndMatch(string obj_loc, string img_loc, int keypointType, bool homogr, string name)
{
///Read the object and image
Mat obj = imread(obj_loc);
Mat img = imread(img_loc);
//Check if the images can be found
if ( obj.empty() || img.empty() ){
cerr << "One or more images can't be found.";
return -1;
}
/// Detect features using ORB, BRISK, or AKAZE
string method;
switch(keypointType)
{
case 1 :
method = "ORB";
break;
case 2 :
method = "BRISK";
break;
case 3 :
method = "AKAZE";
break;
}
//Detect keypoints
vector<KeyPoint> keypointsObj, keypointsImg;
keypointsObj = KeyPointDetection(obj.clone(), keypointType);
keypointsImg = KeyPointDetection(img.clone(), keypointType);
//Calculate descriptors using the detected keypoints
Mat descriptorsObj, descriptorsImg;
descriptorsObj = KeyPointDescription(obj.clone(), keypointsObj, keypointType);
descriptorsImg = KeyPointDescription(img.clone(), keypointsImg, keypointType);
///Match the two images using the computed descriptors
//Brute force matching
BFMatcher matcher(NORM_L2);
vector<DMatch> matches;
matcher.match(descriptorsObj, descriptorsImg, matches);
if ( homogr == 1 )
{
double max_dist = 0;
double min_dist = 1000000;
///Quick calculation of max and min distances between keypoints
for( int i = 0; i < matches.size(); i++)
{
double dist = matches[i].distance;
if(dist < min_dist) min_dist = dist;
if(dist > max_dist) max_dist = dist;
}
///Draw only "good" matches (those whose distance is less than 3*min_dist)
vector<DMatch> good_matches;
for(int i = 0; i < matches.size(); i++)
{
if(matches[i].distance <= 3*min_dist)
{
good_matches.push_back(matches[i]);
}
}
//Draw the good matches
Mat img_matches;
drawMatches(obj, keypointsObj, img, keypointsImg, good_matches, img_matches);
//Show the matches
string title = name + ": Good detected matches: " + method;
imshow(title, img_matches); waitKey(0);
///Use RANSAC to calculate a model that represents the transformation between the object and the image
//Keep only the keypoints that had sufficiently low distances
vector<Point2f> objGood;
vector<Point2f> imgGood;
for(int i=0; i < good_matches.size(); i++)
{
objGood.push_back(keypointsObj[good_matches[i].queryIdx].pt);
imgGood.push_back(keypointsImg[good_matches[i].trainIdx].pt);
}
//Calculate homography
Mat H = findHomography(objGood, imgGood, RANSAC);
///Calculate 4 points at the corners of the object, transform them into the axial system of the detected object, draw lines between them
//Find the corners of the object in the object image
vector<Point2f> objCorners(4);
objCorners[0] = cvPoint(0,0);
objCorners[1] = cvPoint(obj.cols, 0 );
objCorners[2] = cvPoint(obj.cols, obj.rows);
objCorners[3] = cvPoint(0, obj.rows);
//Transform the object into the same axial system as the detected object
vector<Point2f> imgCorners(4);
perspectiveTransform(objCorners, imgCorners, H);
//Draw lines between the corner points
//Add the offset because the original object image has been placed to the left of the image, compensate for this
Point2f offset = Point2f(obj.cols, 0);
line(img_matches, ( imgCorners[0] + offset ), ( imgCorners[1] + offset ), Scalar::all(255), 3);
line(img_matches, ( imgCorners[1] + offset ), ( imgCorners[2] + offset ), Scalar::all(255), 3);
line(img_matches, ( imgCorners[2] + offset ), ( imgCorners[3] + offset ), Scalar::all(255), 3);
line(img_matches, ( imgCorners[3] + offset ), ( imgCorners[0] + offset ), Scalar::all(255), 3);
//Show the end result
title = name + ": Final result, using " + method;
imshow(title, img_matches); waitKey(0);
}
else
{
//Draw the matches
Mat img_matches;
drawMatches(obj, keypointsObj, img, keypointsImg, matches, img_matches);
//Show the matches
string title = name + ": All detected matches: " + method;
imshow(title, img_matches); waitKey(0);
}
return 0;
}
int main(int argc, const char** argv)
{
///Adding a little help option and command line parser input
CommandLineParser parser(argc, argv,
"{help h usage ? | | print this message }"
"{kb_obj p1 | | <required> path to the kinderbueno object }"
"{kb_img p2 | | <required> path to the kinderbueno image }"
"{fcf_obj p3| | <required> path to the fitness cornflakes object }"
"{fcf_img p4| | <required> path to the fitness cornflakes image }"
);
if (parser.has("help"))
{
parser.printMessage();
cerr << "TIP: Use absolute paths for the arguments." << endl;
return 0;
}
///Collect data from arguments
string kb_obj_loc(parser.get<string>("kb_obj"));
string kb_img_loc(parser.get<string>("kb_img"));
string fcf_obj_loc(parser.get<string>("fcf_obj"));
string fcf_img_loc(parser.get<string>("fcf_img"));
//Check of de argumenten niet leeg zijn
if ( kb_obj_loc.empty() || kb_img_loc.empty() || fcf_obj_loc.empty() || fcf_img_loc.empty() ){
cerr << "There's something wrong with your arguments." << endl;
parser.printMessage();
return -1;
}
///4.1: KEYPOINT DETECTION
///Detect and draw features using ORB (1), BRISK (2), and AKAZE (3)
detectKeypoints(kb_obj_loc, kb_img_loc, 1);
detectKeypoints(kb_obj_loc, kb_img_loc, 2);
detectKeypoints(kb_obj_loc, kb_img_loc, 3);
///4.2: KEYPOINT DETECTION, DESCRIPTOR COMPUTATION, AND MATCHING
///Detect features, compute the descriptors and match using ORB (1), BRISK (2), or AKAZE (3), don't serach for homography (0)
detectAndMatch(kb_obj_loc, kb_img_loc, 1, 0, "Bueno");
///4.3: ONLY KEEP GOOD MATCHES, CALCULATE HOMOGRAPHY
///Detect features, compute the descriptors match using ORB (1), BRISK (2), or AKAZE (3) and find the homography (1)
detectAndMatch(kb_obj_loc, kb_img_loc, 1, 1, "Bueno");
detectAndMatch(fcf_obj_loc, fcf_img_loc, 1, 1, "Cornflakes");
}
| [
"woutverschaeren@telenet.be"
] | woutverschaeren@telenet.be |
67ba8245ba10b9547b094fb4fc37e26d62787364 | b3710dfdd0eeb3e28d3a4c666af5df6558a03553 | /cgodeps/godot_engine/core/math/geometry_3d.cpp | 2c19fe20858fa050d73ae4775b8b5a27888e6eb9 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"CC-BY-3.0",
"OFL-1.1",
"BSD-3-Clause",
"Bitstream-Vera",
"FTL",
"MPL-2.0",
"Zlib",
"LicenseRef-scancode-nvidia-2002",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CC-BY-4.0"
] | permissive | gabstv/godot-go | 5befd7539ef35a9e459046644dd4b246a0db1ad9 | e0e7f07e1e44716e18330f063c9b3fd3c2468d31 | refs/heads/master | 2021-05-21T23:48:25.434825 | 2020-08-27T16:52:18 | 2020-08-27T16:52:18 | 252,864,512 | 10 | 3 | MIT | 2020-08-27T16:52:20 | 2020-04-03T23:26:52 | C++ | UTF-8 | C++ | false | false | 25,172 | cpp | /*************************************************************************/
/* geometry_3d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "geometry_3d.h"
#include "core/print_string.h"
#include "thirdparty/misc/clipper.hpp"
#include "thirdparty/misc/triangulator.h"
void Geometry3D::MeshData::optimize_vertices() {
Map<int, int> vtx_remap;
for (int i = 0; i < faces.size(); i++) {
for (int j = 0; j < faces[i].indices.size(); j++) {
int idx = faces[i].indices[j];
if (!vtx_remap.has(idx)) {
int ni = vtx_remap.size();
vtx_remap[idx] = ni;
}
faces.write[i].indices.write[j] = vtx_remap[idx];
}
}
for (int i = 0; i < edges.size(); i++) {
int a = edges[i].a;
int b = edges[i].b;
if (!vtx_remap.has(a)) {
int ni = vtx_remap.size();
vtx_remap[a] = ni;
}
if (!vtx_remap.has(b)) {
int ni = vtx_remap.size();
vtx_remap[b] = ni;
}
edges.write[i].a = vtx_remap[a];
edges.write[i].b = vtx_remap[b];
}
Vector<Vector3> new_vertices;
new_vertices.resize(vtx_remap.size());
for (int i = 0; i < vertices.size(); i++) {
if (vtx_remap.has(i)) {
new_vertices.write[vtx_remap[i]] = vertices[i];
}
}
vertices = new_vertices;
}
struct _FaceClassify {
struct _Link {
int face = -1;
int edge = -1;
void clear() {
face = -1;
edge = -1;
}
_Link() {}
};
bool valid = false;
int group = -1;
_Link links[3];
Face3 face;
_FaceClassify() {}
};
static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
// Connect faces, error will occur if an edge is shared between more than 2 faces.
// Clear connections.
bool error = false;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 3; j++) {
p_faces[i].links[j].clear();
}
}
for (int i = 0; i < len; i++) {
if (p_faces[i].group != p_group) {
continue;
}
for (int j = i + 1; j < len; j++) {
if (p_faces[j].group != p_group) {
continue;
}
for (int k = 0; k < 3; k++) {
Vector3 vi1 = p_faces[i].face.vertex[k];
Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
for (int l = 0; l < 3; l++) {
Vector3 vj2 = p_faces[j].face.vertex[l];
Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
if (vi1.distance_to(vj1) < 0.00001 &&
vi2.distance_to(vj2) < 0.00001) {
if (p_faces[i].links[k].face != -1) {
ERR_PRINT("already linked\n");
error = true;
break;
}
if (p_faces[j].links[l].face != -1) {
ERR_PRINT("already linked\n");
error = true;
break;
}
p_faces[i].links[k].face = j;
p_faces[i].links[k].edge = l;
p_faces[j].links[l].face = i;
p_faces[j].links[l].edge = k;
}
}
if (error) {
break;
}
}
if (error) {
break;
}
}
if (error) {
break;
}
}
for (int i = 0; i < len; i++) {
p_faces[i].valid = true;
for (int j = 0; j < 3; j++) {
if (p_faces[i].links[j].face == -1) {
p_faces[i].valid = false;
}
}
}
return error;
}
static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
if (p_faces[p_index].group >= 0) {
return false;
}
p_faces[p_index].group = p_group;
for (int i = 0; i < 3; i++) {
ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
_group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
}
return true;
}
Vector<Vector<Face3>> Geometry3D::separate_objects(Vector<Face3> p_array) {
Vector<Vector<Face3>> objects;
int len = p_array.size();
const Face3 *arrayptr = p_array.ptr();
Vector<_FaceClassify> fc;
fc.resize(len);
_FaceClassify *_fcptr = fc.ptrw();
for (int i = 0; i < len; i++) {
_fcptr[i].face = arrayptr[i];
}
bool error = _connect_faces(_fcptr, len, -1);
ERR_FAIL_COND_V_MSG(error, Vector<Vector<Face3>>(), "Invalid geometry.");
// Group connected faces in separate objects.
int group = 0;
for (int i = 0; i < len; i++) {
if (!_fcptr[i].valid) {
continue;
}
if (_group_face(_fcptr, len, i, group)) {
group++;
}
}
// Group connected faces in separate objects.
for (int i = 0; i < len; i++) {
_fcptr[i].face = arrayptr[i];
}
if (group >= 0) {
objects.resize(group);
Vector<Face3> *group_faces = objects.ptrw();
for (int i = 0; i < len; i++) {
if (!_fcptr[i].valid) {
continue;
}
if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
}
}
}
return objects;
}
/*** GEOMETRY WRAPPER ***/
enum _CellFlags {
_CELL_SOLID = 1,
_CELL_EXTERIOR = 2,
_CELL_STEP_MASK = 0x1C,
_CELL_STEP_NONE = 0 << 2,
_CELL_STEP_Y_POS = 1 << 2,
_CELL_STEP_Y_NEG = 2 << 2,
_CELL_STEP_X_POS = 3 << 2,
_CELL_STEP_X_NEG = 4 << 2,
_CELL_STEP_Z_POS = 5 << 2,
_CELL_STEP_Z_NEG = 6 << 2,
_CELL_STEP_DONE = 7 << 2,
_CELL_PREV_MASK = 0xE0,
_CELL_PREV_NONE = 0 << 5,
_CELL_PREV_Y_POS = 1 << 5,
_CELL_PREV_Y_NEG = 2 << 5,
_CELL_PREV_X_POS = 3 << 5,
_CELL_PREV_X_NEG = 4 << 5,
_CELL_PREV_Z_POS = 5 << 5,
_CELL_PREV_Z_NEG = 6 << 5,
_CELL_PREV_FIRST = 7 << 5,
};
static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, const Vector3 &voxelsize, const Face3 &p_face) {
AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
aabb.position = aabb.position * voxelsize;
aabb.size = aabb.size * voxelsize;
if (!p_face.intersects_aabb(aabb)) {
return;
}
if (len_x == 1 && len_y == 1 && len_z == 1) {
p_cell_status[x][y][z] = _CELL_SOLID;
return;
}
int div_x = len_x > 1 ? 2 : 1;
int div_y = len_y > 1 ? 2 : 1;
int div_z = len_z > 1 ? 2 : 1;
#define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
if (m_div == 1) { \
m_new_v = m_v; \
m_new_len_v = 1; \
} else if (m_i == 0) { \
m_new_v = m_v; \
m_new_len_v = m_len_v / 2; \
} else { \
m_new_v = m_v + m_len_v / 2; \
m_new_len_v = m_len_v - m_len_v / 2; \
}
int new_x;
int new_len_x;
int new_y;
int new_len_y;
int new_z;
int new_len_z;
for (int i = 0; i < div_x; i++) {
_SPLIT(i, div_x, x, len_x, new_x, new_len_x);
for (int j = 0; j < div_y; j++) {
_SPLIT(j, div_y, y, len_y, new_y, new_len_y);
for (int k = 0; k < div_z; k++) {
_SPLIT(k, div_z, z, len_z, new_z, new_len_z);
_plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
}
}
}
}
static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) {
if (p_cell_status[x][y][z] & 3) {
return; // Nothing to do, already used and/or visited.
}
p_cell_status[x][y][z] = _CELL_PREV_FIRST;
while (true) {
uint8_t &c = p_cell_status[x][y][z];
if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
// Haven't been in here, mark as outside.
p_cell_status[x][y][z] |= _CELL_EXTERIOR;
}
if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
// If not done, increase step.
c += 1 << 2;
}
if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
// Go back.
switch (c & _CELL_PREV_MASK) {
case _CELL_PREV_FIRST: {
return;
} break;
case _CELL_PREV_Y_POS: {
y++;
ERR_FAIL_COND(y >= len_y);
} break;
case _CELL_PREV_Y_NEG: {
y--;
ERR_FAIL_COND(y < 0);
} break;
case _CELL_PREV_X_POS: {
x++;
ERR_FAIL_COND(x >= len_x);
} break;
case _CELL_PREV_X_NEG: {
x--;
ERR_FAIL_COND(x < 0);
} break;
case _CELL_PREV_Z_POS: {
z++;
ERR_FAIL_COND(z >= len_z);
} break;
case _CELL_PREV_Z_NEG: {
z--;
ERR_FAIL_COND(z < 0);
} break;
default: {
ERR_FAIL();
}
}
continue;
}
int next_x = x, next_y = y, next_z = z;
uint8_t prev = 0;
switch (c & _CELL_STEP_MASK) {
case _CELL_STEP_Y_POS: {
next_y++;
prev = _CELL_PREV_Y_NEG;
} break;
case _CELL_STEP_Y_NEG: {
next_y--;
prev = _CELL_PREV_Y_POS;
} break;
case _CELL_STEP_X_POS: {
next_x++;
prev = _CELL_PREV_X_NEG;
} break;
case _CELL_STEP_X_NEG: {
next_x--;
prev = _CELL_PREV_X_POS;
} break;
case _CELL_STEP_Z_POS: {
next_z++;
prev = _CELL_PREV_Z_NEG;
} break;
case _CELL_STEP_Z_NEG: {
next_z--;
prev = _CELL_PREV_Z_POS;
} break;
default:
ERR_FAIL();
}
if (next_x < 0 || next_x >= len_x) {
continue;
}
if (next_y < 0 || next_y >= len_y) {
continue;
}
if (next_z < 0 || next_z >= len_z) {
continue;
}
if (p_cell_status[next_x][next_y][next_z] & 3) {
continue;
}
x = next_x;
y = next_y;
z = next_z;
p_cell_status[x][y][z] |= prev;
}
}
static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, Vector<Face3> &p_faces) {
ERR_FAIL_INDEX(x, len_x);
ERR_FAIL_INDEX(y, len_y);
ERR_FAIL_INDEX(z, len_z);
if (p_cell_status[x][y][z] & _CELL_EXTERIOR) {
return;
}
#define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
static const uint8_t indices[6][4] = {
{ 7, 6, 4, 5 },
{ 7, 3, 2, 6 },
{ 7, 5, 1, 3 },
{ 0, 2, 3, 1 },
{ 0, 1, 5, 4 },
{ 0, 4, 6, 2 },
};
for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
bool plot = false;
if (disp_x < 0 || disp_x >= len_x) {
plot = true;
}
if (disp_y < 0 || disp_y >= len_y) {
plot = true;
}
if (disp_z < 0 || disp_z >= len_z) {
plot = true;
}
if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) {
plot = true;
}
if (!plot) {
continue;
}
for (int j = 0; j < 4; j++) {
face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
}
p_faces.push_back(
Face3(
face_points[0],
face_points[1],
face_points[2]));
p_faces.push_back(
Face3(
face_points[2],
face_points[3],
face_points[0]));
}
}
Vector<Face3> Geometry3D::wrap_geometry(Vector<Face3> p_array, real_t *p_error) {
#define _MIN_SIZE 1.0
#define _MAX_LENGTH 20
int face_count = p_array.size();
const Face3 *faces = p_array.ptr();
AABB global_aabb;
for (int i = 0; i < face_count; i++) {
if (i == 0) {
global_aabb = faces[i].get_aabb();
} else {
global_aabb.merge_with(faces[i].get_aabb());
}
}
global_aabb.grow_by(0.01); // Avoid numerical error.
// Determine amount of cells in grid axis.
int div_x, div_y, div_z;
if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) {
div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
} else {
div_x = _MAX_LENGTH;
}
if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH) {
div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
} else {
div_y = _MAX_LENGTH;
}
if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH) {
div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
} else {
div_z = _MAX_LENGTH;
}
Vector3 voxelsize = global_aabb.size;
voxelsize.x /= div_x;
voxelsize.y /= div_y;
voxelsize.z /= div_z;
// Create and initialize cells to zero.
uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
for (int i = 0; i < div_x; i++) {
cell_status[i] = memnew_arr(uint8_t *, div_y);
for (int j = 0; j < div_y; j++) {
cell_status[i][j] = memnew_arr(uint8_t, div_z);
for (int k = 0; k < div_z; k++) {
cell_status[i][j][k] = 0;
}
}
}
// Plot faces into cells.
for (int i = 0; i < face_count; i++) {
Face3 f = faces[i];
for (int j = 0; j < 3; j++) {
f.vertex[j] -= global_aabb.position;
}
_plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
}
// Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
for (int i = 0; i < div_x; i++) {
for (int j = 0; j < div_y; j++) {
_mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
_mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
}
}
for (int i = 0; i < div_z; i++) {
for (int j = 0; j < div_y; j++) {
_mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
_mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
}
}
for (int i = 0; i < div_x; i++) {
for (int j = 0; j < div_z; j++) {
_mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
_mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
}
}
// Build faces for the inside-outside cell divisors.
Vector<Face3> wrapped_faces;
for (int i = 0; i < div_x; i++) {
for (int j = 0; j < div_y; j++) {
for (int k = 0; k < div_z; k++) {
_build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
}
}
}
// Transform face vertices to global coords.
int wrapped_faces_count = wrapped_faces.size();
Face3 *wrapped_faces_ptr = wrapped_faces.ptrw();
for (int i = 0; i < wrapped_faces_count; i++) {
for (int j = 0; j < 3; j++) {
Vector3 &v = wrapped_faces_ptr[i].vertex[j];
v = v * voxelsize;
v += global_aabb.position;
}
}
// clean up grid
for (int i = 0; i < div_x; i++) {
for (int j = 0; j < div_y; j++) {
memdelete_arr(cell_status[i][j]);
}
memdelete_arr(cell_status[i]);
}
memdelete_arr(cell_status);
if (p_error) {
*p_error = voxelsize.length();
}
return wrapped_faces;
}
Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes) {
MeshData mesh;
#define SUBPLANE_SIZE 1024.0
real_t subplane_size = 1024.0; // Should compute this from the actual plane.
for (int i = 0; i < p_planes.size(); i++) {
Plane p = p_planes[i];
Vector3 ref = Vector3(0.0, 1.0, 0.0);
if (ABS(p.normal.dot(ref)) > 0.95) {
ref = Vector3(0.0, 0.0, 1.0); // Change axis.
}
Vector3 right = p.normal.cross(ref).normalized();
Vector3 up = p.normal.cross(right).normalized();
Vector<Vector3> vertices;
Vector3 center = p.center();
// make a quad clockwise
vertices.push_back(center - up * subplane_size + right * subplane_size);
vertices.push_back(center - up * subplane_size - right * subplane_size);
vertices.push_back(center + up * subplane_size - right * subplane_size);
vertices.push_back(center + up * subplane_size + right * subplane_size);
for (int j = 0; j < p_planes.size(); j++) {
if (j == i) {
continue;
}
Vector<Vector3> new_vertices;
Plane clip = p_planes[j];
if (clip.normal.dot(p.normal) > 0.95) {
continue;
}
if (vertices.size() < 3) {
break;
}
for (int k = 0; k < vertices.size(); k++) {
int k_n = (k + 1) % vertices.size();
Vector3 edge0_A = vertices[k];
Vector3 edge1_A = vertices[k_n];
real_t dist0 = clip.distance_to(edge0_A);
real_t dist1 = clip.distance_to(edge1_A);
if (dist0 <= 0) { // Behind plane.
new_vertices.push_back(vertices[k]);
}
// Check for different sides and non coplanar.
if ((dist0 * dist1) < 0) {
// Calculate intersection.
Vector3 rel = edge1_A - edge0_A;
real_t den = clip.normal.dot(rel);
if (Math::is_zero_approx(den)) {
continue; // Point too short.
}
real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
Vector3 inters = edge0_A + rel * dist;
new_vertices.push_back(inters);
}
}
vertices = new_vertices;
}
if (vertices.size() < 3) {
continue;
}
// Result is a clockwise face.
MeshData::Face face;
// Add face indices.
for (int j = 0; j < vertices.size(); j++) {
int idx = -1;
for (int k = 0; k < mesh.vertices.size(); k++) {
if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
idx = k;
break;
}
}
if (idx == -1) {
idx = mesh.vertices.size();
mesh.vertices.push_back(vertices[j]);
}
face.indices.push_back(idx);
}
face.plane = p;
mesh.faces.push_back(face);
// Add edge.
for (int j = 0; j < face.indices.size(); j++) {
int a = face.indices[j];
int b = face.indices[(j + 1) % face.indices.size()];
bool found = false;
for (int k = 0; k < mesh.edges.size(); k++) {
if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
found = true;
break;
}
if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
found = true;
break;
}
}
if (found) {
continue;
}
MeshData::Edge edge;
edge.a = a;
edge.b = b;
mesh.edges.push_back(edge);
}
}
return mesh;
}
Vector<Plane> Geometry3D::build_box_planes(const Vector3 &p_extents) {
Vector<Plane> planes;
planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
return planes;
}
Vector<Plane> Geometry3D::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
Vector<Plane> planes;
for (int i = 0; i < p_sides; i++) {
Vector3 normal;
normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
planes.push_back(Plane(normal, p_radius));
}
Vector3 axis;
axis[p_axis] = 1.0;
planes.push_back(Plane(axis, p_height * 0.5));
planes.push_back(Plane(-axis, p_height * 0.5));
return planes;
}
Vector<Plane> Geometry3D::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
Vector<Plane> planes;
Vector3 axis;
axis[p_axis] = 1.0;
Vector3 axis_neg;
axis_neg[(p_axis + 1) % 3] = 1.0;
axis_neg[(p_axis + 2) % 3] = 1.0;
axis_neg[p_axis] = -1.0;
for (int i = 0; i < p_lons; i++) {
Vector3 normal;
normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
planes.push_back(Plane(normal, p_radius));
for (int j = 1; j <= p_lats; j++) {
// FIXME: This is stupid.
Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
Vector3 pos = angle * p_radius;
planes.push_back(Plane(pos, angle));
planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
}
}
return planes;
}
Vector<Plane> Geometry3D::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
Vector<Plane> planes;
Vector3 axis;
axis[p_axis] = 1.0;
Vector3 axis_neg;
axis_neg[(p_axis + 1) % 3] = 1.0;
axis_neg[(p_axis + 2) % 3] = 1.0;
axis_neg[p_axis] = -1.0;
for (int i = 0; i < p_sides; i++) {
Vector3 normal;
normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
planes.push_back(Plane(normal, p_radius));
for (int j = 1; j <= p_lats; j++) {
Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
planes.push_back(Plane(pos, angle));
planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
}
}
return planes;
}
Vector<Vector3> Geometry3D::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
Vector<Vector3> points;
// Iterate through every unique combination of any three planes.
for (int i = p_plane_count - 1; i >= 0; i--) {
for (int j = i - 1; j >= 0; j--) {
for (int k = j - 1; k >= 0; k--) {
// Find the point where these planes all cross over (if they
// do at all).
Vector3 convex_shape_point;
if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
// See if any *other* plane excludes this point because it's
// on the wrong side.
bool excluded = false;
for (int n = 0; n < p_plane_count; n++) {
if (n != i && n != j && n != k) {
real_t dp = p_planes[n].normal.dot(convex_shape_point);
if (dp - p_planes[n].d > CMP_EPSILON) {
excluded = true;
break;
}
}
}
// Only add the point if it passed all tests.
if (!excluded) {
points.push_back(convex_shape_point);
}
}
}
}
}
return points;
}
#define square(m_s) ((m_s) * (m_s))
#define INF 1e20
/* dt of 1d function using squared distance */
static void edt(float *f, int stride, int n) {
float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
int *v = (int *)&(d[n]);
float *z = (float *)&v[n];
int k = 0;
v[0] = 0;
z[0] = -INF;
z[1] = +INF;
for (int q = 1; q <= n - 1; q++) {
float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
while (s <= z[k]) {
k--;
s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
}
k++;
v[k] = q;
z[k] = s;
z[k + 1] = +INF;
}
k = 0;
for (int q = 0; q <= n - 1; q++) {
while (z[k + 1] < q) {
k++;
}
d[q] = square(q - v[k]) + f[v[k] * stride];
}
for (int i = 0; i < n; i++) {
f[i * stride] = d[i];
}
}
#undef square
Vector<uint32_t> Geometry3D::generate_edf(const Vector<bool> &p_voxels, const Vector3i &p_size, bool p_negative) {
uint32_t float_count = p_size.x * p_size.y * p_size.z;
ERR_FAIL_COND_V((uint32_t)p_voxels.size() != float_count, Vector<uint32_t>());
float *work_memory = memnew_arr(float, float_count);
for (uint32_t i = 0; i < float_count; i++) {
work_memory[i] = INF;
}
uint32_t y_mult = p_size.x;
uint32_t z_mult = y_mult * p_size.y;
//plot solid cells
{
const bool *voxr = p_voxels.ptr();
for (uint32_t i = 0; i < float_count; i++) {
bool plot = voxr[i];
if (p_negative) {
plot = !plot;
}
if (plot) {
work_memory[i] = 0;
}
}
}
//process in each direction
//xy->z
for (int i = 0; i < p_size.x; i++) {
for (int j = 0; j < p_size.y; j++) {
edt(&work_memory[i + j * y_mult], z_mult, p_size.z);
}
}
//xz->y
for (int i = 0; i < p_size.x; i++) {
for (int j = 0; j < p_size.z; j++) {
edt(&work_memory[i + j * z_mult], y_mult, p_size.y);
}
}
//yz->x
for (int i = 0; i < p_size.y; i++) {
for (int j = 0; j < p_size.z; j++) {
edt(&work_memory[i * y_mult + j * z_mult], 1, p_size.x);
}
}
Vector<uint32_t> ret;
ret.resize(float_count);
{
uint32_t *w = ret.ptrw();
for (uint32_t i = 0; i < float_count; i++) {
w[i] = uint32_t(Math::sqrt(work_memory[i]));
}
}
memdelete_arr(work_memory);
return ret;
}
Vector<int8_t> Geometry3D::generate_sdf8(const Vector<uint32_t> &p_positive, const Vector<uint32_t> &p_negative) {
ERR_FAIL_COND_V(p_positive.size() != p_negative.size(), Vector<int8_t>());
Vector<int8_t> sdf8;
int s = p_positive.size();
sdf8.resize(s);
const uint32_t *rpos = p_positive.ptr();
const uint32_t *rneg = p_negative.ptr();
int8_t *wsdf = sdf8.ptrw();
for (int i = 0; i < s; i++) {
int32_t diff = int32_t(rpos[i]) - int32_t(rneg[i]);
wsdf[i] = CLAMP(diff, -128, 127);
}
return sdf8;
}
| [
"gabs@gabs.tv"
] | gabs@gabs.tv |
bcf61a914a57a68c289f7059ff601e89dd571d3f | a9ab72c3dd7fdfe8b6e0b1b5e296bf4c39b9989d | /round3/leetcode289.cpp | c52cffd83dc3b0dc939c8087ced4216c6c0bc5f6 | [] | no_license | keqhe/leetcode | cd82fc3d98b7fc71a9a08c5e438aa1f82737d76f | 86b2a453255c909f94f9ea3be7f2a97a6680a854 | refs/heads/master | 2020-12-24T06:38:15.444432 | 2016-12-07T19:15:02 | 2016-12-07T19:15:02 | 48,405,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,893 | cpp |
class Solution {
public:
//encoding
//0 dead
//1 live
//00->dead to dead
//01->dead to live
//10->live to dead
//11->live to live
//above encoding is not correct, think why?
//[2nd bit, 1st bit] = [next state, current state]
//[1 0] <----- [live, dead]
//[1 1] <------[live, live]
//[0 1] <------[dead, live]
//[0 0] <------[dead, dead]
int count(vector<vector<int>>& board, int x, int y) {
int tmp[8][2] = {{-1,-1},{1,1}, {-1, 1},{1,-1},{-1, 0}, {1, 0}, {0, -1}, {0,1}};
int m = board.size();
int n = board[0].size();
int cnt = 0;
for (auto p : tmp) {
int x2 = p[0] + x;
int y2 = p[1] + y;
if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < n) {
if (board[x2][y2] == 1 || board[x2][y2] == 3)
cnt ++;
}
}
return cnt;
}
void gameOfLife(vector<vector<int>>& board) {
if (board.empty() || board[0].empty())
return;
int m = board.size();
int n = board[0].size();
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
int live_cnt = count(board, i, j);
if (board[i][j] == 0) {
if (live_cnt == 3)
board[i][j] = 2;
}
else if (board[i][j] == 1) {
if (live_cnt < 2)
board[i][j] = 1;
else if (live_cnt == 2 || live_cnt == 3)
board[i][j] = 3;
else if (live_cnt > 3)
board[i][j] = 1;
}
}
}
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
board[i][j] = (board[i][j] >> 1);
}
}
}
};
| [
"keqhe@cs.wisc.edu"
] | keqhe@cs.wisc.edu |
3504fd8bfe7885283044b4d110804d4c5defc8b5 | 56e806230c41e382372709aa080db7582fdd5686 | /Workspace_Zihan_Zhang_Photon_Amazon/DriverProject1/src/MacBookItem.cpp | 5a354eb25efffd58f7d7d7f0ee8d68667dddd9ca | [] | no_license | ZihanZhang/CSYE6205-Concepts-of-Object-Oriented-Design-with-C-plus-plus--Assignments | c6c67cec9d42b5b675b9690abdc7d9a0e14d8141 | 118921915acf176317443c0a8fd5eb987023ca81 | refs/heads/master | 2020-04-12T16:50:10.800131 | 2018-12-20T23:16:02 | 2018-12-20T23:16:02 | 162,625,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | /*
* MacBookItem.cpp
*
* Created on: 2018年11月6日
* Author: zihan
*/
#include "MacBookItem.h"
namespace edu {
namespace neu {
namespace csye6205 {
MacBookItem::MacBookItem() {
// TODO Auto-generated constructor stub
}
MacBookItem::MacBookItem(int id, string name, double price) {
this->id = id;
this->name = name;
this->price = price;
}
MacBookItem::~MacBookItem() {
// TODO Auto-generated destructor stub
}
} /* namespace csye6205 */
} /* namespace neu */
} /* namespace edu */
| [
"zhang.ziha@husky.neu.edu"
] | zhang.ziha@husky.neu.edu |
f87dd401f12fbc4a62a67915e4fbcee82e9b85e7 | 21a199ffdcb328f42bb3871030bd10c1e2990c12 | /dailymission/1회차/1004/1007_8.27_안영선.cpp | 8056b27d0f235a00d6922937f047d4909c1b1892 | [] | no_license | AYoungSn/Algorithm | 3431f63ce5ad7e71339eb669961da396b8fca26c | 45bcb071f9a40cf868e61d58df0c70a41de10cd1 | refs/heads/master | 2020-12-07T11:50:44.737192 | 2020-11-20T07:24:06 | 2020-11-20T07:24:06 | 232,715,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | cpp | #include <iostream>
using namespace std;
const int SIZE = 3;
void sortRows(const double m[][SIZE], double result[][SIZE])
{
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
result[i][j] = m[i][j];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE - 1; j++) {
double currentMin = result[j][i];
int currentMinIndex = j;
for (int k = j + 1; k < SIZE; k++) {
if (currentMin > result[k][i]) {
currentMin = result[k][i];
currentMinIndex = k;
}
}
if (currentMinIndex != j) {
result[currentMinIndex][i] = result[j][i];
result[j][i] = currentMin;
}
}
}
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++)
cout << result[i][j] << " ";
cout << endl;
}
}
int main()
{
double list1[SIZE][SIZE] = { { 0.15, 0.875, 0.375 },{ 0.55, 0.005, 0.225 },{ 0.30, 0.12, 0.4 } };
cout << "Enter a 3 by 3 matrix row by row\n";
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++)
cout << list1[i][j] << " ";
cout << endl;
}
cout << "The row-sorted array is \n";
double list2[SIZE][SIZE];
sortRows(list1, list2);
system("pause");
return 0;
} | [
"dudtjs0920@naver.com"
] | dudtjs0920@naver.com |
f3fccab46903d0372ea70d066ce5c48100879407 | 43490b42ce26995b925ebdcd752e0b6aadfd09c9 | /skia/include/gpu/GrSurface.h | eaba06f5fc68d6d8938fd6421c617f1db215520e | [] | no_license | lineCode/render_skia2 | 010eb67788573307cee4d805cee9121b9fdaab8c | 6ffb52a596a6a1e7f0920ddde570015ffebce5ab | refs/heads/master | 2020-08-01T13:36:46.880346 | 2019-09-25T14:44:51 | 2019-09-25T15:22:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,161 | h | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrSurface_DEFINED
#define GrSurface_DEFINED
#include "include/core/SkImageInfo.h"
#include "include/core/SkRect.h"
#include "include/gpu/GrBackendSurface.h"
#include "include/gpu/GrGpuResource.h"
#include "include/gpu/GrTypes.h"
class GrRenderTarget;
class GrSurfacePriv;
class GrTexture;
class SK_API GrSurface : public GrGpuResource {
public:
/**
* Retrieves the width of the surface.
*/
int width() const { return fWidth; }
/**
* Retrieves the height of the surface.
*/
int height() const { return fHeight; }
/**
* Helper that gets the width and height of the surface as a bounding rectangle.
*/
SkRect getBoundsRect() const { return SkRect::MakeIWH(this->width(), this->height()); }
/**
* Retrieves the pixel config specified when the surface was created.
* For render targets this can be kUnknown_GrPixelConfig
* if client asked us to render to a target that has a pixel
* config that isn't equivalent with one of our configs.
*/
GrPixelConfig config() const { return fConfig; }
virtual GrBackendFormat backendFormat() const = 0;
void setRelease(sk_sp<GrRefCntedCallback> releaseHelper) {
this->onSetRelease(releaseHelper);
fReleaseHelper = std::move(releaseHelper);
}
// These match the definitions in SkImage, from whence they came.
// TODO: Remove Chrome's need to call this on a GrTexture
typedef void* ReleaseCtx;
typedef void (*ReleaseProc)(ReleaseCtx);
void setRelease(ReleaseProc proc, ReleaseCtx ctx) {
sk_sp<GrRefCntedCallback> helper(new GrRefCntedCallback(proc, ctx));
this->setRelease(std::move(helper));
}
/**
* @return the texture associated with the surface, may be null.
*/
virtual GrTexture* asTexture() { return nullptr; }
virtual const GrTexture* asTexture() const { return nullptr; }
/**
* @return the render target underlying this surface, may be null.
*/
virtual GrRenderTarget* asRenderTarget() { return nullptr; }
virtual const GrRenderTarget* asRenderTarget() const { return nullptr; }
/** Access methods that are only to be used within Skia code. */
inline GrSurfacePriv surfacePriv();
inline const GrSurfacePriv surfacePriv() const;
static size_t WorstCaseSize(const GrSurfaceDesc& desc, GrRenderable renderable,
int renderTargetSampleCnt, bool binSize = false);
static size_t ComputeSize(GrPixelConfig config, int width, int height, int colorSamplesPerPixel,
GrMipMapped, bool binSize = false);
/**
* The pixel values of this surface cannot be modified (e.g. doesn't support write pixels or
* MIP map level regen).
*/
bool readOnly() const { return fSurfaceFlags & GrInternalSurfaceFlags::kReadOnly; }
// Returns true if we are working with protected content.
bool isProtected() const { return fIsProtected == GrProtected::kYes; }
protected:
void setGLRTFBOIDIs0() {
SkASSERT(this->asRenderTarget());
fSurfaceFlags |= GrInternalSurfaceFlags::kGLRTFBOIDIs0;
}
bool glRTFBOIDis0() const {
return fSurfaceFlags & GrInternalSurfaceFlags::kGLRTFBOIDIs0;
}
void setReadOnly() {
SkASSERT(!this->asRenderTarget());
fSurfaceFlags |= GrInternalSurfaceFlags::kReadOnly;
}
// Methods made available via GrSurfacePriv
bool hasPendingRead() const;
bool hasPendingWrite() const;
bool hasPendingIO() const;
// Provides access to methods that should be public within Skia code.
friend class GrSurfacePriv;
GrSurface(GrGpu* gpu, const SkISize& size, GrPixelConfig config, GrProtected isProtected)
: INHERITED(gpu)
, fConfig(config)
, fWidth(size.width())
, fHeight(size.height())
, fSurfaceFlags(GrInternalSurfaceFlags::kNone)
, fIsProtected(isProtected) {}
~GrSurface() override {
// check that invokeReleaseProc has been called (if needed)
SkASSERT(!fReleaseHelper);
}
void onRelease() override;
void onAbandon() override;
private:
const char* getResourceType() const override { return "Surface"; }
// Unmanaged backends (e.g. Vulkan) may want to specially handle the release proc in order to
// ensure it isn't called until GPU work related to the resource is completed.
virtual void onSetRelease(sk_sp<GrRefCntedCallback>) {}
void invokeReleaseProc() {
// Depending on the ref count of fReleaseHelper this may or may not actually trigger the
// ReleaseProc to be called.
fReleaseHelper.reset();
}
GrPixelConfig fConfig;
int fWidth;
int fHeight;
GrInternalSurfaceFlags fSurfaceFlags;
GrProtected fIsProtected;
sk_sp<GrRefCntedCallback> fReleaseHelper;
typedef GrGpuResource INHERITED;
};
#endif
| [
"setoutsoft@qq.com"
] | setoutsoft@qq.com |
18339b3fefa74f6c129a30f2b8d277736d4b0274 | 639437a1b2dbb1431940154e10e3f2043f2ea053 | /restaurant.cpp | dc8ab87bb20c5b8a9d532b532f56b6341683b5f0 | [] | no_license | EthanBayer/CashRegister | 7435afe795238e1004df9e0600fc6b4fc29eafc8 | ce061c074c4c1dd37f17c7dca6d49cc18c031a62 | refs/heads/main | 2023-01-28T08:08:23.521083 | 2020-12-11T00:00:48 | 2020-12-11T00:00:48 | 320,419,504 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | #include "include/drivers/headers/Application.hpp"
int main(){
Application app("../files/users.txt", "../files/items.txt");
app.run();
return 0;
} | [
"bayeres1871@gmail.com"
] | bayeres1871@gmail.com |
75e197f58636bfdf54bb84cbda3d87b59619ced4 | 1a543e7112e6a3b49098c2c8f8b1a7f1973a77fe | /Books/C++프로그래밍/Chapter 01/08_NameAlias.cpp | 886e99c0977940322836e99b16b8e060f63f3a48 | [] | no_license | booknu/PS_Relative | d0bc27cbc695511610b83a6f541410f4c13fafd8 | 944964bfed4ae04f38c20b1dfddea1c63f236f82 | refs/heads/master | 2022-06-09T02:22:12.306623 | 2020-05-05T08:35:20 | 2020-05-05T08:35:20 | 198,022,480 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 850 | cpp | ///************
//<주소> : p48
//**********
//<해결방안> :
//
//namespace가 과도하게 중첩 되었을 때, 그것을 또 하나의 namespace로 통일하여 부를 수 있다.
//
//A::B::C::D::func(10) 을 부르는 대신,
//namespace ABCD = A::B::C::D;
//ABCD::func(10) 을 사용 가능
//
//**********
//<오답노트> :
//
//*/
//
//#include <iostream>
//
//using namespace std; // 이렇게 통째로 namespace를 사용하는 것보다, using sdt::cout 과 같이 하나씩 사용하는게 더 좋은 습관
//
//namespace A {
// namespace B {
// namespace C {
// namespace D {
// int num = 10;
// }
// }
// }
//}
//
//int main(void) {
// cout << "num = " << A::B::C::D::num << endl;
//
// namespace ABCD = A::B::C::D; // 하나의 namespace로 통일하여 부를 수 있음!
// cout << "num = " << ABCD::num << endl;
//} | [
"limsydev@gmail.com"
] | limsydev@gmail.com |
42b1786b101a58dd44a225d61711c68797a9d969 | 634b56ebe32a73a4bfaf74e7f454b9718abdfd25 | /include/topic_tools/DemuxDeleteRequest.h | 7fd73afa2e417bf26c954335b0f599cc0c8ee702 | [] | no_license | uas-at-ucla-dependencies/ros_bazel | dbc9fd422fac1f0aa319eafa4cbb1ebab7a0a0e2 | 9435753c27f9f3c5fa5790e5fa3da382259fda2f | refs/heads/master | 2020-07-09T17:44:31.517810 | 2019-05-29T22:32:34 | 2019-05-29T22:32:34 | 204,037,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,270 | h | // Generated by gencpp from file topic_tools/DemuxDeleteRequest.msg
// DO NOT EDIT!
#ifndef TOPIC_TOOLS_MESSAGE_DEMUXDELETEREQUEST_H
#define TOPIC_TOOLS_MESSAGE_DEMUXDELETEREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace topic_tools
{
template <class ContainerAllocator>
struct DemuxDeleteRequest_
{
typedef DemuxDeleteRequest_<ContainerAllocator> Type;
DemuxDeleteRequest_()
: topic() {
}
DemuxDeleteRequest_(const ContainerAllocator& _alloc)
: topic(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _topic_type;
_topic_type topic;
typedef boost::shared_ptr< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> const> ConstPtr;
}; // struct DemuxDeleteRequest_
typedef ::topic_tools::DemuxDeleteRequest_<std::allocator<void> > DemuxDeleteRequest;
typedef boost::shared_ptr< ::topic_tools::DemuxDeleteRequest > DemuxDeleteRequestPtr;
typedef boost::shared_ptr< ::topic_tools::DemuxDeleteRequest const> DemuxDeleteRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace topic_tools
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/home/comran/Code/ros_lunar_amd64/install_isolated/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
{
static const char* value()
{
return "d8f94bae31b356b24d0427f80426d0c3";
}
static const char* value(const ::topic_tools::DemuxDeleteRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd8f94bae31b356b2ULL;
static const uint64_t static_value2 = 0x4d0427f80426d0c3ULL;
};
template<class ContainerAllocator>
struct DataType< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
{
static const char* value()
{
return "topic_tools/DemuxDeleteRequest";
}
static const char* value(const ::topic_tools::DemuxDeleteRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
{
static const char* value()
{
return "string topic\n\
";
}
static const char* value(const ::topic_tools::DemuxDeleteRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.topic);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct DemuxDeleteRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::topic_tools::DemuxDeleteRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::topic_tools::DemuxDeleteRequest_<ContainerAllocator>& v)
{
s << indent << "topic: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.topic);
}
};
} // namespace message_operations
} // namespace ros
#endif // TOPIC_TOOLS_MESSAGE_DEMUXDELETEREQUEST_H
| [
"comranmorsh@gmail.com"
] | comranmorsh@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.