answer
stringlengths
15
1.25M
#include <ctime> #include <parallel/pthread_tools.hpp> #include <unity/lib/gl_sarray.hpp> #include <unity/lib/gl_sframe.hpp> #include <unity/lib/unity_sarray.hpp> #include <sframe/sarray.hpp> #include <sframe/sarray_reader.hpp> #include <sframe/<API key>.hpp> #include <unity/lib/image_util.hpp> #include <sframe_query_engine/planning/planner.hpp> namespace graphlab { static graphlab::mutex <API key>; /** * Given an array of flexible_type of mixed type, find the common base type * among all of them that I can use to represent the entire array. * Fails if no such type exists. */ flex_type_enum infer_type_of_list(const std::vector<flexible_type>& vec) { std::set<flex_type_enum> types; // Since most of the types we encountered are likely to be the same, // as an optimization only add new ones to the set and ignore the // previous type. flex_type_enum last_type = flex_type_enum::UNDEFINED; for (const flexible_type& val: vec) { if(val.get_type() != last_type && val.get_type() != flex_type_enum::UNDEFINED) { types.insert(val.get_type()); last_type = val.get_type(); } } try { return get_common_type(types); } catch(std::string &e) { throw std::string("Cannot infer Array type. Not all elements of array are the same type."); } } /** * Utility function to throw an error if a vector is of unequal length. * \param[in] gl_sarray of type vector */ void <API key>(const gl_sarray& in) { // Initialize. DASSERT_TRUE(in.dtype() == flex_type_enum::VECTOR); size_t n_threads = thread::cpu_count(); n_threads = std::max(n_threads, size_t(1)); size_t m_size = in.size(); // Throw the following error. auto throw_error = [] (size_t row_number, size_t expected, size_t current) { std::stringstream ss; ss << "Vectors must be of the same size. Row " << row_number << " contains a vector of size " << current << ". Expected a vector of" << " size " << expected << "." << std::endl; log_and_throw(ss.str()); }; // Within each block of the SArray, check that the vectors have the same size. std::vector<size_t> expected_sizes (n_threads, size_t(-1)); in_parallel([&](size_t thread_idx, size_t n_threads) { size_t start_row = thread_idx * m_size / n_threads; size_t end_row = (thread_idx + 1) * m_size / n_threads; size_t expected_size = size_t(-1); size_t row_number = start_row; for (const auto& v: in.range_iterator(start_row, end_row)) { if (v != FLEX_UNDEFINED) { if (expected_size == size_t(-1)) { expected_size = v.size(); expected_sizes[thread_idx] = expected_size; } else { DASSERT_TRUE(v.get_type() == flex_type_enum::VECTOR); if (expected_size != v.size()) { throw_error(row_number, expected_size, v.size()); } } } row_number++; } }); // Make sure sizes accross blocks are also the same. size_t vector_size = size_t(-1); for (size_t thread_idx = 0; thread_idx < n_threads; thread_idx++) { // If this block contains all None values, skip it. if (expected_sizes[thread_idx] != size_t(-1)) { if (vector_size == size_t(-1)) { vector_size = expected_sizes[thread_idx]; } else { if (expected_sizes[thread_idx] != vector_size) { throw_error(thread_idx * m_size / n_threads, vector_size, expected_sizes[thread_idx]); } } } } } /* gl_sarray Constructors */ gl_sarray::gl_sarray() { instantiate_new(); } gl_sarray::gl_sarray(const gl_sarray& other) { m_sarray = other.get_proxy(); } gl_sarray::gl_sarray(gl_sarray&& other) { m_sarray = std::move(other.get_proxy()); } gl_sarray::gl_sarray(const std::string& directory) { instantiate_new(); m_sarray-><API key>(directory); } gl_sarray& gl_sarray::operator=(const gl_sarray& other) { m_sarray = other.get_proxy(); return *this; } gl_sarray& gl_sarray::operator=(gl_sarray&& other) { m_sarray = std::move(other.get_proxy()); return *this; } std::shared_ptr<unity_sarray> gl_sarray::get_proxy() const { return m_sarray; } gl_sarray::gl_sarray(const std::vector<flexible_type>& values, flex_type_enum dtype) { if (dtype == flex_type_enum::UNDEFINED) dtype = infer_type_of_list(values); instantiate_new(); get_proxy()-><API key>(values, dtype); } void gl_sarray::<API key>(const std::vector<flexible_type>& values, flex_type_enum dtype) { if (dtype == flex_type_enum::UNDEFINED) dtype = infer_type_of_list(values); get_proxy()-><API key>(values, dtype); } gl_sarray::gl_sarray(const std::initializer_list<flexible_type>& values) { flex_type_enum dtype = infer_type_of_list(values); instantiate_new(); get_proxy()-><API key>(values, dtype); } gl_sarray gl_sarray::from_const(const flexible_type& value, size_t size) { gl_sarray ret; ret.get_proxy()-><API key>(value, size); return ret; } gl_sarray gl_sarray::from_sequence(size_t start, size_t end, bool reverse) { if (end < start) throw std::string("End must be greater than start"); return unity_sarray::<API key>(end - start, start, reverse); } gl_sarray gl_sarray::from_avro(const std::string& directory) { gl_sarray ret; ret.get_proxy()->construct_from_avro(directory); return ret; } /* gl_sarray Implicit Type Converters */ gl_sarray::gl_sarray(std::shared_ptr<unity_sarray> sarray) { m_sarray = sarray; } gl_sarray::gl_sarray(std::shared_ptr<unity_sarray_base> sarray) { m_sarray = std::<API key><unity_sarray>(sarray); } gl_sarray::gl_sarray(std::shared_ptr<sarray<flexible_type> > sa) : m_sarray(new unity_sarray) { m_sarray-><API key>(sa); } gl_sarray::operator std::shared_ptr<unity_sarray>() const { return get_proxy(); } gl_sarray::operator std::shared_ptr<unity_sarray_base>() const { return get_proxy(); } std::shared_ptr<sarray<flexible_type> > gl_sarray::<API key>() const { return get_proxy()-><API key>(); } /* gl_sarray Operator Overloads */ #define DEFINE_OP(OP)\ gl_sarray gl_sarray::operator OP(const gl_sarray& other) const { \ return get_proxy()->vector_operator(other.get_proxy(), } \ gl_sarray gl_sarray::operator OP(const flexible_type& other) const { \ return get_proxy()-><API key>(other, } \ gl_sarray operator OP(const flexible_type& opnd, const gl_sarray& opnd2) { \ return opnd2.get_proxy()-><API key>(opnd, }\ gl_sarray gl_sarray::operator OP ## =(const gl_sarray& other) { \ (*this) = get_proxy()->vector_operator(other.get_proxy(), return *this; \ } \ gl_sarray gl_sarray::operator OP ## =(const flexible_type& other) { \ (*this) = get_proxy()-><API key>(other, return *this; \ } DEFINE_OP(+) DEFINE_OP(-) DEFINE_OP(*) DEFINE_OP(/) #undef DEFINE_OP #define DEFINE_COMPARE_OP(OP) \ gl_sarray gl_sarray::operator OP(const gl_sarray& other) const { \ return get_proxy()->vector_operator(other.get_proxy(), } \ gl_sarray gl_sarray::operator OP(const flexible_type& other) const { \ return get_proxy()-><API key>(other, } DEFINE_COMPARE_OP(<) DEFINE_COMPARE_OP(>) DEFINE_COMPARE_OP(<=) DEFINE_COMPARE_OP(>=) DEFINE_COMPARE_OP(==) #undef DEFINE_COMPARE_OP gl_sarray gl_sarray::operator&(const gl_sarray& other) const { return get_proxy()->vector_operator(other.get_proxy(), "&"); } gl_sarray gl_sarray::operator|(const gl_sarray& other) const { return get_proxy()->vector_operator(other.get_proxy(), "|"); } gl_sarray gl_sarray::operator&&(const gl_sarray& other) const { return get_proxy()->vector_operator(other.get_proxy(), "&"); } gl_sarray gl_sarray::operator||(const gl_sarray& other) const { return get_proxy()->vector_operator(other.get_proxy(), "|"); } gl_sarray gl_sarray::contains(const flexible_type& other) const { return get_proxy()-><API key>(other, "in"); } flexible_type gl_sarray::operator[](int64_t i) const { if (i < 0 || (size_t)i >= get_proxy()->size()) { throw std::string("Index out of range"); } <API key>(); std::vector<flexible_type> rows(1); size_t rows_read = m_sarray_reader->read_rows(i, i + 1, rows); ASSERT_TRUE(rows.size() > 0); ASSERT_EQ(rows_read, 1); return rows[0]; } gl_sarray gl_sarray::operator[](const gl_sarray& slice) const { return get_proxy()->logical_filter(slice.get_proxy()); } gl_sarray gl_sarray::operator[](const std::initializer_list<int64_t>& _slice) const { std::vector<int64_t> slice(_slice); int64_t start = 0, step = 1, stop = 0; if (slice.size() == 2) { start = slice[0]; stop = slice[1]; } else if (slice.size() == 3) { start = slice[0]; step = slice[1]; stop = slice[2]; } else { throw std::string("Invalid slice. Slice must be of the form {start, end} or {start, step, end}"); } if (start < 0) start = size() + start; if (stop < 0) stop = size() + stop; return get_proxy()->copy_range(start, step, stop); } /* Iterators */ void gl_sarray::<API key>( std::function<bool(size_t, const std::shared_ptr<sframe_rows>&)> callback, size_t nthreads) { if (nthreads == (size_t)(-1)) nthreads = <API key>; graphlab::query_eval::planner().materialize(get_proxy()->get_planner_node(), callback, nthreads); } gl_sarray_range gl_sarray::range_iterator(size_t start, size_t end) const { if (end == (size_t)(-1)) end = get_proxy()->size(); if (start > end) { throw std::string("start must be less than end"); } // basic range check. start must point to existing element, end can point // to one past the end. // but additionally, we need to permit the special case start == end == 0 // so that you can iterate over empty frames. if (!((start < get_proxy()->size() && end <= get_proxy()->size()) || (start == 0 && end == 0))) { throw std::string("Index out of range"); } <API key>(); return gl_sarray_range(m_sarray_reader, start, end); } /* All Other Functions */ void gl_sarray::save(const std::string& directory, const std::string& format) const { if (format == "binary") { get_proxy()->save_array(directory); } else if (format == "text" || format == "csv") { gl_sframe sf; sf["X1"] = (*this); sf.save(directory, "csv"); } else { throw std::string("Unknown format"); } } size_t gl_sarray::size() const { return get_proxy()->size(); } bool gl_sarray::empty() const { return size() == 0; } flex_type_enum gl_sarray::dtype() const { return get_proxy()->dtype(); } void gl_sarray::materialize() { get_proxy()->materialize(); } bool gl_sarray::is_materialized() const { return get_proxy()->is_materialized(); } gl_sarray gl_sarray::head(size_t n) const { return get_proxy()->head(n); } gl_sarray gl_sarray::tail(size_t n) const { return get_proxy()->tail(n); } gl_sarray gl_sarray::count_words(bool to_lower, graphlab::flex_list delimiters) const { return get_proxy()->count_bag_of_words({{"to_lower",to_lower}, {"delimiters",delimiters}}); } gl_sarray gl_sarray::count_ngrams(size_t n, std::string method, bool to_lower, bool ignore_space) const { if (method == "word") { return get_proxy()->count_ngrams(n, {{"to_lower",to_lower}, {"ignore_space",ignore_space}}); } else if (method == "character") { return get_proxy()-><API key>(n, {{"to_lower",to_lower}, {"ignore_space",ignore_space}}); } else { throw std::string("Invalid 'method' input value. Please input either 'word' or 'character' "); <API key>(); } } gl_sarray gl_sarray::dict_trim_by_keys(const std::vector<flexible_type>& keys, bool exclude) const { return get_proxy()->dict_trim_by_keys(keys, exclude); } gl_sarray gl_sarray::dict_trim_by_values(const flexible_type& lower, const flexible_type& upper) const { return get_proxy()->dict_trim_by_values(lower, upper); } gl_sarray gl_sarray::dict_keys() const { return get_proxy()->dict_keys(); } gl_sarray gl_sarray::dict_values() const { return get_proxy()->dict_values(); } gl_sarray gl_sarray::dict_has_any_keys(const std::vector<flexible_type>& keys) const { return get_proxy()->dict_has_any_keys(keys); } gl_sarray gl_sarray::dict_has_all_keys(const std::vector<flexible_type>& keys) const { return get_proxy()->dict_has_all_keys(keys); } gl_sarray gl_sarray::apply(std::function<flexible_type(const flexible_type&)> fn, flex_type_enum dtype, bool skip_undefined) const { return get_proxy()->transform_lambda(fn, dtype, skip_undefined, time(NULL)); } gl_sarray gl_sarray::filter(std::function<bool(const flexible_type&)> fn, bool skip_undefined) const { return (*this)[apply([fn](const flexible_type& arg)->flexible_type { return fn(arg); }, flex_type_enum::INTEGER, skip_undefined)]; } gl_sarray gl_sarray::sample(double fraction) const { return get_proxy()->sample(fraction, time(NULL)); } gl_sarray gl_sarray::sample(double fraction, size_t seed) const { return get_proxy()->sample(fraction, seed); } bool gl_sarray::all() const { return get_proxy()->all(); } bool gl_sarray::any() const { return get_proxy()->any(); } flexible_type gl_sarray::max() const { return get_proxy()->max(); } flexible_type gl_sarray::min() const { return get_proxy()->min(); } flexible_type gl_sarray::sum() const { return get_proxy()->sum(); } flexible_type gl_sarray::mean() const { return get_proxy()->mean(); } flexible_type gl_sarray::std() const { return get_proxy()->std(); } size_t gl_sarray::nnz() const { return get_proxy()->nnz(); } size_t gl_sarray::num_missing() const { return get_proxy()->num_missing(); } gl_sarray gl_sarray::datetime_to_str(const std::string& str_format) const { return get_proxy()->datetime_to_str(str_format); } gl_sarray gl_sarray::str_to_datetime(const std::string& str_format) const { return get_proxy()->str_to_datetime(str_format); } gl_sarray gl_sarray::<API key>(size_t width, size_t height, size_t channels, bool <API key>) const { return image_util:: <API key>( std::<API key><unity_sarray>(get_proxy()), width, height, channels, <API key>); } gl_sarray gl_sarray::astype(flex_type_enum dtype, bool <API key>) const { return get_proxy()->astype(dtype, <API key>); } gl_sarray gl_sarray::clip(flexible_type lower, flexible_type upper) const { if (lower == FLEX_UNDEFINED) lower = NAN; if (upper == FLEX_UNDEFINED) upper = NAN; return get_proxy()->clip(lower, upper); } gl_sarray gl_sarray::clip_lower(flexible_type threshold) const { return get_proxy()->clip(threshold, NAN); } gl_sarray gl_sarray::clip_upper(flexible_type threshold) const { return get_proxy()->clip(NAN, threshold); } gl_sarray gl_sarray::dropna() const { return get_proxy()->drop_missing_values(); } gl_sarray gl_sarray::fillna(flexible_type value) const { return get_proxy()->fill_missing_values(value); } gl_sarray gl_sarray::topk_index(size_t topk, bool reverse) const { return get_proxy()->topk_index(topk, reverse); } gl_sarray gl_sarray::append(const gl_sarray& other) const { return get_proxy()->append(other.get_proxy()); } gl_sarray gl_sarray::unique() const { gl_sframe sf({{"a",(*this)}}); sf = sf.groupby({"a"}); return sf.select_column("a"); } gl_sarray gl_sarray::item_length() const { return get_proxy()->item_length(); } gl_sframe gl_sarray::split_datetime(const std::string& column_name_prefix, const std::vector<std::string>& _limit, bool tzone) const { std::vector<std::string> limit = _limit; if (tzone && std::find(limit.begin(), limit.end(), "tzone") == limit.end()) { limit.push_back("tzone"); } std::map<std::string, flex_type_enum> default_types{ {"year", flex_type_enum::INTEGER}, {"month", flex_type_enum::INTEGER}, {"day", flex_type_enum::INTEGER}, {"hour", flex_type_enum::INTEGER}, {"minute", flex_type_enum::INTEGER}, {"second", flex_type_enum::INTEGER}, {"tzone", flex_type_enum::FLOAT}}; std::vector<flex_type_enum> column_types(limit.size()); for (size_t i = 0;i < limit.size(); ++i) { if (default_types.count(limit[i]) == 0) { throw std::string("Unrecognized date time limit specifier"); } else { column_types[i] = default_types[limit[i]]; } } std::vector<flexible_type> flex_limit(limit.begin(), limit.end()); return get_proxy()->expand(column_name_prefix, flex_limit, column_types); } gl_sframe gl_sarray::unpack(const std::string& column_name_prefix, const std::vector<flex_type_enum>& _column_types, const flexible_type& na_value, const std::vector<flexible_type>& _limit) const { auto column_types = _column_types; auto limit = _limit; if (dtype() != flex_type_enum::DICT && dtype() != flex_type_enum::LIST && dtype() != flex_type_enum::VECTOR) { throw std::string("Only SArray of dict/list/array type supports unpack"); } if (limit.size() > 0) { std::set<flex_type_enum> limit_types; for (const flexible_type& l : limit) limit_types.insert(l.get_type()); if (limit_types.size() != 1) { throw std::string("\'limit\' contains values that are different types"); } if (dtype() != flex_type_enum::DICT && *(limit_types.begin()) != flex_type_enum::INTEGER) { throw std::string("\'limit\' must contain integer values."); } if (std::set<flexible_type>(limit.begin(), limit.end()).size() != limit.size()) { throw std::string("\'limit\' contains duplicate values."); } } if (column_types.size() > 0) { if (limit.size() > 0) { if (limit.size() != column_types.size()) { throw std::string("limit and column_types do not have the same length"); } } else if (dtype() == flex_type_enum::DICT) { throw std::string("if 'column_types' is given, 'limit' has to be provided to unpack dict type."); } else { limit.reserve(column_types.size()); for (size_t i = 0;i < column_types.size(); ++i) limit.push_back(i); } } else { auto head_rows = head(100).dropna(); std::vector<size_t> lengths(head_rows.size()); for (size_t i = 0;i < head_rows.size(); ++i) lengths[i] = head_rows[i].size(); if (lengths.size() == 0 || *std::max_element(lengths.begin(), lengths.end()) == 0) { throw std::string("Cannot infer number of items from the SArray, " "SArray may be empty. please explicitly provide column types"); } if (dtype() != flex_type_enum::DICT) { size_t length = *std::max_element(lengths.begin(), lengths.end()); if (limit.size() == 0) { limit.resize(length); for (size_t i = 0;i < length; ++i) limit[i] = i; } else { length = limit.size(); } if (dtype() == flex_type_enum::VECTOR) { column_types.resize(length, flex_type_enum::FLOAT); } else { column_types.clear(); for(const auto& i : limit) { std::vector<flexible_type> f; for (size_t j = 0;j < head_rows.size(); ++j) { auto x = head_rows[j]; if (x != flex_type_enum::UNDEFINED && x.size() > i) { f.push_back(x.array_at(i)); } } column_types.push_back(infer_type_of_list(f)); } } } } if (dtype() == flex_type_enum::DICT && column_types.size() == 0) { return get_proxy()->unpack_dict(column_name_prefix, limit, na_value); } else { return get_proxy()->unpack(column_name_prefix, limit, column_types, na_value); } } gl_sarray gl_sarray::sort(bool ascending) const { gl_sframe sf({{"a",(*this)}}); sf = sf.sort("a", ascending); return sf.select_column("a"); } gl_sarray gl_sarray::subslice(flexible_type start, flexible_type stop, flexible_type step) { auto dt = dtype(); if (dt != flex_type_enum::STRING && dt != flex_type_enum::VECTOR && dt != flex_type_enum::LIST) { log_and_throw("SArray must contain strings, arrays or lists"); } return get_proxy()->subslice(start, step, stop); } gl_sarray gl_sarray::<API key>(const std::string &fn_name, ssize_t start, ssize_t end, size_t min_observations) const { return get_proxy()-><API key>(fn_name, start, end, min_observations); } gl_sarray gl_sarray::<API key>( std::shared_ptr<<API key>> aggregator) const { flex_type_enum input_type = this->dtype(); flex_type_enum output_type = aggregator->set_input_types({input_type}); if (! aggregator->support_type(input_type)) { std::stringstream ss; ss << "Cannot perform this operation on an SArray of type " << <API key>(input_type) << "." << std::endl; log_and_throw(ss.str()); } // Empty case. size_t m_size = this->size(); if (m_size == 0) { return gl_sarray({}, output_type); } // Make a copy of an newly initialize aggregate for each thread. size_t n_threads = thread::cpu_count(); gl_sarray_writer writer(output_type, n_threads); std::vector<std::shared_ptr<<API key>>> aggregators; for (size_t i = 0; i < n_threads; i++) { aggregators.push_back( std::shared_ptr<<API key>>(aggregator->new_instance())); } // Skip Phases 1,2 when single threaded or more threads than rows. if ((n_threads > 1) && (m_size > n_threads)) { // Phase 1: Compute prefix-sums for each block. in_parallel([&](size_t thread_idx, size_t n_threads) { size_t start_row = thread_idx * m_size / n_threads; size_t end_row = (thread_idx + 1) * m_size / n_threads; for (const auto& v: this->range_iterator(start_row, end_row)) { DASSERT_TRUE(thread_idx < aggregators.size()); if (v != FLEX_UNDEFINED) { aggregators[thread_idx]->add_element_simple(v); } } }); // Phase 2: Combine prefix-sum(s) at the end of each block. for (size_t i = n_threads - 1; i > 0; i for (size_t j = 0; j < i; j++) { DASSERT_TRUE(i < aggregators.size()); DASSERT_TRUE(j < aggregators.size()); aggregators[i]->combine(*aggregators[j]); } } } // Phase 3: Reaggregate with an re-intialized prefix-sum from previous blocks. auto reagg_fn = [&](size_t thread_idx, size_t n_threads) { flexible_type y = FLEX_UNDEFINED; size_t start_row = thread_idx * m_size / n_threads; size_t end_row = (thread_idx + 1) * m_size / n_threads; std::shared_ptr<<API key>> re_aggregator ( aggregator->new_instance()); // Initialize with the merged value. if (thread_idx >= 1) { DASSERT_TRUE(thread_idx - 1 < aggregators.size()); y = aggregators[thread_idx - 1]->emit(); re_aggregator->combine(*aggregators[thread_idx - 1]); } // Write prefix-sum for (const auto& v: this->range_iterator(start_row, end_row)) { if (v != FLEX_UNDEFINED) { re_aggregator->add_element_simple(v); y = re_aggregator->emit(); } writer.write(y, thread_idx); } }; // Run single threaded if more threads than rows. if (m_size > n_threads) { in_parallel(reagg_fn); } else { reagg_fn(0, 1); } return writer.close(); } gl_sarray gl_sarray::<API key>(const std::string& name) const { flex_type_enum input_type = this->dtype(); std::shared_ptr<<API key>> aggregator; // Cumulative sum, and avg support vector types. if (name == "<API key>") { switch(input_type) { case flex_type_enum::VECTOR: { <API key>(*this); aggregator = <API key>(std::string("<API key>")); break; } default: aggregator = <API key>(std::string("__builtin__sum__")); break; } } else if (name == "<API key>") { switch(input_type) { case flex_type_enum::VECTOR: { <API key>(*this); aggregator = <API key>(std::string("<API key>")); break; } default: aggregator = <API key>(std::string("__builtin__avg__")); break; } } else if (name == "<API key>") { aggregator = <API key>(std::string("__builtin__max__")); } else if (name == "<API key>") { aggregator = <API key>(std::string("__builtin__min__")); } else if (name == "<API key>") { aggregator = <API key>(std::string("__builtin__var__")); } else if (name == "<API key>") { aggregator = <API key>(std::string("__builtin__stdv__")); } else { log_and_throw("Internal error. Unknown cumulative aggregator " + name); } return this-><API key>(aggregator); } gl_sarray gl_sarray::cumulative_sum() const { return <API key>("<API key>"); } gl_sarray gl_sarray::cumulative_min() const { return <API key>("<API key>"); } gl_sarray gl_sarray::cumulative_max() const { return <API key>("<API key>"); } gl_sarray gl_sarray::cumulative_avg() const { return <API key>("<API key>"); } gl_sarray gl_sarray::cumulative_std() const { return <API key>("<API key>"); } gl_sarray gl_sarray::cumulative_var() const { return <API key>("<API key>"); } std::ostream& operator<<(std::ostream& out, const gl_sarray& other) { auto t = other.head(10); auto dtype = other.dtype(); out << "dtype: " << <API key>(dtype) << "\n"; out << "Rows: " << other.size() << "\n"; out << "["; bool first = true; for(auto i : t.range_iterator()) { if (!first) out << ","; if (dtype == flex_type_enum::STRING) out << "\""; if (i.get_type() == flex_type_enum::UNDEFINED) out << "None"; else out << i; if (dtype == flex_type_enum::STRING) out << "\""; first = false; } out << "]" << "\n"; return out; } void gl_sarray::instantiate_new() { m_sarray = std::make_shared<unity_sarray>(); } void gl_sarray::<API key>() const { if (!m_sarray_reader) { std::lock_guard<mutex> guard(<API key>); if (!m_sarray_reader) { m_sarray_reader = std::move(get_proxy()-><API key>()->get_reader()); } } } /* gl_sarray_range */ gl_sarray_range::gl_sarray_range( std::shared_ptr<sarray_reader<flexible_type> > m_sarray_reader, size_t start, size_t end) { <API key> = std::make_shared<<API key><flexible_type>> (m_sarray_reader, start, end); // load the first value if available if (<API key>->has_next()) { m_current_value = std::move(<API key>->next()); } } gl_sarray_range::iterator gl_sarray_range::begin() { return iterator(*this, true); } gl_sarray_range::iterator gl_sarray_range::end() { return iterator(*this, false); } /* gl_sarray_range::iterator */ gl_sarray_range::iterator::iterator(gl_sarray_range& range, bool is_start) { m_owner = &range; if (is_start) m_counter = 0; else m_counter = range.<API key>->size(); } void gl_sarray_range::iterator::increment() { ++m_counter; if (m_owner-><API key>->has_next()) { m_owner->m_current_value = std::move(m_owner-><API key>->next()); } } void gl_sarray_range::iterator::advance(size_t n) { n = std::min(n, m_owner-><API key>->size()); for (size_t i = 0;i < n ; ++i) increment(); } const gl_sarray_range::type& gl_sarray_range::iterator::dereference() const { return m_owner->m_current_value; } /* <API key> */ class <API key> { public: <API key>(flex_type_enum type, size_t num_segments); void write(const flexible_type& f, size_t segmentid); size_t num_segments() const; gl_sarray close(); private: std::shared_ptr<sarray<flexible_type> > m_out_sarray; std::vector<sarray<flexible_type>::iterator> m_output_iterators; }; <API key>::<API key>(flex_type_enum type, size_t num_segments) { // open the output array if (num_segments == (size_t)(-1)) num_segments = <API key>; m_out_sarray = std::make_shared<sarray<flexible_type>>(); m_out_sarray->open_for_write(num_segments); m_out_sarray->set_type(type); // store the iterators m_output_iterators.resize(m_out_sarray->num_segments()); for (size_t i = 0;i < m_out_sarray->num_segments(); ++i) { m_output_iterators[i] = m_out_sarray->get_output_iterator(i); } } void <API key>::write(const flexible_type& f, size_t segmentid) { ASSERT_LT(segmentid, m_output_iterators.size()); *(m_output_iterators[segmentid]) = f; } size_t <API key>::num_segments() const { return m_output_iterators.size(); } gl_sarray <API key>::close() { m_output_iterators.clear(); m_out_sarray->close(); auto usarray = std::make_shared<unity_sarray>(); usarray-><API key>(m_out_sarray); return usarray; } /* gl_sarray_writer */ gl_sarray_writer::gl_sarray_writer(flex_type_enum type, size_t num_segments) { // create the pimpl m_writer_impl.reset(new <API key>(type, num_segments)); } void gl_sarray_writer::write(const flexible_type& f, size_t segmentid) { m_writer_impl->write(f, segmentid); } size_t gl_sarray_writer::num_segments() const { return m_writer_impl->num_segments(); } gl_sarray gl_sarray_writer::close() { return m_writer_impl->close(); } gl_sarray_writer::~gl_sarray_writer() { } } // namespace graphlab
#ifndef <API key> #define <API key> #include <string> #include "build/build_config.h" class Profile; // Returns the device ID that is scoped to single signin. // All refresh tokens for |profile| are annotated with this device ID when they // are requested. // On non-ChromeOS platforms, this is equivalent to: // signin::<API key>(profile->GetPrefs()); std::string <API key>(Profile* profile); #if defined(OS_CHROMEOS) // Helper method. The device ID should generally be obtained through // <API key>(). // If |for_ephemeral| is true, special kind of device ID for ephemeral users is // generated. std::string <API key>(bool for_ephemeral); // Moves any existing device ID out of the pref service into the UserManager, // and creates a new ID if it is empty. void <API key>(Profile* profile); #endif #endif // <API key>
#include "ash/system/unified/<API key>.h" #include "ash/metrics/user_metrics_action.h" #include "ash/metrics/<API key>.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/pagination/<API key>.h" #include "ash/public/cpp/system_tray_client.h" #include "ash/session/<API key>.h" #include "ash/shell.h" #include "ash/system/accessibility/<API key>.h" #include "ash/system/accessibility/<API key>.h" #include "ash/system/audio/<API key>.h" #include "ash/system/audio/<API key>.h" #include "ash/system/bluetooth/<API key>.h" #include "ash/system/bluetooth/<API key>.h" #include "ash/system/brightness/<API key>.h" #include "ash/system/cast/<API key>.h" #include "ash/system/cast/<API key>.h" #include "ash/system/ime/<API key>.h" #include "ash/system/ime/<API key>.h" #include "ash/system/locale/<API key>.h" #include "ash/system/locale/<API key>.h" #include "ash/system/model/clock_model.h" #include "ash/system/model/system_tray_model.h" #include "ash/system/network/<API key>.h" #include "ash/system/network/<API key>.h" #include "ash/system/network/<API key>.h" #include "ash/system/network/<API key>.h" #include "ash/system/night_light/<API key>.h" #include "ash/system/privacy_screen/<API key>.h" #include "ash/system/rotation/<API key>.h" #include "ash/system/tray/<API key>.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/feature_pod_button.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/system/unified/<API key>.h" #include "ash/wm/<API key>.h" #include "ash/wm/tablet_mode/<API key>.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/numerics/ranges.h" #include "ui/compositor/<API key>.h" #include "ui/gfx/animation/slide_animation.h" #include "ui/message_center/message_center.h" #include "ui/views/widget/widget.h" namespace ash { namespace { // Threshold in pixel that fully collapses / expands the view through gesture. const int kDragThreshold = 200; } // namespace // TODO(amehfooz): Add histograms for pagination metrics in system tray. void <API key>(ui::EventType type, bool is_tablet_mode) {} class <API key>::<API key> : public ui::<API key> { public: <API key>() = default; ~<API key>() override = default; void <API key>(bool expanded) { target_expanded_ = expanded; } private: // ui:<API key> void Report(int value) override { if (target_expanded_) { <API key>( "ChromeOS.SystemTray.AnimationSmoothness." "<API key>", value); } else { <API key>( "ChromeOS.SystemTray.AnimationSmoothness." "<API key>", value); } } bool target_expanded_; }; <API key>::<API key>( <API key>* model, <API key>* bubble, views::View* owner_view) : views::<API key>(owner_view), model_(model), bubble_(bubble), animation_(std::make_unique<gfx::SlideAnimation>(this)), <API key>( std::make_unique<<API key>>()) { animation_->Reset(model_->IsExpandedOnOpen() ? 1.0 : 0.0); animation_->SetSlideDuration(base::TimeDelta::FromMilliseconds( <API key>)); animation_->SetTweenType(gfx::Tween::EASE_IN_OUT); model_->pagination_model()-><API key>( base::TimeDelta::FromMilliseconds(250), base::TimeDelta::FromMilliseconds(50)); <API key> = std::make_unique<<API key>>( model_->pagination_model(), <API key>::<API key>, base::BindRepeating(&<API key>), Shell::Get()-><API key>()->InTabletMode()); Shell::Get()->metrics()-><API key>(<API key>); <API key>("ChromeOS.SystemTray.IsExpandedOnOpen", model_->IsExpandedOnOpen()); <API key>(<API key>.get()); } <API key>::~<API key>() = default; <API key>* <API key>::CreateView() { DCHECK(!unified_view_); unified_view_ = new <API key>(this, model_->IsExpandedOnOpen()); InitFeaturePods(); <API key> = std::make_unique<<API key>>(this); unified_view_->AddSliderView(<API key>->CreateView()); <API key> = std::make_unique<<API key>>(model_); unified_view_->AddSliderView(<API key>->CreateView()); return unified_view_; } void <API key>::HandleSignOutAction() { Shell::Get()->metrics()-><API key>(<API key>); if (Shell::Get()->session_controller()->IsDemoSession()) base::RecordAction(base::UserMetricsAction("DemoMode.ExitFromSystemTray")); Shell::Get()->session_controller()->RequestSignOut(); } void <API key>::HandleLockAction() { Shell::Get()->metrics()-><API key>(<API key>); Shell::Get()->session_controller()->LockScreen(); } void <API key>::<API key>() { Shell::Get()->metrics()-><API key>(UMA_TRAY_SETTINGS); Shell::Get()->system_tray_model()->client()->ShowSettings(); } void <API key>::HandlePowerAction() { Shell::Get()->metrics()-><API key>(UMA_TRAY_SHUT_DOWN); Shell::Get()-><API key>()->RequestShutdown( ShutdownReason::<API key>); CloseBubble(); } void <API key>::<API key>(int page) { // TODO(amehfooz) Record Pagination Metrics here. model_->pagination_model()->SelectPage(page, true); } void <API key>::<API key>() { ClockModel* model = Shell::Get()->system_tray_model()->clock(); if (Shell::Get()->session_controller()-><API key>()) { model->ShowDateSettings(); } else if (model->can_set_time()) { model->ShowSetTimeDialog(); } } void <API key>::<API key>() { <API key>("ChromeOS.SystemTray.<API key>", <API key>, MANAGED_TYPE_COUNT); Shell::Get()->system_tray_model()->client()->ShowEnterpriseInfo(); } void <API key>::ToggleExpanded() { if (animation_->is_animating()) return; <API key>("ChromeOS.SystemTray.ToggleExpanded", <API key>, <API key>); if (IsExpanded()) { StartAnimation(false /*expand*/); // Expand message center when quick settings is collapsed. if (bubble_) bubble_->ExpandMessageCenter(); } else { // Collapse the message center if screen height is limited after expanding // the quick settings to its full height. if (<API key>()) { bubble_-><API key>(); } StartAnimation(true /*expand*/); } } void <API key>::<API key>() { if (bubble_) bubble_->UpdateTransform(); } void <API key>::BeginDrag(const gfx::Point& location) { // Ignore swipe collapsing when a detailed view is shown as it's confusing. if (<API key>) return; drag_init_point_ = location; was_expanded_ = IsExpanded(); } void <API key>::UpdateDrag(const gfx::Point& location) { // Ignore swipe collapsing when a detailed view is shown as it's confusing. if (<API key>) return; double <API key> = <API key>(location); animation_->Reset(<API key>); <API key>(); if (was_expanded_ && <API key> < <API key>) { bubble_->ExpandMessageCenter(); } else if (<API key> >= <API key> && <API key>()) { bubble_-><API key>(); } } void <API key>::StartAnimation(bool expand) { <API key>-><API key>(expand); if (expand) { animation_->Show(); } else { // To animate to hidden state, first set SlideAnimation::IsShowing() to // true. animation_->Show(); animation_->Hide(); } } void <API key>::EndDrag(const gfx::Point& location) { // Ignore swipe collapsing when a detailed view is shown as it's confusing. if (<API key>) return; if (animation_->is_animating()) { // Prevent overwriting the state right after fling event return; } bool expanded = <API key>(location) > 0.5; if (was_expanded_ != expanded) { <API key>("ChromeOS.SystemTray.ToggleExpanded", <API key>, <API key>); } if (expanded && <API key>()) bubble_-><API key>(); else bubble_->ExpandMessageCenter(); // If dragging is finished, animate to closer state. StartAnimation(expanded); } void <API key>::Fling(int velocity) { // Ignore swipe collapsing when a detailed view is shown as it's confusing. if (<API key>) return; // Expand when flinging up. Collapse otherwise. bool expand = (velocity < 0); if (expand && <API key>()) bubble_-><API key>(); else bubble_->ExpandMessageCenter(); StartAnimation(expand); } void <API key>::ShowUserChooserView() { if (!<API key>::<API key>()) return; animation_->Reset(1.0); <API key>(); ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::<API key>(bool force) { if (!force && !IsExpanded()) return; Shell::Get()->metrics()-><API key>( <API key>); ShowDetailedView( std::make_unique<<API key>>(this)); } void <API key>::<API key>() { if (!IsExpanded()) return; Shell::Get()->metrics()-><API key>( <API key>); ShowDetailedView( std::make_unique<<API key>>(this)); } void <API key>::<API key>() { Shell::Get()->metrics()-><API key>( <API key>); ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::<API key>() { Shell::Get()->metrics()-><API key>( <API key>); ShowDetailedView( std::make_unique<<API key>>(this)); } void <API key>::ShowVPNDetailedView() { Shell::Get()->metrics()-><API key>( <API key>); ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::ShowIMEDetailedView() { ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::<API key>() { ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::<API key>() { ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::<API key>() { DCHECK(Shell::Get()->session_controller()-><API key>()); DCHECK(!Shell::Get()->session_controller()->IsScreenLocked()); ShowDetailedView(std::make_unique<<API key>>(this)); } void <API key>::<API key>(bool restore_focus) { <API key>.reset(); unified_view_->ResetDetailedView(); if (restore_focus) unified_view_->RestoreFocus(); } void <API key>::CloseBubble() { if (unified_view_->GetWidget()) unified_view_->GetWidget()->CloseNow(); } bool <API key>::FocusOut(bool reverse) { return bubble_->FocusOut(reverse); } void <API key>::EnsureCollapsed() { if (IsExpanded()) { animation_->Hide(); } } void <API key>::EnsureExpanded() { if (<API key>) { <API key>.reset(); unified_view_->ResetDetailedView(); } StartAnimation(true /*expand*/); if (<API key>()) bubble_-><API key>(); } void <API key>::AnimationEnded( const gfx::Animation* animation) { <API key>(); } void <API key>::AnimationProgressed( const gfx::Animation* animation) { <API key>(); } void <API key>::AnimationCanceled( const gfx::Animation* animation) { animation_->Reset(std::round(animation_->GetCurrentValue())); <API key>(); } void <API key>::<API key>() { <API key>(); } void <API key>::InitFeaturePods() { AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>()); AddFeaturePodItem(std::make_unique<<API key>>()); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); AddFeaturePodItem(std::make_unique<<API key>>(this)); // If you want to add a new feature pod item, add here. if (Shell::Get()-><API key>()->InTabletMode()) { <API key>("ChromeOS.SystemTray.Tablet.<API key>", unified_view_-><API key>()); } else { <API key>("ChromeOS.SystemTray.<API key>", unified_view_-><API key>()); } } void <API key>::AddFeaturePodItem( std::unique_ptr<<API key>> controller) { DCHECK(unified_view_); FeaturePodButton* button = controller->CreateButton(); button->SetExpandedAmount(IsExpanded() ? 1.0 : 0.0, false /* fade_icon_button */); // Record DefaultView.VisibleRows UMA. <API key> uma_type = controller->GetUmaType(); if (uma_type != <API key>::UMA_NOT_RECORDED && button->visible_preferred()) { <API key>("Ash.SystemMenu.DefaultView.VisibleRows", uma_type, <API key>::UMA_COUNT); } unified_view_->AddFeaturePodButton(button); <API key>.push_back(std::move(controller)); } void <API key>::ShowDetailedView( std::unique_ptr<<API key>> controller) { animation_->Reset(1.0); <API key>(); unified_view_->SaveFocus(); views::FocusManager* manager = unified_view_->GetFocusManager(); if (manager && manager->GetFocusedView()) manager->ClearFocus(); unified_view_->SetDetailedView(controller->CreateView()); <API key> = std::move(controller); // |bubble_| may be null in tests. if (bubble_) bubble_->UpdateBubble(); } void <API key>::<API key>() { double expanded_amount = animation_->GetCurrentValue(); unified_view_->SetExpandedAmount(expanded_amount); // Can be null in unit tests. if (bubble_) bubble_->UpdateTransform(); if (expanded_amount == 0.0 || expanded_amount == 1.0) model_-><API key>( expanded_amount == 1.0 ? <API key>::StateOnOpen::EXPANDED : <API key>::StateOnOpen::COLLAPSED); } void <API key>::<API key>() { if (model_-><API key>()) return; if (features::<API key>() && unified_view_-><API key>()->row_count() == <API key>) { <API key>(); } } void <API key>::<API key>() { unified_view_->SetExpandedAmount(0.0); animation_->Reset(0); } double <API key>::<API key>( const gfx::Point& location) const { double y_diff = (location - drag_init_point_).y(); // If already expanded, only consider swiping down. Otherwise, only consider // swiping up. if (was_expanded_) { return base::ClampToRange(1.0 - std::max(0.0, y_diff) / kDragThreshold, 0.0, 1.0); } else { return base::ClampToRange(std::max(0.0, -y_diff) / kDragThreshold, 0.0, 1.0); } } bool <API key>::IsExpanded() const { return animation_->IsShowing(); } bool <API key>::<API key>() const { // Note: This calculaton should be the same as // <API key>::<API key>(). return (bubble_ && bubble_->CalculateMaxHeight() - unified_view_-><API key>() - <API key> < <API key>); } base::TimeDelta <API key>::<API key>() const { return base::TimeDelta::FromMilliseconds( <API key>); } } // namespace ash
#ifndef <API key> #define <API key> #include <string> #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "chromeos/login/auth/user_context.h" class AccountId; namespace chromeos { class UserContext; namespace quick_unlock { class <API key> { public: using BoolCallback = base::OnceCallback<void(bool)>; // Check to see if the cryptohome implementation can store PINs. static void IsSupported(BoolCallback result); // Transforms |key| for usage in PIN. Returns nullopt if the key could not be // transformed. static base::Optional<Key> TransformKey(const AccountId& account_id, const Key& key); <API key>(); ~<API key>(); void <API key>(const AccountId& account_id, BoolCallback result) const; // Sets a new PIN. If |pin_salt| is empty, |pin| will be hashed and should be // plain-text. If |pin_salt| contains a value, |pin| will not be hashed. void SetPin(const UserContext& user_context, const std::string& pin, const base::Optional<std::string>& pin_salt, BoolCallback did_set); void RemovePin(const UserContext& user_context, BoolCallback did_remove); void CanAuthenticate(const AccountId& account_id, BoolCallback result) const; void TryAuthenticate(const AccountId& account_id, const Key& key, BoolCallback result); private: void <API key>(const std::string& system_salt); bool salt_obtained_ = false; std::string system_salt_; std::vector<base::OnceClosure> <API key>; base::WeakPtrFactory<<API key>> weak_factory_{this}; <API key>(<API key>); }; } // namespace quick_unlock } // namespace chromeos #endif // <API key>
"""Define statements for retrieving the data for each of the types.""" CONSTRAINTS = """ select o.owner, o.constraint_name, o.constraint_type, o.table_name, o.search_condition, o.r_owner, o.r_constraint_name, o.delete_rule, o.deferred, o.deferrable from %(p_ViewPrefix)s_constraints o %(p_WhereClause)s and exists ( select 1 from %(p_ViewPrefix)s_tables where owner = o.owner and table_name = o.table_name ) and (o.generated = 'USER NAME' or o.constraint_type in ('P', 'U')) order by decode(o.constraint_type, 'P', 1, 'U', 2, 'R', 3, 'C', 4), o.owner, o.constraint_name""" CONTEXTS = """ select namespace, schema, package, type from dba_context o %(p_WhereClause)s order by namespace""" INDEXES_ANY = """ select o.owner, o.index_name, o.table_name, o.tablespace_name, o.uniqueness, o.initial_extent, o.next_extent, o.min_extents, o.max_extents, o.pct_increase, o.index_type, o.partitioned, o.temporary, o.compression, o.prefix_length, o.ityp_owner, o.ityp_name, o.parameters from %(p_ViewPrefix)s_indexes o %(p_WhereClause)s and o.index_type in ('NORMAL', 'NORMAL/REV', 'IOT - TOP', 'BITMAP', 'FUNCTION-BASED NORMAL', 'FUNCTION-BASED NORMAL/REV', 'DOMAIN')""" INDEXES = INDEXES_ANY + """ and not exists ( select 1 from %(p_ViewPrefix)s_constraints where owner = o.owner and constraint_name = o.index_name ) order by o.owner, o.index_name""" INDEX_PARTITIONS = """ select o.index_owner, o.partition_name, o.high_value, o.tablespace_name, o.initial_extent, o.next_extent, o.min_extent, o.max_extent, o.pct_increase from %(p_ViewPrefix)s_ind_partitions o %(p_WhereClause)s order by o.partition_position""" LIBRARIES = """ select o.owner, o.library_name, o.file_spec from %(p_ViewPrefix)s_libraries o %(p_WhereClause)s order by o.owner, o.library_name""" LOBS = """ select o.owner, o.column_name, o.table_name, o.segment_name, o.in_row from %(p_ViewPrefix)s_lobs o %(p_WhereClause)s order by o.column_name""" ROLES = """ select o.role, o.password_required from dba_roles o %(p_WhereClause)s order by o.role""" SEQUENCES = """ select o.sequence_owner, o.sequence_name, to_char(min_value), to_char(max_value), to_char(increment_by), cycle_flag, order_flag, to_char(cache_size), to_char(last_number) from %(p_ViewPrefix)s_sequences o %(p_WhereClause)s order by o.sequence_owner, o.sequence_name""" SYNONYMS = """ select o.owner, o.synonym_name, o.table_owner, o.table_name, o.db_link from %(p_ViewPrefix)s_synonyms o %(p_WhereClause)s order by decode(o.owner, 'PUBLIC', 0, 1), o.owner, o.synonym_name""" TABLES = """ select o.owner, o.table_name, o.tablespace_name, o.initial_extent, o.next_extent, o.min_extents, o.max_extents, o.pct_increase, o.temporary, o.partitioned, o.duration, o.iot_type from %(p_ViewPrefix)s_tables o %(p_WhereClause)s and secondary = 'N' order by o.owner, o.table_name""" TABLE_PARTITIONS = """ select o.table_owner, o.partition_name, o.high_value, o.tablespace_name, o.initial_extent, o.next_extent, o.min_extent, o.max_extent, o.pct_increase from %(p_ViewPrefix)s_tab_partitions o %(p_WhereClause)s order by o.partition_position""" TRIGGERS = """ select o.owner, o.trigger_name, o.table_name, o.description, o.when_clause, o.action_type, o.trigger_body from %(p_ViewPrefix)s_triggers o %(p_WhereClause)s order by o.owner, o.trigger_name""" USERS = """ select o.username, o.default_tablespace, o.<API key> from dba_users o %(p_WhereClause)s order by o.username""" VIEWS = """ select o.owner, o.view_name, o.text from %(p_ViewPrefix)s_views o %(p_WhereClause)s order by o.owner, o.view_name"""
{{ define "content" }} <div class="mdl-grid"> <div class="mdl-cell mdl-cell--12-col"><h2 class="card-header">{{ .Name }}</h2></div> <div class="mdl-cell mdl-cell--12-col <API key> mdl-card mdl-shadow--2dp"> <div class="mdl-card__title"> <h3 class="<API key>">When and Where</h2> </div> {{ if .Location.EmbedURL }} <div class="mdl-card__media"> <iframe src="{{ .Location.EmbedURL }}" frameborder="0" style="border:0" allowfullscreen></iframe> </div> {{ end }} <div class="<API key>"> <i class="material-icons">schedule</i> {{ .Datetime }} Eastern<br/> <i class="material-icons">place</i> {{ if .Location.MapURL }}<a href="{{ .Location.MapURL }}" target="_blank">{{ .Location.Where }}</a>{{ else }}{{ .Location.Where }}{{ end }}<br/> <i class="material-icons">directions</i> {{ .Location.Details }} </div> </div> <div class="mdl-cell mdl-cell--12-col <API key> mdl-card mdl-shadow--2dp"> <div class="mdl-card__title"> <h3 class="<API key>">Links</h3> </div> <div class="mdl-card__actions"> {{ if .Links.GooglePlus }}<a class="mdl-button mdl-js-button <API key> mdl-button--primary" href="{{ .Links.GooglePlus }}" target="_blank">Google+</a>{{ end }} {{ if .Links.Meetup }}<a class="mdl-button mdl-js-button <API key> mdl-button--primary" href="{{ .Links.Meetup }}" target="_blank">Meetup</a>{{ end }} {{ if .Links.Slides }}<a class="mdl-button mdl-js-button <API key> mdl-button--primary" href="{{ .Links.Slides }}" target="_blank">Slides</a>{{ end }} </div> </div> {{ if .Links.Video }} <div class="mdl-cell mdl-cell--12-col <API key> mdl-card mdl-shadow--2dp"> <div class="mdl-card__title"> <h3 class="<API key>">Video</h3> </div> <div class="mdl-card__media"> <iframe width="420" height="315" src="{{ .Links.Video }}" allowfullscreen></iframe> </div> </div> {{ end }} <div class="mdl-cell mdl-cell--12-col mdl-card mdl-shadow--2dp"> <div class="mdl-card__title"> <h3 class="<API key>">Details</h3> </div> <div class="<API key>"> {{ .Details }} </div> </div> </div> {{ end }}
<?php /** * Default base class for compiled templates. * * @author Fabien Potencier <fabien@symfony.com> */ abstract class Twig_Template implements <API key> { protected static $cache = array(); protected $parent; protected $parents; protected $env; protected $blocks; protected $traits; /** * Constructor. * * @param Twig_Environment $env A Twig_Environment instance */ public function __construct(Twig_Environment $env) { $this->env = $env; $this->blocks = array(); $this->traits = array(); } /** * Returns the template name. * * @return string The template name */ abstract public function getTemplateName(); /** * {@inheritdoc} */ public function getEnvironment() { return $this->env; } /** * Returns the parent template. * * This method is for internal use only and should never be called * directly. * * @return <API key>|false The parent template or false if there is no parent */ public function getParent(array $context) { if (null !== $this->parent) { return $this->parent; } $parent = $this->doGetParent($context); if (false === $parent) { return false; } elseif ($parent instanceof Twig_Template) { $name = $parent->getTemplateName(); $this->parents[$name] = $parent; $parent = $name; } elseif (!isset($this->parents[$parent])) { $this->parents[$parent] = $this->env->loadTemplate($parent); } return $this->parents[$parent]; } protected function doGetParent(array $context) { return false; } public function isTraitable() { return true; } /** * Displays a parent block. * * This method is for internal use only and should never be called * directly. * * @param string $name The block name to display from the parent * @param array $context The context * @param array $blocks The current set of blocks */ public function displayParentBlock($name, array $context, array $blocks = array()) { $name = (string) $name; if (isset($this->traits[$name])) { $this->traits[$name][0]->displayBlock($name, $context, $blocks); } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, $blocks); } else { throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block', $name), -1, $this->getTemplateName()); } } /** * Displays a block. * * This method is for internal use only and should never be called * directly. * * @param string $name The block name to display * @param array $context The context * @param array $blocks The current set of blocks */ public function displayBlock($name, array $context, array $blocks = array()) { $name = (string) $name; if (isset($blocks[$name])) { $b = $blocks; unset($b[$name]); call_user_func($blocks[$name], $context, $b); } elseif (isset($this->blocks[$name])) { call_user_func($this->blocks[$name], $context, $blocks); } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks)); } } /** * Renders a parent block. * * This method is for internal use only and should never be called * directly. * * @param string $name The block name to render from the parent * @param array $context The context * @param array $blocks The current set of blocks * * @return string The rendered block */ public function renderParentBlock($name, array $context, array $blocks = array()) { ob_start(); $this->displayParentBlock($name, $context, $blocks); return ob_get_clean(); } /** * Renders a block. * * This method is for internal use only and should never be called * directly. * * @param string $name The block name to render * @param array $context The context * @param array $blocks The current set of blocks * * @return string The rendered block */ public function renderBlock($name, array $context, array $blocks = array()) { ob_start(); $this->displayBlock($name, $context, $blocks); return ob_get_clean(); } /** * Returns whether a block exists or not. * * This method is for internal use only and should never be called * directly. * * This method does only return blocks defined in the current template * or defined in "used" traits. * * It does not return blocks from parent templates as the parent * template name can be dynamic, which is only known based on the * current context. * * @param string $name The block name * * @return Boolean true if the block exists, false otherwise */ public function hasBlock($name) { return isset($this->blocks[(string) $name]); } /** * Returns all block names. * * This method is for internal use only and should never be called * directly. * * @return array An array of block names * * @see hasBlock */ public function getBlockNames() { return array_keys($this->blocks); } /** * Returns all blocks. * * This method is for internal use only and should never be called * directly. * * @return array An array of blocks * * @see hasBlock */ public function getBlocks() { return $this->blocks; } /** * {@inheritdoc} */ public function display(array $context, array $blocks = array()) { $this-><API key>($this->env->mergeGlobals($context), $blocks); } /** * {@inheritdoc} */ public function render(array $context) { $level = ob_get_level(); ob_start(); try { $this->display($context); } catch (Exception $e) { while (ob_get_level() > $level) { ob_end_clean(); } throw $e; } return ob_get_clean(); } protected function <API key>(array $context, array $blocks = array()) { try { $this->doDisplay($context, $blocks); } catch (Twig_Error $e) { if (!$e->getTemplateFile()) { $e->setTemplateFile($this->getTemplateName()); } // this is mostly useful for Twig_Error_Loader exceptions // see Twig_Error_Loader if (false === $e->getTemplateLine()) { $e->setTemplateLine(-1); $e->guess(); } throw $e; } catch (Exception $e) { throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, null, $e); } } /** * Auto-generated method to display the template with the given context. * * @param array $context An array of parameters to pass to the template * @param array $blocks An array of blocks to pass to the template */ abstract protected function doDisplay(array $context, array $blocks = array()); /** * Returns a variable from the context. * * This method is for internal use only and should never be called * directly. * * This method should not be overridden in a sub-class as this is an * implementation detail that has been introduced to optimize variable * access for versions of PHP before 5.4. This is not a way to override * the way to get a variable value. * * @param array $context The context * @param string $item The variable to return from the context * @param Boolean $ignoreStrictCheck Whether to ignore the strict variable check or not * * @return The content of the context variable * * @throws Twig_Error_Runtime if the variable does not exist and Twig is running in strict mode */ final protected function getContext($context, $item, $ignoreStrictCheck = false) { if (!array_key_exists($item, $context)) { if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { return null; } throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist', $item), -1, $this->getTemplateName()); } return $context[$item]; } /** * Returns the attribute value for a given array/object. * * @param mixed $object The object or array from where to get the item * @param mixed $item The item to get from the array or object * @param array $arguments An array of arguments to pass if the item is an object method * @param string $type The type of attribute (@see <API key>) * @param Boolean $isDefinedTest Whether this is only a defined check * @param Boolean $ignoreStrictCheck Whether to ignore the strict attribute check or not * * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true * * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false */ protected function getAttribute($object, $item, array $arguments = array(), $type = <API key>::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) { $item = ctype_digit((string) $item) ? (int) $item : (string) $item; // array if (<API key>::METHOD_CALL !== $type) { if ((is_array($object) && array_key_exists($item, $object)) || ($object instanceof ArrayAccess && isset($object[$item])) ) { if ($isDefinedTest) { return true; } return $object[$item]; } if (<API key>::ARRAY_CALL === $type) { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { return null; } if (is_object($object)) { throw new Twig_Error_Runtime(sprintf('Key "%s" in object (with ArrayAccess) of type "%s" does not exist', $item, get_class($object)), -1, $this->getTemplateName()); } elseif (is_array($object)) { throw new Twig_Error_Runtime(sprintf('Key "%s" for array with keys "%s" does not exist', $item, implode(', ', array_keys($object))), -1, $this->getTemplateName()); } else { throw new Twig_Error_Runtime(sprintf('Impossible to access a key ("%s") on a "%s" variable', $item, gettype($object)), -1, $this->getTemplateName()); } } } if (!is_object($object)) { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { return null; } throw new Twig_Error_Runtime(sprintf('Item "%s" for "%s" does not exist', $item, is_array($object) ? 'Array' : $object), -1, $this->getTemplateName()); } $class = get_class($object); // object property if (<API key>::METHOD_CALL !== $type) { if (isset($object->$item) || array_key_exists($item, $object)) { if ($isDefinedTest) { return true; } if ($this->env->hasExtension('sandbox')) { $this->env->getExtension('sandbox')-><API key>($object, $item); } return $object->$item; } } // object method if (!isset(self::$cache[$class]['methods'])) { self::$cache[$class]['methods'] = <API key>(array_flip(get_class_methods($object))); } $lcItem = strtolower($item); if (isset(self::$cache[$class]['methods'][$lcItem])) { $method = $item; } elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) { $method = 'get'.$item; } elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) { $method = 'is'.$item; } elseif (isset(self::$cache[$class]['methods']['__call'])) { $method = $item; } else { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { return null; } throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist', $item, get_class($object)), -1, $this->getTemplateName()); } if ($isDefinedTest) { return true; } if ($this->env->hasExtension('sandbox')) { $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method); } $ret = <API key>(array($object, $method), $arguments); // useful when calling a template method from a template // this is not supported but unfortunately heavily used in the Symfony profiler if ($object instanceof <API key>) { return $ret === '' ? '' : new Twig_Markup($ret, $this->env->getCharset()); } return $ret; } /** * This method is only useful when testing Twig. Do not use it. */ public static function clearCache() { self::$cache = array(); } }
package fr.paris.lutece.portal.web.xss; import fr.paris.lutece.portal.service.message.AdminMessage; import fr.paris.lutece.portal.service.message.AdminMessageService; import javax.servlet.http.HttpServletRequest; /** * This class extends SafeRequestFilter and use AdminMessageService for display error Message * * @author merlinfe * */ public class <API key> extends SafeRequestFilter { /** * {@inheritDoc} */ @Override protected String getMessageUrl( HttpServletRequest request, String strMessageKey, Object [ ] messageArgs, String strTitleKey ) { return AdminMessageService.getMessageUrl( request, strMessageKey, messageArgs, AdminMessage.TYPE_STOP ); } }
<?php /** * Item Service class * * @author jacoe */ namespace BidSite\Service; use Zend\Form\FormInterface as Form; use Zend\ServiceManager\ServiceManager; use Zend\ServiceManager\<API key>; use ZfcBase\EventManager\EventProvider; use BidSite\Mapper\HydratorInterface; use BidSite\Mapper\ItemMapperInterface; use BidSite\Options\<API key> as ServiceOptions; use BidSite\Mapper\<API key>; class ItemService extends EventProvider implements <API key> { protected $itemMapper; protected $itemForm; protected $serviceManager; protected $options; protected $formHydrator; // Additional mappers needed protected $manufacturerMapper; /** * Add a new Item * @param \BidSite\Entity\Item $item * @return boolean */ public function add($item) { $entityClass = $this->getOptions()->getEntityClass("item"); $form = $this->getItemForm(); $form->setHydrator($this->getFormHydrator()); $form->bind(new $entityClass()); $form->setData($item); if ($form->isValid()) { $item = $form->getData(); $events = $this->getEventManager(); $events->trigger(__FUNCTION__, $this, compact('item', 'form')); $this->getItemMapper()->insert($item); $events->trigger(__FUNCTION__.'.post', $this, compact('item', 'form')); return $item; } return false; } /** * Find an Item based on Id * @param int $id * @return \BidSite\Entity\Item */ public function findById($id) { $results = $this->events->trigger(__FUNCTION__.'.pre', $this, array('id' => $id), function ($result) { return ($result instanceof ItemEntity); } ); if ($results->stopped()) { return $results->last(); } $item = $this->getItemMapper()->findById($id); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('item' => $item)); return $item; } /** * Return all Items and join one-to-one db relationships * @return array */ public function findAll() { return $this->getItemMapper()-><API key>($this-><API key>()); } /** * Get all Manufacturers * @return array */ public function <API key>() { return $this-><API key>()->findAll(); } /** * Update an Item entity * @param \BidSite\Entity\Item $item * @return boolean */ public function update($item) { #$entityClass = $this->getOptions()->getEntityClass("item"); $form = $this->getItemForm(); $form->setHydrator($this->getFormHydrator()); $form->bind($item); #$form->setData($data); if ($form->isValid()) { $item = $form->getData(); $events = $this->getEventManager(); $events->trigger(__FUNCTION__, $this, compact('item', 'form')); $this->getItemMapper()->update($item); $events->trigger(__FUNCTION__.'.post', $this, compact('item', 'form')); return $item; } return false; } /** * Set the Item mapper * @param \BidSite\Mapper\ItemMapperInterface $itemMapper * @return \BidSite\Service\ItemService */ public function setItemMapper(ItemMapperInterface $itemMapper) { $this->itemMapper = $itemMapper; return $this; } /** * Return Item Mapper * @return \BidSite\Mapper\ItemMapperInterface */ public function getItemMapper() { if (null === $this->itemMapper) { $this->setItemMapper($this->serviceManager->get('bidsite_item_mapper')); } return $this->itemMapper; } /** * Set Manufacturer mapper * @param \BidSite\Mapper\<API key> $manufacturerMapper * @return \BidSite\Service\ItemService */ public function <API key>(<API key> $manufacturerMapper) { $this->manufacturerMapper = $manufacturerMapper; return $this; } /** * Return Manufacturer mapper * @return \BidSite\Mapper\ManufacturerMapper */ public function <API key>() { if (null === $this->manufacturerMapper) { $this-><API key>($this->serviceManager->get('<API key>')); } return $this->manufacturerMapper; } /** * Return Item form * @return \BidSite\Form\ItemForm */ public function getItemForm() { if (null === $this->itemForm) { $this->setItemForm( $this->serviceManager->get('bidsite_item_form') ); } return $this->itemForm; } /** * Set Item form * @param \Zend\Form\FormInterface $itemForm * @return \BidSite\Service\ItemService */ public function setItemForm(Form $itemForm) { $this->itemForm = $itemForm; return $this; } /** * Return Module Options * @return \BidSite\Options\ModuleOptions */ public function getOptions() { if (!$this->options instanceof ServiceOptions) { $this->setOptions($this->serviceManager->get('<API key>')); } return $this->options; } /** * Set Module Options * @param \BidSite\Options\<API key> $options */ public function setOptions(ServiceOptions $options) { $this->options = $options; } /** * Return Service Manager * @return string */ public function getServiceManager() { return $this->serviceManager; } /** * Set Service Manager * @param \Zend\ServiceManager\ServiceManager $serviceManager * @return \BidSite\Service\ItemService */ public function setServiceManager(ServiceManager $serviceManager) { $this->serviceManager = $serviceManager; return $this; } /** * Return Item form Hydrator * @return \BidSite\Mapper\ItemHydrator */ public function getFormHydrator() { if (!$this->formHydrator instanceof HydratorInterface) { $this->setFormHydrator( $this->serviceManager->get('<API key>') ); } return $this->formHydrator; } /** * Set Item form Hydrator * @param \BidSite\Mapper\HydratorInterface $formHydrator * @return \BidSite\Service\ItemService */ public function setFormHydrator(HydratorInterface $formHydrator) { $this->formHydrator = $formHydrator; return $this; } } ?>
package com.github.sviperll.cli; /** * This exception is thrown in every case * where command line argument parsing goes wrong. * * For example when there is a missing argument for * some command line key * * @author Victor Nazarov <asviraspossible@gmail.com> */ @SuppressWarnings("serial") public class CLIException extends Exception { public CLIException(String message) { super(message); } CLIException(String message, Exception ex) { super(message, ex); } }
<?php require_once(__DIR__ . '/../GitHubClient.php'); require_once(__DIR__ . '/../GitHubService.php'); require_once(__DIR__ . '/../objects/GitHubUser.php'); class <API key> extends GitHubService { /** * List assignees * * @return array<GitHubUser> */ public function listAssignees($owner, $repo) { $data = array(); return $this->client->request("/repos/$owner/$repo/assignees", 'GET', $data, 200, 'GitHubUser', true); } }
#ifndef <API key> #define <API key> // Note this file has a _views suffix so that it may have an optional runtime // dependency on toolkit-views UI. #import <CoreGraphics/CoreGraphics.h> #include <memory> #import "base/mac/scoped_nsobject.h" #include "base/macros.h" #include "chrome/browser/ui/exclusive_access/<API key>.h" #include "chrome/browser/ui/views/<API key>.h" #include "components/prefs/<API key>.h" #include "ui/base/accelerators/accelerator.h" class Browser; class BrowserWindow; @class <API key>; class <API key>; @class <API key>; class GURL; // Component placed into a browser window controller to manage communication // with the exclusive access bubble, which appears for events such as entering // fullscreen. class <API key> : public <API key>, public ui::AcceleratorProvider, public <API key> { public: <API key>(<API key>* controller, Browser* browser); ~<API key>() override; const GURL& url() const { return url_; } <API key> bubble_type() const { return bubble_type_; } <API key>* cocoa_bubble() { return cocoa_bubble_; } // Shows the bubble once the NSWindow has received -<API key>:. void Show(); // Closes any open bubble. void Destroy(); // If showing, position the bubble at the given y-coordinate. void Layout(CGFloat max_y); // <API key>: Profile* GetProfile() override; bool IsFullscreen() const override; bool <API key>() const override; void <API key>(bool with_toolbar) override; void <API key>() override; bool <API key>() const override; void EnterFullscreen(const GURL& url, <API key> type, bool with_toolbar) override; void ExitFullscreen() override; void <API key>( const GURL& url, <API key> bubble_type) override; void <API key>() override; content::WebContents* <API key>() override; void UnhideDownloadShelf() override; void HideDownloadShelf() override; // ui::AcceleratorProvider: bool <API key>(int command_id, ui::Accelerator* accelerator) override; // <API key>: <API key>* <API key>() override; views::Widget* <API key>() override; ui::AcceleratorProvider* <API key>() override; gfx::NativeView GetBubbleParentView() const override; gfx::Point <API key>() const override; gfx::Rect <API key>() const override; bool <API key>() override; gfx::Rect <API key>() override; private: BrowserWindow* GetBrowserWindow() const; <API key>* controller_; // Weak. Owns |this|. Browser* browser_; // Weak. Owned by controller. // When going fullscreen for a tab, we need to store the URL and the // fullscreen type, since we can't show the bubble until // -<API key>: gets called. GURL url_; <API key> bubble_type_; std::unique_ptr<<API key>> views_bubble_; base::scoped_nsobject<<API key>> cocoa_bubble_; // Used to keep track of the <API key> preference. PrefChangeRegistrar pref_registrar_; <API key>(<API key>); }; #endif // <API key>
<?php namespace Anodoc\ClassDoc; use Anodoc\Exception; class InvalidMethodDoc extends Exception {}
#include "chrome/browser/upgrade_detector/<API key>.h" #include <stdio.h> #include <string> #include "base/base_switches.h" #include "base/command_line.h" #include "base/strings/<API key>.h" #include "components/version_info/version_info.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/<API key>.h" namespace { constexpr char kChildModeSwitch[] = "<API key>"; enum class ChildMode { kNoVersion = 0, kProcessError = 1, kWithMonkey = 2, kWithVersion = 3, }; ChildMode GetChildMode() { const auto switch_value = base::CommandLine::ForCurrentProcess()-><API key>( kChildModeSwitch); int mode_int = 0; base::StringToInt(switch_value, &mode_int); return static_cast<ChildMode>(mode_int); } } // namespace // A function run in a child process to print the desired version to stdout, // just like Chrome does. <API key>(<API key>) { switch (GetChildMode()) { case ChildMode::kNoVersion: // Return successful process exit without printing anything. return 0; case ChildMode::kProcessError: // Return a bad exit code without printing anything. break; case ChildMode::kWithMonkey: // Print something unexpected and report success. printf("monkey, monkey, monkey"); return 0; case ChildMode::kWithVersion: // Print the current version and report success. printf("%s\n", version_info::GetVersionNumber().c_str()); return 0; } return 1; } // A multi process test that exercises the Linux implementation of // GetInstalledVersion. class <API key> : public ::testing::Test { protected: <API key>() : <API key>(*base::CommandLine::ForCurrentProcess()) {} ~<API key>() override { *base::CommandLine::ForCurrentProcess() = <API key>; } // Adds switches to the current process command line so that when // GetInstalledVersion relaunches the current process, it has the proper // child proc switch to lead to <API key> above and the // mode switch to tell the child how to behave. void <API key>(ChildMode child_mode) { auto* command_line = base::CommandLine::ForCurrentProcess(); command_line->AppendSwitchASCII(switches::kTestChildProcess, "<API key>"); command_line->AppendSwitchASCII( kChildModeSwitch, base::NumberToString(static_cast<int>(child_mode))); } private: // The original process command line; saved during construction and restored // during destruction. const base::CommandLine <API key>; }; // Tests that an empty instance is returned when the child process reports // nothing. TEST_F(<API key>, NoVersion) { <API key>(ChildMode::kNoVersion); <API key> versions = GetInstalledVersion(); EXPECT_FALSE(versions.installed_version.IsValid()); EXPECT_FALSE(versions.critical_version.has_value()); } // Tests that an empty instance is returned when the child process exits with an // error. TEST_F(<API key>, ProcessError) { <API key>(ChildMode::kProcessError); <API key> versions = GetInstalledVersion(); ASSERT_FALSE(versions.installed_version.IsValid()); EXPECT_FALSE(versions.critical_version.has_value()); } // Tests that an empty instance is returned when the child process reports a // monkey. TEST_F(<API key>, WithMonkey) { <API key>(ChildMode::kWithMonkey); <API key> versions = GetInstalledVersion(); ASSERT_FALSE(versions.installed_version.IsValid()); EXPECT_FALSE(versions.critical_version.has_value()); } // Tests that the expected instance is returned when the child process reports a // valid version. TEST_F(<API key>, WithVersion) { <API key>(ChildMode::kWithVersion); <API key> versions = GetInstalledVersion(); ASSERT_TRUE(versions.installed_version.IsValid()); EXPECT_EQ(versions.installed_version, version_info::GetVersion()); EXPECT_FALSE(versions.critical_version.has_value()); }
set YEAR=2017 set VER=15 mkdir "%PREFIX%\etc\conda\activate.d" COPY "%RECIPE_DIR%\activate.bat" "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" IF "%<API key>%" == "win-64" ( set "target_platform=amd64" echo SET "CMAKE_GENERATOR=Visual Studio %VER% %YEAR% Win64" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo pushd "%%VSINSTALLDIR%%" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" IF "%VSDEVCMD_ARGS%" == "" ( echo CALL "VC\Auxiliary\Build\vcvarsall.bat" x64 >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo popd >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo pushd "%%VSINSTALLDIR%%" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo CALL "VC\Auxiliary\Build\vcvarsall.bat" x86_amd64 >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" ) ELSE ( echo CALL "VC\Auxiliary\Build\vcvarsall.bat" x64 %VSDEVCMD_ARGS% >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo popd >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo pushd "%%VSINSTALLDIR%%" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo CALL "VC\Auxiliary\Build\vcvarsall.bat" x86_amd64 %VSDEVCMD_ARGS% >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" ) echo popd >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" ) else ( set "target_platform=x86" echo SET "CMAKE_GENERATOR=Visual Studio %VER% %YEAR%" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo pushd "%%VSINSTALLDIR%%" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo CALL "VC\Auxiliary\Build\vcvars32.bat" >> "%PREFIX%\etc\conda\activate.d\vs%YEAR%_compiler_vars.bat" echo popd )
#include "device/bluetooth/test/<API key>.h" #include <utility> #include "base/bind.h" #include "base/strings/string_piece.h" #include "base/task_runner_util.h" #include "base/threading/<API key>.h" #include "base/win/async_operation.h" #include "base/win/scoped_hstring.h" #include "device/bluetooth/test/<API key>.h" namespace device { namespace { using ABI::Windows::Devices::Enumeration::DeviceClass; using ABI::Windows::Devices::Enumeration::DeviceInformation; using ABI::Windows::Devices::Enumeration::<API key>; using ABI::Windows::Devices::Enumeration::<API key>; using ABI::Windows::Devices::Enumeration::DeviceThumbnail; using ABI::Windows::Devices::Enumeration::IDeviceInformation; using ABI::Windows::Devices::Enumeration::<API key>; using ABI::Windows::Devices::Enumeration::<API key>; using ABI::Windows::Devices::Enumeration::IDeviceWatcher; using ABI::Windows::Devices::Enumeration::IEnclosureLocation; using ABI::Windows::Foundation::Collections::IIterable; using ABI::Windows::Foundation::Collections::IMapView; using ABI::Windows::Foundation::IAsyncOperation; using Microsoft::WRL::ComPtr; using Microsoft::WRL::Make; } // namespace <API key>::<API key>() = default; <API key>::<API key>(const char* name) : name_(name) {} <API key>::<API key>(std::string name) : name_(std::move(name)) {} <API key>::<API key>( ComPtr<<API key>> pairing) : pairing_(std::move(pairing)) {} <API key>::~<API key>() = default; HRESULT <API key>::get_Id(HSTRING* value) { return E_NOTIMPL; } HRESULT <API key>::get_Name(HSTRING* value) { *value = base::win::ScopedHString::Create(name_).release(); return S_OK; } HRESULT <API key>::get_IsEnabled(boolean* value) { return E_NOTIMPL; } HRESULT <API key>::get_IsDefault(boolean* value) { return E_NOTIMPL; } HRESULT <API key>::<API key>( IEnclosureLocation** value) { return E_NOTIMPL; } HRESULT <API key>::get_Properties( IMapView<HSTRING, IInspectable*>** value) { return E_NOTIMPL; } HRESULT <API key>::Update( <API key>* update_info) { return E_NOTIMPL; } HRESULT <API key>::GetThumbnailAsync( IAsyncOperation<DeviceThumbnail*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::<API key>( IAsyncOperation<DeviceThumbnail*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::get_Kind(<API key>* value) { return E_NOTIMPL; } HRESULT <API key>::get_Pairing( <API key>** value) { return pairing_.CopyTo(value); } <API key>::<API key>( ComPtr<IDeviceInformation> device_information) : device_information_(std::move(device_information)) {} <API key>::~<API key>() = default; HRESULT <API key>::CreateFromIdAsync( HSTRING device_id, IAsyncOperation<DeviceInformation*>** async_op) { auto operation = Make<base::win::AsyncOperation<DeviceInformation*>>(); base::<API key>::Get()->PostTask( FROM_HERE, base::BindOnce(operation->callback(), device_information_)); *async_op = operation.Detach(); return S_OK; } HRESULT <API key>::<API key>( HSTRING device_id, IIterable<HSTRING>* <API key>, IAsyncOperation<DeviceInformation*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::FindAllAsync( IAsyncOperation<<API key>*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::<API key>( DeviceClass device_class, IAsyncOperation<<API key>*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::<API key>( HSTRING aqs_filter, IAsyncOperation<<API key>*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::<API key>( HSTRING aqs_filter, IIterable<HSTRING>* <API key>, IAsyncOperation<<API key>*>** async_op) { return E_NOTIMPL; } HRESULT <API key>::CreateWatcher( IDeviceWatcher** watcher) { return E_NOTIMPL; } HRESULT <API key>::<API key>( DeviceClass device_class, IDeviceWatcher** watcher) { return E_NOTIMPL; } HRESULT <API key>::<API key>( HSTRING aqs_filter, IDeviceWatcher** watcher) { return Make<<API key>>().CopyTo(watcher); } HRESULT <API key>:: <API key>( HSTRING aqs_filter, IIterable<HSTRING>* <API key>, IDeviceWatcher** watcher) { return E_NOTIMPL; } } // namespace device
// Generated by IcedCoffeeScript 1.8.0-d (function() { var constants, d, k, kbp, v, _ref, _ref1; kbp = require('keybase-proofs'); exports.constants = constants = { proof_types: { rooter: 100001 } }; d = {}; _ref = constants.proof_types; for (k in _ref) { v = _ref[k]; d[v] = k; } _ref1 = kbp.constants.proof_types; for (k in _ref1) { v = _ref1[k]; d[v] = k; } exports.<API key> = d; }).call(this);
/* WHATSOCK, 2016 */ /* Specific styles for Accessible Tooltip */ div.tooltip { position: absolute; width: auto; color: #FFF; background: #2E3135; padding: 0.3em 0.5em; -webkit-box-shadow: 0 1px 1px #afafaf, inset 0 1px 0 #868686; -moz-box-shadow: 0 1px 1px #afafaf, inset 0 1px 0 #868686; box-shadow: 0 1px 1px #afafaf, inset 0 1px 0 #868686; z-index: 100; } .accTooltip { font-size: 100%; text-align: center; background: transparent; border: none; } .accTooltip img {display: block; vertical-align: middle; margin: 0.5rem auto 0;} @media screen and (min-width: 750px) { .accTooltip img {display: inline; margin: 0 0 0 0.5rem;} }
namespace DNS.Protocol { public enum RecordType { A = 1, NS = 2, CNAME = 5, SOA = 6, WKS = 11, PTR = 12, MX = 15, TXT = 16, AAAA = 28, SRV = 33, ANY = 255, } }
#ifndef <API key> #define <API key> #include "ash/public/cpp/ash_public_export.h" #include "third_party/skia/include/core/SkColor.h" namespace ash { // The value assigned to the wallpaper color calculation result if calculation // fails or is disabled (e.g. from command line, lock/login screens). constexpr SkColor <API key> = SK_ColorTRANSPARENT; // The width and height of small/large resolution wallpapers. When screen size // is smaller than |<API key>| and |<API key>|, // the small wallpaper is used. Otherwise, use the large wallpaper. constexpr int <API key> = 1366; constexpr int <API key> = 800; constexpr int <API key> = 2560; constexpr int <API key> = 1700; // This enum is used to define the buckets for an enumerated UMA histogram. // Hence, // (a) existing enumerated constants should never be deleted or reordered, // (b) new constants should only be appended at the end of the enumeration. enum WallpaperLayout { // Center the wallpaper on the desktop without scaling it. The wallpaper // may be cropped. <API key>, // Scale the wallpaper (while preserving its aspect ratio) to cover the // desktop; the wallpaper may be cropped. <API key>, // Scale the wallpaper (without preserving its aspect ratio) to match the // desktop's size. <API key>, // Tile the wallpaper over the background without scaling it. <API key>, // This must remain last. <API key>, }; // This enum is used to define the buckets for an enumerated UMA histogram. // Hence, // (a) existing enumerated constants should never be deleted or reordered, // (b) new constants should only be appended at the end of the enumeration. enum WallpaperType { DAILY = 0, // Surprise wallpaper. Changes once a day if enabled. CUSTOMIZED = 1, // Selected by user. DEFAULT = 2, // Default. /* UNKNOWN = 3 */ // Removed. ONLINE = 4, // WallpaperInfo.location denotes an URL. POLICY = 5, // Controlled by policy, can't be changed by the user. THIRDPARTY = 6, // Current wallpaper is set by a third party app. DEVICE = 7, // Current wallpaper is the device policy controlled // wallpaper. It shows on the login screen if the device // is an enterprise managed device. ONE_SHOT = 8, // Current wallpaper is shown one-time only, which doesn't // belong to a particular user and isn't saved to file. It // goes away when another wallpaper is shown or the browser // process exits. Note: the image will never be blurred or // dimmed. <API key> = 9 }; // The color profile type, ordered as the color profiles applied in // ash::WallpaperController. enum class ColorProfileType { DARK_VIBRANT = 0, NORMAL_VIBRANT, LIGHT_VIBRANT, DARK_MUTED, NORMAL_MUTED, LIGHT_MUTED, <API key>, }; } // namespace ash #endif // <API key>
<?php namespace tests\Response; use MaitavrApi\Response\Response; use MaitavrApi\Response\Exceptions\AuthException; use MaitavrApi\Exceptions\ApiException; class ResponseTest extends \<API key> { public function testAuthException(){ $this-><API key>(get_class(new AuthException())); $jsonResponse = json_encode(array('error'=>'true', 'errorText'=>'access denied')); $response = new Response(); $response->setJSONResponse($jsonResponse); } public function testSomeOtherError(){ $this-><API key>(get_class(new ApiException())); $jsonResponse = json_encode(array('error'=>'true', 'errorText'=>'other error')); $response = new Response(); $response->setJSONResponse($jsonResponse); } public function testParseResponse(){ $json = '[ { "firstname": "Александр", "lastname": "Галкин", "bday": "564958800", "country": "Украина" }, { "firstname": "Дмитрий", "lastname": "Образцов", "bday": "327186000", "country": "Россия" }]'; $response = new Response(); $response->setJSONResponse($json); $this->assertEquals(json_decode($json, true), $response->toArray()); } }
class Error(Exception): """ Base error for all coco exceptions. Only when throwing an instance of this error one can be sure it will get caught by the application. All other exceptions might be unhandled leading to crashes. """ pass class BackendError(Error): """ Base error for all backend exceptions. Backend errors are meant to be raised instead of letting the backend's real exception/error pass up the stack. Every error thrown from the backend should be wrapped. """ pass class ConnectionError(BackendError): """ Generic backend error meant to be thrown then a connection to the backend cannot be established. """ pass class NotFoundError(BackendError): """ Generic (backend record) not found error. Error meant to be raised when an operation can not be performed because the resource on which the method should act does not exist. """ pass class <API key>(BackendError): """ Backend error type for container backends. """ pass class <API key>(NotFoundError, <API key>): """ Error meant to be raised when a container does not exist. A reason for such a failure could be that the container on which a method should act, does not exist. """ pass class <API key>(<API key>): pass class <API key>(NotFoundError, <API key>): """ Error meant to be raised when an image (container template) does not exist. """ pass class <API key>(<API key>): """ Error for non-existing container snapshots. Meant to be raised when an operation can not be performed because the snapshot on which the method should act does not exist. """ pass class GroupBackendError(BackendError): """ Backend error type for user backends. """ pass class GroupNotFoundError(NotFoundError, GroupBackendError): """ Error meant to be raised when a group does not exist. """ pass class StorageBackendError(BackendError): """ Backend error type for storage backends. """ pass class <API key>(NotFoundError, StorageBackendError): """ Error to be raised when the directory on which an operation should be performed does not exist. """ pass class UserBackendError(BackendError): """ Backend error type for user backends. """ pass class AuthenticationError(UserBackendError): """ Error meant to be raised when there is a problem while authenticating. """ pass class ReadOnlyError(UserBackendError): """ Error indicating that a user cannot be updated because the backend is read-only. """ pass class UserNotFoundError(NotFoundError, UserBackendError): """ Error meant to be raised when a user does not exist. """ pass class ServiceError(Exception): """ Base exception class for errors raised by service implementations. """ pass class <API key>(ServiceError): """ Service error type for encryption services. """ pass class <API key>(ServiceError): """ Service error type for integrity services. """ pass class <API key>(<API key>): """ Error to be raised when an integrity cannot be verified or the integrity check fails. """ pass
#ifndef <API key> #define <API key> #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/heap/visitor.h" namespace blink { // DisallowNewWrapper wraps a disallow new type in a GarbageCollected class. template <typename T> class DisallowNewWrapper final : public GarbageCollected<DisallowNewWrapper<T>> { public: explicit DisallowNewWrapper(const T& value) : value_(value) { static_assert(WTF::IsDisallowNew<T>::value, "T needs to be a disallow new type"); static_assert(WTF::IsTraceable<T>::value, "T needs to be traceable"); } explicit DisallowNewWrapper(T&& value) : value_(std::forward<T>(value)) { static_assert(WTF::IsDisallowNew<T>::value, "T needs to be a disallow new type"); static_assert(WTF::IsTraceable<T>::value, "T needs to be traceable"); } const T& Value() const { return value_; } T&& TakeValue() { return std::move(value_); } void Trace(Visitor* visitor) { visitor->Trace(value_); } private: T value_; }; // Wraps a disallow new type in a GarbageCollected class, making it possible to // be referenced off heap from a Persistent. template <typename T> DisallowNewWrapper<T>* WrapDisallowNew(const T& value) { return <API key><DisallowNewWrapper<T>>(value); } template <typename T> DisallowNewWrapper<T>* WrapDisallowNew(T&& value) { return <API key><DisallowNewWrapper<T>>(std::forward<T>(value)); } } // namespace blink #endif // <API key>
<?php /* @var $this UnitsController */ /* @var $model Units */ ?> <div id="titlebar"> <div class="listtitle">Update Unit <?php echo $model->unit_id; ?></div> <div class="deletebutton"><?php echo CHtml::submitButton('Delete',array('submit'=>array('delete','id'=>$model->unit_id),'confirm'=>'Are you sure you want to delete this item?')); ?></div> </div> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
#include <iterator> #include "<API key>.h" #ifdef _MSC_VER // has to be deactivated because of a bug in boost v1.59. see Boost bug ticket #11599 // as soon as MITK uses a boost version with a bug fix we can remove the disableling. #pragma warning(push) #pragma warning(disable : 4715) #endif #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/type_traits/make_unsigned.hpp> mitk::<API key>::<API key>(const char *s) { if (s) { SliceMapType slices{{0, s}}; m_Values.insert(std::make_pair(0, slices)); } } mitk::<API key>::<API key>(const std::string &s) { SliceMapType slices{{0, s}}; m_Values.insert(std::make_pair(0, slices)); } mitk::<API key>::<API key>(const <API key> &other) : BaseProperty(other), m_Values(other.m_Values) { } bool mitk::<API key>::IsEqual(const BaseProperty &property) const { return this->m_Values == static_cast<const Self &>(property).m_Values; } bool mitk::<API key>::Assign(const BaseProperty &property) { this->m_Values = static_cast<const Self &>(property).m_Values; return true; } std::string mitk::<API key>::GetValueAsString() const { return GetValue(); } itk::LightObject::Pointer mitk::<API key>::InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); result->UnRegister(); return result; } mitk::<API key>::ValueType mitk::<API key>::GetValue() const { std::string result = ""; if (!m_Values.empty()) { if (!m_Values.begin()->second.empty()) { result = m_Values.begin()->second.begin()->second; } } return result; }; std::pair<bool, mitk::<API key>::ValueType> mitk::<API key>::CheckValue( const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime, bool allowCloseSlice) const { std::string value = ""; bool found = false; TimeMapType::const_iterator timeIter = m_Values.find(timeStep); TimeMapType::const_iterator timeEnd = m_Values.end(); if (timeIter == timeEnd && allowCloseTime) { // search for closest time step (earlier preverd) timeIter = m_Values.upper_bound(timeStep); if (timeIter != m_Values.begin()) { // there is a key lower than time step timeIter = std::prev(timeIter); } } if (timeIter != timeEnd) { const SliceMapType &slices = timeIter->second; SliceMapType::const_iterator sliceIter = slices.find(zSlice); SliceMapType::const_iterator sliceEnd = slices.end(); if (sliceIter == sliceEnd && allowCloseSlice) { // search for closest slice (earlier preverd) sliceIter = slices.upper_bound(zSlice); if (sliceIter != slices.begin()) { // there is a key lower than slice sliceIter = std::prev(sliceIter); } } if (sliceIter != sliceEnd) { value = sliceIter->second; found = true; } } return std::make_pair(found, value); }; mitk::<API key>::ValueType mitk::<API key>::GetValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime, bool allowCloseSlice) const { return CheckValue(timeStep, zSlice, allowCloseTime, allowCloseSlice).second; }; mitk::<API key>::ValueType mitk::<API key>::GetValueBySlice( const IndexValueType &zSlice, bool allowClose) const { return GetValue(0, zSlice, true, allowClose); }; mitk::<API key>::ValueType mitk::<API key>::GetValueByTimeStep( const TimeStepType &timeStep, bool allowClose) const { return GetValue(timeStep, 0, allowClose, true); }; bool mitk::<API key>::HasValue() const { return !m_Values.empty(); }; bool mitk::<API key>::HasValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime, bool allowCloseSlice) const { return CheckValue(timeStep, zSlice, allowCloseTime, allowCloseSlice).first; }; bool mitk::<API key>::HasValueBySlice(const IndexValueType &zSlice, bool allowClose) const { return HasValue(0, zSlice, true, allowClose); }; bool mitk::<API key>::HasValueByTimeStep(const TimeStepType &timeStep, bool allowClose) const { return HasValue(timeStep, 0, allowClose, true); }; std::vector<mitk::<API key>::IndexValueType> mitk::<API key>::GetAvailableSlices( const TimeStepType &timeStep) const { std::vector<IndexValueType> result; TimeMapType::const_iterator timeIter = m_Values.find(timeStep); TimeMapType::const_iterator timeEnd = m_Values.end(); if (timeIter != timeEnd) { for (auto const &element : timeIter->second) { result.push_back(element.first); } } return result; }; std::vector<mitk::TimeStepType> mitk::<API key>::<API key>() const { std::vector<mitk::TimeStepType> result; for (auto const &element : m_Values) { result.push_back(element.first); } return result; }; void mitk::<API key>::SetValue(const TimeStepType &timeStep, const IndexValueType &zSlice, const ValueType &value) { TimeMapType::iterator timeIter = m_Values.find(timeStep); TimeMapType::iterator timeEnd = m_Values.end(); if (timeIter == timeEnd) { SliceMapType slices{{zSlice, value}}; m_Values.insert(std::make_pair(timeStep, slices)); } else { timeIter->second[zSlice] = value; } this->Modified(); }; void mitk::<API key>::SetValue(const ValueType &value) { this->Modified(); m_Values.clear(); this->SetValue(0, 0, value); }; // REMARK: This code is based upon code from boost::ptree::json_writer. // The corresponding boost function was not used directly, because it is not part of // the public interface of ptree::json_writer. :( // A own serialization strategy was implemented instead of using boost::ptree::json_write because // currently (<= boost 1.60) everything (even numbers) are converted into string representations // by the writer, so e.g. it becomes "t":"2" instaed of "t":2 template <class Ch> std::basic_string<Ch> CreateJSONEscapes(const std::basic_string<Ch> &s) { std::basic_string<Ch> result; typename std::basic_string<Ch>::const_iterator b = s.begin(); typename std::basic_string<Ch>::const_iterator e = s.end(); while (b != e) { typedef typename boost::make_unsigned<Ch>::type UCh; UCh c(*b); // This assumes an ASCII superset. // We escape everything outside ASCII, because this code can't // handle high unicode characters. if (c == 0x20 || c == 0x21 || (c >= 0x23 && c <= 0x2E) || (c >= 0x30 && c <= 0x5B) || (c >= 0x5D && c <= 0x7F)) result += *b; else if (*b == Ch('\b')) result += Ch('\\'), result += Ch('b'); else if (*b == Ch('\f')) result += Ch('\\'), result += Ch('f'); else if (*b == Ch('\n')) result += Ch('\\'), result += Ch('n'); else if (*b == Ch('\r')) result += Ch('\\'), result += Ch('r'); else if (*b == Ch('\t')) result += Ch('\\'), result += Ch('t'); else if (*b == Ch('/')) result += Ch('\\'), result += Ch('/'); else if (*b == Ch('"')) result += Ch('\\'), result += Ch('"'); else if (*b == Ch('\\')) result += Ch('\\'), result += Ch('\\'); else { const char *hexdigits = "0123456789ABCDEF"; unsigned long u = (std::min)(static_cast<unsigned long>(static_cast<UCh>(*b)), 0xFFFFul); int d1 = u / 4096; u -= d1 * 4096; int d2 = u / 256; u -= d2 * 256; int d3 = u / 16; u -= d3 * 16; int d4 = u; result += Ch('\\'); result += Ch('u'); result += Ch(hexdigits[d1]); result += Ch(hexdigits[d2]); result += Ch(hexdigits[d3]); result += Ch(hexdigits[d4]); } ++b; } return result; } ::std::string mitk::<API key>::<API key>( const mitk::BaseProperty *prop) { // REMARK: Implemented own serialization instead of using boost::ptree::json_write because // currently (<= boost 1.60) everything (even numbers) are converted into string representations // by the writer, so e.g. it becomes "t":"2" instaed of "t":2 // If this problem is fixed with boost, we shoud switch back to json_writer (and remove the custom // implementation of CreateJSONEscapes (see above)). const mitk::<API key> *tsProp = dynamic_cast<const mitk::<API key> *>(prop); if (!tsProp) { return ""; } std::ostringstream stream; stream << "{\"values\":["; std::vector<mitk::TimeStepType> ts = tsProp-><API key>(); bool first = true; for (auto t : ts) { std::vector<mitk::<API key>::IndexValueType> zs = tsProp->GetAvailableSlices(t); for (auto z : zs) { std::string value = CreateJSONEscapes(tsProp->GetValue(t, z)); if (first) { first = false; } else { stream << ", "; } stream << "{\"t\":" << t << ", \"z\":" << z << ", \"value\":\"" << value << "\"}"; } } stream << "]}"; return stream.str(); } mitk::BaseProperty::Pointer mitk::<API key>::<API key>( const std::string &value) { mitk::<API key>::Pointer prop = mitk::<API key>::New(); boost::property_tree::ptree root; std::istringstream stream(value); boost::property_tree::read_json(stream, root); for (boost::property_tree::ptree::value_type &element : root.get_child("values")) { std::string value = element.second.get("value", ""); mitk::<API key>::IndexValueType z = element.second.get<mitk::<API key>::IndexValueType>("z", 0); TimeStepType t = element.second.get<TimeStepType>("t", 0); prop->SetValue(t, z, value); } return prop.GetPointer(); } #ifdef _MSC_VER #pragma warning(pop) #endif
import { <API key> } from "./<API key>.actions" export function <API key>(payload: boolean) { return <API key>(payload) }
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\Roomreg */ $this->title = $model->rid; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'ข้อมูลการจองห้อง'), 'url' => ['admin']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="roomreg-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->rid], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->rid], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'rid', 'username', 'company', 'phone', 'capacity', 'usedate', 'description:ntext', 'status', 'created_dt', ], ]) ?> </div>
require 'factory_girl' Factory.sequence :email do |n| "somebody#{n}@example.com" end Factory.sequence :user_<API key> do |n| "xxxx#{Time.now.to_i}#{rand(1000)}#{n}xxxxxxxxxxxxx" end Factory.define :user do |f| f.email { Factory.next(:email) } f.login { |u| u.email } f.<API key> { Factory.next(:user_<API key>) } f.password "secret" f.<API key> "secret" end FEATURES_PATH = File.expand_path('../..', __FILE__) # load shared env with features require File.expand_path('../../../../features/support/env', __FILE__)
#include <stdio.h> #include <algorithm> #include <string> #include <vector> #include "mojo/public/c/system/macros.h" #include "mojo/public/cpp/bindings/interface_impl.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "mojo/public/cpp/bindings/lib/connector.h" #include "mojo/public/cpp/bindings/lib/filter_chain.h" #include "mojo/public/cpp/bindings/lib/<API key>.h" #include "mojo/public/cpp/bindings/lib/router.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/message.h" #include "mojo/public/cpp/bindings/tests/<API key>.h" #include "mojo/public/cpp/environment/environment.h" #include "mojo/public/cpp/system/core.h" #include "mojo/public/cpp/test_support/test_support.h" #include "mojo/public/cpp/utility/run_loop.h" #include "mojo/public/interfaces/bindings/tests/<API key>.mojom.h" #include "testing/gtest/include/gtest/gtest.h" namespace mojo { namespace test { namespace { template <typename T> void Append(std::vector<uint8_t>* data_vector, T data) { size_t pos = data_vector->size(); data_vector->resize(pos + sizeof(T)); memcpy(&(*data_vector)[pos], &data, sizeof(T)); } bool TestInputParser(const std::string& input, bool expected_result, const std::vector<uint8_t>& expected_data, size_t <API key>) { std::vector<uint8_t> data; size_t num_handles; std::string error_message; bool result = <API key>(input, &data, &num_handles, &error_message); if (expected_result) { if (result && error_message.empty() && expected_data == data && <API key> == num_handles) { return true; } // Compare with an empty string instead of checking |error_message.empty()|, // so that the message will be printed out if the two are not equal. EXPECT_EQ(std::string(), error_message); EXPECT_EQ(expected_data, data); EXPECT_EQ(<API key>, num_handles); return false; } EXPECT_FALSE(error_message.empty()); return !result && !error_message.empty(); } std::vector<std::string> GetMatchingTests(const std::vector<std::string>& names, const std::string& prefix) { const std::string suffix = ".data"; std::vector<std::string> tests; for (size_t i = 0; i < names.size(); ++i) { if (names[i].size() >= suffix.size() && names[i].substr(0, prefix.size()) == prefix && names[i].substr(names[i].size() - suffix.size()) == suffix) tests.push_back(names[i].substr(0, names[i].size() - suffix.size())); } return tests; } bool ReadFile(const std::string& path, std::string* result) { FILE* fp = <API key>(path.c_str()); if (!fp) { ADD_FAILURE() << "File not found: " << path; return false; } fseek(fp, 0, SEEK_END); size_t size = static_cast<size_t>(ftell(fp)); if (size == 0) { result->clear(); fclose(fp); return true; } fseek(fp, 0, SEEK_SET); result->resize(size); size_t size_read = fread(&result->at(0), 1, size, fp); fclose(fp); return size == size_read; } bool <API key>(const std::string& path, std::vector<uint8_t>* data, size_t* num_handles) { std::string input; if (!ReadFile(path, &input)) return false; std::string error_message; if (!<API key>(input, data, num_handles, &error_message)) { ADD_FAILURE() << error_message; return false; } return true; } bool ReadResultFile(const std::string& path, std::string* result) { if (!ReadFile(path, result)) return false; // Result files are new-line delimited text files. Remove any CRs. result->erase(std::remove(result->begin(), result->end(), '\r'), result->end()); // Remove trailing LFs. size_t pos = result->find_last_not_of('\n'); if (pos == std::string::npos) result->clear(); else result->resize(pos + 1); return true; } std::string GetPath(const std::string& root, const std::string& suffix) { return "mojo/public/interfaces/bindings/tests/data/validation/" + root + suffix; } // |message| should be a newly created object. bool ReadTestCase(const std::string& test, Message* message, std::string* expected) { std::vector<uint8_t> data; size_t num_handles; if (!<API key>(GetPath(test, ".data"), &data, &num_handles) || !ReadResultFile(GetPath(test, ".expected"), expected)) { return false; } message-><API key>(static_cast<uint32_t>(data.size())); if (!data.empty()) memcpy(message->mutable_data(), &data[0], data.size()); message->mutable_handles()->resize(num_handles); return true; } void RunValidationTests(const std::string& prefix, MessageReceiver* <API key>) { std::vector<std::string> names = <API key>(GetPath("", "")); std::vector<std::string> tests = GetMatchingTests(names, prefix); for (size_t i = 0; i < tests.size(); ++i) { Message message; std::string expected; ASSERT_TRUE(ReadTestCase(tests[i], &message, &expected)); std::string result; mojo::internal::<API key> observer; mojo_ignore_result(<API key>->Accept(&message)); if (observer.last_error() == mojo::internal::<API key>) result = "PASS"; else result = mojo::internal::<API key>(observer.last_error()); EXPECT_EQ(expected, result) << "failed test: " << tests[i]; } } class <API key> : public MessageReceiver { public: bool Accept(Message* message) override { return true; // Any message is OK. } }; class ValidationTest : public testing::Test { public: ~ValidationTest() override {} private: Environment env_; }; class <API key> : public ValidationTest { public: <API key>() : <API key>(nullptr) {} ~<API key>() override {} void SetUp() override { <API key> tester_endpoint; ASSERT_EQ(MOJO_RESULT_OK, CreateMessagePipe(nullptr, &tester_endpoint, &testee_endpoint_)); <API key> = new TestMessageReceiver(this, tester_endpoint.Pass()); } void TearDown() override { delete <API key>; <API key> = nullptr; // Make sure that the other end receives the OnConnectionError() // notification. PumpMessages(); } MessageReceiver* <API key>() { return <API key>; } <API key> testee_endpoint() { return testee_endpoint_.Pass(); } private: class TestMessageReceiver : public MessageReceiver { public: TestMessageReceiver(<API key>* owner, <API key> handle) : owner_(owner), connector_(handle.Pass()) { connector_.<API key>(false); } ~TestMessageReceiver() override {} bool Accept(Message* message) override { bool rv = connector_.Accept(message); owner_->PumpMessages(); return rv; } public: <API key>* owner_; mojo::internal::Connector connector_; }; void PumpMessages() { loop_.RunUntilIdle(); } RunLoop loop_; TestMessageReceiver* <API key>; <API key> testee_endpoint_; }; class <API key> : public <API key> { public: ~<API key>() override {} void Method0(BasicStructPtr param0, const Method0Callback& callback) override { callback.Run(Array<uint8_t>::New(0u)); } }; TEST_F(ValidationTest, InputParser) { { // The parser, as well as Append() defined above, assumes that this code is // running on a little-endian platform. Test whether that is true. uint16_t x = 1; ASSERT_EQ(1, *(reinterpret_cast<char*>(&x))); } { // Test empty input. std::string input; std::vector<uint8_t> expected; EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { // Test input that only consists of comments and whitespaces. std::string input = " \t // hello world \n\r \t// the answer is 42 "; std::vector<uint8_t> expected; EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { std::string input = "[u1]0x10// hello world !! \n\r \t [u2]65535 \n" "[u4]65536 [u8]0xFFFFFFFFFFFFFFFF 0 0Xff"; std::vector<uint8_t> expected; Append(&expected, static_cast<uint8_t>(0x10)); Append(&expected, static_cast<uint16_t>(65535)); Append(&expected, static_cast<uint32_t>(65536)); Append(&expected, static_cast<uint64_t>(0xffffffffffffffff)); Append(&expected, static_cast<uint8_t>(0)); Append(&expected, static_cast<uint8_t>(0xff)); EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { std::string input = "[s8]-0x800 [s1]-128\t[s2]+0 [s4]-40"; std::vector<uint8_t> expected; Append(&expected, -static_cast<int64_t>(0x800)); Append(&expected, static_cast<int8_t>(-128)); Append(&expected, static_cast<int16_t>(0)); Append(&expected, static_cast<int32_t>(-40)); EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { std::string input = "[b]00001011 [b]10000000 // hello world\r [b]00000000"; std::vector<uint8_t> expected; Append(&expected, static_cast<uint8_t>(11)); Append(&expected, static_cast<uint8_t>(128)); Append(&expected, static_cast<uint8_t>(0)); EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { std::string input = "[f]+.3e9 [d]-10.03"; std::vector<uint8_t> expected; Append(&expected, +.3e9f); Append(&expected, -10.03); EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { std::string input = "[dist4]foo 0 [dist8]bar 0 [anchr]foo [anchr]bar"; std::vector<uint8_t> expected; Append(&expected, static_cast<uint32_t>(14)); Append(&expected, static_cast<uint8_t>(0)); Append(&expected, static_cast<uint64_t>(9)); Append(&expected, static_cast<uint8_t>(0)); EXPECT_TRUE(TestInputParser(input, true, expected, 0)); } { std::string input = "// This message has handles! \n[handles]50 [u8]2"; std::vector<uint8_t> expected; Append(&expected, static_cast<uint64_t>(2)); EXPECT_TRUE(TestInputParser(input, true, expected, 50)); } // Test some failure cases. { const char* error_inputs[] = {"/ hello world", "[u1]x", "[u2]-1000", "[u1]0x100", "[s2]-0x8001", "[b]1", "[b]1111111k", "[dist4]unmatched", "[anchr]hello [dist8]hello", "[dist4]a [dist4]a [anchr]a", "[dist4]a [anchr]a [dist4]a [anchr]a", "0 [handles]50", nullptr}; for (size_t i = 0; error_inputs[i]; ++i) { std::vector<uint8_t> expected; if (!TestInputParser(error_inputs[i], false, expected, 0)) ADD_FAILURE() << "Unexpected test result for: " << error_inputs[i]; } } } TEST_F(ValidationTest, Conformance) { <API key> dummy_receiver; mojo::internal::FilterChain validators(&dummy_receiver); validators.Append<mojo::internal::<API key>>(); validators.Append<<API key>::RequestValidator_>(); RunValidationTests("conformance_", validators.GetHead()); } // This test is similar to Conformance test but its goal is specifically // do bounds-check testing of message validation. For example we test the // detection of off-by-one errors in method ordinals. TEST_F(ValidationTest, BoundsCheck) { <API key> dummy_receiver; mojo::internal::FilterChain validators(&dummy_receiver); validators.Append<mojo::internal::<API key>>(); validators.Append<<API key>::RequestValidator_>(); RunValidationTests("boundscheck_", validators.GetHead()); } // This test is similar to the Conformance test but for responses. TEST_F(ValidationTest, ResponseConformance) { <API key> dummy_receiver; mojo::internal::FilterChain validators(&dummy_receiver); validators.Append<mojo::internal::<API key>>(); validators.Append<<API key>::ResponseValidator_>(); RunValidationTests("resp_conformance_", validators.GetHead()); } // This test is similar to the BoundsCheck test but for responses. TEST_F(ValidationTest, ResponseBoundsCheck) { <API key> dummy_receiver; mojo::internal::FilterChain validators(&dummy_receiver); validators.Append<mojo::internal::<API key>>(); validators.Append<<API key>::ResponseValidator_>(); RunValidationTests("resp_boundscheck_", validators.GetHead()); } // Test that InterfacePtr<X> applies the correct validators and they don't // conflict with each other: // - <API key> // - X::ResponseValidator_ TEST_F(<API key>, InterfacePtr) { <API key> interface_ptr = MakeProxy<<API key>>(testee_endpoint().Pass()); interface_ptr.internal_state()->router_for_testing()->EnableTestingMode(); RunValidationTests("<API key>", <API key>()); RunValidationTests("integration_msghdr", <API key>()); } // Test that Binding<X> applies the correct validators and they don't // conflict with each other: // - <API key> // - X::RequestValidator_ TEST_F(<API key>, Binding) { <API key> interface_impl; Binding<<API key>> binding( &interface_impl, MakeRequest<<API key>>(testee_endpoint().Pass())); binding.internal_router()->EnableTestingMode(); RunValidationTests("<API key>", <API key>()); RunValidationTests("integration_msghdr", <API key>()); } } // namespace } // namespace test } // namespace mojo
// SeqAn - The Library for Sequence Analysis // modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // 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 KNUT REINERT OR THE FU BERLIN 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. // Implements the affine gap cost functions. #ifndef <API key> #define <API key> namespace seqan { // Forwards // Tags, Classes, Enums // Metafunctions // Functions // Function _computeScore [<API key>, AffineGaps] template <typename TScoreValue, typename TSequenceHValue, typename TSequenceVValue, typename TScoringScheme, typename TAlgorithm, typename TTracebackConfig, typename TExecPolicy> inline typename TraceBitMap_<TScoreValue>::Type _computeScore(DPCell_<TScoreValue, AffineGaps> & current, DPCell_<TScoreValue, AffineGaps> & previousDiagonal, DPCell_<TScoreValue, AffineGaps> const & previousHorizontal, DPCell_<TScoreValue, AffineGaps> & previousVertical, TSequenceHValue const & seqHVal, TSequenceVValue const & seqVVal, TScoringScheme const & scoringScheme, <API key> const &, DPProfile_<TAlgorithm, AffineGaps, TTracebackConfig, TExecPolicy> const &) { // Compute intermediate diagonal result. TScoreValue intermediate = static_cast<TScoreValue>(_scoreOfCell(previousDiagonal) + score(scoringScheme, seqHVal, seqVVal)); // Cache previous Diagonal _scoreOfCell(previousDiagonal) = _scoreOfCell(previousHorizontal); // Compute horizontal direction. auto tmp = _maxScore(<API key>(current), <API key>(previousHorizontal) + <API key>(scoringScheme, seqHVal, seqVVal), _scoreOfCell(previousHorizontal) + <API key>(scoringScheme, seqHVal, seqVVal), TraceBitMap_<TScoreValue>::HORIZONTAL, TraceBitMap_<TScoreValue>::HORIZONTAL_OPEN, TTracebackConfig{}); // Compute vertical direction. tmp |= _maxScore(<API key>(previousVertical), <API key>(previousVertical) + <API key>(scoringScheme, seqHVal, seqVVal), _scoreOfCell(previousVertical) + <API key>(scoringScheme, seqHVal, seqVVal), TraceBitMap_<TScoreValue>::VERTICAL, TraceBitMap_<TScoreValue>::VERTICAL_OPEN, TTracebackConfig{}); auto tmp2 = _maxScore(_scoreOfCell(current), <API key>(previousVertical), <API key>(current), TraceBitMap_<TScoreValue>::<API key>, TraceBitMap_<TScoreValue>::<API key>, TTracebackConfig{}); tmp = _maxScore(_scoreOfCell(current), intermediate, _scoreOfCell(current), TraceBitMap_<TScoreValue>::DIAGONAL | tmp, tmp2 | tmp, TTracebackConfig{}); if (IsLocalAlignment_<TAlgorithm>::VALUE) { tmp = _maxScore(_scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, _scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, tmp, TTracebackConfig{}); } // Cache score for previous vertical. _scoreOfCell(previousVertical) = _scoreOfCell(current); return tmp; } // Function _computeScore [<API key>, AffineGaps] template <typename TScoreValue, typename TSequenceHValue, typename TSequenceVValue, typename TScoringScheme, typename TAlgorithm, typename TTracebackConfig, typename TExecPolicy> inline typename TraceBitMap_<TScoreValue>::Type _computeScore(DPCell_<TScoreValue, AffineGaps> & current, DPCell_<TScoreValue, AffineGaps> & previousDiagonal, DPCell_<TScoreValue, AffineGaps> const & previousHorizontal, DPCell_<TScoreValue, AffineGaps> & previousVertical, TSequenceHValue const & seqHVal, TSequenceVValue const & seqVVal, TScoringScheme const & scoringScheme, <API key> const &, DPProfile_<TAlgorithm, AffineGaps, TTracebackConfig, TExecPolicy> const &) { typedef typename TraceBitMap_<TScoreValue>::Type TTraceValue; // Compute intermediate diagonal result. TScoreValue intermediate = static_cast<TScoreValue>(_scoreOfCell(previousDiagonal) + score(scoringScheme, seqHVal, seqVVal)); // Cache previous Diagonal _scoreOfCell(previousDiagonal) = _scoreOfCell(previousHorizontal); // Compute horiztonal direction. // <API key>(current) = <API key>(previousHorizontal) + // <API key>(scoringScheme, seqHVal, seqVVal); TTraceValue tv = _maxScore(<API key>(current), <API key>(previousHorizontal) + <API key>(scoringScheme, seqHVal, seqVVal), _scoreOfCell(previousHorizontal) + <API key>(scoringScheme, seqHVal, seqVVal), TraceBitMap_<TScoreValue>::HORIZONTAL, TraceBitMap_<TScoreValue>::HORIZONTAL_OPEN, TTracebackConfig()); // Ignore vertical direction in upper diagonal. <API key>(previousVertical) = <API key><DPCell_<TScoreValue, AffineGaps> >::VALUE; // Compute diagonal direction and compare with horizontal. // _scoreOfCell(current) = <API key>(current); tv = _maxScore(_scoreOfCell(current), intermediate, <API key>(current), tv | TraceBitMap_<TScoreValue>::DIAGONAL, tv | TraceBitMap_<TScoreValue>::<API key>, TTracebackConfig()); if (IsLocalAlignment_<TAlgorithm>::VALUE) { tv = _maxScore(_scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, _scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, tv, TTracebackConfig{}); } _scoreOfCell(previousVertical) = _scoreOfCell(current); return tv; } // Function _computeScore [<API key>, AffineGaps] template <typename TScoreValue, typename TSequenceHValue, typename TSequenceVValue, typename TScoringScheme, typename TAlgorithm, typename TTracebackConfig, typename TExecPolicy> inline typename TraceBitMap_<TScoreValue>::Type _computeScore(DPCell_<TScoreValue, AffineGaps> & current, DPCell_<TScoreValue, AffineGaps> const & previousDiagonal, DPCell_<TScoreValue, AffineGaps> const & /*previousHorizontal*/, DPCell_<TScoreValue, AffineGaps> & previousVertical, TSequenceHValue const & seqHVal, TSequenceVValue const & seqVVal, TScoringScheme const & scoringScheme, <API key> const &, DPProfile_<TAlgorithm, AffineGaps, TTracebackConfig, TExecPolicy> const &) { typedef typename TraceBitMap_<TScoreValue>::Type TTraceValue; // Compute vertical direction. TTraceValue tv = _maxScore(<API key>(previousVertical), <API key>(previousVertical) + <API key>(scoringScheme, seqHVal, seqVVal), _scoreOfCell(previousVertical) + <API key>(scoringScheme, seqHVal, seqVVal), TraceBitMap_<TScoreValue>::VERTICAL, TraceBitMap_<TScoreValue>::VERTICAL_OPEN, TTracebackConfig()); // Ignore horizontal direction in lower diagonal. <API key>(current) = <API key><DPCell_<TScoreValue, AffineGaps> >::VALUE; // Compute diagonal direction and compare with vertical. tv = _maxScore(_scoreOfCell(current), _scoreOfCell(previousDiagonal) + score(scoringScheme, seqHVal, seqVVal), <API key>(previousVertical), tv | TraceBitMap_<TScoreValue>::DIAGONAL, tv | TraceBitMap_<TScoreValue>::<API key>, TTracebackConfig()); if (IsLocalAlignment_<TAlgorithm>::VALUE) { tv = _maxScore(_scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, _scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, tv, TTracebackConfig{}); } return tv; } // Function _computeScore [<API key>] template <typename TScoreValue, typename TSequenceHValue, typename TSequenceVValue, typename TScoringScheme, typename TAlgorithm, typename TTracebackConfig, typename TExecPolicy> inline typename TraceBitMap_<TScoreValue>::Type _computeScore(DPCell_<TScoreValue, AffineGaps> & current, DPCell_<TScoreValue, AffineGaps> & previousDiagonal, DPCell_<TScoreValue, AffineGaps> const & previousHorizontal, DPCell_<TScoreValue, AffineGaps> & previousVertical, TSequenceHValue const & seqHVal, TSequenceVValue const & seqVVal, TScoringScheme const & scoringScheme, <API key> const &, DPProfile_<TAlgorithm, AffineGaps, TTracebackConfig, TExecPolicy> const &) { // Cache previous diagonal value. _scoreOfCell(previousDiagonal) = _scoreOfCell(previousHorizontal); // Compute horizontal direction. auto traceDir = _maxScore(<API key>(current), <API key>(previousHorizontal) + <API key>(scoringScheme, seqHVal, seqVVal), _scoreOfCell(previousHorizontal) + <API key>(scoringScheme, seqHVal, seqVVal), TraceBitMap_<TScoreValue>::HORIZONTAL, TraceBitMap_<TScoreValue>::HORIZONTAL_OPEN, TTracebackConfig()) | TraceBitMap_<TScoreValue>::<API key>; // Ignore vertical direction. <API key>(previousVertical) = <API key><DPCell_<TScoreValue, AffineGaps> >::VALUE; _scoreOfCell(current) = <API key>(current); if (IsLocalAlignment_<TAlgorithm>::VALUE) { traceDir = _maxScore(_scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, _scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, traceDir, TTracebackConfig{}); } _scoreOfCell(previousVertical) = _scoreOfCell(current); return traceDir; } // Function _computeScore [<API key>] template <typename TScoreValue, typename TSequenceHValue, typename TSequenceVValue, typename TScoringScheme, typename TAlgorithm, typename TTracebackConfig, typename TExecPolicy> inline typename TraceBitMap_<TScoreValue>::Type _computeScore(DPCell_<TScoreValue, AffineGaps> & current, DPCell_<TScoreValue, AffineGaps> const & /*previousDiagonal*/, DPCell_<TScoreValue, AffineGaps> const & /*previousHorizontal*/, DPCell_<TScoreValue, AffineGaps> & previousVertical, TSequenceHValue const & seqHVal, TSequenceVValue const & seqVVal, TScoringScheme const & scoringScheme, <API key> const &, DPProfile_<TAlgorithm, AffineGaps, TTracebackConfig, TExecPolicy> const &) { // Compute vertical direction. auto traceDir = _maxScore(<API key>(previousVertical), <API key>(previousVertical) + <API key>(scoringScheme, seqHVal, seqVVal), _scoreOfCell(previousVertical) + <API key>(scoringScheme, seqHVal, seqVVal), TraceBitMap_<TScoreValue>::VERTICAL, TraceBitMap_<TScoreValue>::VERTICAL_OPEN, TTracebackConfig()) | TraceBitMap_<TScoreValue>::<API key>; // Ignore horizontal direction. <API key>(current) = <API key><DPCell_<TScoreValue, AffineGaps> >::VALUE; _scoreOfCell(current) = <API key>(previousVertical); if (IsLocalAlignment_<TAlgorithm>::VALUE) { traceDir = _maxScore(_scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, _scoreOfCell(current), TraceBitMap_<TScoreValue>::NONE, traceDir, TTracebackConfig{}); } _scoreOfCell(previousVertical) = _scoreOfCell(current); return traceDir; } } // namespace seqan #endif // #ifndef <API key>
#include <string> #include <fstream> using namespace std; #include "Obj.h" #include "DataSet.h" #include "Prediction.h" using namespace libedm; // void operator +=(PRED_RESULT &a, const PRED_RESULT &b) // if(a.PredLabelIndices.size()==0) // return; // _ASSERT(a.ClassNum==b.ClassNum); // a.CaseNum+=b.CaseNum; // for(int i=0;i<(int)b.PredLabelIndices.size();i++) // a.PredLabelIndices.push_back(b.PredLabelIndices[i]); // for(int i=0;i<(int)b.IsCorrect.size();i++) // a.IsCorrect.push_back(b.IsCorrect[i]); // PRED_RESULT operator +(const PRED_RESULT &a, const PRED_RESULT &b) // _ASSERT(a.ClassNum==b.ClassNum); // PRED_RESULT c; // c.CaseNum=a.CaseNum+b.CaseNum; // c.ClassNum=a.ClassNum; // for(int i=0;i<(int)a.PredLabelIndices.size();i++) // c.PredLabelIndices.push_back(a.PredLabelIndices[i]); // for(int i=0;i<(int)b.PredLabelIndices.size();i++) // c.PredLabelIndices.push_back(b.PredLabelIndices[i]); // for(int i=0;i<(int)a.IsCorrect.size();i++) // c.IsCorrect.push_back(a.IsCorrect[i]); // for(int i=0;i<(int)b.IsCorrect.size();i++) // c.IsCorrect.push_back(b.IsCorrect[i]); // return c; CPrediction::~CPrediction() { } //Dataset: data set be predicted //Probabilities: Probabilities of each instance belong to each class label //start: start time of predicting CPrediction::CPrediction(const CDataset &Dataset,const DoubleArray2d &Probabilities,clock_t PredictTime) { const MATRIX &Data=Dataset.GetData(); const CASE_INFO &Info=Dataset.GetInfo(); CaseNum=Info.Height; ClassNum=Info.ClassNum; Accuracy=0; Probs.assign(Probabilities.begin(),Probabilities.end()); //the label of an instance is the class with the max probability for(int j=0;j<CaseNum;j++) { int Class=0; double MaxProb=0; for(int k=0;k<ClassNum;k++) if(Probs[j][k]>MaxProb) { Class=k; MaxProb=Probs[j][k]; } PredLabelIndices.push_back(Class); //correct prediction count int IdealResult=Data[j][Info.ValidWidth-1].Discr; if(IdealResult==Class) { IsCorrect.push_back(true); Accuracy+=1; } else IsCorrect.push_back(false); } Accuracy/=CaseNum; //Total time consumed CreatingTime = (double)PredictTime/CLOCKS_PER_SEC; } const DoubleArray2d& CPrediction::GetProbs() const { return Probs; } const IntArray& CPrediction::<API key>() const { return PredLabelIndices; } const BoolArray& CPrediction::GetCorrectness() const { return IsCorrect; } double CPrediction::GetAccuracy() const { return Accuracy; }
#ifndef <API key> #define <API key> #include <stdint.h> #include <memory> #include <string> #include <vector> #include "base/containers/queue.h" #include "base/optional.h" #include "base/strings/string16.h" #include "device/bluetooth/bluetooth_common.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/public/cpp/bluetooth_uuid.h" #include "device/bluetooth/test/<API key>.h" #include "testing/gmock/include/gmock/gmock.h" namespace device { class <API key>; class <API key>; class MockBluetoothDevice : public BluetoothDevice { public: MockBluetoothDevice(<API key>* adapter, uint32_t bluetooth_class, const char* name, const std::string& address, bool paired, bool connected); ~MockBluetoothDevice() override; MOCK_CONST_METHOD0(GetBluetoothClass, uint32_t()); MOCK_CONST_METHOD0(GetType, BluetoothTransport()); MOCK_CONST_METHOD0(GetIdentifier, std::string()); MOCK_CONST_METHOD0(GetAddress, std::string()); MOCK_CONST_METHOD0(GetVendorIDSource, BluetoothDevice::VendorIDSource()); MOCK_CONST_METHOD0(GetVendorID, uint16_t()); MOCK_CONST_METHOD0(GetProductID, uint16_t()); MOCK_CONST_METHOD0(GetDeviceID, uint16_t()); MOCK_CONST_METHOD0(GetAppearance, uint16_t()); MOCK_CONST_METHOD0(GetName, base::Optional<std::string>()); MOCK_CONST_METHOD0(GetNameForDisplay, base::string16()); MOCK_CONST_METHOD0(GetDeviceType, BluetoothDeviceType()); MOCK_CONST_METHOD0(IsPaired, bool()); MOCK_CONST_METHOD0(IsConnected, bool()); MOCK_CONST_METHOD0(IsGattConnected, bool()); MOCK_CONST_METHOD0(IsConnectable, bool()); MOCK_CONST_METHOD0(IsConnecting, bool()); MOCK_CONST_METHOD0(GetUUIDs, UUIDSet()); MOCK_CONST_METHOD0(GetInquiryRSSI, base::Optional<int8_t>()); MOCK_CONST_METHOD0(GetInquiryTxPower, base::Optional<int8_t>()); MOCK_CONST_METHOD0(ExpectingPinCode, bool()); MOCK_CONST_METHOD0(ExpectingPasskey, bool()); MOCK_CONST_METHOD0(<API key>, bool()); MOCK_METHOD1(GetConnectionInfo, void(const <API key>& callback)); MOCK_METHOD3(<API key>, void(ConnectionLatency connection_latency, const base::Closure& callback, const ErrorCallback& error_callback)); void Connect(BluetoothDevice::PairingDelegate* pairing_delegate, base::OnceClosure callback, BluetoothDevice::<API key> error_callback) override { Connect_(pairing_delegate, callback, error_callback); } MOCK_METHOD3(Connect_, void(BluetoothDevice::PairingDelegate* pairing_delegate, base::OnceClosure& callback, BluetoothDevice::<API key>& error_callback)); void Pair(BluetoothDevice::PairingDelegate* pairing_delegate, base::OnceClosure callback, BluetoothDevice::<API key> error_callback) override { Pair_(pairing_delegate, callback, error_callback); } MOCK_METHOD3(Pair_, void(BluetoothDevice::PairingDelegate* pairing_delegate, base::OnceClosure& callback, BluetoothDevice::<API key>& error_callback)); MOCK_METHOD1(SetPinCode, void(const std::string&)); MOCK_METHOD1(SetPasskey, void(uint32_t)); MOCK_METHOD0(ConfirmPairing, void()); MOCK_METHOD0(RejectPairing, void()); MOCK_METHOD0(CancelPairing, void()); MOCK_METHOD2(Disconnect, void(const base::Closure& callback, const BluetoothDevice::ErrorCallback& error_callback)); MOCK_METHOD2(Forget, void(const base::Closure& callback, const BluetoothDevice::ErrorCallback& error_callback)); MOCK_METHOD3(ConnectToService, void(const BluetoothUUID& uuid, const <API key>& callback, const <API key>& error_callback)); MOCK_METHOD3(<API key>, void(const BluetoothUUID& uuid, const <API key>& callback, const <API key>& error_callback)); void <API key>( <API key> callback, <API key> error_callback, base::Optional<BluetoothUUID> service_uuid) override { <API key>(callback, error_callback); } MOCK_METHOD2(<API key>, void(<API key>& callback, <API key>& error_callback)); MOCK_METHOD1(<API key>, void(bool)); MOCK_CONST_METHOD0(<API key>, bool()); MOCK_CONST_METHOD0(GetGattServices, std::vector<<API key>*>()); MOCK_CONST_METHOD1(GetGattService, <API key>*(const std::string&)); MOCK_METHOD1(<API key>, void(base::Optional<BluetoothUUID> service_uuid)); MOCK_METHOD0(DisconnectGatt, void()); #if defined(OS_CHROMEOS) MOCK_METHOD2(ExecuteWrite, void(const base::Closure& callback, const <API key>& error_callback)); MOCK_METHOD2(AbortWrite, void(const base::Closure& callback, const <API key>& error_callback)); #endif // BluetoothDevice manages the lifetime of its <API key>. // This method takes ownership of the <API key>. This is only // for convenience as far as testing is concerned, and it's possible to write // test cases without using these functions. // Example: // ON_CALL(*mock_device, GetGattServices)) // .WillByDefault(Invoke(*mock_device, // &MockBluetoothDevice::GetMockServices)); void AddMockService(std::unique_ptr<<API key>> mock_device); std::vector<<API key>*> GetMockServices() const; <API key>* GetMockService( const std::string& identifier) const; void AddUUID(const BluetoothUUID& uuid) { uuids_.insert(uuid); } // Functions to save and run callbacks from this device. Useful when // trying to run callbacks in response to other actions e.g. run a read // value callback in response to a connection request. // Appends callback to the end of the callbacks queue. void PushPendingCallback(base::OnceClosure callback); // Runs all pending callbacks. void RunPendingCallbacks(); void SetConnected(bool connected) { connected_ = connected; } private: uint32_t bluetooth_class_; base::Optional<std::string> name_; std::string address_; BluetoothDevice::UUIDSet uuids_; bool connected_; // Used by tests to save callbacks that will be run in the future. base::queue<base::OnceClosure> pending_callbacks_; std::vector<std::unique_ptr<<API key>>> mock_services_; }; } // namespace device #endif // <API key>
<?php namespace backend\controllers; use common\helper\AjaxReturn; use service\models\message\Message; class WithDrawController extends \backend\common\controller\BaseController { public function actionIndex() { $withDraw = new \backend\models\withDraw\WithDrawMessenge(); $withDrawData = $withDraw->getWithDrawData('1'); $alreadyWithDrawData = $withDraw->getWithDrawData('2'); return $this->render('index', [ 'withDrawData'=>$withDrawData, 'alreadyWithDrawData'=>$alreadyWithDrawData, ]); } public function actionBankCard($uid) { if (\Yii::$app->request->isAjax) { $bankCard = new \backend\models\withDraw\BankCardRecord; $bankCardData = $bankCard->getBackCardData($uid); return AjaxReturn::JSON($bankCardData); } } public function actionWithDraw($id,$uid) { $withDraw = new \backend\models\withDraw\WithDrawMessenge(); $model = new Message(); if($id){ $withDraw->withDrawUpdate($id, 2); $model->send(14273, $uid, '!', '1'); return $this->redirect('/with-draw/index'); } } }
// of patent rights can be found in the PATENTS file in the same directory. #include "table/<API key>.h" #include <assert.h> #include <inttypes.h> #include <stdio.h> #include <list> #include <map> #include <memory> #include <string> #include <unordered_map> #include <utility> #include "db/dbformat.h" #include "rocksdb/cache.h" #include "rocksdb/comparator.h" #include "rocksdb/env.h" #include "rocksdb/filter_policy.h" #include "rocksdb/flush_block_policy.h" #include "rocksdb/merge_operator.h" #include "rocksdb/table.h" #include "table/block.h" #include "table/<API key>.h" #include "table/block_builder.h" #include "table/filter_block.h" #include "table/<API key>.h" #include "table/<API key>.h" #include "table/full_filter_block.h" #include "table/format.h" #include "table/meta_blocks.h" #include "table/table_builder.h" #include "util/string_util.h" #include "util/coding.h" #include "util/compression.h" #include "util/crc32c.h" #include "util/stop_watch.h" #include "util/xxhash.h" namespace rocksdb { extern const std::string <API key>; extern const std::string <API key>; typedef <API key>::IndexType IndexType; class IndexBuilder; namespace { rocksdb::IndexBuilder* CreateIndexBuilder( IndexType index_type, const <API key>* comparator, const SliceTransform* prefix_extractor, int <API key>, uint64_t index_per_partition); } // The interface for building index. // Instruction for adding a new concrete IndexBuilder: // 1. Create a subclass instantiated from IndexBuilder. // 2. Add a new entry associated with that subclass in TableOptions::IndexType. // 3. Add a create function for the new subclass in CreateIndexBuilder. // Note: we can devise more advanced design to simplify the process for adding // new subclass, which will, on the other hand, increase the code complexity and // catch unwanted attention from readers. Given that we won't add/change // indexes frequently, it makes sense to just embrace a more straightforward // design that just works. class IndexBuilder { public: // Index builder will construct a set of blocks which contain: // 1. One primary index block. // 2. (Optional) a set of metablocks that contains the metadata of the // primary index. struct IndexBlocks { Slice <API key>; std::unordered_map<std::string, Slice> meta_blocks; }; explicit IndexBuilder(const <API key>* comparator) : comparator_(comparator) {} virtual ~IndexBuilder() {} // Add a new index entry to index block. // To allow further optimization, we provide `<API key>` and // `<API key>`, based on which the specific implementation can // determine the best index key to be used for the index block. // @<API key>: this parameter maybe overridden with the value // "substitute key". // @<API key>: it will be nullptr if the entry being added is // the last one in the table // REQUIRES: Finish() has not yet been called. virtual void AddIndexEntry(std::string* <API key>, const Slice* <API key>, const BlockHandle& block_handle) = 0; // This method will be called whenever a key is added. The subclasses may // override OnKeyAdded() if they need to collect additional information. virtual void OnKeyAdded(const Slice& key) {} // Inform the index builder that all entries has been written. Block builder // may therefore perform any operation required for block finalization. // REQUIRES: Finish() has not yet been called. inline Status Finish(IndexBlocks* index_blocks) { // Throw away the changes to <API key>. It has no effect // on the first call to Finish anyway. BlockHandle <API key>; return Finish(index_blocks, <API key>); } // This override of Finish can be utilized to build the 2nd level index in // <API key>. // index_blocks will be filled with the resulting index data. If the return // value is Status::InComplete() then it means that the index is partitioned // and the callee should keep calling Finish until Status::OK() is returned. // In that case, <API key> is pointer to the block written // with the result of the last call to Finish. This can be utilized to build // the second level index pointing to each block of partitioned indexes. The // last call to Finish() that returns Status::OK() populates index_blocks with // the 2nd level index content. virtual Status Finish(IndexBlocks* index_blocks, const BlockHandle& <API key>) = 0; // Get the estimated size for index block. virtual size_t EstimatedSize() const = 0; protected: const <API key>* comparator_; }; // This index builder builds space-efficient index block. // Optimizations: // 1. Made block's `<API key>` to be 1, which will avoid linear // search when doing index lookup (can be disabled by setting // <API key>). // 2. Shorten the key length for index block. Other than honestly using the // last key in the data block as the index key, we instead find a shortest // substitute key that serves the same function. class <API key> : public IndexBuilder { public: explicit <API key>(const <API key>* comparator, int <API key>) : IndexBuilder(comparator), <API key>(<API key>) {} virtual void AddIndexEntry(std::string* <API key>, const Slice* <API key>, const BlockHandle& block_handle) override { if (<API key> != nullptr) { comparator_-><API key>(<API key>, *<API key>); } else { comparator_->FindShortSuccessor(<API key>); } std::string handle_encoding; block_handle.EncodeTo(&handle_encoding); <API key>.Add(*<API key>, handle_encoding); } virtual Status Finish( IndexBlocks* index_blocks, const BlockHandle& <API key>) override { index_blocks-><API key> = <API key>.Finish(); return Status::OK(); } virtual size_t EstimatedSize() const override { return <API key>.CurrentSizeEstimate(); } private: BlockBuilder <API key>; }; /** * IndexBuilder for two-level indexing. Internally it creates a new index for * each partition and Finish then in order when Finish is called on it * continiously until Status::OK() is returned. * * The format on the disk would be I I I I I I IP where I is block containing a * partition of indexes built using <API key> and IP is a block * containing a secondary index on the partitions, built using * <API key>. */ class <API key> : public IndexBuilder { public: explicit <API key>(const <API key>* comparator, const SliceTransform* prefix_extractor, const uint64_t index_per_partition, int <API key>) : IndexBuilder(comparator), prefix_extractor_(prefix_extractor), <API key>(<API key>), <API key>(index_per_partition), <API key>(<API key>) { sub_index_builder_ = CreateIndexBuilder(sub_type_, comparator_, prefix_extractor_, <API key>, <API key>); } virtual ~<API key>() { delete sub_index_builder_; } virtual void AddIndexEntry(std::string* <API key>, const Slice* <API key>, const BlockHandle& block_handle) override { sub_index_builder_->AddIndexEntry(<API key>, <API key>, block_handle); num_indexes++; if (UNLIKELY(<API key> == nullptr)) { // no more keys entries_.push_back({std::string(*<API key>), std::unique_ptr<IndexBuilder>(sub_index_builder_)}); sub_index_builder_ = nullptr; } else if (num_indexes % <API key> == 0) { entries_.push_back({std::string(*<API key>), std::unique_ptr<IndexBuilder>(sub_index_builder_)}); sub_index_builder_ = CreateIndexBuilder( sub_type_, comparator_, prefix_extractor_, <API key>, <API key>); } } virtual Status Finish( IndexBlocks* index_blocks, const BlockHandle& <API key>) override { assert(!entries_.empty()); // It must be set to null after last key is added assert(sub_index_builder_ == nullptr); if (finishing == true) { Entry& last_entry = entries_.front(); std::string handle_encoding; <API key>.EncodeTo(&handle_encoding); <API key>.Add(last_entry.key, handle_encoding); entries_.pop_front(); } // If there is no sub_index left, then return the 2nd level index. if (UNLIKELY(entries_.empty())) { index_blocks-><API key> = <API key>.Finish(); return Status::OK(); } else { // Finish the next partition index in line and Incomplete() to indicate we // expect more calls to Finish Entry& entry = entries_.front(); auto s = entry.value->Finish(index_blocks); finishing = true; return s.ok() ? Status::Incomplete() : s; } } virtual size_t EstimatedSize() const override { size_t total = 0; for (auto it = entries_.begin(); it != entries_.end(); ++it) { total += it->value->EstimatedSize(); } total += <API key>.CurrentSizeEstimate(); total += sub_index_builder_ == nullptr ? 0 : sub_index_builder_->EstimatedSize(); return total; } private: static const IndexType sub_type_ = <API key>::kBinarySearch; struct Entry { std::string key; std::unique_ptr<IndexBuilder> value; }; std::list<Entry> entries_; // list of partitioned indexes and their keys const SliceTransform* prefix_extractor_; BlockBuilder <API key>; // top-level index builder IndexBuilder* sub_index_builder_; // the active partition index builder uint64_t <API key>; int <API key>; uint64_t num_indexes = 0; bool finishing = false; // true if Finish is called once but not complete yet. }; // HashIndexBuilder contains a binary-searchable primary index and the // metadata for secondary hash index construction. // The metadata for hash index consists two parts: // - a metablock that compactly contains a sequence of prefixes. All prefixes // are stored consectively without any metadata (like, prefix sizes) being // stored, which is kept in the other metablock. // - a metablock contains the metadata of the prefixes, including prefix size, // restart index and number of block it spans. The format looks like: // | length: 4 bytes | restart interval: 4 bytes | num-blocks: 4 bytes | // | length: 4 bytes | restart interval: 4 bytes | num-blocks: 4 bytes | // | length: 4 bytes | restart interval: 4 bytes | num-blocks: 4 bytes | // The reason of separating these two metablocks is to enable the efficiently // reuse the first metablock during hash index construction without unnecessary // data copy or small heap allocations for prefixes. class HashIndexBuilder : public IndexBuilder { public: explicit HashIndexBuilder(const <API key>* comparator, const SliceTransform* hash_key_extractor, int <API key>) : IndexBuilder(comparator), <API key>(comparator, <API key>), hash_key_extractor_(hash_key_extractor) {} virtual void AddIndexEntry(std::string* <API key>, const Slice* <API key>, const BlockHandle& block_handle) override { ++<API key>; <API key>.AddIndexEntry(<API key>, <API key>, block_handle); } virtual void OnKeyAdded(const Slice& key) override { auto key_prefix = hash_key_extractor_->Transform(key); bool is_first_entry = pending_block_num_ == 0; // Keys may share the prefix if (is_first_entry || <API key> != key_prefix) { if (!is_first_entry) { FlushPendingPrefix(); } // need a hard copy otherwise the underlying data changes all the time. // TODO(kailiu) ToString() is expensive. We may speed up can avoid data // copy. <API key> = key_prefix.ToString(); pending_block_num_ = 1; <API key> = static_cast<uint32_t>(<API key>); } else { // entry number increments when keys share the prefix reside in // different data blocks. auto last_restart_index = <API key> + pending_block_num_ - 1; assert(last_restart_index <= <API key>); if (last_restart_index != <API key>) { ++pending_block_num_; } } } virtual Status Finish( IndexBlocks* index_blocks, const BlockHandle& <API key>) override { FlushPendingPrefix(); <API key>.Finish(index_blocks, <API key>); index_blocks->meta_blocks.insert( {<API key>.c_str(), prefix_block_}); index_blocks->meta_blocks.insert( {<API key>.c_str(), prefix_meta_block_}); return Status::OK(); } virtual size_t EstimatedSize() const override { return <API key>.EstimatedSize() + prefix_block_.size() + prefix_meta_block_.size(); } private: void FlushPendingPrefix() { prefix_block_.append(<API key>.data(), <API key>.size()); <API key>( &prefix_meta_block_, static_cast<uint32_t>(<API key>.size()), <API key>, pending_block_num_); } <API key> <API key>; const SliceTransform* hash_key_extractor_; // stores a sequence of prefixes std::string prefix_block_; // stores the metadata of prefixes std::string prefix_meta_block_; // The following 3 variables keeps unflushed prefix and its metadata. // The details of block_num and entry_index can be found in // "block_hash_index.{h,cc}" uint32_t pending_block_num_ = 0; uint32_t <API key> = 0; std::string <API key>; uint64_t <API key> = 0; }; // Without anonymous namespace here, we fail the warning -Wmissing-prototypes namespace { // Create a index builder based on its type. IndexBuilder* CreateIndexBuilder(IndexType index_type, const <API key>* comparator, const SliceTransform* prefix_extractor, int <API key>, uint64_t index_per_partition) { switch (index_type) { case <API key>::kBinarySearch: { return new <API key>(comparator, <API key>); } case <API key>::kHashSearch: { return new HashIndexBuilder(comparator, prefix_extractor, <API key>); } case <API key>::<API key>: { return new <API key>(comparator, prefix_extractor, index_per_partition, <API key>); } default: { assert(!"Do not recognize the index type "); return nullptr; } } // impossible. assert(false); return nullptr; } // Create a index builder based on its type. FilterBlockBuilder* <API key>(const ImmutableCFOptions& opt, const <API key>& table_opt) { if (table_opt.filter_policy == nullptr) return nullptr; FilterBitsBuilder* filter_bits_builder = table_opt.filter_policy-><API key>(); if (filter_bits_builder == nullptr) { return new <API key>(opt.prefix_extractor, table_opt); } else { return new <API key>(opt.prefix_extractor, table_opt.whole_key_filtering, filter_bits_builder); } } bool <API key>(size_t compressed_size, size_t raw_size) { // Check to see if compressed less than 12.5% return compressed_size < raw_size - (raw_size / 8u); } } // namespace // format_version is the block format as defined in include/rocksdb/table.h Slice CompressBlock(const Slice& raw, const CompressionOptions& compression_options, CompressionType* type, uint32_t format_version, const Slice& compression_dict, std::string* compressed_output) { if (*type == kNoCompression) { return raw; } // Will return compressed block contents if (1) the compression method is // supported in this platform and (2) the compression rate is "good enough". switch (*type) { case kSnappyCompression: if (Snappy_Compress(compression_options, raw.data(), raw.size(), compressed_output) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; // fall back to no compression. case kZlibCompression: if (Zlib_Compress( compression_options, <API key>(kZlibCompression, format_version), raw.data(), raw.size(), compressed_output, compression_dict) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; // fall back to no compression. case kBZip2Compression: if (BZip2_Compress( compression_options, <API key>(kBZip2Compression, format_version), raw.data(), raw.size(), compressed_output) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; // fall back to no compression. case kLZ4Compression: if (LZ4_Compress( compression_options, <API key>(kLZ4Compression, format_version), raw.data(), raw.size(), compressed_output, compression_dict) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; // fall back to no compression. case kLZ4HCCompression: if (LZ4HC_Compress( compression_options, <API key>(kLZ4HCCompression, format_version), raw.data(), raw.size(), compressed_output, compression_dict) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; // fall back to no compression. case kXpressCompression: if (XPRESS_Compress(raw.data(), raw.size(), compressed_output) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; case kZSTD: case <API key>: if (ZSTD_Compress(compression_options, raw.data(), raw.size(), compressed_output, compression_dict) && <API key>(compressed_output->size(), raw.size())) { return *compressed_output; } break; // fall back to no compression. default: {} // Do not recognize this compression type } // Compression method is not supported, or not good compression ratio, so just // fall back to uncompressed form. *type = kNoCompression; return raw; } // <API key> was picked by running // echo rocksdb.table.block_based | sha1sum // and taking the leading 64 bits. // Please note that <API key> may also be accessed by other // .cc files // for that reason we declare it extern in the header but to get the space // allocated // it must be not extern in one place. const uint64_t <API key> = <API key>; // We also support reading and writing legacy block based table format (for // backwards compatibility) const uint64_t <API key> = <API key>; // A collector that collects properties of interest to block-based table. // For now this class looks heavy-weight since we only write one additional // property. // But in the foreseeable future, we will add more and more properties that are // specific to block-based table. class <API key>::<API key> : public IntTblPropCollector { public: explicit <API key>( <API key>::IndexType index_type, bool whole_key_filtering, bool prefix_filtering) : index_type_(index_type), <API key>(whole_key_filtering), prefix_filtering_(prefix_filtering) {} virtual Status InternalAdd(const Slice& key, const Slice& value, uint64_t file_size) override { // Intentionally left blank. Have no interest in collecting stats for // individual key/value pairs. return Status::OK(); } virtual Status Finish(<API key>* properties) override { std::string val; PutFixed32(&val, static_cast<uint32_t>(index_type_)); properties->insert({<API key>::kIndexType, val}); properties->insert({<API key>::kWholeKeyFiltering, <API key> ? kPropTrue : kPropFalse}); properties->insert({<API key>::kPrefixFiltering, prefix_filtering_ ? kPropTrue : kPropFalse}); return Status::OK(); } // The name of the properties collector can be used for debugging purpose. virtual const char* Name() const override { return "<API key>"; } virtual <API key> <API key>() const override { // Intentionally left blank. return <API key>(); } private: <API key>::IndexType index_type_; bool <API key>; bool prefix_filtering_; }; struct <API key>::Rep { const ImmutableCFOptions ioptions; const <API key> table_options; const <API key>& internal_comparator; WritableFileWriter* file; uint64_t offset = 0; Status status; BlockBuilder data_block; BlockBuilder range_del_block; <API key> <API key>; std::unique_ptr<IndexBuilder> index_builder; std::string last_key; const CompressionType compression_type; const CompressionOptions compression_opts; // Data for presetting the compression library's dictionary, or nullptr. const std::string* compression_dict; TableProperties props; bool closed = false; // Either Finish() or Abandon() has been called. std::unique_ptr<FilterBlockBuilder> filter_block; char <API key>[BlockBasedTable::<API key>]; size_t <API key>; BlockHandle pending_handle; // Handle to add to index block std::string compressed_output; std::unique_ptr<FlushBlockPolicy> flush_block_policy; uint32_t column_family_id; const std::string& column_family_name; std::vector<std::unique_ptr<IntTblPropCollector>> <API key>; Rep(const ImmutableCFOptions& _ioptions, const <API key>& table_opt, const <API key>& icomparator, const std::vector<std::unique_ptr<<API key>>>* <API key>, uint32_t _column_family_id, WritableFileWriter* f, const CompressionType _compression_type, const CompressionOptions& _compression_opts, const std::string* _compression_dict, const bool skip_filters, const std::string& _column_family_name) : ioptions(_ioptions), table_options(table_opt), internal_comparator(icomparator), file(f), data_block(table_options.<API key>, table_options.use_delta_encoding), range_del_block(1), // TODO(andrewkr): restart_interval unnecessary <API key>(_ioptions.prefix_extractor), index_builder( CreateIndexBuilder(table_options.index_type, &internal_comparator, &this-><API key>, table_options.<API key>, table_options.index_per_partition)), compression_type(_compression_type), compression_opts(_compression_opts), compression_dict(_compression_dict), filter_block(skip_filters ? nullptr : <API key>( _ioptions, table_options)), flush_block_policy( table_options.<API key>->NewFlushBlockPolicy( table_options, data_block)), column_family_id(_column_family_id), column_family_name(_column_family_name) { for (auto& collector_factories : *<API key>) { <API key>.emplace_back( collector_factories-><API key>(column_family_id)); } <API key>.emplace_back( new <API key>( table_options.index_type, table_options.whole_key_filtering, _ioptions.prefix_extractor != nullptr)); } }; <API key>::<API key>( const ImmutableCFOptions& ioptions, const <API key>& table_options, const <API key>& internal_comparator, const std::vector<std::unique_ptr<<API key>>>* <API key>, uint32_t column_family_id, WritableFileWriter* file, const CompressionType compression_type, const CompressionOptions& compression_opts, const std::string* compression_dict, const bool skip_filters, const std::string& column_family_name) { <API key> <API key>(table_options); if (<API key>.format_version == 0 && <API key>.checksum != kCRC32c) { Log(InfoLogLevel::WARN_LEVEL, ioptions.info_log, "Silently converting format_version to 1 because checksum is " "non-default"); // silently convert format_version to 1 to keep consistent with current // behavior <API key>.format_version = 1; } rep_ = new Rep(ioptions, <API key>, internal_comparator, <API key>, column_family_id, file, compression_type, compression_opts, compression_dict, skip_filters, column_family_name); if (rep_->filter_block != nullptr) { rep_->filter_block->StartBlock(0); } if (table_options.<API key>.get() != nullptr) { BlockBasedTable::GenerateCachePrefix( table_options.<API key>.get(), file->writable_file(), &rep_-><API key>[0], &rep_-><API key>); } } <API key>::~<API key>() { assert(rep_->closed); // Catch errors where caller forgot to call Finish() delete rep_; } void <API key>::Add(const Slice& key, const Slice& value) { Rep* r = rep_; assert(!r->closed); if (!ok()) return; ValueType value_type = ExtractValueType(key); if (IsValueType(value_type)) { if (r->props.num_entries > 0) { assert(r->internal_comparator.Compare(key, Slice(r->last_key)) > 0); } auto should_flush = r->flush_block_policy->Update(key, value); if (should_flush) { assert(!r->data_block.empty()); Flush(); // Add item to index block. // We do not emit the index entry for a block until we have seen the // first key for the next data block. This allows us to use shorter // keys in the index block. For example, consider a block boundary // between the keys "the quick brown fox" and "the who". We can use // "the r" as the key for the index block entry since it is >= all // entries in the first block and < all entries in subsequent // blocks. if (ok()) { r->index_builder->AddIndexEntry(&r->last_key, &key, r->pending_handle); } } if (r->filter_block != nullptr) { r->filter_block->Add(ExtractUserKey(key)); } r->last_key.assign(key.data(), key.size()); r->data_block.Add(key, value); r->props.num_entries++; r->props.raw_key_size += key.size(); r->props.raw_value_size += value.size(); r->index_builder->OnKeyAdded(key); <API key>(key, value, r->offset, r-><API key>, r->ioptions.info_log); } else if (value_type == kTypeRangeDeletion) { // TODO(wanning&andrewkr) add num_tomestone to table properties r->range_del_block.Add(key, value); ++r->props.num_entries; r->props.raw_key_size += key.size(); r->props.raw_value_size += value.size(); <API key>(key, value, r->offset, r-><API key>, r->ioptions.info_log); } else { assert(false); } } void <API key>::Flush() { Rep* r = rep_; assert(!r->closed); if (!ok()) return; if (r->data_block.empty()) return; WriteBlock(&r->data_block, &r->pending_handle, true /* is_data_block */); if (ok() && !r->table_options.<API key>) { r->status = r->file->Flush(); } if (r->filter_block != nullptr) { r->filter_block->StartBlock(r->offset); } r->props.data_size = r->offset; ++r->props.num_data_blocks; } void <API key>::WriteBlock(BlockBuilder* block, BlockHandle* handle, bool is_data_block) { WriteBlock(block->Finish(), handle, is_data_block); block->Reset(); } void <API key>::WriteBlock(const Slice& raw_block_contents, BlockHandle* handle, bool is_data_block) { // File format contains a sequence of blocks where each block has: // block_data: uint8[n] // type: uint8 // crc: uint32 assert(ok()); Rep* r = rep_; auto type = r->compression_type; Slice block_contents; bool abort_compression = false; StopWatchNano timer(r->ioptions.env, <API key>(r->ioptions.env, r->ioptions.statistics)); if (raw_block_contents.size() < <API key>) { Slice compression_dict; if (is_data_block && r->compression_dict && r->compression_dict->size()) { compression_dict = *r->compression_dict; } block_contents = CompressBlock(raw_block_contents, r->compression_opts, &type, r->table_options.format_version, compression_dict, &r->compressed_output); // Some of the compression algorithms are known to be unreliable. If // the verify_compression flag is set then try to de-compress the // compressed data and compare to the input. if (type != kNoCompression && r->table_options.verify_compression) { // Retrieve the uncompressed contents into a new buffer BlockContents contents; Status stat = <API key>( block_contents.data(), block_contents.size(), &contents, r->table_options.format_version, compression_dict, type, r->ioptions); if (stat.ok()) { bool compressed_ok = contents.data.compare(raw_block_contents) == 0; if (!compressed_ok) { // The result of the compression was invalid. abort. abort_compression = true; Log(InfoLogLevel::ERROR_LEVEL, r->ioptions.info_log, "Decompressed block did not match raw block"); r->status = Status::Corruption("Decompressed block did not match raw block"); } } else { // Decompression reported an error. abort. r->status = Status::Corruption("Could not decompress"); abort_compression = true; } } } else { // Block is too big to be compressed. abort_compression = true; } // Abort compression if the block is too big, or did not pass // verification. if (abort_compression) { RecordTick(r->ioptions.statistics, <API key>); type = kNoCompression; block_contents = raw_block_contents; } else if (type != kNoCompression && <API key>(r->ioptions.env, r->ioptions.statistics)) { MeasureTime(r->ioptions.statistics, <API key>, timer.ElapsedNanos()); MeasureTime(r->ioptions.statistics, BYTES_COMPRESSED, raw_block_contents.size()); RecordTick(r->ioptions.statistics, <API key>); } WriteRawBlock(block_contents, type, handle); r->compressed_output.clear(); } void <API key>::WriteRawBlock(const Slice& block_contents, CompressionType type, BlockHandle* handle) { Rep* r = rep_; StopWatch sw(r->ioptions.env, r->ioptions.statistics, <API key>); handle->set_offset(r->offset); handle->set_size(block_contents.size()); r->status = r->file->Append(block_contents); if (r->status.ok()) { char trailer[kBlockTrailerSize]; trailer[0] = type; char* <API key> = trailer + 1; switch (r->table_options.checksum) { case kNoChecksum: // we don't support no checksum yet assert(false); // intentional fallthrough case kCRC32c: { auto crc = crc32c::Value(block_contents.data(), block_contents.size()); crc = crc32c::Extend(crc, trailer, 1); // Extend to cover block type EncodeFixed32(<API key>, crc32c::Mask(crc)); break; } case kxxHash: { void* xxh = XXH32_init(0); XXH32_update(xxh, block_contents.data(), static_cast<uint32_t>(block_contents.size())); XXH32_update(xxh, trailer, 1); // Extend to cover block type EncodeFixed32(<API key>, XXH32_digest(xxh)); break; } } r->status = r->file->Append(Slice(trailer, kBlockTrailerSize)); if (r->status.ok()) { r->status = InsertBlockInCache(block_contents, type, handle); } if (r->status.ok()) { r->offset += block_contents.size() + kBlockTrailerSize; } } } Status <API key>::status() const { return rep_->status; } static void DeleteCachedBlock(const Slice& key, void* value) { Block* block = reinterpret_cast<Block*>(value); delete block; } // Make a copy of the block contents and insert into compressed block cache Status <API key>::InsertBlockInCache(const Slice& block_contents, const CompressionType type, const BlockHandle* handle) { Rep* r = rep_; Cache* <API key> = r->table_options.<API key>.get(); if (type != kNoCompression && <API key> != nullptr) { size_t size = block_contents.size(); std::unique_ptr<char[]> ubuf(new char[size + 1]); memcpy(ubuf.get(), block_contents.data(), size); ubuf[size] = type; BlockContents results(std::move(ubuf), size, true, type); Block* block = new Block(std::move(results), <API key>); // make cache key by appending the file offset to the cache prefix id char* end = EncodeVarint64( r-><API key> + r-><API key>, handle->offset()); Slice key(r-><API key>, static_cast<size_t> (end - r-><API key>)); // Insert into compressed block cache. <API key>->Insert(key, block, block->usable_size(), &DeleteCachedBlock); // Invalidate OS cache. r->file->InvalidateCache(static_cast<size_t>(r->offset), size); } return Status::OK(); } Status <API key>::Finish() { Rep* r = rep_; bool empty_data_block = r->data_block.empty(); Flush(); assert(!r->closed); r->closed = true; BlockHandle filter_block_handle, <API key>, index_block_handle, <API key>, <API key>; // Write filter block if (ok() && r->filter_block != nullptr) { auto filter_contents = r->filter_block->Finish(); r->props.filter_size = filter_contents.size(); WriteRawBlock(filter_contents, kNoCompression, &filter_block_handle); } // To make sure properties block is able to keep the accurate size of index // block, we will finish writing all index entries here and flush them // to storage after metaindex block is written. if (ok() && !empty_data_block) { r->index_builder->AddIndexEntry( &r->last_key, nullptr /* no next data block */, r->pending_handle); } IndexBuilder::IndexBlocks index_blocks; auto <API key> = r->index_builder->Finish(&index_blocks); if (<API key>.IsIncomplete()) { // We we have more than one index partition then meta_blocks are not // supported for the index. Currently meta_blocks are used only by // HashIndexBuilder which is not multi-partition. assert(index_blocks.meta_blocks.empty()); } else if (!<API key>.ok()) { return <API key>; } // Write meta blocks and metaindex block with the following order. // 1. [meta block: filter] // 2. [meta block: properties] // 3. [meta block: compression dictionary] // 4. [meta block: range deletion tombstone] // 5. [metaindex block] // write meta blocks MetaIndexBuilder meta_index_builder; for (const auto& item : index_blocks.meta_blocks) { BlockHandle block_handle; WriteBlock(item.second, &block_handle, false /* is_data_block */); meta_index_builder.Add(item.first, block_handle); } if (ok()) { if (r->filter_block != nullptr) { // Add mapping from "<filter_block_prefix>.Name" to location // of filter data. std::string key; if (r->filter_block->IsBlockBased()) { key = BlockBasedTable::kFilterBlockPrefix; } else { key = BlockBasedTable::<API key>; } key.append(r->table_options.filter_policy->Name()); meta_index_builder.Add(key, filter_block_handle); } // Write properties and compression dictionary blocks. { <API key> <API key>; r->props.column_family_id = r->column_family_id; r->props.column_family_name = r->column_family_name; r->props.filter_policy_name = r->table_options.filter_policy != nullptr ? r->table_options.filter_policy->Name() : ""; r->props.index_size = r->index_builder->EstimatedSize() + kBlockTrailerSize; r->props.comparator_name = r->ioptions.user_comparator != nullptr ? r->ioptions.user_comparator->Name() : "nullptr"; r->props.merge_operator_name = r->ioptions.merge_operator != nullptr ? r->ioptions.merge_operator->Name() : "nullptr"; r->props.compression_name = <API key>(r->compression_type); r->props.<API key> = r->ioptions.prefix_extractor != nullptr ? r->ioptions.prefix_extractor->Name() : "nullptr"; std::string <API key> = "["; <API key> = "["; for (size_t i = 0; i < r->ioptions.<API key>.size(); ++i) { if (i != 0) { <API key> += ","; } <API key> += r->ioptions.<API key>[i]->Name(); } <API key> += "]"; r->props.<API key> = <API key>; // Add basic properties <API key>.AddTableProperty(r->props); // Add use collected properties <API key>(r-><API key>, r->ioptions.info_log, &<API key>); BlockHandle <API key>; WriteRawBlock( <API key>.Finish(), kNoCompression, &<API key> ); meta_index_builder.Add(kPropertiesBlock, <API key>); // Write compression dictionary block if (r->compression_dict && r->compression_dict->size()) { WriteRawBlock(*r->compression_dict, kNoCompression, &<API key>); meta_index_builder.Add(<API key>, <API key>); } } // end of properties/compression dictionary block writing if (ok() && !r->range_del_block.empty()) { WriteRawBlock(r->range_del_block.Finish(), kNoCompression, &<API key>); meta_index_builder.Add(kRangeDelBlock, <API key>); } // range deletion tombstone meta block } // meta blocks // Write index block if (ok()) { // flush the meta index block WriteRawBlock(meta_index_builder.Finish(), kNoCompression, &<API key>); const bool is_data_block = true; WriteBlock(index_blocks.<API key>, &index_block_handle, !is_data_block); // If there are more index partitions, finish them and write them out Status& s = <API key>; while (s.IsIncomplete()) { s = r->index_builder->Finish(&index_blocks, index_block_handle); if (!s.ok() && !s.IsIncomplete()) { return s; } WriteBlock(index_blocks.<API key>, &index_block_handle, !is_data_block); // The last index_block_handle will be for the partition index block } } // Write footer if (ok()) { // No need to write out new footer if we're using default checksum. // We're writing legacy magic number because we want old versions of RocksDB // be able to read files generated with new release (just in case if // somebody wants to roll back after an upgrade) // TODO(icanadi) at some point in the future, when we're absolutely sure // nobody will roll back to RocksDB 2.x versions, retire the legacy magic // number and always write new table files with new magic number bool legacy = (r->table_options.format_version == 0); // this is guaranteed by <API key>'s constructor assert(r->table_options.checksum == kCRC32c || r->table_options.format_version != 0); Footer footer(legacy ? <API key> : <API key>, r->table_options.format_version); footer.<API key>(<API key>); footer.set_index_handle(index_block_handle); footer.set_checksum(r->table_options.checksum); std::string footer_encoding; footer.EncodeTo(&footer_encoding); r->status = r->file->Append(footer_encoding); if (r->status.ok()) { r->offset += footer_encoding.size(); } } return r->status; } void <API key>::Abandon() { Rep* r = rep_; assert(!r->closed); r->closed = true; } uint64_t <API key>::NumEntries() const { return rep_->props.num_entries; } uint64_t <API key>::FileSize() const { return rep_->offset; } bool <API key>::NeedCompact() const { for (const auto& collector : rep_-><API key>) { if (collector->NeedCompact()) { return true; } } return false; } TableProperties <API key>::GetTableProperties() const { TableProperties ret = rep_->props; for (const auto& collector : rep_-><API key>) { for (const auto& prop : collector-><API key>()) { ret.readable_properties.insert(prop); } collector->Finish(&ret.<API key>); } return ret; } const std::string BlockBasedTable::kFilterBlockPrefix = "filter."; const std::string BlockBasedTable::<API key> = "fullfilter."; } // namespace rocksdb
PKG_NAME = db PKG_VERS = 6.2.23 PKG_EXT = tar.gz PKG_DIST_NAME = $(PKG_NAME)-$(PKG_VERS).$(PKG_EXT) PKG_DIST_SITE = http://download.oracle.com/berkeley-db PKG_DIR = $(PKG_NAME)-$(PKG_VERS) SRC_DIR = build_unix DEPENDS = HOMEPAGE = http: COMMENT = Berkeley DB is a family of embedded key-value database libraries providing scalable high-performance data management services to applications. The Berkeley DB products use simple function-call APIs for data access and management. LICENSE = AGPLv3 DOWNLOAD_TARGET = nope CONFIGURE_TARGET = myConfigure include ../../mk/spksrc.cross-cc.mk .PHONY: myConfigure myConfigure: $(RUN) dist/configure $(TC_CONFIGURE_ARGS) --prefix=$(INSTALL_DIR)/$(INSTALL_PREFIX) --<API key> --enable-smallbuild
{- Problem 30 Numbers that can be written as powers of their digits Result 443839 6.28 s Comment The upper boundary can be estimated since 999... = 10^k - 1 has to be equal to 9^5 + 9^5 + ... = k 9^5, which yields the maximum condition k 9^5 = 10^k - 1. A numeric solution for this is 5.51257, which yields a maximum of 10^5.51257 = 325514.24. -} module Problem30 (solution) where import CommonFunctions solution = fromIntegral . sum' $ filter is5thPowerSum [2..325515] -- Can x be written as the sum of fifth power of its digits? is5thPowerSum x = x == (sum' . map toTheFifth $ show x) -- Memoize powers toTheFifth '0' = 0^5 toTheFifth '1' = 1^5 toTheFifth '2' = 2^5 toTheFifth '3' = 3^5 toTheFifth '4' = 4^5 toTheFifth '5' = 5^5 toTheFifth '6' = 6^5 toTheFifth '7' = 7^5 toTheFifth '8' = 8^5 toTheFifth '9' = 9^5 toTheFifth _ = error "Not a digit 'to the fifth' in problem 30"
package game.map; import game.Constants; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; /** * * Class to represent a Cell in the Map. A cell can have many types depending on * what actors can traverse it and how it should be drawn * */ public class Cell implements Constants { public int x, y; public char type; /**Constructor makes a new cell with a specific type*/ public Cell(int x, int y, char type) { this.type = type; this.x = x; this.y = y; } //called once to create background image /**draws the cells to the background for each type of cell*/ public void drawBackground(Graphics g,Color c) { switch (type) { case 'e': //corral exit g.setColor(Color.WHITE); g.fillRect(x*CELL, y*CELL + CELL/2 - 1, CELL, 3); break; case 'h': //horizontal line g.setColor(c); g.fillRect(x*CELL, y*CELL + CELL/2 - 1, CELL, 3); break; case 'v': //vertical line g.setColor(c); g.fillRect(x*CELL + CELL/2 - 1, y*CELL, 3, CELL); break; case 'm': corner(g, -1, 1,c); break; //northeast corner ('m' = maine) case 'w': corner(g, 1, 1,c); break; //northwest corner ('w' = washington) case 'f': corner(g, -1, -1,c); break; //southeast corner ('f' = florida) case 'c': corner(g, 1, -1,c); break; //southwest corner ('c' = california) case 'o': //empty navigable cell case 'W': //warp space case '.': //navigable cell with edible dot case '*': //navigable cell with big edible dot case 'x': //empty non-navigable cell case 'C': //empty the Corral default: break; } } //draw a rounded corner 3 pixels thick /**Draws corners a specific way*/ public void corner(Graphics g, int xSign, int ySign,Color c) { Rectangle oldClip = g.getClipBounds(); g.setClip(x*CELL, y*CELL, CELL, CELL); int xBase = x*CELL + xSign*CELL/2; int yBase = y*CELL + ySign*CELL/2; g.setColor(c); g.drawOval(xBase, yBase, CELL, CELL); g.drawOval(xBase + 1, yBase + 1, CELL - 2, CELL - 2); g.drawOval(xBase - 1, yBase - 1, CELL + 2, CELL + 2); g.setClip(oldClip); } /** * returns true if the specified actor is allowed to run over this cell. * Ghosts are allowed to go everywhere pacman can, and also into the corral * @param isGhost * @return */ public boolean isNavigable(boolean isGhost) { if (isGhost) return "o.*eCW".indexOf(type) >= 0; return "o.*W".indexOf(type) >= 0; } /** * returns true if this cell is a Token * @return */ public boolean isToken() { return ".*".indexOf(type) >= 0; } }
#ifndef <API key> #define <API key> #include <stdint.h> #include <memory> #include <unordered_map> #include "base/macros.h" #include "cc/test/<API key>.h" #include "components/viz/common/surfaces/<API key>.h" #include "components/viz/service/display/display.h" #include "components/viz/service/frame_sinks/<API key>.h" #include "components/viz/test/<API key>.h" #include "components/viz/test/test_image_factory.h" #include "components/viz/test/<API key>.h" #include "gpu/ipc/common/surface_handle.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/viz/privileged/mojom/compositing/<API key>.mojom.h" #include "ui/compositor/compositor.h" namespace viz { class <API key>; } namespace ui { class <API key>; class <API key> : public ContextFactory { public: // Both |<API key>| and |frame_sink_manager| must outlive the // ContextFactory. The constructor without |use_skia_renderer| will use // SkiaRenderer if the feature is enabled. // TODO(crbug.com/657959): |frame_sink_manager| should go away and we should // use the LayerTreeFrameSink from the <API key>. <API key>(viz::<API key>* <API key>, viz::<API key>* frame_sink_manager); <API key>(viz::<API key>* <API key>, viz::<API key>* frame_sink_manager, bool use_skia_renderer); ~<API key>() override; viz::<API key>* GetFrameSinkManager() { return frame_sink_manager_; } // If true (the default) an OutputSurface is created that does not display // anything. Set to false if you want to see results on the screen. void <API key>(bool use_test_surface) { use_test_surface_ = use_test_surface; } // Set refresh rate will be set to 200 to spend less time waiting for // BeginFrame when used for tests. void <API key>(); // ContextFactory implementation. void <API key>(base::WeakPtr<Compositor> compositor) override; scoped_refptr<viz::ContextProvider> <API key>() override; scoped_refptr<viz::<API key>> <API key>() override; void RemoveCompositor(Compositor* compositor) override; gpu::<API key>* <API key>() override; cc::TaskGraphRunner* GetTaskGraphRunner() override; viz::FrameSinkId AllocateFrameSinkId() override; viz::<API key>* <API key>() override; SkMatrix44 <API key>(Compositor* compositor) const; gfx::DisplayColorSpaces <API key>(Compositor* compositor) const; float GetSDRWhiteLevel(Compositor* compositor) const; base::TimeTicks <API key>(Compositor* compositor) const; base::TimeDelta <API key>(Compositor* compositor) const; void <API key>(Compositor* compositor); private: class PerCompositorData; PerCompositorData* <API key>(Compositor* compositor); scoped_refptr<<API key>> <API key>; scoped_refptr<<API key>> <API key>; viz::<API key> <API key>; viz::<API key> <API key>; viz::TestImageFactory image_factory_; cc::TestTaskGraphRunner task_graph_runner_; viz::<API key> <API key>; bool use_test_surface_; bool disable_vsync_ = false; double refresh_rate_ = 60.0; viz::<API key>* const <API key>; viz::<API key>* const frame_sink_manager_; viz::RendererSettings renderer_settings_; using <API key> = std::unordered_map<Compositor*, std::unique_ptr<PerCompositorData>>; <API key> <API key>; <API key>(<API key>); }; } // namespace ui #endif // <API key>
package owltools.io; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Map; import org.junit.Test; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.<API key>; import owltools.OWLToolsTestBasics; public class <API key> extends OWLToolsTestBasics { private static boolean verbose = false; @Test public void testParseCatalogXML() throws Exception { File resource = getResource("owl-mirror.txt"); InputStream inputStream = new FileInputStream(resource); File parentFolder = resource.getParentFile(); Map<IRI, IRI> mappings = <API key>.<API key>(inputStream, parentFolder); assertTrue(mappings.size() == 2); } @Test public void <API key>() throws Exception { <API key> m = new <API key>("src/test/resources/owl-mirror.txt"); IRI iri = m.getDocumentIRI(IRI.create("http://purl.obolibrary.org/obo/go.owl")); assertNotNull(iri); } @Test public void <API key>() throws Exception { <API key> m = new <API key>("src/test/resources/owl-mirror.txt"); ParserWrapper p = new ParserWrapper(); p.addIRIMapper(m); if (verbose) { p.manager.<API key>(new <API key>()); } OWLOntology owlOntology = p.parse(<API key>("mutual-import-1.owl")); assertNotNull(owlOntology); } public static final class <API key> implements <API key> { @Override public void <API key>(LoadingStartedEvent event) { System.out.println("Loading: "+event.getDocumentIRI()); } @Override public void <API key>(<API key> event) { System.out.println("Finished: "+event.getDocumentIRI()); } } }
#ifndef _FFCONF #define _FFCONF 4004 /* Revision ID */ #define _FS_TINY 0 /* 0:Normal or 1:Tiny */ /* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system / object instead of the sector buffer in the individual file object for file / data transfer. This reduces memory consumption 512 bytes each file object. */ #define _FS_READONLY 0 /* 0:Read/Write or 1:Read only */ /* Setting _FS_READONLY to 1 defines read only configuration. This removes / writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename, / f_truncate and useless f_getfree. */ #define _FS_MINIMIZE 0 /* 0 to 3 */ /* The _FS_MINIMIZE option defines minimization level to remove some functions. / / 0: Full function. / 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename / are removed. / 2: f_opendir and f_readdir are removed in addition to 1. / 3: f_lseek is removed in addition to 2. */ #define _USE_STRFUNC 0 /* 0:Disable or 1-2:Enable */ /* To enable string functions, set _USE_STRFUNC to 1 or 2. */ #define _USE_MKFS 1 /* 0:Disable or 1:Enable */ /* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */ #define _USE_FORWARD 0 /* 0:Disable or 1:Enable */ /* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */ #define _USE_FASTSEEK 0 /* 0:Disable or 1:Enable */ /* To enable fast seek feature, set _USE_FASTSEEK to 1. */ #define _CODE_PAGE 437 /* The _CODE_PAGE specifies the OEM code page to be used on the target system. / Incorrect setting of the code page can cause a file open failure. / / 932 - Japanese Shift-JIS (DBCS, OEM, Windows) / 936 - Simplified Chinese GBK (DBCS, OEM, Windows) / 949 - Korean (DBCS, OEM, Windows) / 950 - Traditional Chinese Big5 (DBCS, OEM, Windows) / 1250 - Central Europe (Windows) / 1251 - Cyrillic (Windows) / 1252 - Latin 1 (Windows) / 1253 - Greek (Windows) / 1254 - Turkish (Windows) / 1255 - Hebrew (Windows) / 1256 - Arabic (Windows) / 1257 - Baltic (Windows) / 1258 - Vietnam (OEM, Windows) / 437 - U.S. (OEM) / 720 - Arabic (OEM) / 737 - Greek (OEM) / 775 - Baltic (OEM) / 850 - Multilingual Latin 1 (OEM) / 858 - Multilingual Latin 1 + Euro (OEM) / 852 - Latin 2 (OEM) / 855 - Cyrillic (OEM) / 866 - Russian (OEM) / 857 - Turkish (OEM) / 862 - Hebrew (OEM) / 874 - Thai (OEM, Windows) / 1 - ASCII only (Valid for non LFN cfg.) */ #define _USE_LFN 3 /* 0 to 3 */ #define _MAX_LFN 255 /* Maximum LFN length to handle (12 to 255) */ /* The _USE_LFN option switches the LFN support. / / 0: Disable LFN feature. _MAX_LFN and _LFN_UNICODE have no effect. / 1: Enable LFN with static working buffer on the BSS. Always NOT reentrant. / 2: Enable LFN with dynamic working buffer on the STACK. / 3: Enable LFN with dynamic working buffer on the HEAP. / / The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. To enable LFN, / Unicode handling functions ff_convert() and ff_wtoupper() must be added / to the project. When enable to use heap, memory control functions / ff_memalloc() and ff_memfree() must be added to the project. */ #define _LFN_UNICODE 1 /* 0:ANSI/OEM or 1:Unicode */ /* To switch the character code set on FatFs API to Unicode, / enable LFN feature and set _LFN_UNICODE to 1. */ #define _FS_RPATH 0 /* 0 to 2 */ /* The _FS_RPATH option configures relative path feature. / / 0: Disable relative path feature and remove related functions. / 1: Enable relative path. f_chdrive() and f_chdir() are available. / 2: f_getcwd() is available in addition to 1. / / Note that output of the f_readdir fnction is affected by this option. */ #define _VOLUMES 1 /* Number of volumes (logical drives) to be used. */ #define _MAX_SS 512 /* 512, 1024, 2048 or 4096 */ /* Maximum sector size to be handled. / Always set 512 for memory card and hard disk but a larger value may be / required for on-board flash memory, floppy disk and optical disk. / When _MAX_SS is larger than 512, it configures FatFs to variable sector size / and GET_SECTOR_SIZE command must be implememted to the disk_ioctl function. */ #define _MULTI_PARTITION 0 /* 0:Single partition, 1/2:Enable multiple partition */ /* When set to 0, each volume is bound to the same physical drive number and / it can mount only first primaly partition. When it is set to 1, each volume / is tied to the partitions listed in VolToPart[]. */ #define _USE_ERASE 0 /* 0:Disable or 1:Enable */ /* To enable sector erase feature, set _USE_ERASE to 1. CTRL_ERASE_SECTOR command / should be added to the disk_ioctl functio. */ #define _WORD_ACCESS 0 /* 0 or 1 */ /* Set 0 first and it is always compatible with all platforms. The _WORD_ACCESS / option defines which access method is used to the word data on the FAT volume. / / 0: Byte-by-byte access. / 1: Word access. Do not choose this unless following condition is met. / / When the byte order on the memory is big-endian or address miss-aligned word / access results incorrect behavior, the _WORD_ACCESS must be set to 0. / If it is not the case, the value can also be set to 1 to improve the / performance and code size. */ /* A header file that defines sync object types on the O/S, such as / windows.h, ucos_ii.h and semphr.h, must be included prior to ff.h. */ #define _FS_REENTRANT 0 /* 0:Disable or 1:Enable */ #define _FS_TIMEOUT 1000 /* Timeout period in unit of time ticks */ #define _SYNC_t HANDLE /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */ /* The _FS_REENTRANT option switches the reentrancy (thread safe) of the FatFs module. / / 0: Disable reentrancy. _SYNC_t and _FS_TIMEOUT have no effect. / 1: Enable reentrancy. Also user provided synchronization handlers, / ff_req_grant, ff_rel_grant, ff_del_syncobj and ff_cre_syncobj / function must be added to the project. */ #define _FS_LOCK 0 /* 0:Disable or >=1:Enable */ /* To enable file lock control feature, set _FS_LOCK to 1 or greater. The value defines how many files can be opened simultaneously. */ #endif /* _FFCONFIG */
#include "bzlib_private.h" static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } #define RETURN(rrr) \ { retVal = rrr; goto <API key>; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1 || nSelectors > BZ_MAX_SELECTORS) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v pos[0] = tmp; s->selector[i] = tmp; } } for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr } s->len[t][i] = curr; } } for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } <API key> ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii for (jj = MTFL_SIZE-1; jj >= 0; jj s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno] s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno } s->mtfbase[0] s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii for (jj = MTFL_SIZE-1; jj >= 0; jj s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); <API key>: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; }
<?php /* @var $this yii\web\View */ /* @var $model common\models\Taxonomy */ $this->title = Yii::t('writesdown', 'Update Taxonomy: {taxonomy_name}', ['taxonomy_name' => $model->taxonomy_sn]); $this->params['breadcrumbs'][] = ['label' => Yii::t('writesdown', 'Taxonomies'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->taxonomy_sn, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = Yii::t('writesdown', 'Update'); ?> <div class="taxonomy-update"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
<?php namespace Ice\Action; use Ice\Core\Logger; use Ice\Core\Model_Account; use Ice\Core\Security as Core_Security; use Ice\Model\Account; use Ice\Widget\Account_<API key>; class Security_<API key> extends Security { /** Run action * * @param array $input * @return array */ public function run(array $input) { /** @var Security_<API key> $form */ $form = $input['widget']; $accountModelClass = $form-><API key>(); if (!$accountModelClass) { return $form->getLogger() ->exception( ['Unknown accountModelClass', [], $form->getResource()], __FILE__, __LINE__ ); } try { $values = $form->validate(); /** @var Model_Account $account */ $account = $accountModelClass::createQueryBuilder() ->eq(['user' => Core_Security::getInstance()->getUser()]) ->limit(1) ->getSelectQuery(['/pk', 'password', '/expired', 'user__fk']) ->getModel(); if (!$account) { $form->getLogger()->exception('Account not found', __FILE__, __LINE__); } if (!$account->securityVerify($values)) { $form->getLogger()->exception('Authentication data is not valid. Please, check input.', __FILE__, __LINE__); } $accountData = ['password' => $account->securityHash($values, 'new_password')]; $this->changePassword($account, $accountData, $input); return array_merge( ['success' => $form->getLogger()->info('Change password successfully', Logger::SUCCESS, true)], parent::run($input) ); } catch (\Exception $e) { return ['error' => $form->getLogger()->info($e->getMessage(), Logger::DANGER, true)]; } } }
// <API key>: Apache-2.0 WITH LLVM-exception #include "FindTarget.h" #include "Selection.h" #include "TestTU.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Testing/Support/Annotations.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <initializer_list> namespace clang { namespace clangd { namespace { // A referenced Decl together with its DeclRelationSet, for assertions. // There's no great way to assert on the "content" of a Decl in the general case // that's both expressive and unambiguous (e.g. clearly distinguishes between // templated decls and their specializations). // We use the result of pretty-printing the decl, with the {body} truncated. struct PrintedDecl { PrintedDecl(const char *Name, DeclRelationSet Relations = {}) : Name(Name), Relations(Relations) {} PrintedDecl(const NamedDecl *D, DeclRelationSet Relations = {}) : Relations(Relations) { std::string S; llvm::raw_string_ostream OS(S); D->print(OS); llvm::StringRef FirstLine = llvm::StringRef(OS.str()).take_until([](char C) { return C == '\n'; }); FirstLine = FirstLine.rtrim(" {"); Name = std::string(FirstLine.rtrim(" {")); } std::string Name; DeclRelationSet Relations; }; bool operator==(const PrintedDecl &L, const PrintedDecl &R) { return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations); } llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const PrintedDecl &D) { return OS << D.Name << " Rel=" << D.Relations; } // The test cases in for targetDecl() take the form // - a piece of code (Code = "...") // - Code should have a single AST node marked as a [[range]] // - an EXPECT_DECLS() assertion that verify the type of node selected, and // all the decls that targetDecl() considers it to reference // Despite the name, these cases actually test allTargetDecls() for brevity. class TargetDeclTest : public ::testing::Test { protected: using Rel = DeclRelation; std::string Code; std::vector<std::string> Flags; // Asserts that `Code` has a marked selection of a node `NodeType`, // and returns allTargetDecls() as PrintedDecl structs. // Use via EXPECT_DECLS(). std::vector<PrintedDecl> <API key>(const char *NodeType) { llvm::Annotations A(Code); auto TU = TestTU::withCode(A.code()); TU.ExtraArgs = Flags; auto AST = TU.build(); llvm::Annotations::Range R = A.range(); auto Selection = SelectionTree::createRight( AST.getASTContext(), AST.getTokens(), R.Begin, R.End); const SelectionTree::Node *N = Selection.commonAncestor(); if (!N) { ADD_FAILURE() << "No node selected!\n" << Code; return {}; } EXPECT_EQ(N->kind(), NodeType) << Selection; std::vector<PrintedDecl> ActualDecls; for (const auto &Entry : allTargetDecls(N->ASTNode)) ActualDecls.emplace_back(Entry.first, Entry.second); return ActualDecls; } }; // This is a macro to preserve line numbers in assertion failures. // It takes the expected decls as varargs to work around comma-in-macro issues. #define EXPECT_DECLS(NodeType, ...) \ EXPECT_THAT(<API key>(NodeType), \ ::testing::<API key>( \ std::vector<PrintedDecl>({__VA_ARGS__}))) \ << Code using ExpectedDecls = std::vector<PrintedDecl>; TEST_F(TargetDeclTest, Exprs) { Code = R"cpp( int f(); int x = [[f]](); )cpp"; EXPECT_DECLS("DeclRefExpr", "int f()"); Code = R"cpp( struct S { S operator+(S) const; }; auto X = S() [[+]] S(); )cpp"; EXPECT_DECLS("DeclRefExpr", "S operator+(S) const"); Code = R"cpp( int foo(); int s = foo[[()]]; )cpp"; EXPECT_DECLS("CallExpr", "int foo()"); Code = R"cpp( struct X { void operator()(int n); }; void test() { X x; x[[(123)]]; } )cpp"; EXPECT_DECLS("CXXOperatorCallExpr", "void operator()(int n)"); Code = R"cpp( void test() { goto [[label]]; label: return; } )cpp"; EXPECT_DECLS("GotoStmt", "label:"); Code = R"cpp( void test() { [[label]]: return; } )cpp"; EXPECT_DECLS("LabelStmt", "label:"); } TEST_F(TargetDeclTest, Recovery) { Code = R"cpp( // error-ok: testing behavior on broken code int f(); int f(int, int); int x = [[f]](42); )cpp"; EXPECT_DECLS("<API key>", "int f()", "int f(int, int)"); } TEST_F(TargetDeclTest, UsingDecl) { Code = R"cpp( namespace foo { int f(int); int f(char); } using foo::f; int x = [[f]](42); )cpp"; // f(char) is not referenced! EXPECT_DECLS("DeclRefExpr", {"using foo::f", Rel::Alias}, {"int f(int)", Rel::Underlying}); Code = R"cpp( namespace foo { int f(int); int f(char); } [[using foo::f]]; )cpp"; // All overloads are referenced. EXPECT_DECLS("UsingDecl", {"using foo::f", Rel::Alias}, {"int f(int)", Rel::Underlying}, {"int f(char)", Rel::Underlying}); Code = R"cpp( struct X { int foo(); }; struct Y : X { using X::foo; }; int x = Y().[[foo]](); )cpp"; EXPECT_DECLS("MemberExpr", {"using X::foo", Rel::Alias}, {"int foo()", Rel::Underlying}); } TEST_F(TargetDeclTest, ConstructorInitList) { Code = R"cpp( struct X { int a; X() : [[a]](42) {} }; )cpp"; EXPECT_DECLS("CXXCtorInitializer", "int a"); Code = R"cpp( struct X { X() : [[X]](1) {} X(int); }; )cpp"; EXPECT_DECLS("RecordTypeLoc", "struct X"); } TEST_F(TargetDeclTest, DesignatedInit) { Flags = {"-xc"}; // array designators are a C99 extension. Code = R"c( struct X { int a; }; struct Y { int b; struct X c[2]; }; struct Y y = { .c[0].[[a]] = 1 }; )c"; EXPECT_DECLS("DesignatedInitExpr", "int a"); } TEST_F(TargetDeclTest, NestedNameSpecifier) { Code = R"cpp( namespace a { namespace b { int c; } } int x = a::[[b::]]c; )cpp"; EXPECT_DECLS("<API key>", "namespace b"); Code = R"cpp( namespace a { struct X { enum { y }; }; } int x = a::[[X::]]y; )cpp"; EXPECT_DECLS("<API key>", "struct X"); Code = R"cpp( template <typename T> int x = [[T::]]y; )cpp"; EXPECT_DECLS("<API key>", "typename T"); Code = R"cpp( namespace a { int x; } namespace b = a; int y = [[b]]::x; )cpp"; EXPECT_DECLS("<API key>", {"namespace b = a", Rel::Alias}, {"namespace a", Rel::Underlying}); } TEST_F(TargetDeclTest, Types) { Code = R"cpp( struct X{}; [[X]] x; )cpp"; EXPECT_DECLS("RecordTypeLoc", "struct X"); Code = R"cpp( struct S{}; typedef S X; [[X]] x; )cpp"; EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias}, {"struct S", Rel::Underlying}); Code = R"cpp( namespace ns { struct S{}; } typedef ns::S X; [[X]] x; )cpp"; EXPECT_DECLS("TypedefTypeLoc", {"typedef ns::S X", Rel::Alias}, {"struct S", Rel::Underlying}); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. Flags = {"-<API key>"}; Code = R"cpp( template<class T> void foo() { [[T]] x; } )cpp"; EXPECT_DECLS("<API key>", "class T"); Flags.clear(); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. Flags = {"-<API key>"}; Code = R"cpp( template<template<typename> class T> void foo() { [[T<int>]] x; } )cpp"; EXPECT_DECLS("<API key>", "template <typename> class T"); Flags.clear(); Code = R"cpp( struct S{}; S X; [[decltype]](X) Y; )cpp"; EXPECT_DECLS("DecltypeTypeLoc", {"struct S", Rel::Underlying}); Code = R"cpp( struct S{}; [[auto]] X = S{}; )cpp"; EXPECT_DECLS("AutoTypeLoc"); Code = R"cpp( template <typename... E> struct S { static const int size = sizeof...([[E]]); }; )cpp"; EXPECT_DECLS("SizeOfPackExpr", "typename ...E"); Code = R"cpp( template <typename T> class Foo { void f([[Foo]] x); }; )cpp"; EXPECT_DECLS("<API key>", "class Foo"); } TEST_F(TargetDeclTest, ClassTemplate) { Code = R"cpp( // Implicit specialization. template<int x> class Foo{}; [[Foo<42>]] B; )cpp"; EXPECT_DECLS("<API key>", {"template<> class Foo<42>", Rel::<API key>}, {"class Foo", Rel::TemplatePattern}); Code = R"cpp( template<typename T> class Foo {}; // The "Foo<int>" SpecializationDecl is incomplete, there is no // instantiation happening. void func([[Foo<int>]] *); )cpp"; EXPECT_DECLS("<API key>", {"class Foo", Rel::TemplatePattern}, {"template<> class Foo<int>", Rel::<API key>}); Code = R"cpp( // Explicit specialization. template<int x> class Foo{}; template<> class Foo<42>{}; [[Foo<42>]] B; )cpp"; EXPECT_DECLS("<API key>", "template<> class Foo<42>"); Code = R"cpp( // Partial specialization. template<typename T> class Foo{}; template<typename T> class Foo<T*>{}; [[Foo<int*>]] B; )cpp"; EXPECT_DECLS("<API key>", {"template<> class Foo<int *>", Rel::<API key>}, {"template <typename T> class Foo<T *>", Rel::TemplatePattern}); Code = R"cpp( // Class template argument deduction template <typename T> struct Test { Test(T); }; void foo() { [[Test]] a(5); } )cpp"; Flags.push_back("-std=c++17"); EXPECT_DECLS("<API key>", {"struct Test", Rel::TemplatePattern}); } TEST_F(TargetDeclTest, Concept) { Code = R"cpp( template <typename T> concept Fooable = requires (T t) { t.foo(); }; template <typename T> requires [[Fooable]]<T> void bar(T t) { t.foo(); } )cpp"; Flags.push_back("-std=c++2a"); EXPECT_DECLS( "<API key>", // FIXME: Should we truncate the pretty-printed form of a concept decl // somewhere? {"template <typename T> concept Fooable = requires (T t) { t.foo(); };"}); } TEST_F(TargetDeclTest, FunctionTemplate) { Code = R"cpp( // Implicit specialization. template<typename T> bool foo(T) { return false; }; bool x = [[foo]](42); )cpp"; EXPECT_DECLS("DeclRefExpr", {"template<> bool foo<int>(int)", Rel::<API key>}, {"bool foo(T)", Rel::TemplatePattern}); Code = R"cpp( // Explicit specialization. template<typename T> bool foo(T) { return false; }; template<> bool foo<int>(int) { return false; }; bool x = [[foo]](42); )cpp"; EXPECT_DECLS("DeclRefExpr", "template<> bool foo<int>(int)"); } TEST_F(TargetDeclTest, VariableTemplate) { // Pretty-printer doesn't do a very good job of variable templates :-( Code = R"cpp( // Implicit specialization. template<typename T> int foo; int x = [[foo]]<char>; )cpp"; EXPECT_DECLS("DeclRefExpr", {"int foo", Rel::<API key>}, {"int foo", Rel::TemplatePattern}); Code = R"cpp( // Explicit specialization. template<typename T> int foo; template <> bool foo<char>; int x = [[foo]]<char>; )cpp"; EXPECT_DECLS("DeclRefExpr", "bool foo"); Code = R"cpp( // Partial specialization. template<typename T> int foo; template<typename T> bool foo<T*>; bool x = [[foo]]<char*>; )cpp"; EXPECT_DECLS("DeclRefExpr", {"bool foo", Rel::<API key>}, {"bool foo", Rel::TemplatePattern}); } TEST_F(TargetDeclTest, TypeAliasTemplate) { Code = R"cpp( template<typename T, int X> class SmallVector {}; template<typename U> using TinyVector = SmallVector<U, 1>; [[TinyVector<int>]] X; )cpp"; EXPECT_DECLS("<API key>", {"template<> class SmallVector<int, 1>", Rel::<API key> | Rel::Underlying}, {"class SmallVector", Rel::TemplatePattern | Rel::Underlying}, {"using TinyVector = SmallVector<U, 1>", Rel::Alias | Rel::TemplatePattern}); } TEST_F(TargetDeclTest, MemberOfTemplate) { Code = R"cpp( template <typename T> struct Foo { int x(T); }; int y = Foo<int>().[[x]](42); )cpp"; EXPECT_DECLS("MemberExpr", {"int x(int)", Rel::<API key>}, {"int x(T)", Rel::TemplatePattern}); Code = R"cpp( template <typename T> struct Foo { template <typename U> int x(T, U); }; int y = Foo<char>().[[x]]('c', 42); )cpp"; EXPECT_DECLS("MemberExpr", {"template<> int x<int>(char, int)", Rel::<API key>}, {"int x(T, U)", Rel::TemplatePattern}); } TEST_F(TargetDeclTest, Lambda) { Code = R"cpp( void foo(int x = 42) { auto l = [ [[x]] ]{ return x + 1; }; }; )cpp"; EXPECT_DECLS("DeclRefExpr", "int x = 42"); // It seems like this should refer to another var, with the outer param being // an underlying decl. But it doesn't seem to exist. Code = R"cpp( void foo(int x = 42) { auto l = [x]{ return [[x]] + 1; }; }; )cpp"; EXPECT_DECLS("DeclRefExpr", "int x = 42"); Code = R"cpp( void foo() { auto l = [x = 1]{ return [[x]] + 1; }; }; )cpp"; // FIXME: why both auto and int? EXPECT_DECLS("DeclRefExpr", "auto int x = 1"); } TEST_F(TargetDeclTest, OverloadExpr) { // FIXME: Auto-completion in a template requires disabling delayed template // parsing. Flags = {"-<API key>"}; Code = R"cpp( void func(int*); void func(char*); template <class T> void foo(T t) { [[func]](t); }; )cpp"; EXPECT_DECLS("<API key>", "void func(int *)", "void func(char *)"); Code = R"cpp( struct X { void func(int*); void func(char*); }; template <class T> void foo(X x, T t) { x.[[func]](t); }; )cpp"; EXPECT_DECLS("<API key>", "void func(int *)", "void func(char *)"); } TEST_F(TargetDeclTest, ObjC) { Flags = {"-xobjective-c"}; Code = R"cpp( @interface Foo {} -(void)bar; @end void test(Foo *f) { [f [[bar]] ]; } )cpp"; EXPECT_DECLS("ObjCMessageExpr", "- (void)bar"); Code = R"cpp( @interface Foo { @public int bar; } @end int test(Foo *f) { return [[f->bar]]; } )cpp"; EXPECT_DECLS("ObjCIvarRefExpr", "int bar"); Code = R"cpp( @interface Foo {} -(int) x; -(void) setX:(int)x; @end void test(Foo *f) { [[f.x]] = 42; } )cpp"; EXPECT_DECLS("ObjCPropertyRefExpr", "- (void)setX:(int)x"); Code = R"cpp( @interface I {} @property(retain) I* x; @property(retain) I* y; @end void test(I *f) { [[f.x]].y = 0; } )cpp"; EXPECT_DECLS("ObjCPropertyRefExpr", "@property(atomic, retain, readwrite) I *x"); Code = R"cpp( @protocol Foo @end id test() { return [[@protocol(Foo)]]; } )cpp"; EXPECT_DECLS("ObjCProtocolExpr", "@protocol Foo"); Code = R"cpp( @interface Foo @end void test([[Foo]] *p); )cpp"; EXPECT_DECLS("<API key>", "@interface Foo"); Code = R"cpp( @protocol Foo @end void test([[id<Foo>]] p); )cpp"; EXPECT_DECLS("ObjCObjectTypeLoc", "@protocol Foo"); Code = R"cpp( @class C; @protocol Foo @end void test(C<[[Foo]]> *p); )cpp"; // FIXME: there's no AST node corresponding to 'Foo', so we're stuck. EXPECT_DECLS("ObjCObjectTypeLoc"); } class <API key> : public ::testing::Test { protected: struct AllRefs { std::string AnnotatedCode; std::string DumpedReferences; }; Parses \p Code, finds function or namespace '::foo' and annotates its body with results of <API key>. See actual tests for examples of annotation format. AllRefs <API key>(llvm::StringRef Code) { TestTU TU; TU.Code = std::string(Code); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. TU.ExtraArgs.push_back("-<API key>"); TU.ExtraArgs.push_back("-std=c++2a"); TU.ExtraArgs.push_back("-xobjective-c++"); auto AST = TU.build(); auto *TestDecl = &findDecl(AST, "foo"); if (auto *T = llvm::dyn_cast<<API key>>(TestDecl)) TestDecl = T->getTemplatedDecl(); std::vector<ReferenceLoc> Refs; if (const auto *Func = llvm::dyn_cast<FunctionDecl>(TestDecl)) <API key>(Func->getBody(), [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); }); else if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(TestDecl)) <API key>(NS, [&Refs, &NS](ReferenceLoc R) { // Avoid adding the namespace foo decl to the results. if (R.Targets.size() == 1 && R.Targets.front() == NS) return; Refs.push_back(std::move(R)); }); else ADD_FAILURE() << "Failed to find ::foo decl for test"; auto &SM = AST.getSourceManager(); llvm::sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) { return SM.<API key>(L.NameLoc, R.NameLoc); }); std::string AnnotatedCode; unsigned NextCodeChar = 0; for (unsigned I = 0; I < Refs.size(); ++I) { auto &R = Refs[I]; SourceLocation Pos = R.NameLoc; assert(Pos.isValid()); if (Pos.isMacroID()) // FIXME: figure out how to show macro locations. Pos = SM.getExpansionLoc(Pos); assert(Pos.isFileID()); FileID File; unsigned Offset; std::tie(File, Offset) = SM.getDecomposedLoc(Pos); if (File == SM.getMainFileID()) { // Print the reference in a source code. assert(NextCodeChar <= Offset); AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar); AnnotatedCode += "$" + std::to_string(I) + "^"; NextCodeChar = Offset; } } AnnotatedCode += Code.substr(NextCodeChar); std::string DumpedReferences; for (unsigned I = 0; I < Refs.size(); ++I) DumpedReferences += std::string(llvm::formatv("{0}: {1}\n", I, Refs[I])); return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)}; } }; TEST_F(<API key>, All) { std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] = {// Simple expressions. {R"cpp( int global; int func(); void foo(int param) { $0^global = $1^param + $2^func(); } )cpp", "0: targets = {global}\n" "1: targets = {param}\n" "2: targets = {func}\n"}, {R"cpp( struct X { int a; }; void foo(X x) { $0^x.$1^a = 10; } )cpp", "0: targets = {x}\n" "1: targets = {X::a}\n"}, {R"cpp( // error-ok: testing with broken code int bar(); int foo() { return $0^bar() + $1^bar(42); } )cpp", "0: targets = {bar}\n" "1: targets = {bar}\n"}, // Namespaces and aliases. {R"cpp( namespace ns {} namespace alias = ns; void foo() { using namespace $0^ns; using namespace $1^alias; } )cpp", "0: targets = {ns}\n" "1: targets = {alias}\n"}, // Using declarations. {R"cpp( namespace ns { int global; } void foo() { using $0^ns::$1^global; } )cpp", "0: targets = {ns}\n" "1: targets = {ns::global}, qualifier = 'ns::'\n"}, // Simple types. {R"cpp( struct Struct { int a; }; using Typedef = int; void foo() { $0^Struct $1^x; $2^Typedef $3^y; static_cast<$4^Struct*>(0); } )cpp", "0: targets = {Struct}\n" "1: targets = {x}, decl\n" "2: targets = {Typedef}\n" "3: targets = {y}, decl\n" "4: targets = {Struct}\n"}, // Name qualifiers. {R"cpp( namespace a { namespace b { struct S { typedef int type; }; } } void foo() { $0^a::$1^b::$2^S $3^x; using namespace $4^a::$5^b; $6^S::$7^type $8^y; } )cpp", "0: targets = {a}\n" "1: targets = {a::b}, qualifier = 'a::'\n" "2: targets = {a::b::S}, qualifier = 'a::b::'\n" "3: targets = {x}, decl\n" "4: targets = {a}\n" "5: targets = {a::b}, qualifier = 'a::'\n" "6: targets = {a::b::S}\n" "7: targets = {a::b::S::type}, qualifier = 'struct S::'\n" "8: targets = {y}, decl\n"}, // Simple templates. {R"cpp( template <class T> struct vector { using value_type = T; }; template <> struct vector<bool> { using value_type = bool; }; void foo() { $0^vector<int> $1^vi; $2^vector<bool> $3^vb; } )cpp", "0: targets = {vector<int>}\n" "1: targets = {vi}, decl\n" "2: targets = {vector<bool>}\n" "3: targets = {vb}, decl\n"}, // Template type aliases. {R"cpp( template <class T> struct vector { using value_type = T; }; template <> struct vector<bool> { using value_type = bool; }; template <class T> using valias = vector<T>; void foo() { $0^valias<int> $1^vi; $2^valias<bool> $3^vb; } )cpp", "0: targets = {valias}\n" "1: targets = {vi}, decl\n" "2: targets = {valias}\n" "3: targets = {vb}, decl\n"}, // Injected class name. {R"cpp( namespace foo { template <typename $0^T> class $1^Bar { ~$2^Bar(); void $3^f($4^Bar); }; } )cpp", "0: targets = {foo::Bar::T}, decl\n" "1: targets = {foo::Bar}, decl\n" "2: targets = {foo::Bar}\n" "3: targets = {foo::Bar::f}, decl\n" "4: targets = {foo::Bar}\n"}, // MemberExpr should know their using declaration. {R"cpp( struct X { void func(int); }; struct Y : X { using X::func; }; void foo(Y y) { $0^y.$1^func(1); } )cpp", "0: targets = {y}\n" "1: targets = {Y::func}\n"}, // DeclRefExpr should know their using declaration. {R"cpp( namespace ns { void bar(int); } using ns::bar; void foo() { $0^bar(10); } )cpp", "0: targets = {bar}\n"}, // References from a macro. {R"cpp( #define FOO a #define BAR b void foo(int a, int b) { $0^FOO+$1^BAR; } )cpp", "0: targets = {a}\n" "1: targets = {b}\n"}, // No references from implicit nodes. {R"cpp( struct vector { int *begin(); int *end(); }; void foo() { for (int $0^x : $1^vector()) { $2^x = 10; } } )cpp", "0: targets = {x}, decl\n" "1: targets = {vector}\n" "2: targets = {x}\n"}, // Handle <API key>. // FIXME // This case fails when expensive checks are enabled. // Seems like the order of ns1::func and ns2::func isn't defined. #ifndef EXPENSIVE_CHECKS {R"cpp( namespace ns1 { void func(char*); } namespace ns2 { void func(int*); } using namespace ns1; using namespace ns2; template <class T> void foo(T t) { $0^func($1^t); } )cpp", "0: targets = {ns1::func, ns2::func}\n" "1: targets = {t}\n"}, #endif // Handle <API key>. {R"cpp( struct X { void func(char*); void func(int*); }; template <class T> void foo(X x, T t) { $0^x.$1^func($2^t); } )cpp", "0: targets = {x}\n" "1: targets = {X::func, X::func}\n" "2: targets = {t}\n"}, // Handle <API key>. {R"cpp( template <class T> struct S { static int value; }; template <class T> void foo() { $0^S<$1^T>::$2^value; } )cpp", "0: targets = {S}\n" "1: targets = {T}\n" "2: targets = {S::value}, qualifier = 'S<T>::'\n"}, // Handle <API key>. {R"cpp( template <class T> struct S { int value; }; template <class T> void foo(S<T> t) { $0^t.$1^value; } )cpp", "0: targets = {t}\n" "1: targets = {S::value}\n"}, // Type template parameters. {R"cpp( template <class T> void foo() { static_cast<$0^T>(0); $1^T(); $2^T $3^t; } )cpp", "0: targets = {T}\n" "1: targets = {T}\n" "2: targets = {T}\n" "3: targets = {t}, decl\n"}, // Non-type template parameters. {R"cpp( template <int I> void foo() { int $0^x = $1^I; } )cpp", "0: targets = {x}, decl\n" "1: targets = {I}\n"}, // Template template parameters. {R"cpp( template <class T> struct vector {}; template <template<class> class TT, template<class> class ...TP> void foo() { $0^TT<int> $1^x; $2^foo<$3^TT>(); $4^foo<$5^vector>(); $6^foo<$7^TP...>(); } )cpp", "0: targets = {TT}\n" "1: targets = {x}, decl\n" "2: targets = {foo}\n" "3: targets = {TT}\n" "4: targets = {foo}\n" "5: targets = {vector}\n" "6: targets = {foo}\n" "7: targets = {TP}\n"}, // Non-type template parameters with declarations. {R"cpp( int func(); template <int(*)()> struct wrapper {}; template <int(*FuncParam)()> void foo() { $0^wrapper<$1^func> $2^w; $3^FuncParam(); } )cpp", "0: targets = {wrapper<&func>}\n" "1: targets = {func}\n" "2: targets = {w}, decl\n" "3: targets = {FuncParam}\n"}, // declaration references. {R"cpp( namespace ns {} class S {}; void foo() { class $0^Foo { $1^Foo(); ~$2^Foo(); int $3^field; }; int $4^Var; enum $5^E { $6^ABC }; typedef int $7^INT; using $8^INT2 = int; namespace $9^NS = $10^ns; } )cpp", "0: targets = {Foo}, decl\n" "1: targets = {foo()::Foo::Foo}, decl\n" "2: targets = {Foo}\n" "3: targets = {foo()::Foo::field}, decl\n" "4: targets = {Var}, decl\n" "5: targets = {E}, decl\n" "6: targets = {foo()::ABC}, decl\n" "7: targets = {INT}, decl\n" "8: targets = {INT2}, decl\n" "9: targets = {NS}, decl\n" "10: targets = {ns}\n"}, // User-defined conversion operator. {R"cpp( void foo() { class $0^Bar {}; class $1^Foo { public: // FIXME: This should have only one reference to Bar. $2^operator $3^$4^Bar(); }; $5^Foo $6^f; $7^f.$8^operator $9^Bar(); } )cpp", "0: targets = {Bar}, decl\n" "1: targets = {Foo}, decl\n" "2: targets = {foo()::Foo::operator Bar}, decl\n" "3: targets = {Bar}\n" "4: targets = {Bar}\n" "5: targets = {Foo}\n" "6: targets = {f}, decl\n" "7: targets = {f}\n" "8: targets = {foo()::Foo::operator Bar}\n" "9: targets = {Bar}\n"}, // Destructor. {R"cpp( void foo() { class $0^Foo { public: ~$1^Foo() {} void $2^destructMe() { this->~$3^Foo(); } }; $4^Foo $5^f; $6^f.~ $7^Foo(); } )cpp", "0: targets = {Foo}, decl\n" // FIXME: It's better to target destructor's FunctionDecl instead of // the type itself (similar to constructor). "1: targets = {Foo}\n" "2: targets = {foo()::Foo::destructMe}, decl\n" "3: targets = {Foo}\n" "4: targets = {Foo}\n" "5: targets = {f}, decl\n" "6: targets = {f}\n" "7: targets = {Foo}\n"}, // cxx constructor initializer. {R"cpp( class Base {}; void foo() { // member initializer class $0^X { int $1^abc; $2^X(): $3^abc() {} }; // base initializer class $4^Derived : public $5^Base { $6^Base $7^B; $8^Derived() : $9^Base() {} }; // delegating initializer class $10^Foo { $11^Foo(int); $12^Foo(): $13^Foo(111) {} }; } )cpp", "0: targets = {X}, decl\n" "1: targets = {foo()::X::abc}, decl\n" "2: targets = {foo()::X::X}, decl\n" "3: targets = {foo()::X::abc}\n" "4: targets = {Derived}, decl\n" "5: targets = {Base}\n" "6: targets = {Base}\n" "7: targets = {foo()::Derived::B}, decl\n" "8: targets = {foo()::Derived::Derived}, decl\n" "9: targets = {Base}\n" "10: targets = {Foo}, decl\n" "11: targets = {foo()::Foo::Foo}, decl\n" "12: targets = {foo()::Foo::Foo}, decl\n" "13: targets = {Foo}\n"}, // Anonymous entities should not be reported. { R"cpp( void foo() { class {} $0^x; int (*$1^fptr)(int $2^a, int) = nullptr; } )cpp", "0: targets = {x}, decl\n" "1: targets = {fptr}, decl\n" "2: targets = {a}, decl\n"}, // Namespace aliases should be handled properly. { R"cpp( namespace ns { struct Type {}; } namespace alias = ns; namespace rec_alias = alias; void foo() { $0^ns::$1^Type $2^a; $3^alias::$4^Type $5^b; $6^rec_alias::$7^Type $8^c; } )cpp", "0: targets = {ns}\n" "1: targets = {ns::Type}, qualifier = 'ns::'\n" "2: targets = {a}, decl\n" "3: targets = {alias}\n" "4: targets = {ns::Type}, qualifier = 'alias::'\n" "5: targets = {b}, decl\n" "6: targets = {rec_alias}\n" "7: targets = {ns::Type}, qualifier = 'rec_alias::'\n" "8: targets = {c}, decl\n"}, // Handle SizeOfPackExpr. { R"cpp( template <typename... E> void foo() { constexpr int $0^size = sizeof...($1^E); }; )cpp", "0: targets = {size}, decl\n" "1: targets = {E}\n"}, // Class template argument deduction { R"cpp( template <typename T> struct Test { Test(T); }; void foo() { $0^Test $1^a(5); } )cpp", "0: targets = {Test}\n" "1: targets = {a}, decl\n"}, // Templates {R"cpp( namespace foo { template <typename $0^T> class $1^Bar {}; } )cpp", "0: targets = {foo::Bar::T}, decl\n" "1: targets = {foo::Bar}, decl\n"}, // Templates {R"cpp( namespace foo { template <typename $0^T> void $1^func(); } )cpp", "0: targets = {T}, decl\n" "1: targets = {foo::func}, decl\n"}, // Templates {R"cpp( namespace foo { template <typename $0^T> $1^T $2^x; } )cpp", "0: targets = {foo::T}, decl\n" "1: targets = {foo::T}\n" "2: targets = {foo::x}, decl\n"}, // Templates {R"cpp( template<typename T> class vector {}; namespace foo { template <typename $0^T> using $1^V = $2^vector<$3^T>; } )cpp", "0: targets = {foo::T}, decl\n" "1: targets = {foo::V}, decl\n" "2: targets = {vector}\n" "3: targets = {foo::T}\n"}, // Concept { R"cpp( template <typename T> concept Drawable = requires (T t) { t.draw(); }; namespace foo { template <typename $0^T> requires $1^Drawable<$2^T> void $3^bar($4^T $5^t) { $6^t.$7^draw(); } } )cpp", "0: targets = {T}, decl\n" "1: targets = {Drawable}\n" "2: targets = {T}\n" "3: targets = {foo::bar}, decl\n" "4: targets = {T}\n" "5: targets = {t}, decl\n" "6: targets = {t}\n" "7: targets = {}\n"}, // Objective-C: properties { R"cpp( @interface I {} @property(retain) I* x; @property(retain) I* y; @end I *f; void foo() { $0^f.$1^x.$2^y = 0; } )cpp", "0: targets = {f}\n" "1: targets = {I::x}\n" "2: targets = {I::y}\n"}, // Objective-C: implicit properties { R"cpp( @interface I {} -(I*)x; -(void)setY:(I*)y; @end I *f; void foo() { $0^f.$1^x.$2^y = 0; } )cpp", "0: targets = {f}\n" "1: targets = {I::x}\n" "2: targets = {I::setY:}\n"}, // Designated initializers. {R"cpp( void foo() { struct $0^Foo { int $1^Bar; }; $2^Foo $3^f { .$4^Bar = 42 }; } )cpp", "0: targets = {Foo}, decl\n" "1: targets = {foo()::Foo::Bar}, decl\n" "2: targets = {Foo}\n" "3: targets = {f}, decl\n" "4: targets = {foo()::Foo::Bar}\n"}, {R"cpp( void foo() { struct $0^Baz { int $1^Field; }; struct $2^Bar { $3^Baz $4^Foo; }; $5^Bar $6^bar { .$7^Foo.$8^Field = 42 }; } )cpp", "0: targets = {Baz}, decl\n" "1: targets = {foo()::Baz::Field}, decl\n" "2: targets = {Bar}, decl\n" "3: targets = {Baz}\n" "4: targets = {foo()::Bar::Foo}, decl\n" "5: targets = {Bar}\n" "6: targets = {bar}, decl\n" "7: targets = {foo()::Bar::Foo}\n" "8: targets = {foo()::Baz::Field}\n"}, {R"cpp( template<typename T> void crash(T); template<typename T> void foo() { $0^crash({.$1^x = $2^T()}); } )cpp", "0: targets = {crash}\n" "1: targets = {}\n" "2: targets = {T}\n" }, // unknown template name should not crash. {R"cpp( template <template <typename> typename T> struct Base {}; namespace foo { template <typename $0^T> struct $1^Derive : $2^Base<$3^T::template $4^Unknown> {}; } )cpp", "0: targets = {foo::Derive::T}, decl\n" "1: targets = {foo::Derive}, decl\n" "2: targets = {Base}\n" "3: targets = {foo::Derive::T}\n" "4: targets = {}, qualifier = 'T::'\n"}, }; for (const auto &C : Cases) { llvm::StringRef ExpectedCode = C.first; llvm::StringRef ExpectedRefs = C.second; auto Actual = <API key>(llvm::Annotations(ExpectedCode).code()); EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode); EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode; } } } // namespace } // namespace clangd } // namespace clang
(function () { var app = window.app, collection; collection = (new Backbone.Collection); collection.findPlayer = function () { return this.where({isPlayer: true})[0]; } app.collection.user = collection; })();
<?php namespace frontend\models; use yii\db\ActiveRecord; use Yii; /** * This is the model class for table "{{%tbl_job}}". * * @property string $id * @property integer $category_id * @property integer $user_id * @property string $title * @property string $description * @property string $type * @property string $reqierement * @property string $salary * @property string $city * @property string $state * @property string $zipcode * @property string $contact_email * @property string $contact_form * @property integer $is_published * @property string $create_date */ class Job extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%tbl_job}}'; } /** * @inheritdoc */ public function rules() { return [ [['category_id', 'title', 'description', 'type', 'reqierement', 'salary', 'city', 'state', 'zipcode', 'contact_email', 'contact_phone'], 'required'], [['category_id'], 'integer'], ['contact_email', 'email'], [['description'], 'string'], [['title', 'type', 'reqierement', 'salary', 'contact_phone'], 'string', 'max' => 255], [['city', 'state', 'zipcode', 'contact_email'], 'string', 'max' => 50] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'category_id' => 'Category ID', 'title' => 'Title', 'description' => 'Description', 'type' => 'Type', 'reqierement' => 'Reqierement', 'salary' => 'Salary', 'city' => 'City', 'state' => 'State', 'zipcode' => 'Zipcode', 'contact_email' => 'Contact Email', 'contact_phone' => 'Contact Phone', 'is_published' => 'Is Published', 'create_date' => 'Create Date', ]; } public static function dateVacancy($job){ /* * convert datetime to UNIX timestamp */ $timeAgo = ''; $yes = ''; $phpdate = strtotime($job->create_date); ?> <? $pr = time() - $phpdate; if (date('d', $phpdate) == date('d', time())) { $yes = "<i style='color: #00aa00'>today </i>"; if($pr < 7200) { $timeAgo = round(($pr - 3600)/60) . ' minutes ago '; if(round(($pr - 3600)/60) == 0) { $timeAgo = "Right Now "; return $timeAgo . date("F j, Y, g:i a:", $phpdate); } return $yes . $timeAgo . " | " . date("F j, Y, g:i a:", $phpdate); } if($pr > 7200 && $pr < 89000){ $timeAgo = round(($pr - 3600)/3600) . ' hours ago '; return $yes . $timeAgo . " | " . date("F j, Y, g:i a:", $phpdate); } } $s = 1; if ((date('d', $phpdate) == date('d', time()) - $s) && (date('m', $phpdate) == date('m', time()))) { $yes = "<i style='color: #0097cf'>yesterday </i> "; return $yes . $timeAgo . " | " . date("F j, Y, g:i a:", $phpdate); } $mounth31 = ['01', '03', '05', '07', '09', '11', '12']; $i = -1; while ($i < count($mounth31) - 1) { $i++; if ((date('d', time()) == '01' && date('m', time()) == $mounth31[$i]) && date('d', $phpdate) == '30') { $yes = "yesterday "; } } $mounth30 = ['02', '04', '06', '08', '10']; $i = -1; while ($i < count($mounth30) - 1) { $i++; if ((date('d', time()) == '01' && date('m', time()) == $mounth30[$i]) && date('d', $phpdate) == '31') { $yes = "yesterday "; } } if ((date('d', time()) == '01' && date('m', time()) == '03') && date('d', $phpdate) == '28') { $yes = "yesterday "; } if($pr > 89000 && $pr < 2600000){ $timeAgo = round(($pr - 3600)/86400) . ' days ago '; } return $formatedDate = $yes . $timeAgo . " | " . date("F j, Y, g:i a:", $phpdate); } public function getCategory(){ return $this->hasMany(Job::className(), ['category_id' => 'id']); } public function beforeSave($insert){ $this->user_id = Yii::$app->user->identity->getId(); return parent::beforeSave($insert); } // public function beforeValidate(){ // if($this->is_published == '1') $this->is_published = 1; // return parent::beforeValidate(); }
import logging; logger = logging.getLogger("morse." + __name__) import sys import yarp from morse.core.request_manager import RequestManager, <API key> from morse.core import status class YarpRequestManager(RequestManager): """Implements services to control the MORSE simulator over YARP The syntax of requests is: id component_name service [params with Python syntax] 'id' is an identifier set by the client to conveniently identify the request. It must be less that 80 chars in [a-zA-Z0-9]. The server answers: id OK|FAIL result_in_python|error_msg """ def __str__(self): return "Yarp service manager" def initialization(self): # Create dictionaries for the input and output ports self._yarp_request_ports = dict() self._yarp_reply_ports = dict() # Create a dictionary for the port names self._component_ports = dict() # For asynchronous request, this holds the mapping between a # request_id and the socket which requested it. self._pending_ports = dict() # Stores for each port the pending results to write back. self._results_to_output = dict() # Create a dictionary for the evailable bottles self._in_bottles = dict() self._reply_bottles = dict() return True def finalization(self): logger.info("Closing yarp request ports...") for port in self._yarp_request_ports.values(): port.close() return True def <API key>(self, request_id, results): port = None try: port, id = self._pending_ports[request_id] except KeyError: logger.info(str(self) + ": ERROR: I can not find the port which requested " + request_id) return if port in self._results_to_output: self._results_to_output[port].append((id, results)) else: self._results_to_output[port] = [(id, results)] def post_registration(self, component_name, service, is_async): """ Register a connection of a service with YARP """ # Get the Network attribute of yarp, # then call its init method self._yarp_module = sys.modules['yarp'] self.yarp_object = self._yarp_module.Network() # Create the names of the ports request_port_name = '/morse/services/{0}/request'.format(component_name) reply_port_name = '/morse/services/{0}/reply'.format(component_name) if not component_name in self._yarp_request_ports.keys(): # Create the ports to accept and reply to requests request_port = self._yarp_module.BufferedPortBottle() reply_port = self._yarp_module.BufferedPortBottle() request_port.open(request_port_name) reply_port.open(reply_port_name) self._yarp_request_ports[component_name] = request_port self._yarp_reply_ports[component_name] = reply_port # Create bottles to use in the responses bottle_in = self._yarp_module.Bottle() self._in_bottles[component_name] = bottle_in bottle_reply = self._yarp_module.Bottle() self._reply_bottles[component_name] = bottle_reply logger.info("Yarp service manager now listening on port " + request_port_name + ".") logger.info("Yarp service manager will reply on port " + reply_port_name + ".") return True def main(self): """ Read commands from the ports, and prepare the response""" # Read data from available ports for component_name, port in self._yarp_request_ports.items(): # Get the bottles to read and write bottle_in = self._in_bottles[component_name] bottle_reply = self._reply_bottles[component_name] bottle_in = port.read(False) if bottle_in != None: logger.debug("Received command from port '%s'" % (component_name)) try: try: id, component_name, service, params = self._parse_request(bottle_in) except ValueError: # Request contains < 2 tokens. raise <API key>("Malformed request! ") logger.info("Got '%s | %s | %s' (id = %s) from %s" % (component_name, service, params, id, component_name)) # on_incoming_request returns either #(True, result) if it's a synchronous # request that has been immediately executed, or # (False, request_id) if it's an asynchronous request whose # termination will be notified via # <API key>. is_sync, value = self.on_incoming_request(component_name, service, params) if is_sync: if port in self._results_to_output: self._results_to_output[port].append((id, value)) else: self._results_to_output[port] = [(id, value)] else: # Stores the mapping request/socket to notify # the right port when the service completes. # (cf :py:meth:<API key>) # Here, 'value' is the internal request id while # 'id' is the id used by the socket client. self._pending_ports[value] = (port, id) except <API key> as e: if port in self._results_to_output: self._results_to_output[port].append((id, (status.FAILED, e.value))) else: self._results_to_output[port] = [(id, (status.FAILED, e.value))] if self._results_to_output: for component_name, port in self._yarp_request_ports.items(): if port in self._results_to_output: for r in self._results_to_output[port]: response = "%s %s %s" % (r[0], r[1][0], str(r[1][1]) if r[1][1] else "") # Send the reply through the same yarp port reply_port = self._yarp_reply_ports[component_name] bottle_reply = reply_port.prepare() bottle_reply.clear() bottle_reply.addString(response) reply_port.write() logger.debug("Sent back '" + response + "'. Component: " + component_name + ". Port: " + str(port)) del self._results_to_output[port] def _parse_request(self, bottle): """ Parse the incoming bottle. """ try: id = bottle.get(0).asInt() component_name = bottle.get(1).toString() service = bottle.get(2).toString() except IndexError as e: raise <API key>("Malformed request: at least 3 values and at most 4 are expected (id, component_name, service, [params])") try: params = bottle.get(3).toString() import ast p = ast.literal_eval(params) except (NameError, SyntaxError) as e: raise <API key>("Invalid request syntax: error while parsing the parameters. " + str(e)) return (id, component_name, service, p)
package za.org.grassroot.core.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.<API key>; import za.org.grassroot.core.domain.notification.EventNotification; public interface <API key> extends JpaRepository<EventNotification, Long>, <API key><EventNotification> { }
#include "Video_PR.h" #include "xparameters.h" #include "stdio.h" #include "xil_io.h" #define <API key> 0x10 /** * * Run a self-test on the driver/device. Note this may be a destructive test if * resets of the device are performed. * * If the hardware system is not built correctly, this function may never * return to the caller. * * @param baseaddr_p is the base address of the VIDEO_PRinstance to be worked on. * * @return * * - XST_SUCCESS if all self-test code passed * - XST_FAILURE if any self-test code failed * * @note Caching must be turned off for this function to work. * @note Self test may fail if data memory and device are not on the same bus. * */ XStatus <API key>(void * baseaddr_p) { u32 baseaddr; int write_loop_index; int read_loop_index; int Index; baseaddr = (u32) baseaddr_p; xil_printf("******************************\n\r"); xil_printf("* User Peripheral Self Test\n\r"); xil_printf("******************************\n\n\r"); /* * Write to user logic slave module register(s) and read back */ xil_printf("User logic slave module test...\n\r"); for (write_loop_index = 0 ; write_loop_index < 4; write_loop_index++) VIDEO_PR_mWriteReg (baseaddr, write_loop_index*4, (write_loop_index+1)*<API key>); for (read_loop_index = 0 ; read_loop_index < 4; read_loop_index++) if ( VIDEO_PR_mReadReg (baseaddr, read_loop_index*4) != (read_loop_index+1)*<API key>){ xil_printf ("Error reading register value at address %x\n", (int)baseaddr + read_loop_index*4); return XST_FAILURE; } xil_printf(" - slave register write/read passed\n\n\r"); return XST_SUCCESS; }
#include <stdlib.h> #include <math.h> double atanh_th_th(double x,double y){ /* returns argth(th(x)*th(y)) */ double yy,xx,xm,ym,res; int isigne; if(x*y>=0) isigne=1; else isigne=-1; xx=fabs(x); yy=fabs(y); if(xx<yy) { xm=xx; ym=yy; } else { xm=yy; ym=xx; } //res= xm-.5*log((1+exp(-2*(ym-xm)))/(1+exp(-2*(xx+yy)))); res=xm-.5*log1p(exp(-2*(ym-xm)))+.5*log1p(exp(-2*(xx+yy))); return ((double)isigne)*res; } double deriv_atanh_th_th(double x, double y, double z){ double thx, thy, thxy; thx = tanh(x); thy = tanh(y); thxy = thx * thy; return (thx * (1 - thy*thy) / (1 - thxy * thxy)) * (1 + z); }
#ifndef <API key> #define <API key> #include <array> #include <QByteArray> #include "k8090_defines.h" namespace biomolecules { namespace sprelay { namespace core { namespace k8090 { namespace impl_ { Scoped enumeration listing timer delay types. enum struct TimerDelayType : unsigned char { Total = 0u, ///< Total timer time. Remaining = 1u << 0u, ///< Currently remaining timer time. All = 0xFFu ///< Determines the highest element. }; \brief %Command representation. \headerfile "" struct Command { using IdType = k8090::CommandID; using NumberType = typename std::underlying_type<IdType>::type; Command() = default; explicit Command( IdType id, int priority = 0, unsigned char mask = 0, unsigned char param1 = 0, unsigned char param2 = 0) : id(id), priority{priority}, params{mask, param1, param2} {} static NumberType idAsNumber(IdType id) { return as_number(id); } IdType id{k8090::CommandID::None}; int priority{0}; std::array<unsigned char, 3> params; Command& operator|=(const Command& other); bool operator==(const Command& other) const { if (id != other.id) { return false; } for (int i = 0; i < 3; ++i) { if (params[i] != other.params[i]) { return false; } } return true; } bool operator!=(const Command& other) const { return !(*this == other); } bool isCompatible(const Command& other) const; }; Computes checksum of bytes in the msg. unsigned char check_sum(const unsigned char* msg, int n); \brief Wraps message from or to the Velleman %K8090 relay card. \headerfile "" struct CardMessage { CardMessage(unsigned char stx, unsigned char cmd, unsigned char mask, unsigned char param1, unsigned char param2, unsigned char chk, unsigned char etx); CardMessage(QByteArray::const_iterator begin, QByteArray::const_iterator end); CardMessage(const unsigned char* begin, const unsigned char* end); explicit CardMessage(const std::array<unsigned char, 7>& message); void checksumMessage(); bool isValid() const; unsigned char commandByte() const; std::array<unsigned char, 7> data; }; } // namespace impl_ } // namespace k8090 } // namespace core } // namespace sprelay } // namespace biomolecules #endif // <API key>
#ifndef __HTTPD_FS_H__ #define __HTTPD_FS_H__ #define HTTPD_FS_STATISTICS 1 struct httpd_fs_file { char *data; long len; }; /* file must be allocated by caller and will be filled in by the function. */ int httpd_fs_open(const char *name, struct httpd_fs_file *file); #ifdef HTTPD_FS_STATISTICS #if HTTPD_FS_STATISTICS == 1 u16_t httpd_fs_count(char *name); #endif /* HTTPD_FS_STATISTICS */ #endif /* HTTPD_FS_STATISTICS */ void httpd_fs_init(void); #endif /* __HTTPD_FS_H__ */
/** * @file <API key>.h * @author Naohisa Sakamoto */ #pragma once #include <kvs/Module> #include <kvs/ImageRenderer> #include <kvs/ProgramObject> namespace kvs { class ObjectBase; class Camera; class Light; class <API key> : public kvs::ImageRenderer { kvsModule( kvs::<API key>, Renderer ); kvsModuleBaseClass( kvs::ImageRenderer ); private: kvs::ProgramObject m_shader_program{}; ///< shader program public: <API key>() = default; void exec( kvs::ObjectBase* object, kvs::Camera* camera, kvs::Light* light ); private: void <API key>(); }; } // end of namespace kvs
""" Django JSON Field. This extends Django Model Fields to store JSON as a field-type. """ #TODO - Move this to utils or another application. This is tangential to reporting and useful for other things. from django.db import models try: import json as simplejson except ImportError: from django.utils import simplejson from django.core.serializers.json import DjangoJSONEncoder import logging class JSONFieldDescriptor(object): def __init__(self, field, datatype=dict): """ Create a JSONFieldDescriptor :param field: The field to create the descriptor for. :param datatype: The datatype of the descriptor. """ self.field = field self.datatype = datatype def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) if not hasattr(instance, self.field.get_cache_name()): data = instance.__dict__.get(self.field.attname, self.datatype()) if not isinstance(data, self.datatype): data = self.field.loads(data) if data is None: data = self.datatype() setattr(instance, self.field.get_cache_name(), data) return getattr(instance, self.field.get_cache_name()) def __set__(self, instance, value): if not isinstance(value, (self.datatype, basestring)): value = self.datatype(value) instance.__dict__[self.field.attname] = value try: delattr(instance, self.field.get_cache_name()) except AttributeError: pass class JSONField(models.TextField): """ A field for storing JSON-encoded data. The data is accessible as standard Python data types and is transparently encoded/decoded to/from a JSON string in the database. """ serialize_to_string = True descriptor_class = JSONFieldDescriptor def __init__(self, verbose_name=None, name=None, encoder=DjangoJSONEncoder(), decoder=simplejson.JSONDecoder(), datatype=dict, **kwargs): """ Create a new JSONField :param verbose_name: The verbose name of the field :param name: The short name of the field. :param encoder: The encoder used to turn native datatypes into JSON. :param decoder: The decoder used to turn JSON into native datatypes. :param datatype: The native datatype to store. :param kwargs: Other arguments to pass to parent constructor. """ blank = kwargs.pop('blank', True) models.TextField.__init__(self, verbose_name, name, blank=blank, **kwargs) self.encoder = encoder self.decoder = decoder self.datatype = datatype #TODO - Is this used anywhere? If not, let's remove it. def db_type(self, connection=None): """ Returns the database type. Overrides django.db.models.Field's db_type. :param connection: The database connection - defaults to none. :return: The database type. Always returns the string 'text'. """ return "text" def contribute_to_class(self, cls, name): """ Overrides django.db.models.Field's contribute to class to handle descriptors. :param cls: The class to contribute to. :param name: The name. """ super(JSONField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self, self.datatype)) def pre_save(self, model_instance, add): "Returns field's value just before saving. If a descriptor, get's that instead of value from object." descriptor = getattr(model_instance, self.attname) if isinstance(descriptor, self.datatype): return descriptor return self.field.value_from_object(model_instance) def get_db_prep_save(self, value, *args, **kwargs): if not isinstance(value, basestring): value = self.dumps(value) return super(JSONField, self).get_db_prep_save(value, *args, **kwargs) def value_to_string(self, obj): """ Turns the value to a JSON string. :param obj: An object. :return: A string. """ return self.dumps(self.value_from_object(obj)) def dumps(self, data): """ Encodes data and dumps. :param data: A value. :return: An encoded string. """ return self.encoder.encode(data) def loads(self, val): """ :param val: A JSON encoddd string. :return: A dict with data from val """ try: val = self.decoder.decode(val)#, encoding=settings.DEFAULT_CHARSET) # XXX We need to investigate why this is happening once we have # a solid repro case. if isinstance(val, basestring): logging.warning("JSONField decode error. Expected dictionary, " "got string for input '%s'" % val) # For whatever reason, we may have gotten back val = self.decoder.decode(val)#, encoding=settings.DEFAULT_CHARSET) except ValueError: val = None return val def south_field_triple(self): """ Returns a suitable description of this field for South." :return: A tuple of field_class, args and kwargs from South's introspector. """ # We'll just introspect the _actual_ field. from south.modelsinspector import introspector field_class = "django.db.models.fields.TextField" args, kwargs = introspector(self) # That's our definition! return (field_class, args, kwargs)
#include "content/browser/browser_plugin/old/<API key>.h" #include "content/browser/browser_plugin/old/browser_plugin_host.h" #include "content/common/<API key>.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/<API key>.h" #include "ui/gfx/size.h" namespace content { <API key>::<API key>( BrowserPluginHost* browser_plugin_host, RenderViewHost* render_view_host) : <API key>(render_view_host), <API key>(browser_plugin_host) { } <API key>::~<API key>() { } bool <API key>::OnMessageReceived(const IPC::Message& message) { bool handled = true; <API key>(<API key>, message) IPC_MESSAGE_HANDLER(<API key>, OnConnectToChannel) IPC_MESSAGE_HANDLER(<API key>, <API key>) IPC_MESSAGE_HANDLER(<API key>, OnResizeGuest) <API key>(handled = false) IPC_END_MESSAGE_MAP() return handled; } void <API key>::OnConnectToChannel( const IPC::ChannelHandle& channel_handle) { <API key>-><API key>( render_view_host(), channel_handle); } void <API key>::<API key>( int32 instance_id, long long frame_id, const std::string& src) { <API key>-><API key>( render_view_host(), instance_id, frame_id, src); } void <API key>::OnResizeGuest(int width, int height) { render_view_host()->GetView()->SetSize(gfx::Size(width, height)); } } // namespace content
// Authors: Alessandro Tasora, Radu Serban #ifndef <API key> #define <API key> #include "chrono/fea/<API key>.h" namespace chrono { namespace fea { Class for thermal fields, for FEA problems involving temperature, heat, etc. class ChContinuumThermal : public <API key> { private: double <API key>; double <API key>; public: ChContinuumThermal() : <API key>(1), <API key>(1000) {} ChContinuumThermal(const ChContinuumThermal& other) : <API key>(other) { <API key> = other.<API key>; <API key> = other.<API key>; } virtual ~ChContinuumThermal() {} Sets the k conductivity constant of the material, expressed in watts per meter kelvin [ W/(m K) ]. Ex. (approx.): water = 0.6, aluminium = 200, steel = 50, plastics=0.9-0.2 Sets the conductivity matrix as isotropic (diagonal k) void <API key>(double mk) { <API key> = mk; ConstitutiveMatrix.Reset(); ConstitutiveMatrix.FillDiag(<API key>); } Gets the k conductivity constant of the material, expressed in watts per meter kelvin (W/(m K)). double <API key>() const { return <API key>; } Sets the c mass-specific heat capacity of the material, expressed as Joule per kg Kelvin [ J / (kg K) ] void <API key>(double mc) { <API key> = mc; } Sets the c mass-specific heat capacity of the material, expressed as Joule per kg Kelvin [ J / (kg K) ] double <API key>() const { return <API key>; } Get the k conductivity matrix ChMatrixDynamic<> Get_ThermalKmatrix() { return ConstitutiveMatrix; } override base: (the dT/dt term has multiplier rho*c with rho=density, c=heat capacity) virtual double Get_DtMultiplier() override { return density * <API key>; } }; } // end namespace fea } // end namespace chrono #endif
package simulation; import net.unitedfield.cc.<API key>; import processing.core.PApplet; import test.p5.OrangeWavePApplet; import com.jme3.app.SimpleApplication; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.font.BitmapText; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.Ray; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.terrain.geomipmap.TerrainQuad; import com.jme3.terrain.heightmap.AbstractHeightMap; import com.jme3.terrain.heightmap.ImageBasedHeightMap; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import com.jme3.util.SkyFactory; public class DisplayLandscapeNew extends SimpleApplication { private TerrainQuad terrain; Material mat_terrain; Node shootables; int displayNum = 0; @Override public void simpleInitApp() { shootables = new Node("Shootables"); rootNode.attachChild(shootables); setupScene(); createTerrain(); initCrossHairs(); initKeys(); } private void setupScene(){ cam.setLocation(new Vector3f(-150f, 4.0f, 0f)); flyCam.setMoveSpeed(10); //flyCam.setDragToRotate(true); rootNode.attachChild(SkyFactory.createSky(assetManager, "Textures/Sky/Bright/BrightSky.dds", false)); DirectionalLight sun = new DirectionalLight(); sun.setDirection(new Vector3f(-.5f,-.5f,-.5f).normalizeLocal()); rootNode.addLight(sun); } public void createTerrain(){ mat_terrain = new Material(assetManager, "Common/MatDefs/Terrain/Terrain.j3md"); mat_terrain.setTexture("Alpha", assetManager.loadTexture("Textures/Terrain/splat/alphamap.png")); Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex1", grass); mat_terrain.setFloat("Tex1Scale", 64f); Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg"); dirt.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex2", dirt); mat_terrain.setFloat("Tex2Scale", 32f); Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg"); rock.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex3", rock); mat_terrain.setFloat("Tex3Scale", 256f); AbstractHeightMap heightmap = null; Texture heightMapImage = assetManager.loadTexture("Textures/Terrain/splat/mountains512.png"); heightmap = new ImageBasedHeightMap(heightMapImage.getImage()); heightmap.load(); int patchSize = 65; terrain = new TerrainQuad("my terrain", patchSize, 513, heightmap.getHeightMap()); terrain.setMaterial(mat_terrain); terrain.setLocalTranslation(0, 0, 0); terrain.setLocalScale(1f, 0.05f, 1f); shootables.attachChild(terrain); } protected void initCrossHairs() { guiNode.detachAllChildren(); guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); BitmapText ch = new BitmapText(guiFont, false); ch.setSize(guiFont.getCharSet().getRenderedSize() * 2); ch.setText("+"); ch.setLocalTranslation( settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2, settings.getHeight() / 2 + ch.getLineHeight() / 2, 0); guiNode.attachChild(ch); } private void initKeys() { // Shoot inputManager.addMapping("Shoot", new KeyTrigger(KeyInput.KEY_SPACE), new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); // Shoot inputManager.addListener(actionListener, "Shoot"); } private ActionListener actionListener = new ActionListener() { public void onAction(String name, boolean keyPressed, float tpf) { // Shoot if (name.equals("Shoot") && !keyPressed) { CollisionResults results = new CollisionResults(); Ray ray = new Ray(cam.getLocation(), cam.getDirection()); shootables.collideWith(ray, results); if (results.size() > 0) { CollisionResult closest = results.getClosestCollision(); if(displayNum < 1){ putNewGirl(closest.getContactPoint()); } else { putNewDisplay(closest.getContactPoint()); } } } } }; private void putNewGirl(Vector3f pos){ Spatial girl = assetManager.loadModel("myAssets/Models/WalkingGirl/WalkingGirl.obj"); girl.rotate(0, (float)(Math.PI), 0); girl.setLocalTranslation(pos); this.rootNode.attachChild(girl); displayNum++; } private void putNewDisplay(Vector3f pos){ PApplet applet = new OrangeWavePApplet(); <API key> display = new <API key>("display"+displayNum, assetManager, 0.4f, 2f, applet, 20, 100, false); rootNode.attachChild(display); display.setLocalTranslation(pos.x, pos.y+1f, pos.z); displayNum++; } public void destroy() { super.destroy(); System.exit(0); } public static void main(String[] args) { SimpleApplication app = new DisplayLandscapeNew(); app.start(); } }
<?php namespace Application\Entity; use Zend\Form\Annotation; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\EntityRepository; /** * Task * Beschreibt eine spezifische Aufgabe. Diese kann einem Angestellten zugewiesen werden * * @ORM\Entity * @ORM\Entity(repositoryClass="TaskRepository") * @ORM\Table(name="task") */ class Task extends KnowledgeSuperclass { /** * @ORM\Column(nullable=false, length=50000) */ protected $description; /** * @ORM\Column(nullable=true, length=2000) */ protected $solution; /** * @ORM\Column(nullable=true, length=2000) */ protected $problems; /** * @ORM\Column(name="problemsDate", type="datetime", nullable=true) */ protected $problemsDate; /** * @ORM\Column(name="solutionDate", type="datetime", nullable=true) */ protected $solutionDate; /** * @ORM\ManyToOne(targetEntity="User") * @ORM\JoinColumn(name="assignee", <API key>="id") */ protected $assignee; public function getContent() { return $this->description; } public function getDescription() { return $this->description; } public function setDescription($description) { $this->description = $description; } public function getAssignee() { return $this->assignee; } public function setAssignee($assignee) { $this->assignee = $assignee; } public function getSolution() { return $this->solution; } public function setSolution($solution) { $this->solution = $solution; } public function getStatusText() { if ($this->status == 0 && $this->problems != null) { return "nacharbeiten"; } if ($this->status == 0) { return "offen"; } else if ($this->status == 2) { return "wartet auf Abnahme"; } } public function getSolutionDate() { return $this->solutionDate; } public function setSolutionDate($solutionDate) { $this->solutionDate = $solutionDate; } public function getProblems() { return $this->problems; } public function setProblems($problems) { $this->problems = $problems; } public function getProblemsDate() { return $this->problemsDate; } public function setProblemsDate($problemsDate) { $this->problemsDate = $problemsDate; } } Class TaskRepository extends EntityRepository { public function <API key>() { $q = $this->_em->createQuery('SELECT COUNT(t) FROM \Application\Entity\Task t WHERE t.status LIKE :status ORDER BY t.id DESC')->setParameter("status", "1"); $count = $q-><API key>(); return $count; } public function getRecommendations($tech, $comp, $tags) { $q = $this->_em->createQuery('SELECT k FROM \Application\Entity\Knowledge k WHERE k.status = 1'); $items = $q->getResult(); $q = $this->_em->createQuery('SELECT t FROM \Application\Entity\Task t WHERE t.status = 1'); $items = array_merge($q->getResult(), $items); $return = array(); foreach ($items as $k) { $foo["score"] = 0; $foo["id"] = $k->getId(); if ($k->getTechnology() == $tech && $k->getCompany() == $comp && $k->hasTags($tags)) { $foo["score"] += count($k->hasTags($tags)) + 5; } else if ( $k->getTechnology() == $tech && $k->getCompany() == $comp || $k->getTechnology() == $tech && $k->hasTags($tags) || $k->getCompany() == $comp && $k->hasTags($tags)) { $foo["score"] += count($k->hasTags($tags)) + 3; } else if ($k->getTechnology() == $tech || $k->getCompany() == $comp || $k->hasTags($tags)) { $foo["score"] += count($k->hasTags($tags)) + 1; } if ($foo["score"] > 0) { if (method_exists($k, "getSolution")) { $foo["description"] = $k->getSolution(); } else { $foo["description"] = $k->getContent(); } $duplicate = false; foreach ($return as $key => $e) { similar_text($e["description"], $foo["description"], $v); if ($v > 90) { $return[$key]["score"] = (intval($foo["score"]) + intval($e["score"])); $duplicate = true; } } if (!$duplicate) { $return[] = $foo; } } } return $return; } } ?>
#pragma once #include <memory> #include <string> #include <vector> #include "mcrouter/config.h" #include "mcrouter/lib/<API key>.h" #include "mcrouter/lib/Operation.h" #include "mcrouter/lib/<API key>.h" #include "mcrouter/<API key>.h" #include "mcrouter/ProxyRequestContext.h" #include "mcrouter/routes/FailoverRateLimiter.h" namespace facebook { namespace memcache { namespace mcrouter { /** * Sends the same request sequentially to each destination in the list in order, * until the first non-error reply. If all replies result in errors, returns * the last destination's reply. */ template <class RouteHandleIf, typename FailoverPolicyT> class FailoverRoute { public: static std::string routeName() { return "failover"; } template <class Operation, class Request> void traverse(const Request& req, Operation, const <API key><RouteHandleIf>& t) const { if (fiber_local::getFailoverDisabled()) { t(*targets_[0], req, Operation()); } else { t(targets_, req, Operation()); } } FailoverRoute(std::vector<std::shared_ptr<RouteHandleIf>> targets, <API key> failoverErrors, std::unique_ptr<FailoverRateLimiter> rateLimiter, bool failoverTagging, const folly::dynamic& policyConfig = nullptr) : targets_(std::move(targets)), failoverErrors_(std::move(failoverErrors)), rateLimiter_(std::move(rateLimiter)), failoverTagging_(failoverTagging), failoverPolicy_(targets_, policyConfig) { assert(targets_.size() > 1); } template <class Operation, class Request> ReplyT<Operation, Request> route(const Request& req, Operation) { auto normalReply = targets_[0]->route(req, Operation()); if (rateLimiter_) { rateLimiter_->bumpTotalReqs(); } if (fiber_local::getSharedCtx()->failoverDisabled() || !failoverErrors_.shouldFailover(normalReply, Operation())) { return normalReply; } auto& proxy = fiber_local::getSharedCtx()->proxy(); stat_incr(proxy.stats, failover_all_stat, 1); if (rateLimiter_ && !rateLimiter_->failoverAllowed()) { stat_incr(proxy.stats, <API key>, 1); return normalReply; } // Failover return fiber_local::runWithLocals([this, &req, &proxy, &normalReply]() { fiber_local::setFailoverTag(failoverTagging_ && req.hasHashStop()); fiber_local::addRequestClass(RequestClass::kFailover); auto doFailover = [this, &req, &proxy, &normalReply]( typename FailoverPolicyT::Iterator& child) { auto failoverReply = child->route(req, Operation()); logFailover(proxy, Operation::name, child.getTrueIndex(), targets_.size() - 1, req, normalReply, failoverReply); return failoverReply; }; auto cur = failoverPolicy_.begin(); auto nx = cur; for (++nx; nx != failoverPolicy_.end(); ++cur, ++nx) { auto failoverReply = doFailover(cur); if (!failoverErrors_.shouldFailover(failoverReply, Operation())) { return failoverReply; } } auto failoverReply = doFailover(cur); if (failoverReply.isError()) { stat_incr(proxy.stats, <API key>, 1); } return failoverReply; }); } private: const std::vector<std::shared_ptr<RouteHandleIf>> targets_; const <API key> failoverErrors_; std::unique_ptr<FailoverRateLimiter> rateLimiter_; const bool failoverTagging_{false}; FailoverPolicyT failoverPolicy_; }; }}} // facebook::memcache::mcrouter
#include "RvsArchiveAdapter.h" #include "<API key>.h" #include <boost/archive/archive_exception.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/vector.hpp> #include <sstream> #include <algorithm> using std::stringstream; using namespace boost::serialization; using namespace boost::archive; namespace redis{ template<class Archive> void serialize(Archive & ar, RVSKeyValue & objKeyValue, const unsigned int version) { ar & objKeyValue.dwKey; ar & objKeyValue.strValue; } } string CRvsArchiveAdapter::Oarchive(const vector<RVSKeyValue> &vecKeyValue) { RVS_XLOG(XLOG_DEBUG, "CRvsArchiveAdapter::%s\n", __FUNCTION__); stringstream sso; try { boost::archive::binary_oarchive pboa(sso); pboa & vecKeyValue; } catch (boost::archive::archive_exception & e) { RVS_XLOG(XLOG_ERROR, "CRvsArchiveAdapter::%s, error[%s]\n", __FUNCTION__, e.what()); } return sso.str(); } int CRvsArchiveAdapter::Iarchive(const string &ar, vector<RVSKeyValue>& vecKeyValue) { RVS_XLOG(XLOG_DEBUG, "CRvsArchiveAdapter::%s\n", __FUNCTION__); stringstream ssi(ar); try { boost::archive::binary_iarchive pbia(ssi); pbia & vecKeyValue; } catch (boost::archive::archive_exception & e) { RVS_XLOG(XLOG_ERROR, "CRvsArchiveAdapter::%s, error[%s]\n", __FUNCTION__, e.what()); return -1; } return 0; }
<?php namespace Parametros\Controller; use Zend\Mvc\Controller\<API key>; class IndexController extends <API key> { public function indexAction() { return array(); } }
var NAVTREE = [ [ "AADC", "index.html", [ [ "Namespaces", null, [ [ "Namespace List", "namespaces.html", "namespaces" ], [ "Namespace Members", "namespacemembers.html", [ [ "All", "namespacemembers.html", null ], [ "Functions", "<API key>.html", null ], [ "Enumerations", "<API key>.html", null ] ] ] ] ], [ "Classes", null, [ [ "Class List", "annotated.html", "annotated" ], [ "Class Index", "classes.html", null ], [ "Class Hierarchy", "hierarchy.html", "hierarchy" ], [ "Class Members", "functions.html", [ [ "All", "functions.html", "functions_dup" ], [ "Functions", "functions_func.html", null ], [ "Variables", "functions_vars.html", "functions_vars" ] ] ] ] ], [ "Files", null, [ [ "File List", "files.html", "files" ] ] ] ] ] ]; var NAVTREEINDEX = [ "<API key>.html", "<API key>.html#<API key>", "<API key>.html#<API key>", "<API key>.html", "<API key>.html#<API key>" ]; var SYNCONMSG = 'click to disable panel synchronisation'; var SYNCOFFMSG = 'click to enable panel synchronisation'; var navTreeSubIndices = new Array(); function getData(varName) { var i = varName.lastIndexOf('/'); var n = i>=0 ? varName.substring(i+1) : varName; return eval(n.replace(/\-/g,'_')); } function stripPath(uri) { return uri.substring(uri.lastIndexOf('/')+1); } function stripPath2(uri) { var i = uri.lastIndexOf('/'); var s = uri.substring(i+1); var m = uri.substring(0,i+1).match(/\/d\w\/d\w\w\/$/); return m ? uri.substring(i-6) : s; } function hashValue() { return $(location).attr('hash').substring(1).replace(/[^\w\-]/g,''); } function hashUrl() { return '#'+hashValue(); } function pathName() { return $(location).attr('pathname').replace(/[^-A-Za-z0-9+&@ } function <API key>() { try { return 'localStorage' in window && window['localStorage'] !== null && window.localStorage.getItem; } catch(e) { return false; } } function storeLink(link) { if (!$("#nav-sync").hasClass('sync') && <API key>()) { window.localStorage.setItem('navpath',link); } } function deleteLink() { if (<API key>()) { window.localStorage.setItem('navpath',''); } } function cachedLink() { if (<API key>()) { return window.localStorage.getItem('navpath'); } else { return ''; } } function getScript(scriptName,func,show) { var head = document.<API key>("head")[0]; var script = document.createElement('script'); script.id = scriptName; script.type = 'text/javascript'; script.onload = func; script.src = scriptName+'.js'; if ($.browser.msie && $.browser.version<=8) { // script.onload does not work with older versions of IE script.onreadystatechange = function() { if (script.readyState=='complete' || script.readyState=='loaded') { func(); if (show) showRoot(); } } } head.appendChild(script); } function createIndent(o,domNode,node,level) { var level=-1; var n = node; while (n.parentNode) { level++; n=n.parentNode; } if (node.childrenData) { var imgNode = document.createElement("img"); imgNode.style.paddingLeft=(16*level).toString()+'px'; imgNode.width = 16; imgNode.height = 22; imgNode.border = 0; node.plus_img = imgNode; node.expandToggle = document.createElement("a"); node.expandToggle.href = "javascript:void(0)"; node.expandToggle.onclick = function() { if (node.expanded) { $(node.getChildrenUL()).slideUp("fast"); node.plus_img.src = node.relpath+"ftv2pnode.png"; node.expanded = false; } else { expandNode(o, node, false, false); } } node.expandToggle.appendChild(imgNode); domNode.appendChild(node.expandToggle); imgNode.src = node.relpath+"ftv2pnode.png"; } else { var span = document.createElement("span"); span.style.display = 'inline-block'; span.style.width = 16*(level+1)+'px'; span.style.height = '22px'; span.innerHTML = '&#160;'; domNode.appendChild(span); } } var animationInProgress = false; function gotoAnchor(anchor,aname,updateLocation) { var pos, docContent = $('#doc-content'); var ancParent = $(anchor.parent()); if (ancParent.hasClass('memItemLeft') || ancParent.hasClass('fieldname') || ancParent.hasClass('fieldtype') || ancParent.is(':header')) { pos = ancParent.position().top; } else if (anchor.position()) { pos = anchor.position().top; } if (pos) { var dist = Math.abs(Math.min( pos-docContent.offset().top, docContent[0].scrollHeight- docContent.height()-docContent.scrollTop())); animationInProgress=true; docContent.animate({ scrollTop: pos + docContent.scrollTop() - docContent.offset().top },Math.max(50,Math.min(500,dist)),function(){ if (updateLocation) window.location.href=aname; animationInProgress=false; }); } } function newNode(o, po, text, link, childrenData, lastNode) { var node = new Object(); node.children = Array(); node.childrenData = childrenData; node.depth = po.depth + 1; node.relpath = po.relpath; node.isLast = lastNode; node.li = document.createElement("li"); po.getChildrenUL().appendChild(node.li); node.parentNode = po; node.itemDiv = document.createElement("div"); node.itemDiv.className = "item"; node.labelSpan = document.createElement("span"); node.labelSpan.className = "label"; createIndent(o,node.itemDiv,node,0); node.itemDiv.appendChild(node.labelSpan); node.li.appendChild(node.itemDiv); var a = document.createElement("a"); node.labelSpan.appendChild(a); node.label = document.createTextNode(text); node.expanded = false; a.appendChild(node.label); if (link) { var url; if (link.substring(0,1)=='^') { url = link.substring(1); link = url; } else { url = node.relpath+link; } a.className = stripPath(link.replace(' if (link.indexOf(' var aname = '#'+link.split('#')[1]; var srcPage = stripPath(pathName()); var targetPage = stripPath(link.split(' a.href = srcPage!=targetPage ? url : "javascript:void(0)"; a.onclick = function(){ storeLink(link); if (!$(a).parent().parent().hasClass('selected')) { $('.item').removeClass('selected'); $('.item').removeAttr('id'); $(a).parent().parent().addClass('selected'); $(a).parent().parent().attr('id','selected'); } var anchor = $(aname); gotoAnchor(anchor,aname,true); }; } else { a.href = url; a.onclick = function() { storeLink(link); } } } else { if (childrenData != null) { a.className = "nolink"; a.href = "javascript:void(0)"; a.onclick = node.expandToggle.onclick; } } node.childrenUL = null; node.getChildrenUL = function() { if (!node.childrenUL) { node.childrenUL = document.createElement("ul"); node.childrenUL.className = "children_ul"; node.childrenUL.style.display = "none"; node.li.appendChild(node.childrenUL); } return node.childrenUL; }; return node; } function showRoot() { var headerHeight = $("#top").height(); var footerHeight = $("#nav-path").height(); var windowHeight = $(window).height() - headerHeight - footerHeight; (function (){ // retry until we can scroll to the selected item try { var navtree=$('#nav-tree'); navtree.scrollTo('#selected',0,{offset:-windowHeight/2}); } catch (err) { setTimeout(arguments.callee, 0); } })(); } function expandNode(o, node, imm, showRoot) { if (node.childrenData && !node.expanded) { if (typeof(node.childrenData)==='string') { var varName = node.childrenData; getScript(node.relpath+varName,function(){ node.childrenData = getData(varName); expandNode(o, node, imm, showRoot); }, showRoot); } else { if (!node.childrenVisited) { getNode(o, node); } if (imm || ($.browser.msie && $.browser.version>8)) { // somehow slideDown jumps to the start of tree for IE9 :-( $(node.getChildrenUL()).show(); } else { $(node.getChildrenUL()).slideDown("fast"); } if (node.isLast) { node.plus_img.src = node.relpath+"ftv2mlastnode.png"; } else { node.plus_img.src = node.relpath+"ftv2mnode.png"; } node.expanded = true; } } } function glowEffect(n,duration) { n.addClass('glow').delay(duration).queue(function(next){ $(this).removeClass('glow');next(); }); } function highlightAnchor() { var aname = hashUrl(); var anchor = $(aname); if (anchor.parent().attr('class')=='memItemLeft'){ var rows = $('.memberdecls tr[class$="'+hashValue()+'"]'); glowEffect(rows.children(),300); // member without details } else if (anchor.parent().attr('class')=='fieldname'){ glowEffect(anchor.parent().parent(),1000); // enum value } else if (anchor.parent().attr('class')=='fieldtype'){ glowEffect(anchor.parent().parent(),1000); // struct field } else if (anchor.parent().is(":header")) { glowEffect(anchor.parent(),1000); // section header } else { glowEffect(anchor.next(),1000); // normal member } gotoAnchor(anchor,aname,false); } function selectAndHighlight(hash,n) { var a; if (hash) { var link=stripPath(pathName())+':'+hash.substring(1); a=$('.item a[class$="'+link+'"]'); } if (a && a.length) { a.parent().parent().addClass('selected'); a.parent().parent().attr('id','selected'); highlightAnchor(); } else if (n) { $(n.itemDiv).addClass('selected'); $(n.itemDiv).attr('id','selected'); } if ($('#nav-tree-contents .item:first').hasClass('selected')) { $('#nav-sync').css('top','30px'); } else { $('#nav-sync').css('top','5px'); } showRoot(); } function showNode(o, node, index, hash) { if (node && node.childrenData) { if (typeof(node.childrenData)==='string') { var varName = node.childrenData; getScript(node.relpath+varName,function(){ node.childrenData = getData(varName); showNode(o,node,index,hash); },true); } else { if (!node.childrenVisited) { getNode(o, node); } $(node.getChildrenUL()).css({'display':'block'}); if (node.isLast) { node.plus_img.src = node.relpath+"ftv2mlastnode.png"; } else { node.plus_img.src = node.relpath+"ftv2mnode.png"; } node.expanded = true; var n = node.children[o.breadcrumbs[index]]; if (index+1<o.breadcrumbs.length) { showNode(o,n,index+1,hash); } else { if (typeof(n.childrenData)==='string') { var varName = n.childrenData; getScript(n.relpath+varName,function(){ n.childrenData = getData(varName); node.expanded=false; showNode(o,node,index,hash); // retry with child node expanded },true); } else { var rootBase = stripPath(o.toroot.replace(/\..+$/, '')); if (rootBase=="index" || rootBase=="pages" || rootBase=="search") { expandNode(o, n, true, true); } selectAndHighlight(hash,n); } } } } else { selectAndHighlight(hash); } } function removeToInsertLater(element) { var parentNode = element.parentNode; var nextSibling = element.nextSibling; parentNode.removeChild(element); return function() { if (nextSibling) { parentNode.insertBefore(element, nextSibling); } else { parentNode.appendChild(element); } }; } function getNode(o, po) { var insertFunction = removeToInsertLater(po.li); po.childrenVisited = true; var l = po.childrenData.length-1; for (var i in po.childrenData) { var nodeData = po.childrenData[i]; po.children[i] = newNode(o, po, nodeData[0], nodeData[1], nodeData[2], i==l); } insertFunction(); } function gotoNode(o,subIndex,root,hash,relpath) { var nti = navTreeSubIndices[subIndex][root+hash]; o.breadcrumbs = $.extend(true, [], nti ? nti : navTreeSubIndices[subIndex][root]); if (!o.breadcrumbs && root!=NAVTREE[0][1]) { // fallback: show index navTo(o,NAVTREE[0][1],"",relpath); $('.item').removeClass('selected'); $('.item').removeAttr('id'); } if (o.breadcrumbs) { o.breadcrumbs.unshift(0); // add 0 for root node showNode(o, o.node, 0, hash); } } function navTo(o,root,hash,relpath) { var link = cachedLink(); if (link) { var parts = link.split(' root = parts[0]; if (parts.length>1) hash = '#'+parts[1].replace(/[^\w\-]/g,''); else hash=''; } if (hash.match(/^ var anchor=$('a[name='+hash.substring(1)+']'); glowEffect(anchor.parent(),1000); // line number hash=''; // strip line number anchors } var url=root+hash; var i=-1; while (NAVTREEINDEX[i+1]<=url) i++; if (i==-1) { i=0; root=NAVTREE[0][1]; } // fallback: show index if (navTreeSubIndices[i]) { gotoNode(o,i,root,hash,relpath) } else { getScript(relpath+'navtreeindex'+i,function(){ navTreeSubIndices[i] = eval('NAVTREEINDEX'+i); if (navTreeSubIndices[i]) { gotoNode(o,i,root,hash,relpath); } },true); } } function showSyncOff(n,relpath) { n.html('<img src="'+relpath+'sync_off.png" title="'+SYNCOFFMSG+'"/>'); } function showSyncOn(n,relpath) { n.html('<img src="'+relpath+'sync_on.png" title="'+SYNCONMSG+'"/>'); } function toggleSyncButton(relpath) { var navSync = $('#nav-sync'); if (navSync.hasClass('sync')) { navSync.removeClass('sync'); showSyncOff(navSync,relpath); storeLink(stripPath2(pathName())+hashUrl()); } else { navSync.addClass('sync'); showSyncOn(navSync,relpath); deleteLink(); } } function initNavTree(toroot,relpath) { var o = new Object(); o.toroot = toroot; o.node = new Object(); o.node.li = document.getElementById("nav-tree-contents"); o.node.childrenData = NAVTREE; o.node.children = new Array(); o.node.childrenUL = document.createElement("ul"); o.node.getChildrenUL = function() { return o.node.childrenUL; }; o.node.li.appendChild(o.node.childrenUL); o.node.depth = 0; o.node.relpath = relpath; o.node.expanded = false; o.node.isLast = true; o.node.plus_img = document.createElement("img"); o.node.plus_img.src = relpath+"ftv2pnode.png"; o.node.plus_img.width = 16; o.node.plus_img.height = 22; if (<API key>()) { var navSync = $('#nav-sync'); if (cachedLink()) { showSyncOff(navSync,relpath); navSync.removeClass('sync'); } else { showSyncOn(navSync,relpath); } navSync.click(function(){ toggleSyncButton(relpath); }); } $(window).load(function(){ navTo(o,toroot,hashUrl(),relpath); showRoot(); }); $(window).bind('hashchange', function(){ if (window.location.hash && window.location.hash.length>1){ var a; if ($(location).attr('hash')){ var clslink=stripPath(pathName())+':'+hashValue(); a=$('.item a[class$="'+clslink.replace(/</g,'\\3c ')+'"]'); } if (a==null || !$(a).parent().parent().hasClass('selected')){ $('.item').removeClass('selected'); $('.item').removeAttr('id'); } var link=stripPath2(pathName()); navTo(o,link,hashUrl(),relpath); } else if (!animationInProgress) { $('#doc-content').scrollTop(0); $('.item').removeClass('selected'); $('.item').removeAttr('id'); navTo(o,toroot,hashUrl(),relpath); } }) }
#include "extensions/renderer/<API key>.h" #include "base/guid.h" #include "components/lookalikes/core/lookalike_url_util.h" #include "components/version_info/version_info.h" #include "content/public/common/url_constants.h" #include "content/public/renderer/v8_value_converter.h" #include "extensions/common/url_pattern.h" #include "extensions/renderer/bindings/api_signature.h" #include "gin/converter.h" #include "gin/dictionary.h" #include "url/gurl.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_constants.h" #include "app/<API key>.h" namespace extensions { namespace { using RequestResult = APIBindingHooks::RequestResult; const char <API key>[] = "chrome-devtools"; const char kDevToolsScheme[] = "devtools"; } // namespace <API key>::<API key>() = default; <API key>::~<API key>() = default; // This is based on <API key>::HandleRequest(). RequestResult <API key>::HandleRequest( const std::string& method_name, const APISignature* signature, v8::Local<v8::Context> context, std::vector<v8::Local<v8::Value>>* arguments, const APITypeReferenceMap& refs) { using Handler = RequestResult (<API key>::*)( v8::Local<v8::Context>, const std::vector<v8::Local<v8::Value>>&); static struct { Handler handler; base::StringPiece method; } kHandlers[] = { {&<API key>::HandleGenerateGUID, "utilities.generateGUID"}, {&<API key>::<API key>, "utilities.getUrlFragments"}, {&<API key>::HandleGetVersion, "utilities.getVersion"}, {&<API key>::HandleIsUrlValid, "utilities.isUrlValid"}, }; Handler handler = nullptr; for (const auto& handler_entry : kHandlers) { if (handler_entry.method == method_name) { handler = handler_entry.handler; break; } } if (!handler) return RequestResult(RequestResult::NOT_HANDLED); APISignature::V8ParseResult parse_result = signature->ParseArgumentsToV8(context, *arguments, refs); if (!parse_result.succeeded()) { RequestResult result(RequestResult::INVALID_INVOCATION); result.error = std::move(*parse_result.error); return result; } return (this->*handler)(std::move(context), *parse_result.arguments); } RequestResult <API key>::HandleGenerateGUID( v8::Local<v8::Context> context, const std::vector<v8::Local<v8::Value>>& arguments) { base::GUID guid = base::GUID::GenerateRandomV4(); v8::Isolate* isolate = context->GetIsolate(); RequestResult result(RequestResult::HANDLED); result.return_value = gin::StringToV8(isolate, guid.AsLowercaseString()); return result; } RequestResult <API key>::<API key>( v8::Local<v8::Context> context, const std::vector<v8::Local<v8::Value>>& arguments) { DCHECK_EQ(1u, arguments.size()); DCHECK(arguments[0]->IsString()); v8::Isolate* isolate = context->GetIsolate(); std::string url_string = gin::V8ToString(isolate, arguments[0]); GURL url(url_string); url::Parsed parsed; if (url.is_valid()) { if (url.SchemeIsFile()) { ParseFileURL(url.spec().c_str(), url.spec().length(), &parsed); } else { ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); if (url.host().empty() && parsed.host.end() > 0) { // Of the type "javascript:..." ParsePathURL(url.spec().c_str(), url.spec().length(), false, &parsed); } } } v8::Local<v8::Object> fragments = v8::Object::New(isolate); auto set_fragment = [&](base::StringPiece key, base::StringPiece value) { fragments ->Set(context, gin::StringToV8(isolate, key), gin::StringToV8(isolate, value)) .ToChecked(); }; if (parsed.scheme.is_valid()) { set_fragment("scheme", url.scheme_piece()); } if (parsed.username.is_valid()) { set_fragment("username", url.username_piece()); } if (parsed.password.is_valid()) { set_fragment("password", url.password_piece()); } if (parsed.host.is_valid()) { set_fragment("host", url.host_piece()); } if (parsed.port.is_valid()) { set_fragment("port", url.port_piece()); } if (parsed.path.is_valid()) { set_fragment("path", url.path_piece()); } if (parsed.query.is_valid()) { set_fragment("query", url.query_piece()); } if (parsed.ref.is_valid()) { set_fragment("ref", url.ref_piece()); } if (parsed.host.is_valid()) { DomainInfo info = GetDomainInfo(url); base::StringPiece tld(info.domain_and_registry); if (!info.<API key>.empty()) { tld = tld.substr(info.<API key>.length() + 1); } set_fragment("tld", tld); } RequestResult result(RequestResult::HANDLED); result.return_value = std::move(fragments); return result; } RequestResult <API key>::HandleGetVersion( v8::Local<v8::Context> context, const std::vector<v8::Local<v8::Value>>& arguments) { v8::Isolate* isolate = context->GetIsolate(); v8::Local<v8::Object> version_object = v8::Object::New(isolate); version_object ->Set(context, gin::StringToV8(isolate, "vivaldiVersion"), gin::StringToV8(isolate, ::vivaldi::<API key>())) .ToChecked(); version_object ->Set(context, gin::StringToV8(isolate, "chromiumVersion"), gin::StringToV8(isolate, version_info::GetVersionNumber())) .ToChecked(); RequestResult result(RequestResult::HANDLED); result.return_value = std::move(version_object); return result; } namespace { bool <API key>(const GURL& url) { base::StringPiece scheme = url.scheme_piece(); if (URLPattern::<API key>(scheme)) return true; static const base::StringPiece extra_schemes[] = { url::kJavaScriptScheme, url::kDataScheme, url::kMailToScheme, content::kViewSourceScheme, <API key>, kDevToolsScheme, }; for (base::StringPiece extra_scheme : extra_schemes) { if (scheme == extra_scheme) return true; } // For about: urls only the blank page is supported. return url.IsAboutBlank(); } } // namespace RequestResult <API key>::HandleIsUrlValid( v8::Local<v8::Context> context, const std::vector<v8::Local<v8::Value>>& arguments) { DCHECK_EQ(1u, arguments.size()); DCHECK(arguments[0]->IsString()); v8::Isolate* isolate = context->GetIsolate(); std::string url_string = gin::V8ToString(isolate, arguments[0]); GURL url(url_string); bool url_valid = url.is_valid(); bool is_browser_url = <API key>(url); std::string scheme_parsed = url.scheme(); // GURL::spec() can only be called when url is valid. std::string normalized_url = url.is_valid() ? url.spec() : std::string(); v8::Local<v8::Object> result_object = v8::Object::New(isolate); result_object ->Set(context, gin::StringToV8(isolate, "urlValid"), v8::Boolean::New(isolate, url_valid)) .ToChecked(); result_object ->Set(context, gin::StringToV8(isolate, "isBrowserUrl"), v8::Boolean::New(isolate, is_browser_url)) .ToChecked(); result_object ->Set(context, gin::StringToV8(isolate, "schemeParsed"), gin::StringToV8(isolate, scheme_parsed)) .ToChecked(); result_object ->Set(context, gin::StringToV8(isolate, "normalizedUrl"), gin::StringToV8(isolate, normalized_url)) .ToChecked(); RequestResult result(RequestResult::HANDLED); result.return_value = std::move(result_object); return result; } } // namespace extensions
require 'date' require 'time' require 'bigdecimal' module Hippo class Field attr_accessor :name, :sequence, :datatype, :options, :restrictions, :minimum, :maximum, :required, :separator, :composite, :composite_sequence def minimum @minimum ||= 0 end def formatted_value(value) return nil if value.nil? case datatype when :binary then value when :integer then value.to_i when :decimal then parse_decimal(value) when :date then parse_date(value) when :time then parse_time(value) else parse_string(value) end end def string_value(value) return '' if value.nil? && !required case datatype when :binary then value when :integer then value.to_s.rjust(minimum, '0') when :decimal then generate_decimal(value) when :date then generate_date(value) when :time then generate_time(value) else generate_string(value) end end def generate_string(value) if required value.to_s.ljust(minimum) else value.to_s end end def parse_string(value) if value.to_s.empty? && !required nil else value.to_s.strip end end def generate_decimal(value) value ||= BigDecimal.new('0') value.to_s('F').sub(/\.0\z/,'').rjust(minimum, '0') end def parse_decimal(value) if value == '' invalid! if required return nil end BigDecimal.new(value.to_s) end def generate_time(value) value ||= Time.now if maximum == 4 || value.sec == 0 value.strftime('%H%M') else value.strftime('%H%M%S') end end def parse_time(value) if value == '' invalid! if required return nil end case value.class.to_s when 'Time' then value when 'String' format = case value when /\A\d{4}\z/ then '%H%M' when /\A\d{6}\z/ then '%H%M%S' when /\A\d{7,8}\z/ then '%H%M%S%N' else invalid! end Time.strptime(value, format) else invalid! end rescue invalid! end def generate_date(value) value ||= Date.today if value.class.to_s == 'Range' "#{value.first.strftime('%Y%m%d')}-#{value.last.strftime('%Y%m%d')}" elsif maximum == 6 value.strftime('%y%m%d') else value.strftime('%Y%m%d') end end def parse_date(value) if value == '' invalid! if required return nil end case value.class.to_s when "Range" then value when "Date" then value when "Time" then value.to_date when "String" format = case value when /\A\d{6}\z/ then '%y%m%d' when /\A\d{8}\z/ then '%Y%m%d' when /\A(\d{8})-(\d{8})\z/ then return Date.parse($1, '%Y%m%d')..Date.parse($2, '%Y%m%d') else invalid! end Date.parse(value, format) else invalid! "Invalid datatype(#{value.class}) for date field." end rescue invalid! end def invalid!(message = "Invalid value specified for #{self.datatype} field.") raise Hippo::Exceptions::InvalidValue.new message end end end
#ifndef <API key> #define <API key> #include "base/compiler_specific.h" #include <stdlib.h> #include <type_traits> #include <utility> // THIS IS *NOT* A GENERAL PURPOSE HASH TABLE TEMPLATE. INSTEAD, IT CAN // CAN BE USED AS THE BASIS FOR VERY HIGH SPEED AND COMPACT HASH TABLES // THAT OBEY VERY STRICT CONDITIONS DESCRIBED BELOW. // DO NOT USE THIS UNLESS YOU HAVE A GOOD REASON, I.E. THAT PROFILING // SHOWS THERE *IS* AN OVERALL BENEFIT TO DO SO. FOR MOST CASES, // std::set<>, std::unordered_set<> and base::flat_set<> ARE PERFECTLY // FINE AND SHOULD BE PREFERRED. // That being said, this implementation uses a completely typical // open-addressing scheme with a buckets array size which is always // a power of 2, instead of a prime number. Experience shows this is // not detrimental to performance as long as you have a sufficiently // good hash function (which is the case of all C++ standard libraries // these days for strings and pointers). // The reason it is so fast is due to its compactness and the very // simple but tight code for a typical lookup / insert / deletion // operation. // The |buckets_| field holds a pointer to an array of NODE_TYPE // instances, called nodes. Each node represents one of the following: // a free entry in the table, an inserted item, or a tombstone marking // the location of a previously deleted item. Tombstones are only // used if the hash table instantiation requires deletion support // (see the is_tombstone() description below). // The template requires that Node be a type with the following traits: // - It *must* be a trivial type, that is zero-initialized. // - It provides an is_null() const method, which should return true // if the corresponding node matches a 'free' entry in the hash // table, i.e. one that has not been assigned to an item, or // to a deletion tombstone (see below). // Of course, a default (zeroed) value, should always return true. // - It provides an is_tombstone() const method, which should return // return true if the corresponding node indicates a previously // deleted item. // Note that if your hash table does not need deletion support, // it is highly recommended to make this a static constexpr method // that always return false. Doing so will optimize the lookup loop // automatically! // - It must provide an is_valid() method, that simply returns // (!is_null() && !is_tombstone()). This is a convenience for this // template, but also for the derived class that will extend it // (more on this below, in the usage description). // Note that because Node instances are trivial, std::unique_ptr<> // cannot be used in them. Item lifecycle must this be managed // explicitly by a derived class of the template instantiation // instead. // Lookup, insertion and deletion are performed in ways that // are *very* different from standard containers, and the reason // is, unsurprisingly, performance. // Use NodeLookup() to look for an existing item in the hash table. // This takes the item's hash value, and a templated callable to // compare a node against the search key. This scheme allows // heterogeneous lookups, and keeps the node type details // out of this header. Any recent C++ optimizer will generate // very tight machine code for this call. // The NodeLookup() function always returns a non-null and // mutable |node| pointer. If |node->is_valid()| is true, // then the item was found, and |node| points to it. // Otherwise, |node| corresponds to a location that may be // used for insertion. To do so, the caller should update the // content of |node| appropriately (e.g. writing a pointer and/or // hash value to it), then call <API key>(), which // may eventually grow the table and rehash nodes in it. // To delete an item, call NodeLookup() first to verify that // the item is present, then write a tombstone value to |node|, // then call UpdateAfterDeletion(). // Note that what the tombstone value is doesn't matter to this // header, as long as |node->is_tombstone()| returns true for // Here's an example of a concrete implementation that stores // a hash value and an owning pointer in each node: // struct MyFooNode { // size_t hash; // Foo* foo; // bool is_null() const { return !foo; } // bool is_tombstone() const { return foo == &kTombstone; } // bool is_valid() const { return !is_null() && !is_tombstone(); } // static const Foo kTombstone; // class MyFooSet : public HashTableBase<MyFoodNode> { // public: // using BaseType = HashTableBase<MyFooNode>; // using Node = BaseType::Node; // ~MyFooSet() { // // Destroy all items in the set. // // Note that the iterator only parses over valid items. // for (Node* node : *this) { // delete node->foo; // // Returns true if this set contains |key|. // bool contains(const Foo& key) const { // Node* node = BaseType::NodeLookup( // MakeHash(key), // [&](const Node* node) { return node->foo == key; }); // return node->is_valid(); // // Try to add |key| to the set. Return true if the insertion // // was successful, or false if the item was already in the set. // bool add(const Foo& key) { // size_t hash = MakeHash(key); // Node* node = NodeLookup( // hash, // [&](const Node* node) { return node->foo == key; }); // if (node->is_valid()) { // // Already in the set. // return false; // // Add it. // node->hash = hash; // node->foo = new Foo(key); // UpdateAfterInsert(); // return true; // // Try to remove |key| from the set. Return true if the // // item was already in it, false otherwise. // bool erase(const Foo& key) { // Node* node = BaseType::NodeLookup( // MakeHash(key), // [&](const Node* node) { return node->foo == key; }); // if (!node->is_valid()) { // // Not in the set. // return false; // delete node->foo; // node->foo = Node::kTombstone; // UpdateAfterDeletion(). // return true; // static size_t MakeHash(const Foo& foo) { // return std::hash<Foo>()(); // For more concrete examples, see the implementation of // StringAtom or UniqueVector<> template <typename NODE_TYPE> class HashTableBase { public: using Node = NODE_TYPE; static_assert(std::is_trivial<NODE_TYPE>::value, "KEY_TYPE should be a trivial type!"); static_assert(std::is_standard_layout<NODE_TYPE>::value, "KEY_TYPE should be a standard layout type!"); // Default constructor. HashTableBase() = default; // Destructor. This only deals with the |buckets_| array itself. ~HashTableBase() { if (buckets_ != buckets0_) free(buckets_); } // Copy and move operations. These only operate on the |buckets_| array // so any owned pointer inside nodes should be handled by custom // constructors and operators in the derived class, if needed. HashTableBase(const HashTableBase& other) : count_(other.count_), size_(other.size_) { if (other.buckets_ != other.buckets0_) { // NOTE: using malloc() here to clarify that no object construction // should occur here. buckets_ = reinterpret_cast<Node*>(malloc(other.size_ * sizeof(Node))); } memcpy(buckets_, other.buckets_, other.size_ * sizeof(Node)); } HashTableBase& operator=(const HashTableBase& other) { if (this != &other) { this->~HashTableBase(); new (this) HashTableBase(other); } return *this; } HashTableBase(HashTableBase&& other) noexcept : count_(other.count_), size_(other.size_), buckets_(other.buckets_) { if (buckets_ == other.buckets0_) { buckets0_[0] = other.buckets0_[0]; buckets_ = buckets0_; } else { other.buckets_ = other.buckets0_; } other.NodeClear(); } HashTableBase& operator=(HashTableBase&& other) noexcept { if (this != &other) { this->~HashTableBase(); new (this) HashTableBase(std::move(other)); } return *this; } // Return true if the table is empty. bool empty() const { return count_ == 0; } // Return the number of keys in the set. size_t size() const { return count_; } protected: // The following should only be called by derived classes that // extend this template class, and are not available to their // clients. This forces the derived class to implement lookup // insertion and deletion with sane APIs instead. // Iteration support note: // Derived classes, if they wish to support iteration, should provide their // own iterator/const_iterator/begin()/end() types and methods, possibly as // simple wrappers around the NodeIterator/NodeBegin/NodeEnd below. // Defining a custom iterator is as easy as deriving from NodeIterator // and overloading operator*() and operator->(), as in: // struct FooNode { // size_t hash; // Foo* foo_ptr; // class FooTable : public HashTableBase<FooNode> { // public: // // Iterators point to Foo instances, not table nodes. // struct ConstIterator : NodeIterator { // const Foo* operator->() { return node_->foo_ptr; } // const Foo& operator*)) { return *(node_->foo_ptr); } // ConstIterator begin() const { return { NodeBegin() }; } // ConstIterator end() const { return { NodeEnd() }; } // The NodeIterator type has a valid() method that can be used to perform // faster iteration though at the cost of using a slightly more annoying // syntax: // for (auto it = my_table.begin(); it.valid(); ++it) { // const Foo& foo = *it; // Instead of: // for (const Foo& foo : my_table) { // The ValidNodesRange() method also returns a object that has begin() and // end() methods to be used in for-range loops over Node values as in: // for (Node& node : my_table.ValidNodesRange()) { ... } struct NodeIterator { Node& operator*() { return *node_; } const Node& operator*() const { return *node_; } Node* operator->() { return node_; } const Node* operator->() const { return node_; } bool operator==(const NodeIterator& other) const { return node_ == other.node_; } bool operator!=(const NodeIterator& other) const { return node_ != other.node_; } // pre-increment NodeIterator& operator++() { node_++; while (node_ < node_limit_ && !node_->is_valid()) node_++; return *this; } // post-increment NodeIterator operator++(int) { NodeIterator result = *this; ++(*this); return result; } // Returns true if the iterator points to a valid node. bool valid() const { return node_ != node_limit_; } Node* node_ = nullptr; Node* node_limit_ = nullptr; }; // NOTE: This is intentionally not public to avoid exposing // them in derived classes by mistake. If a derived class // wants to support iteration, it provide its own begin() and end() // methods, possibly using NodeBegin() and NodeEnd() below to // implement them. NodeIterator begin() { return NodeBegin(); } NodeIterator end() { return NodeEnd(); } // Providing methods named NodeBegin() and NodeEnd(), instead of // just using begin() and end() is a convenience to derived classes // that need to provide their own begin() and end() method, e.g. // consider this class: // struct FooNode { // size_t hash; // Foo* foo_ptr; // class FooTable : public HashTableBase<FooNode> { // public: // // Iterators point to Foo instances, not table nodes. // struct ConstIterator : NodeIterator { // const Foo* operator->() { return node_->foo_ptr; } // const Foo& operator*)) { return *(node_->foo_ptr); } // and compare two ways to implement its begin() method: // Foo::ConstIterator Foo::begin() const { // return { // reinterpret_cast<const HashTableBase<FooNode> *>(this)->begin() // with: // Foo::ConstIterator Foo::begin() const { // return { NodeBegin(); } NodeIterator NodeBegin() const { Node* node = buckets_; Node* limit = node + size_; while (node < limit && !node->is_valid()) node++; return {node, limit}; } NodeIterator NodeEnd() const { Node* limit = buckets_ + size_; return {limit, limit}; } // ValidNodeRange() allows a derived-class to use range-based loops // over valid nodes, even if they have defined their own begin() and // end() methods, e.g. following the same class design as in the // above comment: // FooTable::~FooTable() { // for (const FooNode& node : ValidNodesRange()) { // delete node->foo_ptr; // which is a little bit clearer than the (valid) alternative: // FooTable::~FooTable() { // for (Foo& foo : *this) { // delete &foo; // WHAT!? struct NodeIteratorPair { NodeIterator begin() { return begin_; } NodeIterator end() { return end_; } NodeIterator begin_; NodeIterator end_; }; NodeIteratorPair ValidNodesRange() const { return {NodeBegin(), NodeEnd()}; } // Clear the nodes table completely. void NodeClear() { if (buckets_ != buckets0_) free(buckets_); count_ = 0; size_ = 1; buckets_ = buckets0_; buckets0_[0] = Node{}; } // Lookup for a node in the hash table that matches the |node_equal| // predicate, which takes a const Node* pointer argument, and returns // true if this corresponds to a lookup match. // IMPORTANT: |node_equal| may or may not check the node hash value, // the choice is left to the implementation. // Returns a non-null *mutable* node pointer. |node->is_valid()| will // be true for matches, and false for misses. // NOTE: In case of a miss, this will return the location of the first // tombstone encountered during probing, if any, or the first free entry // otherwise. This keeps the table consistent in case the node is overwritten // by the caller in a following insert operation. template <typename NODE_EQUAL> Node* NodeLookup(size_t hash, NODE_EQUAL node_equal) const { size_t mask = size_ - 1; size_t index = hash & mask; Node* tombstone = nullptr; // First tombstone node found, if any. for (;;) { Node* node = buckets_ + index; if (node->is_null()) { return tombstone ? tombstone : node; } if (node->is_tombstone()) { if (!tombstone) tombstone = node; } else if (node_equal(node)) { return node; } index = (index + 1) & mask; } } // Call this method after updating the content of the |node| pointer // returned by an unsuccessful NodeLookup(). Return true to indicate that // the table size changed, and that existing iterators were invalidated. bool UpdateAfterInsert() { count_ += 1; if (UNLIKELY(count_ * 4 >= size_ * 3)) { GrowBuckets(); return true; } return false; } // Call this method after updating the content of the |node| value // returned a by successful NodeLookup, to the tombstone value, if any. // Return true to indicate a table size change, ie. that existing // iterators where invalidated. bool UpdateAfterRemoval() { count_ -= 1; // For now don't support shrinking since this is not useful for GN. return false; } private: #if defined(__GNUC__) || defined(__clang__) [[gnu::noinline]] #endif void GrowBuckets() { size_t size = size_; size_t new_size = (size == 1) ? 8 : size * 2; size_t new_mask = new_size - 1; // NOTE: Using calloc() since no object constructiopn can or should take // place here. Node* new_buckets = reinterpret_cast<Node*>(calloc(new_size, sizeof(Node))); for (size_t src_index = 0; src_index < size; ++src_index) { const Node* node = &buckets_[src_index]; if (!node->is_valid()) continue; size_t dst_index = node->hash_value() & new_mask; for (;;) { Node* node2 = new_buckets + dst_index; if (node2->is_null()) { *node2 = *node; break; } dst_index = (dst_index + 1) & new_mask; } } if (buckets_ != buckets0_) free(buckets_); buckets_ = new_buckets; buckets0_[0] = Node{}; size_ = new_size; } // NOTE: The reason for <API key> |buckets_| to a storage slot // inside the object is to ensure the value is never null. This removes one // nullptr check from each NodeLookup() instantiation. size_t count_ = 0; size_t size_ = 1; Node* buckets_ = buckets0_; Node buckets0_[1] = {{}}; }; #endif // <API key>
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>PVeins: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">PVeins </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all class members with links to the classes they belong to:</div> <h3><a id="index_l"></a>- l -</h3><ul> <li>LaneSetTrigger() : <a class="el" href="<API key>.html#<API key>">traci_api::LaneSetTrigger</a> </li> <li>length : <a class="el" href="<API key>.html#<API key>">DimensionalData</a> </li> <li>lengthLen : <a class="el" href="<API key>.html#<API key>">tcpip::Socket</a> </li> <li><API key>() : <a class="el" href="<API key>.html#<API key>">traci_api::<API key></a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html>
module.exports = require("./loadable-components");
#ifndef BTTRACKER_NET_H_ #define BTTRACKER_NET_H_ /* * Buffer length used to receive data from clients. This value was defined * based on the largest packet to be received, which is a scrape request * packet. According to the spec, the maximum number of torrents that can * be sent in a scrape request is about 74, so (74*20)+16 = 1496. */ #define BT_RECV_BUFLEN (1496) /* 64-bit integer that identifies the UDP-based tracker protocol. */ #define BT_PROTOCOL_ID (0x41727101980LL) /* Fills request struct with buffer data. */ void <API key>(const char *buffer, bt_req_t *req); /* Writes the error response data to an output buffer. */ void bt_write_error_data(char *resp_buffer, bt_req_t *req, const char* msg); /* Writes the connection response data to an output buffer. */ void <API key>(char *buffer, <API key> *resp); /* Fills the announce request with buffer data. */ void <API key>(const char *buffer, bt_announce_req_t *req); /* Writes the announce response data to an output buffer. */ void <API key>(char *resp_buffer, bt_announce_resp_t *resp); /* Writes the peer data to be sent along the announce response. */ void <API key>(char *resp_buffer, bt_list *peers); /* Fills the scrape request with buffer data. */ void <API key>(const char *buffer, size_t buflen, bt_scrape_req_t *req); /* Writes the scrape response data to an output buffer. */ void <API key>(char *resp_buffer, bt_scrape_resp_t *resp); /* Fills a `struct addrinfo` and returns a corresponding UDP socket. */ int bt_ipv4_udp_sock(const char *addr, uint16_t port, struct addrinfo **addrinfo); #endif // BTTRACKER_NET_H_
package ring import "io" // MsgRing will send and receive Msg instances to and from ring nodes. See // TCPMsgRing for a concrete implementation. type MsgRing interface { Ring() Ring // MaxMsgLength indicates the maximum number of bytes the content of a // message may contain to be handled by this MsgRing. MaxMsgLength() uint64 // SetMsgHandler associates a message type with a handler; any incoming // messages with the type will be delivered to the handler. Message types // just need to be unique uint64 values; usually picking 64 bits of a UUID // is fine. SetMsgHandler(msgType uint64, handler MsgUnmarshaller) // MsgToNode attempts to the deliver the message to the indicated node. MsgToNode(nodeID uint64, msg Msg) // MsgToNode attempts to the deliver the message to all other replicas of a // partition. If the ring is not bound to a specific node (LocalNode() // returns nil) then the delivery attempts will be to all replicas. The // ring version is used to short circuit any messages based on a different // ring version; if the ring version does not match Version(), the message // will simply be discarded. MsgToOtherReplicas(ringVersion int64, partition uint32, msg Msg) } // Msg is a single message to be sent to another node or nodes. type Msg interface { // MsgType is the unique designator for the type of message content (such // as a pull replication request, a read request, etc.). Message types just // need to be unique values; usually picking 64 bits of a UUID is fine. MsgType() uint64 // MsgLength returns the number of bytes for the content of the message // (the amount that will be written with a call to WriteContent). MsgLength() uint64 // WriteContent will send the contents of the message to the given writer; // note that WriteContent may be called multiple times and may be called // concurrently. WriteContent(io.Writer) (uint64, error) // Done will be called when the MsgRing is done processing the message and // allows the message to free any resources it may have. Done() } // MsgUnmarshaller will attempt to read desiredBytesToRead from the reader and // will return the number of bytes actually read as well as any error that may // have occurred. If error is nil then actualBytesRead must equal // desiredBytesToRead. type MsgUnmarshaller func(reader io.Reader, desiredBytesToRead uint64) (actualBytesRead uint64, err error)
define(['jquery', 'fury.notify', 'jquery-ui', '<API key>'], function ($, notify) { $(function () { function sortableInit() { $('.sortable').nestedSortable({ handle: 'div', items: 'li', toleranceElement: '> div' }); } sortableInit(); $('body') .on('change', '.<API key> .select-tree select', function () { var $this = $(this); var $grid = $('[data-spy="grid"]'); $.ajax({ url: '/categories/management/index/' + $this.val(), type: 'get', dataType: 'html', beforeSend: function () { $grid.find('a, .btn').addClass('disabled'); }, success: function (html) { $grid.html($(html).children().unwrap()); $('body').trigger('grid.loaded', []); } }); }) .on('click', '#save', function (e) { $('.sortable li').each(function (key, value) { $(this).attr('data-order', key + 1); }); var arraied = $('ol.sortable').nestedSortable('toArray', {startDepthCount: 0}); $.ajax({ url: '/categories/management/order', type: 'post', success: function (data) { notify.set(data); }, dataType: 'json', data: { tree: JSON.stringify(arraied), treeParent: $('.tree-header').attr('data-parent-id') } }); }) .on('grid.loaded', function () { sortableInit(); }); }); });
{{extend 'layout.html'}} <h1>Add submission</h1> {{if instructions:}} <div class="alert alert-info"><i class="icon-info-sign"></i> {{=instructions}} </div> {{pass}} <p>Venue : {{=A(T('Assignment') + ' ' + venue.name, _href=URL('venues', 'view_venue', args=[venue.id]))}} {{=form}} {{if request.is_local:}} {{=response.toolbar()}} {{pass}}
var searchData= [ ['turnoffvblankflag',['TurnOffVBlankFlag',['../class_g_p_u.html#<API key>',1,'GPU']]] ];
# -*- coding: utf-8 -*- import pytest from flask import url_for from myflaskapp.models.user import User from .factories import UserFactory class TestLoggingIn: def <API key>(self, user, testapp): # Goes to homepage res = testapp.get("/") # Fills out login form in navbar form = res.forms['loginForm'] form['username'] = user.username form['password'] = 'myprecious' # Submits res = form.submit().follow() assert res.status_code == 200 def <API key>(self, user, testapp): res = testapp.get("/") # Fills out login form in navbar form = res.forms['loginForm'] form['username'] = user.username form['password'] = 'myprecious' # Submits res = form.submit().follow() res = testapp.get(url_for('public.logout')).follow() # sees alert assert 'You are logged out.' in res def <API key>(self, user, testapp): # Goes to homepage res = testapp.get("/") # Fills out login form, password incorrect form = res.forms['loginForm'] form['username'] = user.username form['password'] = 'wrong' # Submits res = form.submit() # sees error assert "Invalid password" in res def <API key>(self, user, testapp): # Goes to homepage res = testapp.get("/") # Fills out login form, password incorrect form = res.forms['loginForm'] form['username'] = 'unknown' form['password'] = 'myprecious' # Submits res = form.submit() # sees error assert "Unknown user" in res class TestRegistering: def test_can_register(self, user, testapp): old_count = len(User.query.all()) # Goes to homepage res = testapp.get("/") # Clicks Create Account button res = res.click("Create account") # Fills out the form form = res.forms["registerForm"] form['username'] = 'foobar' form['email'] = 'foo@bar.com' form['password'] = 'secret' form['confirm'] = 'secret' # Submits res = form.submit().follow() assert res.status_code == 200 # A new user was created assert len(User.query.all()) == old_count + 1 def <API key>(self, user, testapp): # Goes to registration page res = testapp.get(url_for("public.register")) # Fills out form, but passwords don't match form = res.forms["registerForm"] form['username'] = 'foobar' form['email'] = 'foo@bar.com' form['password'] = 'secret' form['confirm'] = 'secrets' # Submits res = form.submit() # sees error message assert "Passwords must match" in res def <API key>(self, user, testapp): user = UserFactory(active=True) # A registered user user.save() # Goes to registration page res = testapp.get(url_for("public.register")) # Fills out form, but username is already registered form = res.forms["registerForm"] form['username'] = user.username form['email'] = 'foo@bar.com' form['password'] = 'secret' form['confirm'] = 'secret' # Submits res = form.submit() # sees error assert "Username already registered" in res
#include "color_utilities.hpp" #include <algorithm> #include <string> #include <cmath> namespace wgt { namespace ColorUtilities { const float GAMMA = 2.2; Int4 makeColor(const Vector4& color) { const auto clampedColor = clamp(color); return Int4 { int(clampedColor.x * 255.0f), int(clampedColor.y * 255.0f), int(clampedColor.z * 255.0f), int(clampedColor.w * 255.0f) }; } Vector4 makeColor(int r, int g, int b, int a) { return clamp(Vector4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f)); } Vector4 makeHDRColor(int r, int g, int b, float intensity) { return setExposure(makeColor(r, g, b), intensity); } Vector4 setExposure(const Vector4& v, float intensity) { return v * std::pow(2.0f, intensity); } Vector4 clamp(const Vector4& v) { return Vector4(std::max(std::min(1.0f, v.x), 0.0f), std::max(std::min(1.0f, v.y), 0.0f), std::max(std::min(1.0f, v.z), 0.0f), std::max(std::min(1.0f, v.w), 0.0f)); } Vector4 reinhardTonemap(const Vector4& v, float luminanceWhite) { const float EPSILON = 0.00000000001f; const float lum = luminance(v); if (lum < EPSILON) { return v; } const float tmLum = (lum * (1.0f + (lum / (luminanceWhite * luminanceWhite)))) / (1.0f + lum); const float scale = tmLum / lum; return clamp(Vector4(std::pow(v.x * scale, 1.0f / GAMMA), std::pow(v.y * scale, 1.0f / GAMMA), std::pow(v.z * scale, 1.0f / GAMMA), std::pow(v.w * scale, 1.0f / GAMMA))); } float luminance(const Vector4& v) { return 0.2126f * v.x + 0.7152f * v.y + 0.0722f * v.z; } Vector4 convertKelvinToRGB(int kelvin) { Vector4 rgb(0.0f, 0.0f, 0.0f, 1.0f); const float k = std::max(0.0f, (float)kelvin); if (k <= 6500.0f) { rgb.x = 1.0f; } else { rgb.x = 108180.0f * std::pow((k - 2080.2f), -1.422f) + 0.29533f; } if (k < 6600.0f) { rgb.y = -0.03021f * std::pow(k, 0.64623f) + 0.9153f * std::pow(k, 0.99946f) - 0.90952f * k + 0.29523f; } else { rgb.y = 3985.0f * std::pow((k - 2600.8f), -1.0858f) + 0.45791f; } if (k <= 1900.0f) { rgb.z = 0.0f; } else if (k > 6600.0f) { rgb.z = 1.0f; } else { rgb.z = -6.107e-12f * std::pow(k, 3.0f) + 9.068E-8f * std::pow(k, 2.0f) - 1.9202e-4f * k + 7.4626e-2f; } return clamp(rgb); } } } // end namespace wgt
#ifndef <API key> #define <API key> #include <Universe/World.h> #include <Player.h> namespace ChronoRage { class GameMode; const Core::String POWERUP_FILE = L"/ChronoRageData/voxels-power-up.tga"; const float MAX_LIFETIME = 10.0f; LM_ENUM_5(EPowerUPState, <API key>, <API key>, POWER_UP_ACTIVE, <API key>, <API key>); class LM_API_CHR PowerUp : public Core::Object { public: PowerUp(const Ptr<Universe::World> & pWorld, const Ptr<Player> & pPlayer, GameMode & gameMode); virtual ~PowerUp(); virtual void initialize(const Core::Vector3f & position); virtual Core::Vector3f getPosition() const; virtual void update(double elapsed); virtual void <API key>(); virtual bool collidesPlayer(); virtual void selfDestruct(); virtual bool isKilled(); bool isCollisionActive() const; protected: virtual void updateCreation(double elapsed); virtual void updateActive(double elapsed); virtual void updateDestruction(double elapsed); virtual Ptr<VoxelSpriteTemplate> getTemplate() const; static Ptr<VoxelSpriteTemplate> spTemplate; protected: Ptr<Universe::World> _pWorld; Ptr<Player> _pPlayer; GameMode & _gameMode; Ptr<Universe::Node> _pNodePowerUp; Ptr<VoxelSprite> _pVoxelSprite; Ptr<Core::CollisionShape> _pCollisionShape; EPowerUPState _state; Ptr<Universe::NodeDecal> _pShockWaveRefrac; float <API key>; bool _createShockWave; Core::Vector3f _direction; Core::Vector4f _color; float _width; float _height; float _speed; }; }//namespace ChronoRage #endif/*<API key>*/
# Tests: Diffusion Problems Tests with elements for diffusion(-like) problems ## Diffusion 1. diffu01a. Diffusion (Poisson) equation 01. Check DOFs 2. diffu02a. Diffusion (Poisson) equation 02. Check DOFs 3. diffu02b. Diffusion (Poisson) equation 02. Run ## Vector term 1. phi01 2. phi02
<?php namespace Gajus\Strading\Exception; class RuntimeException extends StradingException {}
<?php namespace app\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; use yii\db\Expression; /** * This is the model class for table "{{%mailtempl}}". * * @property integer $mt_id * @property string $mt_createtime * @property string $mt_name * @property string $mt_text */ class Mailtempl extends \yii\db\ActiveRecord { /** * @return array */ public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['mt_createtime'], ], 'value' => ( strtolower($this->db->driverName) != 'sqlite' ) ? new Expression('NOW()') : date('Y-m-d H:i:s'), ], ]; } /** * @inheritdoc */ public static function tableName() { return '{{%mailtempl}}'; } /** * @inheritdoc */ public function rules() { return [ [['mt_createtime'], 'safe'], [['mt_text'], 'string'], [['mt_name'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'mt_id' => 'ID', 'mt_createtime' => 'Создан', 'mt_name' => 'Название', 'mt_text' => 'Текст', ]; } }
#define SUITE printable #include "vast/test/test.hpp" #include <sstream> #include <caf/optional.hpp> #include "vast/concept/printable/core.hpp" #include "vast/concept/printable/numeric.hpp" #include "vast/concept/printable/print.hpp" #include "vast/concept/printable/std/chrono.hpp" #include "vast/concept/printable/stream.hpp" #include "vast/concept/printable/string.hpp" #include "vast/concept/printable/to.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/data.hpp" #include "vast/concept/printable/vast/view.hpp" #include "vast/detail/escapers.hpp" using namespace std::string_literals; using namespace vast; using namespace vast::printer_literals; #define CHECK_TO_STRING(expr, str) \ { \ auto x = expr; \ if constexpr (!std::is_same_v<decltype(x), data>) { \ CHECK_EQUAL(to_string(x), str); \ CHECK_EQUAL(to_string(make_view(x)), str); \ } \ data data_expr{x}; \ CHECK_EQUAL(to_string(data_expr), str); \ CHECK_EQUAL(to_string(make_view(data_expr)), str); \ } TEST(signed integers) { MESSAGE("no sign"); auto i = 42; std::string str; CHECK(printers::integral<int>(str, i)); CHECK_EQUAL(str, "42"); MESSAGE("forced sign"); str.clear(); CHECK(printers::integral<int, policy::force_sign>(str, i)); CHECK_EQUAL(str, "+42"); MESSAGE("negative sign"); str.clear(); int8_t j = -42; CHECK(printers::i8(str, j)); CHECK_EQUAL(str, "-42"); } TEST(unsigned integers) { auto i = 42u; std::string str; CHECK(printers::integral<unsigned>(str, i)); CHECK_EQUAL(str, "42"); } TEST(integral minimum digits) { std::string str; auto i = 0; CHECK(printers::integral<int, policy::plain, 5>(str, i)); CHECK_EQUAL(str, "00000"); str.clear(); i = 42; CHECK(printers::integral<int, policy::force_sign, 4>(str, i)); CHECK_EQUAL(str, "+0042"); } TEST(floating point) { std::string str; auto d = double{0.0}; CHECK(printers::real(str, d)); CHECK_EQUAL(str, "0.0"); d = 1.0; str.clear(); CHECK(printers::real(str, d)); CHECK_EQUAL(str, "1.0"); d = 0.005; str.clear(); CHECK(printers::real(str, d)); CHECK_EQUAL(str, "0.005"); d = 123.456; str.clear(); CHECK(printers::real(str, d)); CHECK_EQUAL(str, "123.456"); d = -123.456; str.clear(); CHECK(printers::real(str, d)); CHECK_EQUAL(str, "-123.456"); d = 123456.1234567890123; str.clear(); CHECK(printers::real(str, d)); CHECK_EQUAL(str, "123456.123456789"); d = 123456.1234567890123; str.clear(); CHECK(real_printer<double, 6>{}(str, d)); CHECK_EQUAL(str, "123456.123457"); d = 123456.8888; str.clear(); CHECK(real_printer<double, 0>{}(str, d)); CHECK_EQUAL(str, "123457"); d = 123456.1234567890123; str.clear(); CHECK(real_printer<double, 1>{}(str, d)); CHECK_EQUAL(str, "123456.1"); d = 123456.00123; str.clear(); CHECK(real_printer<double, 6>{}(str, d)); CHECK_EQUAL(str, "123456.00123"); d = 123456.123; str.clear(); CHECK(real_printer<double, 6, 6>{}(str, d)); CHECK_EQUAL(str, "123456.123000"); } TEST(string) { std::string str; CHECK(printers::str(str, "foo")); CHECK_EQUAL(str, "foo"); str.clear(); CHECK(printers::str(str, "foo"s)); CHECK_EQUAL(str, "foo"); } TEST(escape) { std::string result; auto p = printers::escape(detail::hex_escaper); CHECK(p(result, "foo")); CHECK_EQUAL(result, R"__(\x66\x6F\x6F)__"); } TEST(literals) { std::string str; auto p = 42_P << " "_P << 3.14_P; CHECK(p(str, unused)); CHECK_EQUAL(str, "42 3.14"); } TEST(sequence tuple) { auto f = 'f'; auto oo = "oo"; auto bar = "bar"s; std::string str; auto p = printers::any << printers::str << printers::str; CHECK(p(str, std::tie(f, oo, bar))); CHECK_EQUAL(str, "foobar"); } TEST(sequence pair) { auto f = 'f'; auto oo = "oo"; std::string str; auto p = printers::any << printers::str; CHECK(p(str, std::make_pair(f, oo))); CHECK_EQUAL(str, "foo"); } TEST(choice) { using namespace printers; auto x = caf::variant<char, bool, int64_t>{true}; auto p = any | tf | i64; std::string str; CHECK(p(str, x)); CHECK_EQUAL(str, "T"); str.clear(); x = 'c'; CHECK(p(str, x)); CHECK_EQUAL(str, "c"); str.clear(); x = int64_t{64}; CHECK(p(str, x)); CHECK_EQUAL(str, "64"); } TEST(kleene) { auto xs = std::vector<char>{'f', 'o', 'o'}; std::string str; auto p = *printers::any; CHECK(p(str, xs)); CHECK_EQUAL(str, "foo"); xs.clear(); str.clear(); CHECK(p(str, xs)); // 0 elements are allowed. } TEST(plus) { auto xs = std::vector<char>{'b', 'a', 'r'}; std::string str; auto p = +printers::any; CHECK(p(str, xs)); CHECK_EQUAL(str, "bar"); xs.clear(); str.clear(); CHECK(!p(str, xs)); // 0 elements are *not* allowed! } TEST(list) { auto xs = std::vector<int>{1, 2, 4, 8}; auto p = printers::integral<int> % ' '; std::string str; CHECK(p(str, xs)); CHECK_EQUAL(str, "1 2 4 8"); xs.resize(1); str.clear(); CHECK(p(str, xs)); CHECK_EQUAL(str, "1"); xs.clear(); CHECK(!p(str, xs)); // need at least one element } TEST(optional) { caf::optional<int> x; auto p = -printers::integral<int>; std::string str; CHECK(p(str, x)); CHECK(str.empty()); // nothing to see here, move along x = 42; CHECK(p(str, x)); CHECK_EQUAL(str, "42"); } TEST(action) { auto flag = false; // no args, void result type auto p0 = printers::integral<int> ->* [&] { flag = true; }; std::string str; CHECK(p0(str, 42)); CHECK(flag); CHECK_EQUAL(str, "42"); // one arg, void result type auto p1 = printers::integral<int> ->* [&](int i) { flag = i % 2 == 0; }; str.clear(); CHECK(p1(str, 8)); CHECK_EQUAL(str, "8"); // no args, non-void result type auto p2 = printers::integral<int> ->* [] { return 42; }; str.clear(); CHECK(p2(str, 7)); CHECK_EQUAL(str, "42"); // one arg, non-void result type auto p3 = printers::integral<int> ->* [](int i) { return ++i; }; str.clear(); CHECK(p3(str, 41)); CHECK_EQUAL(str, "42"); } TEST(epsilon) { std::string str; CHECK(printers::eps(str, "whatever")); } TEST(guard) { std::string str; auto always_false = printers::eps.with([] { return false; }); CHECK(!always_false(str, 0)); auto even = printers::integral<int>.with([](int i) { return i % 2 == 0; }); CHECK(str.empty()); CHECK(!even(str, 41)); CHECK(str.empty()); CHECK(even(str, 42)); CHECK_EQUAL(str, "42"); } TEST(and) { std::string str; auto flag = true; auto p = &printers::eps.with([&] { return flag; }) << printers::str; CHECK(p(str, "yoda")); CHECK_EQUAL(str, "yoda"); flag = false; str.clear(); CHECK(!p(str, "chewie")); CHECK(str.empty()); } TEST(not) { std::string str; auto flag = true; auto p = !printers::eps.with([&] { return flag; }) << printers::str; CHECK(!p(str, "yoda")); CHECK(str.empty()); flag = false; CHECK(p(str, "chewie")); CHECK_EQUAL(str, "chewie"); } TEST(data) { data r{real{12.21}}; CHECK_TO_STRING(r, "12.21"); data b{true}; CHECK_TO_STRING(b, "T"); data c{count{23}}; CHECK_TO_STRING(c, "23"); data i{integer{42}}; CHECK_TO_STRING(i, "+42"); data s{std::string{"foobar"}}; CHECK_TO_STRING(s, "\"foobar\""); data d{duration{512}}; CHECK_TO_STRING(d, "512.0ns"); data v{vector{r, b, c, i, s, d}}; CHECK_TO_STRING(v, "[12.21, T, 23, +42, \"foobar\", 512.0ns]"); } TEST(duration) { using namespace std::chrono_literals; CHECK_TO_STRING(15ns, "15.0ns"); CHECK_TO_STRING(15'450ns, "15.45us"); CHECK_TO_STRING(42us, "42.0us"); CHECK_TO_STRING(42'123us, "42.12ms"); CHECK_TO_STRING(-7ms, "-7.0ms"); CHECK_TO_STRING(59s, "59.0s"); CHECK_TO_STRING(60s, "1.0m"); CHECK_TO_STRING(-90s, "-1.5m"); CHECK_TO_STRING(390s, "6.5m"); CHECK_TO_STRING(-2400h, "-100.0d"); } TEST(time) { using namespace std::chrono_literals; CHECK_TO_STRING(vast::time{0s}, "1970-01-01T00:00:00"); CHECK_TO_STRING(vast::time{1ms}, "1970-01-01T00:00:00.001"); CHECK_TO_STRING(vast::time{1us}, "1970-01-01T00:00:00.000001"); CHECK_TO_STRING(vast::time{1502658642123456us}, "2017-08-13T21:10:42.123456"); } TEST(stream) { using namespace std::chrono; std::ostringstream ss; auto x = nanoseconds(42); ss << x; CHECK_EQUAL(ss.str(), "42.0ns"); } TEST(to) { auto t = to<std::string>(true); REQUIRE(t); CHECK(*t == "T"); } TEST(to_string) { auto str = to_string(true); CHECK_EQUAL(str, "T"); }
<?php namespace backend\modules\products\controllers; use backend\controllers\CRUDController; use backend\models\Product; use backend\models\search\ProductSearch; use Yii; use yii\web\<API key>; use yii\web\Response; use yii\widgets\ActiveForm; /** * ProductsController implements the CRUD actions for Product model. */ class ProductsController extends CRUDController { /** * Init bean class */ public function init() { $this->beanClass = Product::className(); $this->beanSearchClass = ProductSearch::className(); $this-><API key> = false; parent::init(); } /** * Ajax validation of the Product * Return JSON Response * @param null $id * @return array * @throws <API key> */ public function actionValidate($id = null) { $model = new Product(); if (isset($id)) { $model = $this->findModel($id); } if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; $errors = ActiveForm::validate($model); return $errors; } } }
#ifndef <API key> #define <API key> #define <API key> 0 #define <API key> 0 #define <API key> 0 #define <API key> 0 #define BCM1250_M3_WAR 0 #define SIBYTE_1956_WAR 0 #define <API key> 0 #define MIPS_CACHE_SYNC_WAR 0 #define <API key> 0 #define <API key> 0 #define R10000_LLSC_WAR 0 #define <API key> 0 #endif /* <API key> */
package tournaments import ( "errors" "net/http" "appengine" "github.com/taironas/gonawin/extract" "github.com/taironas/gonawin/helpers" templateshlp "github.com/taironas/gonawin/helpers/templates" mdl "github.com/taironas/gonawin/models" ) // A GroupJSON is a variable to hold a the name of a group and an array of Teams. // We use it to group tournament teams information by group to meet world cup organization. type GroupJSON struct { Name string Teams []TeamJSON } // A TeamJSON is a variable to hold the basic information of a Team: // The name of the team, the number of points recorded in the group phase, the goals for and against. type TeamJSON struct { Name string Points int64 GoalsF int64 GoalsA int64 Iso string } // Groups handelr sends the JSON tournament groups data. // use this handler to get groups of a tournament. func Groups(w http.ResponseWriter, r *http.Request, u *mdl.User) error { if r.Method != "GET" { return &helpers.BadRequest{Err: errors.New(helpers.<API key>)} } c := appengine.NewContext(r) desc := "Tournament Group Handler:" extract := extract.NewContext(c, desc, r) var err error var tournament *mdl.Tournament if tournament, err = extract.Tournament(); err != nil { return err } groups := mdl.Groups(c, tournament.GroupIds) groupsJSON := formatGroupsJSON(groups) data := struct { Groups []GroupJSON }{ groupsJSON, } return templateshlp.RenderJSON(w, c, data) } // Format a TGroup array into a GroupJSON array. func formatGroupsJSON(groups []*mdl.Tgroup) []GroupJSON { groupsJSON := make([]GroupJSON, len(groups)) for i, g := range groups { groupsJSON[i].Name = g.Name teams := make([]TeamJSON, len(g.Teams)) for j, t := range g.Teams { teams[j].Name = t.Name teams[j].Points = g.Points[j] teams[j].GoalsF = g.GoalsF[j] teams[j].GoalsA = g.GoalsA[j] teams[j].Iso = t.Iso } groupsJSON[i].Teams = teams } return groupsJSON }
from cerberus import errors from cerberus.tests import assert_fail, assert_success def test_regex(validator): field = 'a_regex_email' assert_success({field: 'valid.email@gmail.com'}, validator=validator) assert_fail( {field: 'invalid'}, update=True, error=( field, (field, 'regex'), errors.REGEX_MISMATCH, r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', ), ) def <API key>(): assert_success({"item": "hOly grAil"}, {"item": {"regex": "(?i)holy grail"}}) assert_fail({"item": "hOly grAil"}, {"item": {"regex": "holy grail"}})
<!DOCTYPE html> <html lang="en"> <head> <title>UIImageView(CDAAsset) Category Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/objc/Extension/UIImageView(CDAAsset)" class="dashAnchor"></a> <a title="UIImageView(CDAAsset) Category Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html"><API key> Docs</a> (99% documented)</p> <p class="header-right"><a href="https://github.com/contentful/contentful.objc"><img src="../img/gh.png"/>View on GitHub</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html"><API key> Reference</a> <img id="carat" src="../img/carat.png" /> UIImageView(CDAAsset) Category Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Categories.html">Categories</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Categories/UIImageView(CDAAsset).html">UIImageView(CDAAsset)</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Classes/CDAArray.html">CDAArray</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAAsset.html">CDAAsset</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAClient.html">CDAClient</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAConfiguration.html">CDAConfiguration</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAContentType.html">CDAContentType</a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/CDAEntry.html">CDAEntry</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAError.html">CDAError</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAField.html">CDAField</a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/CDARequest.html">CDARequest</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAResource.html">CDAResource</a> </li> <li class="nav-group-task"> <a href="../Classes/CDAResourceCell.html">CDAResourceCell</a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes.html#/c:objc(cs)CDAResponse">CDAResponse</a> </li> <li class="nav-group-task"> <a href="../Classes/CDASpace.html">CDASpace</a> </li> <li class="nav-group-task"> <a href="../Classes/CDASyncedSpace.html">CDASyncedSpace</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Constants.html">Constants</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Constants.html#/c:@CDAErrorDomain">CDAErrorDomain</a> </li> <li class="nav-group-task"> <a href="../Constants.html#/c:@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Constants.html#/c:@CDARadiusMaximum">CDARadiusMaximum</a> </li> <li class="nav-group-task"> <a href="../Constants.html#/c:@CDARadiusNone">CDARadiusNone</a> </li> <li class="nav-group-task"> <a href="../Constants.html#/c:@CDA_DEFAULT_SERVER">CDA_DEFAULT_SERVER</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Enums.html">Enums</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Enums/CDAFieldType.html">CDAFieldType</a> </li> <li class="nav-group-task"> <a href="../Enums/CDAFitType.html">CDAFitType</a> </li> <li class="nav-group-task"> <a href="../Enums/CDAImageFormat.html">CDAImageFormat</a> </li> <li class="nav-group-task"> <a href="../Enums/CDAResourceType.html">CDAResourceType</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/CDAPersistedAsset.html">CDAPersistedAsset</a> </li> <li class="nav-group-task"> <a href="../Protocols/CDAPersistedEntry.html">CDAPersistedEntry</a> </li> <li class="nav-group-task"> <a href="../Protocols/CDAPersistedSpace.html">CDAPersistedSpace</a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Type Definitions.html">Type Definitions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> <li class="nav-group-task"> <a href="../Type Definitions.html#/c:CDAClient.h@T@<API key>"><API key></a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>UIImageView(CDAAsset)</h1> <div class="declaration"> <div class="language"> <pre class="highlight"><code><span class="k">@interface</span> <span class="nc">UIImageView</span> <span class="p">(</span><span class="nl">CDAAsset</span><span class="p">)</span></code></pre> </div> </div> <p>Convenience category on <code>UIImageView</code> which allows asynchronously setting its image from a given Asset. </p> <p>Attempting non-sensical operations like using an Asset pointing to a video will throw exceptions.</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/c:objc(cs)UIImageView(im)<API key>:"></a> <a name="//apple_ref/objc/Method/-<API key>:" class="dashAnchor"></a> <a class="token" href="#/c:objc(cs)UIImageView(im)<API key>:">-<API key>:</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Set this image view&rsquo;s image to the image file retrieved from the given Asset. </p> <p>This will happen asynchronously in the background.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Objective-C</p> <pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf"><API key></span><span class="p">:(</span><span class="n"><a href="../Classes/CDAAsset.html">CDAAsset</a></span> <span class="o">*</span><span class="n">_Nonnull</span><span class="p">)</span><span class="nv">asset</span><span class="p">;</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>asset</em> </code> </td> <td> <div> <p>An Asset pointing to an image. @exception <API key> If the Asset is pointing to an image.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/contentful/contentful.objc/tree/2.0.1/<API key>/UIKit/UIImageView+CDAAsset.h#L35">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:objc(cs)UIImageView(im)<API key>:size:"></a> <a name="//apple_ref/objc/Method/-<API key>:size:" class="dashAnchor"></a> <a class="token" href="#/c:objc(cs)UIImageView(im)<API key>:size:">-<API key>:size:</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Set this image view&rsquo;s image to the image file retrieved from the given Asset.</p> <p>This will happen asynchronously in the background.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Objective-C</p> <pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf"><API key></span><span class="p">:(</span><span class="n"><a href="../Classes/CDAAsset.html">CDAAsset</a></span> <span class="o">*</span><span class="n">_Nonnull</span><span class="p">)</span><span class="nv">asset</span> <span class="nf">size</span><span class="p">:(</span><span class="n">CGSize</span><span class="p">)</span><span class="nv">size</span><span class="p">;</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>asset</em> </code> </td> <td> <div> <p>An Asset pointing to an image.</p> </div> </td> </tr> <tr> <td> <code> <em>size</em> </code> </td> <td> <div> <p>The desired size of the image. It will be resized by the server. @exception <API key> If the Asset is pointing to an image.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/contentful/contentful.objc/tree/2.0.1/<API key>/UIKit/UIImageView+CDAAsset.h#L46">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:objc(cs)UIImageView(im)<API key>:placeholderImage:"></a> <a name="//apple_ref/objc/Method/-<API key>:placeholderImage:" class="dashAnchor"></a> <a class="token" href="#/c:objc(cs)UIImageView(im)<API key>:placeholderImage:">-<API key>:placeholderImage:</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Set this image view&rsquo;s image to the image file retrieved from the given Asset. </p> <p>This will happen asynchronously in the background. Until the image is loaded, the <code>placeholderImage</code> is displayed.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Objective-C</p> <pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf"><API key></span><span class="p">:(</span><span class="n"><a href="../Classes/CDAAsset.html">CDAAsset</a></span> <span class="o">*</span><span class="n">_Nonnull</span><span class="p">)</span><span class="nv">asset</span> <span class="nf">placeholderImage</span><span class="p">:(</span><span class="n">UIImage</span> <span class="o">*</span><span class="n">_Nullable</span><span class="p">)</span><span class="nv">placeholderImage</span><span class="p">;</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>asset</em> </code> </td> <td> <div> <p>An Asset pointing to an image.</p> </div> </td> </tr> <tr> <td> <code> <em>placeholderImage</em> </code> </td> <td> <div> <p>An alternative image which will be displayed until <code>asset</code> is loaded. @exception <API key> If the Asset is pointing to an image.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/contentful/contentful.objc/tree/2.0.1/<API key>/UIKit/UIImageView+CDAAsset.h#L58-L59">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:objc(cs)UIImageView(im)<API key>:size:placeholderImage:"></a> <a name="//apple_ref/objc/Method/-<API key>:size:placeholderImage:" class="dashAnchor"></a> <a class="token" href="#/c:objc(cs)UIImageView(im)<API key>:size:placeholderImage:">-<API key>:size:placeholderImage:</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Set this image view&rsquo;s image to the image file retrieved from the given Asset.</p> <p>This will happen asynchronously in the background. Until the image is loaded, the <code>placeholderImage</code> is displayed.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Objective-C</p> <pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf"><API key></span><span class="p">:(</span><span class="n"><a href="../Classes/CDAAsset.html">CDAAsset</a></span> <span class="o">*</span><span class="n">_Nonnull</span><span class="p">)</span><span class="nv">asset</span> <span class="nf">size</span><span class="p">:(</span><span class="n">CGSize</span><span class="p">)</span><span class="nv">size</span> <span class="nf">placeholderImage</span><span class="p">:(</span><span class="n">UIImage</span> <span class="o">*</span><span class="n">_Nullable</span><span class="p">)</span><span class="nv">placeholderImage</span><span class="p">;</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>asset</em> </code> </td> <td> <div> <p>An Asset pointing to an image.</p> </div> </td> </tr> <tr> <td> <code> <em>size</em> </code> </td> <td> <div> <p>The desired size of the image. It will be resized by the server.</p> </div> </td> </tr> <tr> <td> <code> <em>placeholderImage</em> </code> </td> <td> <div> <p>An alternative image which will be displayed until <code>asset</code> is loaded. @exception <API key> If the Asset is pointing to an image.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/contentful/contentful.objc/tree/2.0.1/<API key>/UIKit/UIImageView+CDAAsset.h#L72-L74">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:objc(cs)UIImageView(im)<API key>:client:size:placeholderImage:"></a> <a name="//apple_ref/objc/Method/-<API key>:client:size:placeholderImage:" class="dashAnchor"></a> <a class="token" href="#/c:objc(cs)UIImageView(im)<API key>:client:size:placeholderImage:">-<API key>:client:size:placeholderImage:</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Set this image view&rsquo;s image to the image file retrieved from the given Asset.</p> <p>This will happen asynchronously in the background. Until the image is loaded, the <code>placeholderImage</code> is displayed.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Objective-C</p> <pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf"><API key></span><span class="p">:(</span><span class="n">id</span><span class="o">&lt;</span><span class="n"><a href="../Protocols/CDAPersistedAsset.html">CDAPersistedAsset</a></span><span class="o">&gt;</span> <span class="n">_Nonnull</span><span class="p">)</span><span class="nv">asset</span> <span class="nf">client</span><span class="p">:(</span><span class="n"><a href="../Classes/CDAClient.html">CDAClient</a></span> <span class="o">*</span><span class="n">_Nonnull</span><span class="p">)</span><span class="nv">client</span> <span class="nf">size</span><span class="p">:(</span><span class="n">CGSize</span><span class="p">)</span><span class="nv">size</span> <span class="nf">placeholderImage</span><span class="p">:(</span><span class="n">UIImage</span> <span class="o">*</span><span class="n">_Nullable</span><span class="p">)</span><span class="nv">placeholderImage</span><span class="p">;</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>asset</em> </code> </td> <td> <div> <p>An Asset pointing to an image.</p> </div> </td> </tr> <tr> <td> <code> <em>client</em> </code> </td> <td> <div> <p>The client object to use for requests to Contentful.</p> </div> </td> </tr> <tr> <td> <code> <em>size</em> </code> </td> <td> <div> <p>The desired size of the image. It will be resized by the server.</p> </div> </td> </tr> <tr> <td> <code> <em>placeholderImage</em> </code> </td> <td> <div> <p>An alternative image which will be displayed until <code>asset</code> is loaded. @exception <API key> If the Asset is pointing to an image.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/contentful/contentful.objc/tree/2.0.1/<API key>/UIKit/UIImageView+CDAAsset.h#L88-L91">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> <div class="task-group"> <div class="task-name-container"> <a name="/Use%20Offline%20Caching%20*/"></a> <a name="//apple_ref/objc/Section/Use Offline Caching */" class="dashAnchor"></a> <a href="#/Use%20Offline%20Caching%20*/"> <h3 class="section-name">Use Offline Caching */</h3> </a> </div> <ul> <li class="item"> <div> <code> <a name="/c:objc(cs)UIImageView(py)offlineCaching_cda"></a> <a name="//apple_ref/objc/Property/offlineCaching_cda" class="dashAnchor"></a> <a class="token" href="#/c:objc(cs)UIImageView(py)offlineCaching_cda">offlineCaching_cda</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Enable automatic disk caching of any image loaded by one of the Asset category methods.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Objective-C</p> <pre class="highlight"><code><span class="k">@property</span> <span class="p">(</span><span class="n">assign</span><span class="p">,</span> <span class="n">readwrite</span><span class="p">,</span> <span class="n">nonatomic</span><span class="p">)</span> <span class="n">BOOL</span> <span class="n">offlineCaching_cda</span><span class="p">;</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/contentful/contentful.objc/tree/2.0.1/<API key>/UIKit/UIImageView+CDAAsset.h#L96">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2017 <a class="link" href="https: <p>Generated by <a class="link" href="https: </section> </article> </div> </body> </div> </html>
public class MicroKanren { static class Cons<A,D> { protected final A a; protected final D d; public Cons(A a, D d) { this.a = a; this.d = d; } public A car() {return a;} public D cdr() {return d;} static <A,D> Cons<A,D> cons(A a, D d) { return new Cons<A,D>(a, d); } public String toString() { return "(" + a + " . " + d + ")"; } } static class Var { private final int c; public Var(int c) { this.c = c; } public boolean equals(Object o) { return (o instanceof Var) && this.c == ((Var) o).c; } public String toString() {return "v" + c;} } static boolean isVar(Object o) { return o instanceof Var; } static class Assoc extends Cons<Var, Object> { public Assoc(Var var, Object o) { super(var, o); } } static class Subst extends Cons<Assoc, Subst> { public Subst(Assoc assoc, Subst subst) { super(assoc, subst); } public Assoc assq(Object o) { if (a == null) return null; if (a.car().equals(o)) return a; return d != null ? d.assq(o) : null; } } static Subst ext(Subst s, Var x, Object v) { return new Subst(new Assoc(x, v), s); } static Object walk(Object u, Subst s) { if (s == null || !isVar(u)) return u; Assoc pr = s.assq(u); if (pr == null) return u; return walk(pr.cdr(), s); } //Extends s in such a way that u made equals with v, returns the resulted substitution //Returns null if there is no way to unify u and v static Subst unify(Object u, Object v, Subst s) { u = walk(u, s); v = walk(v, s); if (isVar(u) && isVar(v) && u.equals(v)) return s; if (isVar(u)) return ext(s, (Var) u, v); if (isVar(v)) return ext(s, (Var) v, u); if (u instanceof Cons && v instanceof Cons) { s = unify(((Cons)u).car(), ((Cons)v).car(), s); if (s == null) return null; return unify(((Cons)u).cdr(), ((Cons)v).cdr(), s); } if (u.equals(v)) return s; return null; } static class State { final Subst s; final int c; public State(Subst s, int c) { this.s = s; this.c = c; } public String toString() {return "{" + (s == null ? "()" : s) +", " + c + "}";} } interface Stream {} static abstract class ImmatureStream implements Stream { abstract Stream realize(); public String toString() {return "immature";} } static class MatureStream extends Cons<State, Stream> implements Stream { public MatureStream(State a, Stream d) {super(a, d);} } interface Goal { Stream run(State s); } interface GoalFn { Goal call(Var v); } static Goal same(final Object u, final Object v) { return new Goal() { public Stream run(State state) { Subst s = unify(u, v, state.s); if (s == null) return null; return unit(new State(s, state.c)); } }; } static Goal callFresh(final GoalFn f) { return new Goal() { public Stream run(State s) { return f.call(new Var(s.c)).run(new State(s.s, s.c + 1)); } }; } static Stream unit(State s) { return new MatureStream(s, null); } static Goal disj(final Goal g1, final Goal g2) { return new Goal() { public Stream run(State s) { return mplus(g1.run(s), g2.run(s)); } }; } static Goal conj(final Goal g1, final Goal g2) { return new Goal() { public Stream run(State s) { return bind(g1.run(s), g2); } }; } static Stream mplus(final Stream s1, final Stream s2) { if (s1 == null) return s2; if (s1 instanceof ImmatureStream) { return new ImmatureStream() { Stream realize() { return mplus(s2, ((ImmatureStream) s1).realize()); } }; } MatureStream ms = (MatureStream) s1; return new MatureStream(ms.car(), mplus(ms.cdr(), s2)); } static Stream bind(final Stream s, final Goal g) { if (s == null) return s; if (s instanceof ImmatureStream) { return new ImmatureStream() { Stream realize() { return bind(((ImmatureStream) s).realize(), g); } }; } MatureStream ms = (MatureStream) s; return mplus(g.run(ms.car()), bind(ms.cdr(), g)); } static class DelayedGoal implements Goal { private final GoalFn f; private final Var v; public DelayedGoal(GoalFn f, Var v) { this.f = f; this.v = v; } public Stream run(final State s) { return new ImmatureStream() { Stream realize() { return f.call(v).run(s); } }; } } static Goal delayedCall(GoalFn f, Var v) { return new DelayedGoal(f, v); } static void print(Stream s) { print(s, Integer.MAX_VALUE); } static void print(Stream s, int n) { while (n > 0) { if (s == null) { System.out.println("()"); return; } if (s instanceof ImmatureStream) { s = ((ImmatureStream) s).realize(); continue; } MatureStream ms = (MatureStream) s; System.out.println(ms.car()); n s = ms.cdr(); } } static State emptyState() { return new State(null, 0); } public static void main(String... args) { final GoalFn fives = new GoalFn() { public Goal call(final Var v) { return disj(same(v, 5), delayedCall(this, v)); } }; final GoalFn sixes = new GoalFn() { public Goal call(final Var v) { Goal eq6 = same(v, 6); return disj(same(v, 6), delayedCall(this, v)); } }; Goal fivesAndSixes = callFresh(new GoalFn() { public Goal call(Var v) { return disj(fives.call(v), sixes.call(v)); } }); Stream s = fivesAndSixes.run(emptyState()); print(s, 10); } }
# of this software and associated documentation files (the ""Software""), to # deal in the Software without restriction, including without limitation the # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # all copies or substantial portions of the Software. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # 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. import unittest import subprocess import sys import isodate import tempfile import json from datetime import date, datetime, timedelta, tzinfo import os from os.path import dirname, pardir, join, realpath, sep, pardir cwd = dirname(realpath(__file__)) root = realpath(join(cwd , pardir, pardir, pardir, pardir, pardir)) sys.path.append(join(root, "ClientRuntimes" , "Python", "msrest")) log_level = int(os.environ.get('PythonLogLevel', 30)) tests = realpath(join(cwd, pardir, "Expected", "AcceptanceTests")) sys.path.append(join(tests, "BodyComplex")) from msrest.serialization import Deserializer from msrest.exceptions import <API key>, SerializationError, ValidationError from <API key> import ( <API key>, <API key>) from <API key>.models import * class UTC(tzinfo): def utcoffset(self,dt): return timedelta(hours=0,minutes=0) def tzname(self,dt): return "Z" def dst(self,dt): return timedelta(0) class ComplexTests(unittest.TestCase): def test_complex(self): config = <API key>(base_url="http://localhost:3000",api_version="2015-01-01") config.log_level = log_level client = <API key>(config) # GET basic/valid basic_result = client.basic_operations.get_valid() self.assertEqual(2, basic_result.id) self.assertEqual("abc", basic_result.name); self.assertEqual(CMYKColors.yellow, basic_result.color); # PUT basic/valid basic_result = Basic(id=2, name='abc', color=CMYKColors.magenta) client.basic_operations.put_valid(basic_result) # GET basic/empty basic_result = client.basic_operations.get_empty() self.assertIsNone(basic_result.id) self.assertIsNone(basic_result.name) # GET basic/null basic_result = client.basic_operations.get_null() self.assertIsNone(basic_result.id) self.assertIsNone(basic_result.name) # GET basic/notprovided basic_result = client.basic_operations.get_not_provided() self.assertIsNone(basic_result) # GET basic/invalid with self.assertRaises(<API key>): client.basic_operations.get_invalid() """ COMPLEX TYPE WITH PRIMITIVE PROPERTIES """ # GET primitive/integer intResult = client.primitive.get_int(); self.assertEqual(-1, intResult.field1) self.assertEqual(2, intResult.field2) # PUT primitive/integer intRequest = IntWrapper(field1=-1, field2=2) client.primitive.put_int(intRequest) # GET primitive/long longResult = client.primitive.get_long(); self.assertEqual(1099511627775, longResult.field1) self.assertEqual(-999511627788, longResult.field2) # PUT primitive/long longRequest = LongWrapper(field1=1099511627775, field2=-999511627788) client.primitive.put_long(longRequest) # GET primitive/float floatResult = client.primitive.get_float() self.assertEqual(1.05, floatResult.field1) self.assertEqual(-0.003, floatResult.field2) # PUT primitive/float floatRequest = FloatWrapper(field1=1.05, field2=-0.003) client.primitive.put_float(floatRequest) # GET primitive/double doubleResult = client.primitive.get_double() self.assertEqual(3e-100, doubleResult.field1) self.assertEqual(-5e-57, doubleResult.field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose) # PUT primitive/double doubleRequest = DoubleWrapper(field1=3e-100) doubleRequest.field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose = -5e-57 client.primitive.put_double(doubleRequest); # GET primitive/bool boolResult = client.primitive.get_bool() self.assertTrue(boolResult.field_true) self.assertFalse(boolResult.field_false) # PUT primitive/bool boolRequest = BooleanWrapper(field_true=True, field_false=False) client.primitive.put_bool(boolRequest); # GET primitive/string stringResult = client.primitive.get_string(); self.assertEqual("goodrequest", stringResult.field) self.assertEqual("", stringResult.empty) self.assertIsNone(stringResult.null) # PUT primitive/string stringRequest = StringWrapper(null=None, empty="", field="goodrequest") client.primitive.put_string(stringRequest); # GET primitive/date dateResult = client.primitive.get_date() self.assertEqual(isodate.parse_date("0001-01-01"), dateResult.field) self.assertEqual(isodate.parse_date("2016-02-29"), dateResult.leap) dateRequest = DateWrapper( field=isodate.parse_date('0001-01-01'), leap=isodate.parse_date('2016-02-29')) client.primitive.put_date(dateRequest) # GET primitive/datetime datetimeResult = client.primitive.get_date_time() min_date = datetime.min min_date = min_date.replace(tzinfo=UTC()) self.assertEqual(min_date, datetimeResult.field) datetime_request = DatetimeWrapper( field=isodate.parse_datetime("0001-01-01T00:00:00Z"), now=isodate.parse_datetime("2015-05-18T18:38:00Z")) client.primitive.put_date_time(datetime_request) # GET primitive/datetimerfc1123 <API key> = client.primitive.<API key>() self.assertEqual(min_date, <API key>.field) datetime_request = <API key>( field=isodate.parse_datetime("0001-01-01T00:00:00Z"), now=isodate.parse_datetime("2015-05-18T11:38:00Z")) client.primitive.<API key>(datetime_request) # GET primitive/duration expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) self.assertEqual(expected, client.primitive.get_duration().field) client.primitive.put_duration(expected) # GET primitive/byte byteResult = client.primitive.get_byte() valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) self.assertEqual(valid_bytes, byteResult.field) # PUT primitive/byte client.primitive.put_byte(valid_bytes) """ COMPLEX TYPE WITH ARRAY PROPERTIES """ # GET array/valid array_result = client.array.get_valid() self.assertEqual(5, len(array_result.array)) array_value = ["1, 2, 3, 4", "", None, "&S "The quick brown fox jumps over the lazy dog"] self.assertEqual(array_result.array, array_value) # PUT array/valid client.array.put_valid(array_value) # GET array/empty array_result = client.array.get_empty() self.assertEqual(0, len(array_result.array)) # PUT array/empty client.array.put_empty([]) # Get array/notprovided self.assertIsNone(client.array.get_not_provided().array) """ COMPLEX TYPE WITH DICTIONARY PROPERTIES """ # GET dictionary/valid dict_result = client.dictionary.get_valid() self.assertEqual(5, len(dict_result.default_program)) dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} self.assertEqual(dict_val, dict_result.default_program) # PUT dictionary/valid client.dictionary.put_valid(dict_val) # GET dictionary/empty dict_result = client.dictionary.get_empty() self.assertEqual(0, len(dict_result.default_program)) # PUT dictionary/empty client.dictionary.put_empty(default_program={}) # GET dictionary/null self.assertIsNone(client.dictionary.get_null().default_program) # GET dictionary/notprovided self.assertIsNone(client.dictionary.get_not_provided().default_program) """ COMPLEX TYPES THAT INVOLVE INHERITANCE """ # GET inheritance/valid inheritanceResult = client.inheritance.get_valid() self.assertEqual(2, inheritanceResult.id) self.assertEqual("Siameeee", inheritanceResult.name) self.assertEqual(-1, inheritanceResult.hates[1].id) self.assertEqual("Tomato", inheritanceResult.hates[1].name) # PUT inheritance/valid request = Siamese( id=2, name="Siameeee", color="green", breed="persian", hates=[Dog(id=1, name="Potato", food="tomato"), Dog(id=-1, name="Tomato", food="french fries")] ) client.inheritance.put_valid(request) """ COMPLEX TYPES THAT INVOLVE POLYMORPHISM """ # GET polymorphism/valid result = client.polymorphism.get_valid() self.assertIsNotNone(result) self.assertEqual(result.location, "alaska") self.assertEqual(len(result.siblings), 3) self.assertIsInstance(result.siblings[0], Shark) self.assertIsInstance(result.siblings[1], Sawshark) self.assertIsInstance(result.siblings[2], Goblinshark) self.assertEqual(result.siblings[0].age, 6) self.assertEqual(result.siblings[1].age, 105) self.assertEqual(result.siblings[2].age, 1) # PUT polymorphism/valid request = Salmon(1, iswild = True, location = "alaska", species = "king", siblings = [Shark(20, isodate.parse_datetime("2012-01-05T01:00:00Z"), age=6, species="predator"), Sawshark(10, isodate.parse_datetime("1900-01-05T01:00:00Z"), age=105, species="dangerous", picture=bytearray([255, 255, 255, 255, 254])), Goblinshark(30, isodate.parse_datetime("2015-08-08T00:00:00Z"), age=1, species="scary", jawsize=5)] ) client.polymorphism.put_valid(request) bad_request = Salmon(1, iswild=True, location="alaska", species="king", siblings = [ Shark(20, isodate.parse_datetime("2012-01-05T01:00:00Z"), age=6, species="predator"), Sawshark(10, None, age=105, species="dangerous", picture=bytearray([255, 255, 255, 255, 254]))] ) with self.assertRaises(ValidationError): client.polymorphism.<API key>(bad_request) """ COMPLEX TYPES THAT INVOLVE RECURSIVE REFERENCE """ # GET <API key>/valid result = client.<API key>.get_valid() self.assertIsInstance(result, Salmon) self.assertIsInstance(result.siblings[0], Shark) self.assertIsInstance(result.siblings[0].siblings[0], Salmon) self.assertEqual(result.siblings[0].siblings[0].location, "atlantic") request = Salmon( iswild=True, length=1, species="king", location="alaska", siblings=[ Shark( age=6, length=20, species="predator", siblings=[ Salmon( iswild=True, length=2, location="atlantic", species="coho", siblings=[ Shark( age=6, length=20, species="predator", birthday=isodate.parse_datetime("2012-01-05T01:00:00Z")), Sawshark( age=105, length=10, species="dangerous", birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), picture=bytearray([255, 255, 255, 255, 254]))]), Sawshark( age=105, length=10, species="dangerous", siblings=[], birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), picture=bytearray([255, 255, 255, 255, 254]))], birthday=isodate.parse_datetime("2012-01-05T01:00:00Z")), Sawshark( age=105, length=10, species="dangerous", siblings=[], birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), picture=bytearray([255, 255, 255, 255, 254]))]) # PUT <API key>/valid client.<API key>.put_valid(request) if __name__ == '__main__': unittest.main()
<?php declare(strict_types=1); namespace Sylius\Component\Core\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\<API key>; use Sylius\Component\Order\Repository\<API key> as <API key>; interface <API key> extends <API key> { public function <API key>(): QueryBuilder; public function <API key>($customerId): QueryBuilder; public function <API key>($customerId, $channelId): QueryBuilder; public function <API key>(CustomerInterface $customer, <API key> $coupon): int; public function countByCustomer(CustomerInterface $customer): int; /** * @return array|OrderInterface[] */ public function findByCustomer(CustomerInterface $customer): array; /** * @return array|OrderInterface[] */ public function <API key>(CustomerInterface $customer): array; public function findOneForPayment($id): ?OrderInterface; public function <API key>(string $number, CustomerInterface $customer): ?OrderInterface; public function findCartByChannel($id, ChannelInterface $channel): ?OrderInterface; public function <API key>(ChannelInterface $channel, CustomerInterface $customer): ?OrderInterface; public function <API key>(ChannelInterface $channel): int; public function <API key>(ChannelInterface $channel): int; public function <API key>(ChannelInterface $channel, \DateTimeInterface $startDate, \DateTimeInterface $endDate): int; public function <API key>(ChannelInterface $channel): int; public function countPaidByChannel(ChannelInterface $channel): int; public function <API key>(ChannelInterface $channel, \DateTimeInterface $startDate, \DateTimeInterface $endDate): int; /** * @return array|OrderInterface[] */ public function findLatestInChannel(int $count, ChannelInterface $channel): array; /** * @return array|OrderInterface[] */ public function <API key>(\DateTimeInterface $terminalDate): array; public function findCartForSummary($id): ?OrderInterface; public function <API key>($id): ?OrderInterface; public function <API key>($id): ?OrderInterface; public function <API key>($id): ?OrderInterface; }
export {}; // Verify we don't produce a type mentioning 'anonymous class' // for variables that involve anonymous classes. Instead we just // produce {?}. const anonClassInstance = new class { foo: string; }; // Verify the same thing in a namespace. // We don't rely on namespaces really but the logic around generating type // names has some logic near namespaces so we might as well verify the output // looks ok. namespace ns { export const anonInstance2 = new class { foo: string; }; export const anonClass = class { foo: string; }; } const aliasToAnon = ns.anonInstance2; const anonClassNs = new ns.anonClass();
<?php namespace Oro\Bundle\ApiBundle\Processor\GetConfig; use Oro\Component\ChainProcessor\ActionProcessor; /** * The main processor for "get_config" action. */ class ConfigProcessor extends ActionProcessor { /** * {@inheritdoc} */ protected function createContextObject() { return new ConfigContext(); } }
from enum import Enum __author__ = 'dirkfuchs' class Format(Enum): oneLine = 0 oracle = 1
// This file is part of the "Irrlicht Engine". #include "IrrCompileConfig.h" #ifdef <API key> #include "CSMFMeshFileLoader.h" #include "CMeshTextureLoader.h" #include "SAnimatedMesh.h" #include "SMeshBuffer.h" #include "IReadFile.h" #include "coreutil.h" #include "os.h" #include "IVideoDriver.h" namespace irr { namespace scene { CSMFMeshFileLoader::CSMFMeshFileLoader(irr::io::IFileSystem* fs, video::IVideoDriver* driver) { TextureLoader = new CMeshTextureLoader( fs, driver ); } //! Returns true if the file might be loaded by this class. bool CSMFMeshFileLoader::<API key>(const io::path& filename) const { return core::hasFileExtension(filename, "smf"); } //! Creates/loads an animated mesh from the file. IAnimatedMesh* CSMFMeshFileLoader::createMesh(io::IReadFile* file) { if ( !file ) return 0; if ( <API key>() ) <API key>()->setMeshFile(file); // create empty mesh SMesh *mesh = new SMesh(); // load file u16 version; u8 flags; s32 limbCount; s32 i; io::BinaryFile::read(file, version); io::BinaryFile::read(file, flags); io::BinaryFile::read(file, limbCount); // load mesh data core::matrix4 identity; for (i=0; i < limbCount; ++i) loadLimb(file, mesh, identity); // recalculate buffer bounding boxes for (i=0; i < (s32)mesh->getMeshBufferCount(); ++i) mesh->getMeshBuffer(i)-><API key>(); mesh-><API key>(); SAnimatedMesh *am = new SAnimatedMesh(); am->addMesh(mesh); mesh->drop(); am-><API key>(); return am; } void CSMFMeshFileLoader::loadLimb(io::IReadFile* file, SMesh* mesh, const core::matrix4 &<API key>) { core::matrix4 transformation; // limb transformation core::vector3df translate, rotate, scale; io::BinaryFile::read(file, translate); io::BinaryFile::read(file, rotate); io::BinaryFile::read(file, scale); transformation.setTranslation(translate); transformation.setRotationDegrees(rotate); transformation.setScale(scale); transformation = <API key> * transformation; core::stringc textureName, textureGroupName; // texture information io::BinaryFile::read(file, textureGroupName); io::BinaryFile::read(file, textureName); // attempt to load texture using known formats video::ITexture* texture = 0; const c8* extensions[] = {".jpg", ".png", ".tga", ".bmp", 0}; for (const c8 **ext = extensions; !texture && *ext; ++ext) { texture = <API key>() ? <API key>()->getTexture(textureName + *ext) : NULL; if (texture) { textureName = textureName + *ext; break; } } // find the correct mesh buffer u32 i; for (i=0; i<mesh->MeshBuffers.size(); ++i) if (mesh->MeshBuffers[i]->getMaterial().TextureLayer[0].Texture == texture) break; // create mesh buffer if none was found if (i == mesh->MeshBuffers.size()) { CMeshBuffer<video::S3DVertex>* mb = new CMeshBuffer<video::S3DVertex>(); mb->Material.TextureLayer[0].Texture = texture; // horribly hacky way to do this, maybe it's in the flags? if (core::hasFileExtension(textureName, "tga", "png")) mb->Material.MaterialType = video::<API key>; else mb->Material.MaterialType = video::EMT_SOLID; mesh->MeshBuffers.push_back(mb); } CMeshBuffer<video::S3DVertex>* mb = (CMeshBuffer<video::S3DVertex>*)mesh->MeshBuffers[i]; u16 vertexCount, firstVertex = mb->getVertexCount(); io::BinaryFile::read(file, vertexCount); mb->Vertices.reallocate(mb->Vertices.size() + vertexCount); // add vertices and set positions for (i=0; i<vertexCount; ++i) { core::vector3df pos; io::BinaryFile::read(file, pos); transformation.transformVect(pos); video::S3DVertex vert; vert.Color = 0xFFFFFFFF; vert.Pos = pos; mb->Vertices.push_back(vert); } // set vertex normals for (i=0; i < vertexCount; ++i) { core::vector3df normal; io::BinaryFile::read(file, normal); transformation.rotateVect(normal); mb->Vertices[firstVertex + i].Normal = normal; } // set texture coordinates for (i=0; i < vertexCount; ++i) { core::vector2df tcoords; io::BinaryFile::read(file, tcoords); mb->Vertices[firstVertex + i].TCoords = tcoords; } // triangles u32 triangleCount; // vertexCount used as temporary io::BinaryFile::read(file, vertexCount); triangleCount=3*vertexCount; mb->Indices.reallocate(mb->Indices.size() + triangleCount); for (i=0; i < triangleCount; ++i) { u16 index; io::BinaryFile::read(file, index); mb->Indices.push_back(firstVertex + index); } // read limbs s32 limbCount; io::BinaryFile::read(file, limbCount); for (s32 l=0; l < limbCount; ++l) loadLimb(file, mesh, transformation); } } // namespace scene // todo: at some point in the future let's move these to a place where everyone can use them. namespace io { #if _BIGENDIAN #define _SYSTEM_BIG_ENDIAN_ (true) #else #define _SYSTEM_BIG_ENDIAN_ (false) #endif template <class T> void BinaryFile::read(io::IReadFile* file, T &out, bool bigEndian) { file->read((void*)&out, sizeof(out)); if (bigEndian != (_SYSTEM_BIG_ENDIAN_)) out = os::Byteswap::byteswap(out); } //! reads a 3d vector from the file, moving the file pointer along void BinaryFile::read(io::IReadFile* file, core::vector3df &outVector2d, bool bigEndian) { BinaryFile::read(file, outVector2d.X, bigEndian); BinaryFile::read(file, outVector2d.Y, bigEndian); BinaryFile::read(file, outVector2d.Z, bigEndian); } //! reads a 2d vector from the file, moving the file pointer along void BinaryFile::read(io::IReadFile* file, core::vector2df &outVector2d, bool bigEndian) { BinaryFile::read(file, outVector2d.X, bigEndian); BinaryFile::read(file, outVector2d.Y, bigEndian); } //! reads a null terminated string from the file, moving the file pointer along void BinaryFile::read(io::IReadFile* file, core::stringc &outString, bool bigEndian) { c8 c; file->read((void*)&c, 1); while (c) { outString += c; file->read((void*)&c, 1); } } } // namespace io } // namespace irr #endif // compile with SMF loader
// WriteBatch holds a collection of updates to apply atomically to a DB. // The updates are applied in the order in which they are added // to the WriteBatch. For example, the value of "key" will be "v3" // after the following batch is written: // batch.Put("key", "v1"); // batch.Delete("key"); // batch.Put("key", "v2"); // batch.Put("key", "v3"); // Multiple threads can invoke const methods on a WriteBatch without // external synchronization, but if any of the threads may call a // non-const method, all threads accessing the same WriteBatch must use // external synchronization. #ifndef <API key> #define <API key> #include <string> #include "leveldb/status.h" namespace leveldb { class Slice; class WriteBatch { public: WriteBatch(); ~WriteBatch(); // Store the mapping "key->value" in the database. void Put(const Slice& key, const Slice& value); // If the database contains a mapping for "key", erase it. Else do nothing. void Delete(const Slice& key); // Clear all updates buffered in this batch. void Clear(); // Support for iterating over the contents of a batch. class Handler { public: virtual ~Handler(); virtual void Put(const Slice& key, const Slice& value) = 0; virtual void Delete(const Slice& key) = 0; }; Status Iterate(Handler* handler) const; private: friend class WriteBatchInternal; std::string rep_; // See comment in write_batch.cc for the format of rep_ // Intentionally copyable }; } // namespace leveldb #endif // <API key>
<?php return unserialize('a:1:{i:0;O:30:"Doctrine\\ORM\\Mapping\\OneToMany":6:{s:8:"mappedBy";s:8:"category";s:12:"targetEntity";s:7:"Article";s:7:"cascade";a:1:{i:0;s:3:"all";}s:5:"fetch";s:4:"LAZY";s:13:"orphanRemoval";b:1;s:7:"indexBy";N;}}');
// AppDelegate.h // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <<API key>> @property (strong, nonatomic) UIWindow *window; @end
package com.merakianalytics.orianna.types.data.status; import java.util.List; import com.merakianalytics.orianna.types.data.CoreData; public class Service extends CoreData { private static final long serialVersionUID = -<API key>; private List<Incident> incidents; private String status, name; @Override public boolean equals(final Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } final Service other = (Service)obj; if(incidents == null) { if(other.incidents != null) { return false; } } else if(!incidents.equals(other.incidents)) { return false; } if(name == null) { if(other.name != null) { return false; } } else if(!name.equals(other.name)) { return false; } if(status == null) { if(other.status != null) { return false; } } else if(!status.equals(other.status)) { return false; } return true; } /** * @return the incidents */ public List<Incident> getIncidents() { return incidents; } /** * @return the name */ public String getName() { return name; } /** * @return the status */ public String getStatus() { return status; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (incidents == null ? 0 : incidents.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); result = prime * result + (status == null ? 0 : status.hashCode()); return result; } /** * @param incidents * the incidents to set */ public void setIncidents(final List<Incident> incidents) { this.incidents = incidents; } /** * @param name * the name to set */ public void setName(final String name) { this.name = name; } /** * @param status * the status to set */ public void setStatus(final String status) { this.status = status; } }
// exporting modules to be included the UMD bundle import disabled from './disabled'; import focusRelevant from './focus-relevant'; import focusable from './focusable'; import onlyTabbable from './only-tabbable'; import shadowed from './shadowed'; import tabbable from './tabbable'; import validArea from './valid-area'; import validTabindex from './valid-tabindex'; import visible from './visible'; export default { disabled, focusRelevant, focusable, onlyTabbable, shadowed, tabbable, validArea, validTabindex, visible, };
import sys import textwrap from pip.basecommand import Command, SUCCESS from pip.util import get_terminal_size from pip.log import logger from pip.backwardcompat import xmlrpclib, reduce, cmp from pip.exceptions import CommandError from pip.status_codes import NO_MATCHES_FOUND from pip._vendor import pkg_resources from distutils.version import StrictVersion, LooseVersion class SearchCommand(Command): """Search for PyPI packages whose name or summary contains <query>.""" name = 'search' usage = """ %prog [options] <query>""" summary = 'Search PyPI for packages.' def __init__(self, *args, **kw): super(SearchCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '--index', dest='index', metavar='URL', default='https://pypi.python.org/pypi', help='Base URL of Python Package Index (default %default)') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): if not args: raise CommandError('Missing required argument (search query).') query = args index_url = options.index pypi_hits = self.search(query, index_url) hits = transform_hits(pypi_hits) terminal_width = None if sys.stdout.isatty(): terminal_width = get_terminal_size()[0] print_results(hits, terminal_width=terminal_width) if pypi_hits: return SUCCESS return NO_MATCHES_FOUND def search(self, query, index_url): pypi = xmlrpclib.ServerProxy(index_url) hits = pypi.search({'name': query, 'summary': query}, 'or') return hits def transform_hits(hits): """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = {} for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] score = hit['_pypi_ordering'] if score is None: score = 0 if name not in packages.keys(): packages[name] = { 'name': name, 'summary': summary, 'versions': [version], 'score': score, } else: packages[name]['versions'].append(version) # if this is the highest version, replace summary and score if version == highest_version(packages[name]['versions']): packages[name]['summary'] = summary packages[name]['score'] = score # each record has a unique name now, so we will convert the dict into a # list sorted by score package_list = sorted( packages.values(), key=lambda x: x['score'], reverse=True, ) return package_list def print_results(hits, name_column_width=25, terminal_width=None): installed_packages = [p.project_name for p in pkg_resources.working_set] for hit in hits: name = hit['name'] summary = hit['summary'] or '' if terminal_width is not None: # wrap and indent summary to fit terminal summary = textwrap.wrap( summary, terminal_width - name_column_width - 5, ) summary = ('\n' + ' ' * (name_column_width + 3)).join(summary) line = '%s - %s' % (name.ljust(name_column_width), summary) try: logger.notify(line) if name in installed_packages: dist = pkg_resources.get_distribution(name) logger.indent += 2 try: latest = highest_version(hit['versions']) if dist.version == latest: logger.notify('INSTALLED: %s (latest)' % dist.version) else: logger.notify('INSTALLED: %s' % dist.version) logger.notify('LATEST: %s' % latest) finally: logger.indent -= 2 except UnicodeEncodeError: pass def compare_versions(version1, version2): try: return cmp(StrictVersion(version1), StrictVersion(version2)) # in case of abnormal version number, fall back to LooseVersion except ValueError: pass try: return cmp(LooseVersion(version1), LooseVersion(version2)) except TypeError: # certain LooseVersion comparions raise due to unorderable types, # fallback to string comparison return cmp([str(v) for v in LooseVersion(version1).version], [str(v) for v in LooseVersion(version2).version]) def highest_version(versions): return reduce( (lambda v1, v2: compare_versions(v1, v2) == 1 and v1 or v2), versions, )
using System; using FMOD; namespace SupersonicSound.LowLevel { public struct <API key> { public DspParameterType Type { get; private set; } public string Name { get; private set; } public string Label { get; private set; } public string Description { get; private set; } private readonly <API key> _descUnion; public <API key> BoolDescription { get { if (Type!= DspParameterType.Boolean) throw new <API key>("Cannot fetch bool parameters, parameter is not bool"); return new <API key>(_descUnion.booldesc); } } public <API key> IntDescription { get { if (Type != DspParameterType.Integer) throw new <API key>("Cannot fetch int parameters, parameter is not int"); return new <API key>(_descUnion.intdesc); } } public <API key> FloatDescription { get { if (Type != DspParameterType.Float) throw new <API key>("Cannot fetch float parameters, parameter is not float"); return new <API key>(_descUnion.floatdesc); } } private <API key>(string name, string label, string description, DspParameterType type) : this() { Type = type; Name = name; Label = label; Description = description; } public <API key>(string name, string label, string description, <API key> dBool) : this(name, label, description, DspParameterType.Boolean) { _descUnion.booldesc = dBool.ToFmod(); } public <API key>(string name, string label, string description, <API key> dInt) : this(name, label, description, DspParameterType.Integer) { _descUnion.intdesc = dInt.ToFmod(); } public <API key>(string name, string label, string description, <API key> dFloat) : this(name, label, description, DspParameterType.Float) { _descUnion.floatdesc = dFloat.ToFmod(); } //public <API key>(string name, string label, string description, <API key> dData) // : this(name, label, description, DspParameterType.Data) // _descUnion = dData.ToFmod(); public <API key>(ref DSP_PARAMETER_DESC desc) : this() { Type = (DspParameterType)desc.type; Name = new string(desc.name); Label = new string(desc.label); Description = desc.description; _descUnion = desc.desc; } } public struct <API key> { public bool DefaultValue { get; private set; } public <API key>(bool defaultValue) : this() { DefaultValue = defaultValue; } public <API key>(<API key> dBool) : this(dBool.defaultval) { } public <API key> ToFmod() { return new <API key> { defaultval = DefaultValue }; } } public struct <API key> { public int DefaultValue { get; private set; } public int Min { get; private set; } public int Max { get; private set; } public bool GoesToInfinity { get; private set; } public <API key>(int defaultValue, int min, int max, bool goesToInfinity) : this() { DefaultValue = defaultValue; Min = min; Max = max; GoesToInfinity = goesToInfinity; } public <API key>(<API key> dInt) : this(dInt.defaultval, dInt.min, dInt.max, dInt.goestoinf) { } public <API key> ToFmod() { return new <API key> { defaultval = DefaultValue, goestoinf = GoesToInfinity, max = Max, min = Min }; } } public struct <API key> { public float DefaultValue { get; private set; } public float Min { get; private set; } public float Max { get; private set; } public <API key>(float defaultValue, float min, float max) : this() { DefaultValue = defaultValue; Min = min; Max = max; } public <API key>(<API key> dFloat) : this(dFloat.defaultval, dFloat.min, dFloat.max) { } public <API key> ToFmod() { return new <API key> { defaultval = DefaultValue, min = Min, max = Max, }; } } [EquivalentEnum(typeof(DSP_PARAMETER_TYPE))] public enum DspParameterType { Float = DSP_PARAMETER_TYPE.FLOAT, Integer = DSP_PARAMETER_TYPE.INT, Boolean = DSP_PARAMETER_TYPE.BOOL, Data = DSP_PARAMETER_TYPE.DATA } }
package edu.princeton.safe; import edu.princeton.safe.model.Neighborhood; public interface <API key> { double[] <API key>(Neighborhood current, int attributeIndex); }
<?php if(!defined('LOADALL')) define('LOADALL',true); define('PACKAGE_PATH',dirname(__FILE__).'/../'); define('APPPATH',dirname(__FILE__).'/../'); define('LIB','/app/'); define('DOMAIN',LIB.'domain/'); define('VIEWS',LIB.'Views/'); define('CONTROLLERS',LIB.'/Controllers/'); include(PACKAGE_PATH.'autoloader.php'); if(LOADALL){ include(PACKAGE_PATH . 'lib/Route.php'); include(PACKAGE_PATH . 'lib/Debug.php'); load(PACKAGE_PATH.'lib/Helpers/'); load(PACKAGE_PATH.'lib/Events/'); load(PACKAGE_PATH.'lib/Interfaces/'); load(PACKAGE_PATH.'lib/Core/'); // load(PACKAGE_PATH.'lib/Filters/'); //include(PACKAGE_PATH.'lib/Controllers/Filters/IFilter.php'); //include(PACKAGE_PATH.'lib/Controllers/Filters/SecurityFilter.php'); load(PACKAGE_PATH.'lib/Controllers/'); if(defined('VIEWENGINE') && VIEWENGINE=='WordPress'){ //C:\Users\andreas\My Projects\development\aoisora\wp-content\plugins\AoiSora\tests\config.php include('/../../../../wp-load.php'); load(PACKAGE_PATH.'lib/ViewEngines/'.VIEWENGINE.'/');//.VIEWENGINE.'.php'); } } if(LOADDATABASE){ global $db; $db = new MySqlDatabase(); global $db_prefix; $db_prefix='wp_aoisora_'; }