max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
315
#include "Tools/Math/utils.h" #include "Tools/Noise/Sigma.hpp" #include "Tools/Noise/Sigma.hpp" #include "Tools/Noise/Event_probability.hpp" #include "Tools/Noise/Received_optical_power.hpp" #include "Tools/Noise/noise_utils.h" namespace aff3ct { namespace tools { template <typename T, typename R> struct Noise_cast { inline static Noise<T>* cast(const Noise<R>& n) { Noise<T> * cast_n = nullptr; switch(n.get_type()) { case Noise_type::SIGMA: cast_n = new Sigma <T>(dynamic_cast<const Sigma <R>&>(n)); break; case Noise_type::EP: cast_n = new Event_probability <T>(dynamic_cast<const Event_probability <R>&>(n)); break; case Noise_type::ROP: cast_n = new Received_optical_power<T>(dynamic_cast<const Received_optical_power<R>&>(n)); break; } return cast_n; } }; template <typename R> struct Noise_cast<R,R> { inline static Noise<R>* cast(const Noise<R>& n) { return n.clone(); } }; template <typename T, typename R> Noise<T>* cast(const Noise<R>& n) { return Noise_cast<T,R>::cast(n); } template <typename R> constexpr R unknown_symbol_val() { return tools::sat_val<R>(); } template <typename R> constexpr R unknown_llr_val() { return (R)1e-5; } template <typename R> bool is_unknown_symbol(const R& v) { return v == tools::unknown_symbol_val<R>(); } template <typename R> mipp::Msk<mipp::N<R>()> is_unknown_symbol(const mipp::Reg<R>& q_in) { const mipp::Reg<R> r_unks = tools::unknown_symbol_val<R>(); return q_in == tools::unknown_symbol_val<R>(); } template <typename R> bool is_unknown_llr(const R& v) { return (v <= tools::unknown_llr_val<R>() && v >= -tools::unknown_llr_val<R>()); } template <typename R> mipp::Msk<mipp::N<R>()> is_unknown_llr(const mipp::Reg<R>& q_in) { const mipp::Reg<R> r_unk = tools::unknown_llr_val<R>(); const mipp::Reg<R> r_unkm = -tools::unknown_llr_val<R>(); return (q_in <= r_unk) & (q_in >= r_unkm); } } }
883
347
<reponame>hbraha/ovirt-engine<filename>backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/vdscommands/UserConfiguredNetworkData.java<gh_stars>100-1000 package org.ovirt.engine.core.common.vdscommands; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment; import org.ovirt.engine.core.compat.Guid; public class UserConfiguredNetworkData { private final List<NetworkAttachment> networkAttachments; private final Set<Guid> removedNetworkAttachments; private final Map<String, UserOverriddenNicValues> userOverriddenNicValuesByNicName; public UserConfiguredNetworkData() { this(Collections.emptyList(), Collections.emptySet(), new HashMap<>()); } public UserConfiguredNetworkData(List<NetworkAttachment> networkAttachments, Set<Guid> removedNetworkAttachments, Map<String, UserOverriddenNicValues> userOverriddenNicValuesByNicName) { this.networkAttachments = networkAttachments; this.removedNetworkAttachments = removedNetworkAttachments; this.userOverriddenNicValuesByNicName = userOverriddenNicValuesByNicName; } public List<NetworkAttachment> getNetworkAttachments() { return networkAttachments; } public Map<String, UserOverriddenNicValues> getUserOverriddenNicValuesByNicName() { return userOverriddenNicValuesByNicName; } public Set<Guid> getRemovedNetworkAttachments() { return removedNetworkAttachments; } }
545
1,010
#include "main/shmem/shmem_file.h" #include <assert.h> #include <errno.h> #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/param.h> #include <sys/stat.h> #include <unistd.h> #include "lib/logger/logger.h" #include "main/shmem/shmem_util.h" static const char* SHADOW_PREFIX = "shadow_shmemfile"; static const char PID_DELIM = '-'; const static int SHMEM_PERMISSION_BITS = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; static void _shmemfile_getName(size_t nbytes, char* str) { assert(str != NULL && nbytes >= 3); struct timespec ts = {0}; clock_gettime(CLOCK_MONOTONIC, &ts); pid_t pid = getpid(); snprintf(str, MIN(SHD_SHMEM_FILE_NAME_NBYTES, nbytes), "/%s_%llu.%llu%c%" PRId64, SHADOW_PREFIX, (unsigned long long)ts.tv_sec, (unsigned long long)ts.tv_nsec, PID_DELIM, (int64_t)pid); } bool shmemfile_nameHasShadowPrefix(const char* name) { const char* pfx = strstr(name, SHADOW_PREFIX); return (pfx != NULL); } pid_t shmemfile_pidFromName(const char* name) { pid_t ret = -1; long long int x = 0; const char* delim = strchr(name, '-'); if (delim) { // try to parse the end of the string x = strtol(delim + 1, NULL, 10); if (x == 0 || x > INT_MAX || x <= INT_MIN) { // we had trouble parsing ret = -1; } else { ret = (pid_t)x; } } return ret; } static size_t _shmemfile_roundUpToMultiple(size_t x, size_t multiple) { assert(multiple != 0); return ((x + multiple - 1) / multiple) * multiple; } static size_t _shmemfile_systemPageNBytes() { return (size_t)sysconf(_SC_PAGESIZE); } int shmemfile_alloc(size_t nbytes, ShMemFile* shmf) { if (nbytes == 0 || nbytes % _shmemfile_systemPageNBytes() != 0) { panic("ShMemFile size must be a positive multiple of %zu but requested " "size was %zu", _shmemfile_systemPageNBytes(), nbytes); return -1; } if (shmf == NULL) { panic("shmf must not be null"); return -1; } memset(shmf, 0, sizeof(ShMemFile)); _shmemfile_getName(SHD_SHMEM_FILE_NAME_NBYTES, shmf->name); bool bad = false; int fd = shm_open(shmf->name, O_RDWR | O_CREAT | O_EXCL, SHMEM_PERMISSION_BITS); if (fd >= 0) { int rc = ftruncate(fd, nbytes); if (rc == 0) { void* p = mmap(NULL, nbytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p != MAP_FAILED) { shmf->p = p; shmf->nbytes = nbytes; } else { panic("error on mmap: %s", strerror(errno)); bad = true; } } else { // failed truncate panic("error on truncate: %s", strerror(errno)); bad = true; } close(fd); if (bad) { rc = shm_unlink(shmf->name); assert(rc == 0); } } else { bad = true; panic("error on shm_open: %s", strerror(errno)); } return -1 * (bad); } // rwails: cleanup redundant logic int shmemfile_map(const char* name, size_t nbytes, ShMemFile* shmf) { if (nbytes == 0 || nbytes % _shmemfile_systemPageNBytes() != 0) { panic("ShMemFile size must be a positive multiple of %zu but requested " "size was %zu", _shmemfile_systemPageNBytes(), nbytes); return -1; } if (shmf == NULL) { panic("shmf must not be null"); return -1; } int rc = 0; memset(shmf, 0, sizeof(ShMemFile)); strncpy(shmf->name, name, SHD_SHMEM_FILE_NAME_NBYTES); bool bad = false; int fd = shm_open(shmf->name, O_RDWR, SHMEM_PERMISSION_BITS); if (fd >= 0) { void* p = mmap(NULL, nbytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p != MAP_FAILED) { shmf->p = p; shmf->nbytes = nbytes; } else { panic("error on mmap: %s", strerror(errno)); bad = true; } close(fd); if (bad) { rc = shm_unlink(shmf->name); assert(rc == 0); } } else { bad = true; panic("error on shm_open: %s", strerror(errno)); } return -1 * (bad); } int shmemfile_unmap(ShMemFile* shmf) { int rc = munmap(shmf->p, shmf->nbytes); if (rc) { panic("error on munmap: %s", strerror(errno)); } return rc; } int shmemfile_free(ShMemFile* shmf) { int rc = shmemfile_unmap(shmf); if (rc == 0) { rc = shm_unlink(shmf->name); if (rc) { panic("error on shm_unlink of %s: %s", shmf->name, strerror(errno)); } } return rc; } size_t shmemfile_goodSizeNBytes(size_t requested_nbytes) { return _shmemfile_roundUpToMultiple( requested_nbytes, _shmemfile_systemPageNBytes()); }
2,569
1,379
<reponame>adschw1/vim-awesome<gh_stars>1000+ """Utility functions for the submitted plugins table.""" import time import rethinkdb as r import db r_conn = db.util.r_conn def ensure_table(): db.util.ensure_table('submitted_plugins') db.util.ensure_index('submitted_plugins', 'submitted_at') db.util.ensure_index('submitted_plugins', 'vimorg_id') def insert(plugin_data): if not plugin_data.get('submitted_at'): plugin_data['submitted_at'] = int(time.time()) r.table('submitted_plugins').insert(plugin_data).run(r_conn()) def get_list(): return list(r.table('submitted_plugins') .order_by(index=r.desc('submitted_at')) .filter(r.row['approved'] != True, default=True) # NOQA .filter(r.row['rejected'] != True, default=True) # NOQA .filter(r.row['github-link'] != '', default=True) # NOQA .run(r_conn())) def get_by_id(id): return r.table('submitted_plugins').get(id).run(r_conn()) def reject(id): return r.table('submitted_plugins').get(id).update({ 'rejected': True }).run(r_conn()) def approve_and_enable_scraping(id, plugin_info): update_data = { 'approved': True } if plugin_info['vimorg_id']: update_data['vimorg_id'] = plugin_info['vimorg_id'] r.table('submitted_plugins').get(id).update(update_data).run(r_conn()) plugin = get_by_id(id) if plugin_info['github_owner'] and plugin_info['github_repo_name']: db.github_repos.PluginGithubRepos.upsert_with_owner_repo({ 'owner': plugin_info['github_owner'], 'repo_name': plugin_info['github_repo_name'], 'from_submission': plugin }) return plugin
766
3,200
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "runtime/device/ascend/ge_runtime/task/aicpu_task.h" #include <vector> #include "runtime/mem.h" #include "runtime/kernel.h" #include "runtime/device/ascend/ge_runtime/task/task_factory.h" #include "aicpu/common/aicpu_task_struct.h" #include "mindspore/core/utils/convert_utils_base.h" namespace mindspore::ge::model_runner { AicpuTask::AicpuTask(const ModelContext &model_context, const std::shared_ptr<AicpuTaskInfo> &task_info) : TaskRepeater<AicpuTaskInfo>(model_context, task_info), task_info_(task_info), stream_(nullptr), args_(nullptr), ext_info_(nullptr), input_output_addr_(nullptr) { MS_EXCEPTION_IF_NULL(task_info_); auto stream_list = model_context.stream_list(); if (stream_list.size() == 1) { stream_ = stream_list[0]; } else if (stream_list.size() > task_info_->stream_id()) { stream_ = stream_list[task_info_->stream_id()]; } else { MS_LOG(EXCEPTION) << "Index: " << task_info_->stream_id() << " >= stream_list.size(): " << stream_list.size(); } } AicpuTask::~AicpuTask() { ReleaseRtMem(&args_); ReleaseRtMem(&ext_info_); } void AicpuTask::Distribute() { MS_LOG(INFO) << "InitAicpuTask start."; std::vector<void *> io_addrs; io_addrs.insert(io_addrs.end(), task_info_->input_data_addrs().begin(), task_info_->input_data_addrs().end()); io_addrs.insert(io_addrs.end(), task_info_->output_data_addrs().begin(), task_info_->output_data_addrs().end()); auto io_addrs_num = static_cast<uint32_t>(io_addrs.size()); auto io_addrs_size = static_cast<uint32_t>(io_addrs_num * sizeof(void *)); constexpr uint32_t io_addr_offset = sizeof(aicpu::AicpuParamHead); uint32_t node_def_len_offset = io_addr_offset + io_addrs_size; uint32_t node_def_addr_offset = node_def_len_offset + sizeof(uint32_t); uint32_t args_size = sizeof(aicpu::AicpuParamHead) + io_addrs_size + static_cast<uint32_t>(task_info_->node_def().size()) + sizeof(uint32_t); // Malloc device memory for args rtError_t rt_ret = rtMalloc(&args_, args_size, RT_MEMORY_HBM); if (rt_ret != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMalloc failed, ret: " << rt_ret; } SetAicpuParamHead(args_size, io_addrs_num); SetInputOutputAddrs(io_addrs, io_addr_offset); SetNodeDef(node_def_len_offset, node_def_addr_offset); // for data dump input_output_addr_ = reinterpret_cast<void *>(reinterpret_cast<uint8_t *>(args_) + io_addr_offset); auto dump_flag = task_info_->dump_flag() ? RT_KERNEL_DUMPFLAG : RT_KERNEL_DEFAULT; MS_LOG(INFO) << "Distribute AicpuTask start, args_size = " << args_size << ", io_addrs_num =" << io_addrs_num << ", so_name = " << task_info_->so_name() << ", kernel_name = " << task_info_->kernel_name() << ", dump_flag = " << dump_flag; rt_ret = rtCpuKernelLaunchWithFlag(reinterpret_cast<const void *>(task_info_->so_name().data()), reinterpret_cast<const void *>(task_info_->kernel_name().data()), 1, args_, args_size, nullptr, stream_, dump_flag); if (rt_ret != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtCpuKernelLaunchWithFlag failed, ret: " << rt_ret; } MS_LOG(INFO) << "Distribute AicpuTask end."; } void AicpuTask::ReleaseRtMem(void **ptr) noexcept { if (ptr == nullptr || *ptr == nullptr) { return; } rtError_t rt_ret = rtFree(*ptr); if (rt_ret != RT_ERROR_NONE) { return; } *ptr = nullptr; } void AicpuTask::SetAicpuParamHead(uint32_t args_size, uint32_t io_addrs_num) { aicpu::AicpuParamHead aicpu_param_head; aicpu_param_head.length = args_size; aicpu_param_head.ioAddrNum = io_addrs_num; const auto &ext_info = task_info_->ext_info(); uint32_t ext_size = SizeToUint(ext_info.size()); if (ext_info.empty()) { aicpu_param_head.extInfoLength = 0; aicpu_param_head.extInfoAddr = 0; } else { rtError_t flag = rtMalloc(&ext_info_, ext_size, RT_MEMORY_HBM); if (flag != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMalloc failed, ret: " << flag; } flag = rtMemcpy(ext_info_, ext_size, const_cast<void *>(reinterpret_cast<const void *>(ext_info.data())), ext_size, RT_MEMCPY_HOST_TO_DEVICE); if (flag != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMemcpy failed, ret: " << flag; } MS_LOG(INFO) << "ext info size: " << ext_size; aicpu_param_head.extInfoLength = ext_size; aicpu_param_head.extInfoAddr = reinterpret_cast<uintptr_t>(ext_info_); } // Memcpy AicpuParamHead auto rt_ret = rtMemcpy(args_, sizeof(aicpu::AicpuParamHead), reinterpret_cast<void *>(&aicpu_param_head), sizeof(aicpu::AicpuParamHead), RT_MEMCPY_HOST_TO_DEVICE); if (rt_ret != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMemcpy failed, ret: " << rt_ret; } } void AicpuTask::SetInputOutputAddrs(const std::vector<void *> &io_addrs, uint32_t io_addr_offset) { // Memcpy io addrs if (!io_addrs.empty()) { auto rt_ret = rtMemcpy(reinterpret_cast<void *>(reinterpret_cast<uint8_t *>(args_) + io_addr_offset), static_cast<uint32_t>(io_addrs.size()) * sizeof(void *), io_addrs.data(), static_cast<uint32_t>(io_addrs.size()) * sizeof(void *), RT_MEMCPY_HOST_TO_DEVICE); if (rt_ret != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMemcpy failed, ret: " << rt_ret; } } } void AicpuTask::SetNodeDef(uint32_t node_def_len_offset, uint32_t node_def_addr_offset) { // Memcpy node def auto size = task_info_->node_def().size(); auto rt_ret = rtMemcpy(reinterpret_cast<void *>(reinterpret_cast<uint8_t *>(args_) + node_def_len_offset), sizeof(uint32_t), reinterpret_cast<const void *>(&size), sizeof(uint32_t), RT_MEMCPY_HOST_TO_DEVICE); if (rt_ret != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMemcpy failed, ret: " << rt_ret; } // Memcpy node def rt_ret = rtMemcpy(reinterpret_cast<void *>(reinterpret_cast<uint8_t *>(args_) + node_def_addr_offset), task_info_->node_def().size(), reinterpret_cast<const void *>(task_info_->node_def().data()), task_info_->node_def().size(), RT_MEMCPY_HOST_TO_DEVICE); if (rt_ret != RT_ERROR_NONE) { MS_LOG(EXCEPTION) << "Call rt api rtMemcpy failed, ret: " << rt_ret; } } REGISTER_TASK(TaskInfoType::AICPU, AicpuTask, AicpuTaskInfo); } // namespace mindspore::ge::model_runner
3,033
1,514
#ifndef CUBIC_SPLINE_H #define CUBIC_SPLINE_H #include <vector> using std::vector; #include "RageTypes.h" struct lua_State; struct CubicSpline { CubicSpline() :m_spatial_extent(0.0f) {} void solve_looped(); void solve_straight(); void solve_polygonal(); void p_and_tfrac_from_t(float t, bool loop, size_t& p, float& tfrac) const; float evaluate(float t, bool loop) const; float evaluate_derivative(float t, bool loop) const; float evaluate_second_derivative(float t, bool loop) const; float evaluate_third_derivative(float t, bool loop) const; void set_point(size_t i, float v); void set_coefficients(size_t i, float b, float c, float d); void get_coefficients(size_t i, float& b, float& c, float& d) const; void set_point_and_coefficients(size_t i, float a, float b, float c, float d); void get_point_and_coefficients(size_t i, float& a, float& b, float& c, float& d) const; void resize(size_t s); size_t size() const; bool empty() const; float m_spatial_extent; private: bool check_minimum_size(); void prep_inner(size_t last, vector<float>& results); void set_results(size_t last, vector<float>& diagonals, vector<float>& results); struct SplinePoint { float a, b, c, d; }; vector<SplinePoint> m_points; }; struct CubicSplineN { CubicSplineN() :m_owned_by_actor(false), m_loop(false), m_polygonal(false), m_dirty(true) {} static void weighted_average(CubicSplineN& out, const CubicSplineN& from, const CubicSplineN& to, float between); void solve(); void evaluate(float t, vector<float>& v) const; void evaluate_derivative(float t, vector<float>& v) const; void evaluate_second_derivative(float t, vector<float>& v) const; void evaluate_third_derivative(float t, vector<float>& v) const; void evaluate(float t, RageVector3& v) const; void evaluate_derivative(float t, RageVector3& v) const; void set_point(size_t i, const vector<float>& v); void set_coefficients(size_t i, const vector<float>& b, const vector<float>& c, const vector<float>& d); void get_coefficients(size_t i, vector<float>& b, vector<float>& c, vector<float>& d); void set_spatial_extent(size_t i, float extent); float get_spatial_extent(size_t i); void resize(size_t s); size_t size() const; void redimension(size_t d); size_t dimension() const; bool empty() const; float get_max_t() const { if(m_loop) { return static_cast<float>(size()); } else { return static_cast<float>(size()-1); } } typedef vector<CubicSpline> spline_cont_t; void set_loop(bool l); bool get_loop() const; void set_polygonal(bool p); bool get_polygonal() const; void set_dirty(bool d); bool get_dirty() const; bool m_owned_by_actor; void PushSelf(lua_State* L); private: bool m_loop; bool m_polygonal; bool m_dirty; spline_cont_t m_splines; }; #endif // Side note: Actually written between 2014/12/26 and 2014/12/28 /* * Copyright (c) 2014-2015 <NAME> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
1,443
1,773
<reponame>psunde/primefaces /* * The MIT License * * Copyright (c) 2009-2021 PrimeTek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.primefaces.model; import org.primefaces.component.api.DynamicColumn; import org.primefaces.component.api.UIColumn; import org.primefaces.component.column.ColumnBase; import org.primefaces.component.datatable.feature.FilterFeature; import org.primefaces.model.filter.FilterConstraint; import org.primefaces.model.filter.FunctionFilterConstraint; import org.primefaces.model.filter.GlobalFilterConstraint; import javax.el.ELContext; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.context.FacesContext; import java.io.Serializable; import java.util.Objects; public class FilterMeta implements Serializable { public static final String GLOBAL_FILTER_KEY = "globalFilter"; private static final long serialVersionUID = 1L; private String field; private String columnKey; private ValueExpression filterBy; private Object filterValue; private MatchMode matchMode = MatchMode.CONTAINS; private FilterConstraint constraint; public FilterMeta() { // NOOP } FilterMeta(String columnKey, String field, FilterConstraint constraint, ValueExpression filterBy, Object filterValue, MatchMode matchMode) { this.field = field; this.columnKey = columnKey; this.filterBy = filterBy; this.constraint = constraint; this.filterValue = filterValue; this.matchMode = matchMode; } /** * @deprecated Use FilterMeta#builder() instead */ @Deprecated public FilterMeta(String field, String columnKey, ValueExpression filterByVE, MatchMode filterMatchMode, Object filterValue) { this.field = field; this.columnKey = columnKey; this.filterBy = filterByVE; this.constraint = FilterFeature.FILTER_CONSTRAINTS.get(filterMatchMode); this.filterValue = filterValue; this.matchMode = filterMatchMode; } public static FilterMeta of(FacesContext context, String var, UIColumn column) { if (column instanceof DynamicColumn) { ((DynamicColumn) column).applyStatelessModel(); } if (!column.isFilterable()) { return null; } String field = column.getField(); ValueExpression filterByVE = column.getValueExpression(ColumnBase.PropertyKeys.filterBy.name()); if (field == null && filterByVE == null) { return null; } if (field == null) { field = column.resolveField(context, filterByVE); } else if (filterByVE == null) { filterByVE = UIColumn.createValueExpressionFromField(context, var, field); } MatchMode matchMode = MatchMode.of(column.getFilterMatchMode()); FilterConstraint constraint = FilterFeature.FILTER_CONSTRAINTS.get(matchMode); if (column.getFilterFunction() != null) { constraint = new FunctionFilterConstraint(column.getFilterFunction()); } return new FilterMeta(column.getColumnKey(), field, constraint, filterByVE, column.getFilterValue(), matchMode); } public static FilterMeta of(Object globalFilterValue, MethodExpression globalFilterFunction) { FilterConstraint constraint = globalFilterFunction == null ? new GlobalFilterConstraint() : new FunctionFilterConstraint(globalFilterFunction); return new FilterMeta(GLOBAL_FILTER_KEY, GLOBAL_FILTER_KEY, constraint, null, globalFilterValue, MatchMode.GLOBAL); } public String getField() { return field; } public String getColumnKey() { return columnKey; } public ValueExpression getFilterBy() { return filterBy; } public void setFilterBy(ValueExpression filterBy) { this.filterBy = filterBy; } public Object getFilterValue() { return filterValue; } public void setFilterValue(Object filterValue) { this.filterValue = filterValue; } public FilterConstraint getConstraint() { return constraint; } public void setConstraint(FilterConstraint constraint) { this.constraint = constraint; } public boolean isActive() { return filterValue != null; } public MatchMode getMatchMode() { return matchMode; } public void setMatchMode(MatchMode matchMode) { this.matchMode = matchMode; } public boolean isGlobalFilter() { return GLOBAL_FILTER_KEY.equals(columnKey); } public Object getLocalValue(ELContext elContext, UIColumn column) { if (column instanceof DynamicColumn) { ((DynamicColumn) column).applyStatelessModel(); } return filterBy.getValue(elContext); } public static Builder builder() { return new Builder(); } public static final class Builder { private final FilterMeta filterBy; private Builder() { filterBy = new FilterMeta(); } public Builder field(String field) { filterBy.field = field; return this; } public Builder filterBy(ValueExpression filterBy) { this.filterBy.filterBy = filterBy; return this; } public Builder filterValue(Object filterValue) { filterBy.filterValue = filterValue; return this; } public Builder constraint(FilterConstraint constraint) { filterBy.constraint = constraint; return this; } public Builder matchMode(MatchMode matchMode) { filterBy.matchMode = matchMode; return this; } public FilterMeta build() { if (filterBy.matchMode != null) { filterBy.constraint = FilterFeature.FILTER_CONSTRAINTS.get(filterBy.matchMode); } Objects.requireNonNull(filterBy.constraint, "Filter constraint is required"); Objects.requireNonNull(filterBy.field, "Field is required"); return filterBy; } } @Override public String toString() { return "FilterMeta{" + "field='" + field + '\'' + ", columnKey='" + columnKey + '\'' + ", filterBy=" + filterBy + ", filterValue=" + filterValue + ", matchMode=" + matchMode + ", constraint=" + constraint + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FilterMeta that = (FilterMeta) o; return Objects.equals(field, that.field) && Objects.equals(columnKey, that.columnKey); } @Override public int hashCode() { return Objects.hash(field, columnKey); } }
3,340
4,935
<gh_stars>1000+ #include "../include/v8_helpers.h" namespace nodegit { v8::Local<v8::Value> safeGetField(v8::Local<v8::Object> &containerObject, std::string field) { auto maybeFieldName = Nan::New(field); if (maybeFieldName.IsEmpty()) { v8::Local<v8::Value> emptyResult; return emptyResult; } auto maybeRetrievedField = Nan::Get(containerObject, maybeFieldName.ToLocalChecked()); if (maybeRetrievedField.IsEmpty()) { v8::Local<v8::Value> emptyResult; return emptyResult; } return maybeRetrievedField.ToLocalChecked(); } }
224
1,133
<reponame>vincentschut/isce2<filename>components/isceobj/Sensor/src/asa_im_decode/asa_im_decode.c<gh_stars>1000+ /*********************************************************************************************************************************** asa_im_decode.c Decodes Envisat ASAR Image Mode Level 0 data compiled on a Sun and SGI with command gcc -O2 asa_im_decode.c -o asa_im_decode v1.0, Feb/Mar 2004, <NAME> v1.05, Mar 25, 2004, <NAME>, now fills missing lines with zeroes in float mode and 0.*127.5+127.5 + .5 = 128 for byte mode v1.1, 17 Feb 2005, <NAME>: 1. This program can run on a little endian machine as well as a big endian machine! 2. On Linux, compiled with command gcc -O2 asa_im_decode.c -o asa_im_decode 3. On Unix, compiled with command gcc -O2 asa_im_decode.c -o asa_im_decode v1.1.1, 8 Nov 2005, <NAME>, now runs correctly on 64-bit compilers. ***********************************************************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> /** * The <code>EPR_DataTypeId</code> enumeration lists all possible data * types for field elements in ENVISAT dataset records. */ // added by <NAME> on 16/02/2005 // extracted from ESA BEAM epr_api package enum EPR_DataTypeId { /** The ID for unknown types. */ e_tid_unknown = 0, /** An array of unsigned 8-bit integers, C type is <code>uchar*</code> */ e_tid_uchar = 1, /** An array of signed 8-bit integers, C type is <code>char*</code> */ e_tid_char = 2, /** An array of unsigned 16-bit integers, C type is <code>ushort*</code> */ e_tid_ushort = 3, /** An array of signed 16-bit integers, C type is <code>short*</code> */ e_tid_short = 4, /** An array of unsigned 32-bit integers, C type is <code>ulong*</code> */ e_tid_ulong = 5, /** An array of signed 32-bit integers, C type is <code>long*</code> */ e_tid_long = 6, /** An array of 32-bit floating point numbers, C type is <code>float*</code> */ e_tid_float = 7, /** An array of 64-bit floating point numbers, C type is <code>double*</code> */ e_tid_double = 8, /** A zero-terminated ASCII string, C type is <code>char*</code> */ e_tid_string = 11, /** An array of unsigned character, C type is <code>uchar*</code> */ e_tid_spare = 13, /** A time (MJD) structure, C type is <code>EPR_Time</code> */ e_tid_time = 21 }; /* structures */ struct mphStruct { char product[ 62 ]; char procStage[ 1 ]; char refDoc[ 23 ]; char spare1[ 40 ]; char acquisitionStation[ 20 ]; char procCenter[ 6 ]; char procTime[ 27 ]; char softwareVer[ 14 ]; char spare2[ 40 ]; char sensingStart[ 27 ]; char sensingStop[ 27 ]; char spare3[ 40 ]; char phase[ 1 ]; int cycle; int relOrbit; int absOrbit; char stateVectorTime[ 27 ]; double deltaUt1; double xPosition; double yPosition; double zPosition; double xVelocity; double yVelocity; double zVelocity; char vectorSource[ 2 ]; char spare4[ 40 ]; char utcSbtTime[ 27 ]; unsigned int satBinaryTime; unsigned int clockStep; char spare5[ 32 ]; char leapUtc[ 27 ]; int leapSign; int leapErr; char spare6[ 40]; int productErr; int totSize; int sphSize; int numDsd; int dsdSize; int numDataSets; char spare7[ 40 ]; }; struct dsdStruct { char dsName[ 28 ]; char dsType[ 1 ]; char filename[ 62 ]; int dsOffset; int dsSize; int numDsr; int dsrSize; }; struct sphStruct { char sphDescriptor[ 28 ]; double startLat; double startLon; double stopLat; double stopLon; double satTrack; char spare1[ 50 ]; int ispErrorsSignificant; int missingIspsSignificant; int ispDiscardedSignificant; int rsSignificant; char spare2[ 50 ]; int numErrorIsps; double errorIspsThresh; int numMissingIsps; double missingIspsThresh; int numDiscardedIsps; double discardedIspsThresh; int numRsIsps; double rsThresh; char spare3[ 100 ]; char txRxPolar[ 5 ]; char swath[ 3 ]; char spare4[ 41 ]; struct dsdStruct dsd[ 4 ]; }; struct sphAuxStruct { char sphDescriptor[ 28 ]; char spare1[ 51 ]; struct dsdStruct dsd[ 1 ]; }; struct dsrTimeStruct { int days; int seconds; int microseconds; }; struct calPulseStruct { float nomAmplitude[ 32 ]; float nomPhase[ 32 ]; }; struct nomPulseStruct { float pulseAmpCoeff[ 4 ]; float pulsePhsCoeff[ 4 ]; float pulseDuration; }; struct dataConfigStruct { char echoCompMethod[ 4 ]; char echoCompRatio[ 3 ]; char echoResampFlag[ 1 ]; char initCalCompMethod[ 4 ]; char initCalCompRatio[ 3 ]; char initCalResampFlag[ 1 ]; char perCalCompMethod[ 4 ]; char perCalCompRatio[ 3 ]; char perCalResampFlag[ 1 ]; char noiseCompMethod[ 4 ]; char noiseCompRatio[ 3 ]; char noiseResampFlag[ 1 ]; }; struct swathConfigStruct { unsigned short numSampWindowsEcho[ 7 ]; unsigned short numSampWindowsInitCal[ 7 ]; unsigned short numSampWindowsPerCal[ 7 ]; unsigned short numSampWindowsNoise[ 7 ]; float resampleFactor[ 7 ]; }; struct swathIdStruct { unsigned short swathNum[ 7 ]; unsigned short beamSetNum[ 7 ]; }; struct timelineStruct { unsigned short swathNums[ 7 ]; unsigned short mValues[ 7 ]; unsigned short rValues[ 7 ]; unsigned short gValues[ 7 ]; }; /* problems begin with field 132 - check the double statement */ struct testStruct { float operatingTemp; float rxGainDroopCoeffSmb[ 16 ]; /* this needs to be converted to a double array of eight elements */ //double rxGainDroopCoeffSmb[ 8 ]; /* Something wrong here, why?*/ }; struct insGadsStruct { /* see pages 455-477 for the 142 fields associated with this gads - got length of 121712 bytes */ struct dsrTimeStruct dsrTime; unsigned int dsrLength; float radarFrequency; float sampRate; float offsetFreq; struct calPulseStruct calPulseIm0TxH1; struct calPulseStruct calPulseIm0TxV1; struct calPulseStruct calPulseIm0TxH1a; struct calPulseStruct calPulseIm0TxV1a; struct calPulseStruct calPulseIm0RxH2; struct calPulseStruct calPulseIm0RxV2; struct calPulseStruct calPulseIm0H3; struct calPulseStruct calPulseIm0V3; struct calPulseStruct calPulseImTxH1[ 7 ]; struct calPulseStruct calPulseImTxV1[ 7 ]; struct calPulseStruct calPulseImTxH1a[ 7 ]; struct calPulseStruct calPulseImTxV1a[ 7 ]; struct calPulseStruct calPulseImRxH2[ 7 ]; struct calPulseStruct calPulseImRxV2[ 7 ]; struct calPulseStruct calPulseImH3[ 7 ]; struct calPulseStruct calPulseImV3[ 7 ]; struct calPulseStruct calPulseApTxH1[ 7 ]; struct calPulseStruct calPulseApTxV1[ 7 ]; struct calPulseStruct calPulseApTxH1a[ 7 ]; struct calPulseStruct calPulseApTxV1a[ 7 ]; struct calPulseStruct calPulseApRxH2[ 7 ]; struct calPulseStruct calPulseApRxV2[ 7 ]; struct calPulseStruct calPulseApH3[ 7 ]; struct calPulseStruct calPulseApV3[ 7 ]; struct calPulseStruct calPulseWvTxH1[ 7 ]; struct calPulseStruct calPulseWvTxV1[ 7 ]; struct calPulseStruct calPulseWvTxH1a[ 7 ]; struct calPulseStruct calPulseWvTxV1a[ 7 ]; struct calPulseStruct calPulseWvRxH2[ 7 ]; struct calPulseStruct calPulseWvRxV2[ 7 ]; struct calPulseStruct calPulseWvH3[ 7 ]; struct calPulseStruct calPulseWvV3[ 7 ]; struct calPulseStruct calPulseWsTxH1[ 5 ]; struct calPulseStruct calPulseWsTxV1[ 5 ]; struct calPulseStruct calPulseWsTxH1a[ 5 ]; struct calPulseStruct calPulseWsTxV1a[ 5 ]; struct calPulseStruct calPulseWsRxH2[ 5 ]; struct calPulseStruct calPulseWsRxV2[ 5 ]; struct calPulseStruct calPulseWsH3[ 5 ]; struct calPulseStruct calPulseWsV3[ 5 ]; struct calPulseStruct calPulseGmTxH1[ 5 ]; struct calPulseStruct calPulseGmTxV1[ 5 ]; struct calPulseStruct calPulseGmTxH1a[ 5 ]; struct calPulseStruct calPulseGmTxV1a[ 5 ]; struct calPulseStruct calPulseGmRxH2[ 5 ]; struct calPulseStruct calPulseGmRxV2[ 5 ]; struct calPulseStruct calPulseGmH3[ 5 ]; struct calPulseStruct calPulseGmV3[ 5 ]; struct nomPulseStruct nomPulseIm[ 7 ]; struct nomPulseStruct nomPulseAp[ 7 ]; struct nomPulseStruct nomPulseWv[ 7 ]; struct nomPulseStruct nomPulseWs[ 5 ]; struct nomPulseStruct nomPulseGm[ 5 ]; float azPatternIs1[ 101 ]; float azPatternIs2[ 101 ]; float azPatternIs3Ss2[ 101 ]; float azPatternIs4Ss3[ 101 ]; float azPatternIs5Ss4[ 101 ]; float azPatternIs6Ss5[ 101 ]; float azPatternIs7[ 101 ]; float azPatternSs1[ 101 ]; float rangeGateBias; float rangeGateBiasGm; float adcLutI[ 255 ]; float adcLutQ[ 255 ]; char spare1[ 648 ]; float full8LutI[ 256 ]; float full8LutQ[ 256 ]; float fbaq4LutI[ 4096 ]; float fbaq3LutI[ 2048 ]; float fbaq2LutI[ 1024 ]; float fbaq4LutQ[ 4096 ]; float fbaq3LutQ[ 2048 ]; float fbaq2LutQ[ 1024 ]; float fbaq4NoAdc[ 4096 ]; float fbaq3NoAdc[ 2048 ]; float fbaq2NoAdc[ 1024 ]; float smLutI[ 16 ]; float smLutQ[ 16 ]; struct dataConfigStruct dataConfigIm; struct dataConfigStruct dataConfigAp; struct dataConfigStruct dataConfigWs; struct dataConfigStruct dataConfigGm; struct dataConfigStruct dataConfigWv; struct swathConfigStruct swathConfigIm; struct swathConfigStruct swathConfigAp; struct swathConfigStruct swathConfigWs; struct swathConfigStruct swathConfigGm; struct swathConfigStruct swathConfigWv; unsigned short perCalWindowsEc; unsigned short perCalWindowsMs; struct swathIdStruct swathIdIm; struct swathIdStruct swathIdAp; struct swathIdStruct swathIdWs; struct swathIdStruct swathIdGm; struct swathIdStruct swathIdWv; unsigned short initCalBeamSetWv; unsigned short beamSetEc; unsigned short beamSetMs; unsigned short calSeq[ 32 ]; struct timelineStruct timelineIm; struct timelineStruct timelineAp; struct timelineStruct timelineWs; struct timelineStruct timelineGm; struct timelineStruct timelineWv; unsigned short mEc; char spare2[ 44 ]; float refElevAngleIs1; float refElevAngleIs2; float refElevAngleIs3Ss2; float refElevAngleIs4Ss3; float refElevAngleIs5Ss4; float refElevAngleIs6Ss5; float refElevAngleIs7; float refElevAngleSs1; char spare3[ 64 ]; float calLoopRefIs1[ 128 ]; float calLoopRefIs2[ 128 ]; float calLoopRefIs3Ss2[ 128 ]; float calLoopRefIs4Ss3[ 128 ]; float calLoopRefIs5Ss4[ 128 ]; float calLoopRefIs6Ss5[ 128 ]; float calLoopRefIs7[ 128 ]; float calLoopRefSs1[ 128 ]; char spare4[ 5120 ]; struct testStruct im; struct testStruct ap; struct testStruct ws; struct testStruct gm; struct testStruct wv; float swstCalP2; char spare5[ 72 ]; }; typedef struct { int samples; int lines; }ImageOutput ; // added by <NAME> on 16/02/2005 typedef enum EPR_DataTypeId EPR_EDataTypeId; typedef int boolean; typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; /* function prototypes */ struct mphStruct readMph( const char *mphPtr, const int printMphIfZero ); struct sphStruct readSph( const char *sphPtr, const int printSphIfZero, const struct mphStruct mph ); struct sphAuxStruct readSphAux( const char *sphPtr, const int printSphIfZero, const struct mphStruct mph ); struct insGadsStruct readInsGads( const char *gadsPtr, const int printInsGadsIfZero ); void printInsGads( const struct insGadsStruct ); // added by <NAME> on 16/02/2005 int is_bigendian(); void byte_swap_short(short *buffer, uint number_of_swaps); void byte_swap_ushort(ushort* buffer, uint number_of_swaps); void byte_swap_long(long *buffer, uint number_of_swaps); void byte_swap_ulong(ulong* buffer, uint number_of_swaps); void byte_swap_float(float* buffer, uint number_of_swaps); /* new byte_swap_int type added below*/ void byte_swap_int(int *buffer, uint number_of_swaps); void byte_swap_uint(uint *buffer, uint number_of_swaps); /* new byte_swap_uint type added above*/ void swap_endian_order(EPR_EDataTypeId data_type_id, void* elems, uint num_elems); void byte_swap_InsGads( struct insGadsStruct* InsGads ); /**********************************************************************************************************************************/ void asa_im_decode(char *imFileName, char *insFileName, char *outFileName, char * timesOutFileName, int outType, unsigned short windowStartTimeCodeword0, int daysToRemove, int *samples, int *lines) { /* variable definitions */ FILE *imFilePtr; FILE *outFilePtr; FILE *blockIdFilePtr; FILE *insFilePtr; FILE * dsrfp; //char imFileName[ 200 ]; //char outFileName[ 200 ]; char blockIdFileName[ 200 ] = "blockId"; //char insFileName[ 200 ]; char *mphPtr; char *sphPtr; char *gadsPtr; unsigned char onBoardTimeLSB; unsigned char auxTxMonitorLevel; unsigned char mdsrBlockId[ 200 ]; unsigned char mdsrCheck[ 63 ]; unsigned char beamAdjDeltaCodeword; unsigned char compressionRatio; unsigned char echoFlag; unsigned char noiseFlag; unsigned char calFlag; unsigned char calType; unsigned char spare; unsigned char antennaBeamSetNumber; unsigned char TxPolarization; unsigned char RxPolarization; unsigned char calibrationRowNumber; unsigned char chirpPulseBandwidthCodeword; unsigned char mdsrLineChar[ 20000 ]; int printImMphIfZero = 1; int printImSphIfZero = 1; int printImMdsrIfZero = 1; int printInsMphIfZero = 1; int printInsSphIfZero = 1; int printInsGadsIfZero = 1; int printBlockIdIfZero = 1; int noAdcIfZero = 1; int firstTimeEqualsZero = 0; int mphSize = 1247; /* fixed size */ int outSamples = 0; int outLines = 0; int sampleShift = 0; int bytesRead = 0; int nonOverlappingLineIfZero = 0; //int outType = 4; int i; int ii; int j; int k; int m; int n; int numFiles = 1; int mdsrDsrTimeDays; int mdsrDsrTimeSeconds; int mdsrDsrTimeMicroseconds; int mdsrGsrtTimeDays; int mdsrGsrtTimeSeconds; int mdsrGsrtTimeMicroseconds; int mdsrLineInt; unsigned int modePacketCount; unsigned int modePacketCountOld; unsigned int onBoardTimeIntegerSeconds = 0; short upConverterLevel; short downConverterLevel; unsigned short resamplingFactor; unsigned short onBoardTimeMSW; unsigned short onBoardTimeLSW; unsigned short mdsrIspLength; unsigned short mdsrCrcErrs; unsigned short mdsrRsErrs; unsigned short mdsrSpare1; unsigned short mdsrPacketIdentification; unsigned short mdsrPacketSequenceControl; unsigned short mdsrPacketLength; unsigned short mdsrPacketDataHeader[ 15 ]; unsigned short onBoardTimeFractionalSecondsInt = 0; unsigned short TxPulseLengthCodeword; unsigned short priCodeword; unsigned short priCodewordOld; unsigned short priCodewordOldOld; unsigned short windowStartTimeCodeword; //unsigned short windowStartTimeCodeword0; unsigned short windowStartTimeCodewordOld; unsigned short windowStartTimeCodewordOldOld; unsigned short windowLengthCodeword; unsigned short dataFieldHeaderLength; unsigned short modeID; unsigned short cyclePacketCount; float LUTi[ 4096 ]; float LUTq[ 4096 ]; float mdsrLine[ 20000 ]; double dateAux[2]; double onBoardTimeFractionalSeconds; double TxPulseLength; double beamAdjDelta; double chirpPulseBandwidth; double c = 299792458.; double timeCode; double pri; double windowStartTime; double windowLength; struct mphStruct mph; struct mphStruct mphIns; struct sphStruct sph; struct sphAuxStruct sphIns; struct insGadsStruct insGads; int is_littlendian; /* usage note //printf( "\n*** asa_im_decode v1.0 by smb ***\n\n" ); printf( "\n*** asa_im_decode v1.1 by smb ***\n\n" ); if ( (argc-1) < 5 ) { printf( "Decodes Envisat ASAR Image Mode Level 0 data.\n\n" ); printf( "Usage: asa_im_decode <asa_im> <asa_ins> <out> <outType> <swst>\n\n" ); printf( " asa_im input image file(s) (multiple files if merging along-track)\n" ); printf( " asa_ins input auxilary instrument characterization data file\n" ); printf( " out output raw data file\n" ); printf( " outType output file type (1=byte,4=float)\n" ); printf( " swst window start time codeword to which to set all lines (0=use first line start time)\n\n" ); printf( "Notes:\n\n" ); printf( "out is a complex file with no headers (byte/float I1, byte/float Q1, byte/float I2, byte/float Q2, ...)\n\n" ); printf( "if outType is byte, then the decoded floats are multiplied by 127.5, shifted by 127.5, rounded to the nearest integer and limited to the range 0-255\n\n" ); printf( "starting range computed as (rank*pri+windowStartTime)*c/2 where rank is the number of pri between transmitted pulse and return echo\n\n" ); printf( "calibration/noise lines are replaced with previous echo data line\n\n" ); printf( "missing lines within a data set and between adjacent along-track data sets are filled with zeroes in float mode and 0.*127.5+127.5 + .5 = 128 for byte mode\n\n" ); printf( "auxilary data files can be found at http://envisat.esa.int/services/auxiliary_data/asar/\n\n" ); printf( "Envisat ASAR Product Handbook, Issue 1.1, 1 December 2002 can be found at http://envisat.esa.int/dataproducts/asar/CNTR6-3-6.htm#eph.asar.asardf.0pASA_IM__0P\n\n" ); return 0; }*/ /* These are passed in now */ /* read in command-line arguments numFiles = (argc-1) - 4; sscanf( argv[ numFiles+1 ], "%s", insFileName ); sscanf( argv[ numFiles+2 ], "%s", outFileName ); sscanf( argv[ numFiles+3 ], "%d", &outType ); sscanf( argv[ numFiles+4 ], "%hd", &windowStartTimeCodeword0 ); debug numFiles = 1; sscanf( "D:\\data\\scign\\ASAR_RAW\\09786-2925-20040113\\ASA_IM__0CNPDK20040113_180720_000000152023_00213_09786_1579.N1", "%s", insFileName ); sscanf( "D:\\data\\scign\\ASARAux\\ASA_INS_AXVIEC20031209_113421_20030211_000000_20041231_000000", "%s", insFileName ); sscanf( "D:\\temp\\tmp_IMAGERY.raw", "%s", outFileName ); sscanf( "1", "%d", &outType ); sscanf( "0", "%hd", &windowStartTimeCodeword0 ); printImMphIfZero = 0; printImSphIfZero = 0; printImMdsrIfZero = 1; printInsMphIfZero = 0; printInsSphIfZero = 0; printInsGadsIfZero = 0; printBlockIdIfZero = 0; */ /* modified the messages below EJF 2005/11/9 */ if (is_bigendian()) { printf("Running on big-endian CPU...\n"); is_littlendian = 0; } else { printf("Running on little-endian CPU...\n"); is_littlendian = 1; } /* open files */ outFilePtr = fopen( outFileName, "wb" ); if ( outFilePtr == NULL ) { printf( "*** ERROR - cannot open file: %s\n", outFileName ); printf( "\n" ); exit( -1 ); } if ( printBlockIdIfZero == 0 ) { blockIdFilePtr = fopen( blockIdFileName, "wb" ); if ( blockIdFilePtr == NULL ) { printf( "*** ERROR - cannot open file: %s\n", blockIdFileName ); printf( "\n" ); exit( -1 ); } } insFilePtr = fopen( insFileName, "rb" ); if ( insFilePtr == NULL ) { printf( "*** ERROR - cannot open file: %s\n", insFileName ); printf( "\n" ); exit( -1 ); } if((dsrfp=fopen(timesOutFileName, "wb"))==NULL) { printf("Cannot open file: %s\n",timesOutFileName); } /* read MPH of ins file */ printf( "Reading MPH of ins file...\n\n" ); mphPtr = ( char * ) malloc( sizeof( char ) * mphSize ); if ( mphPtr == NULL ){ printf( "ERROR - mph allocation memory\n" ); exit( -1 ); } if ( (fread( mphPtr, sizeof( char ), mphSize, insFilePtr ) ) != mphSize ){ printf( "ERROR - mph read error\n\n" ); exit( -1 ); } mphIns = readMph( mphPtr, printInsMphIfZero ); /* extract information from MPH */ free ( mphPtr ); /* read SPH from ins file */ printf( "Reading SPH from ins file...\n\n" ); sphPtr = ( char * ) malloc( sizeof( char ) * mphIns.sphSize ); if ( sphPtr == NULL ){ printf( "ERROR - sph allocation memory\n" ); exit( -1 ); } if ( (fread( sphPtr, sizeof( char ), mphIns.sphSize, insFilePtr ) ) != mphIns.sphSize ){ printf( "ERROR - sph read error\n\n" ); exit( -1 ); } sphIns = readSphAux( sphPtr, printInsSphIfZero, mphIns ); /* extract information from SPH */ free ( sphPtr ); /* read GADS from ins file */ printf( "Reading GADS from ins file...\n\n" ); /*gadsPtr = ( char * ) malloc( sizeof( char ) * sphIns.dsd[ 0 ].dsrSize ); if ( gadsPtr == NULL ){ printf( "ERROR - gads allocation memory\n" ); exit( -1 ); } //edited by <NAME> at UCL on 16/02/2005 if ( (fread( gadsPtr, sizeof( char ), sizeof( insGads ), insFilePtr ) ) != sizeof( insGads ) ){ printf( "sizeof( insGads ): %d\n", sizeof( insGads ) ); printf( "ERROR - gads read error\n\n" ); printf( "%d %d %d\n", 171648, sizeof ( insGads ), 171648-sizeof( insGads ) ); exit( -1 ); } insGads = readInsGads( gadsPtr, printInsGadsIfZero ); free (gadsPtr); */ if ( (fread( &insGads, sizeof( insGads ), 1, insFilePtr ) ) != 1 ){ printf( "sizeof( insGads ): %d\n", sizeof( insGads ) ); printf( "ERROR - gads read error\n\n" ); printf( "%d %d %d\n", 171648, sizeof ( insGads ), 171648-sizeof( insGads ) ); exit( -1 ); } if (is_littlendian) { byte_swap_InsGads( &insGads ); } if ( printInsGadsIfZero == 0 ) printInsGads( insGads ); fclose( insFilePtr ); /* fill LUTs */ for ( i = 0; i < 4096; i++ ) { if ( i < 2048 ) ii = i; else ii = 256*(23-(i/256))+(i%256); if ( noAdcIfZero == 0 ){ LUTi[ i ] = insGads.fbaq4NoAdc[ ii ]; LUTq[ i ] = insGads.fbaq4NoAdc[ ii ]; } else { LUTi[ i ] = insGads.fbaq4LutI[ ii ]; LUTq[ i ] = insGads.fbaq4LutQ[ ii ]; } } /* begin loop over files */ for ( ii = 0; ii < numFiles; ii++ ) { /* open image file */ //sscanf( argv[ ii+1 ], "%s", imFileName ); //debug // sscanf( "D:\\data\\scign\\ASAR_RAW\\09786-2925-20040113\\ASA_IM__0CNPDK20040113_180720_000000152023_00213_09786_1579.N1", "%s", imFileName ); imFilePtr = fopen( imFileName, "rb" ); if ( imFilePtr == NULL ) { printf( "*** ERROR - cannot open file: %s\n", imFileName ); printf( "\n" ); exit( -1 ); } /* read image MPH */ printf( "Reading image MPH...\n\n" ); mphPtr = ( char * ) malloc( sizeof( char ) * mphSize ); if ( mphPtr == NULL ){ printf( "ERROR - mph allocation memory\n" ); exit( -1 ); } if ( (fread( mphPtr, sizeof( char ), mphSize, imFilePtr ) ) != mphSize ){ printf( "ERROR - mph read error\n\n" ); exit( -1 ); } mph = readMph( mphPtr, printImMphIfZero ); /* extract information from MPH */ free ( mphPtr ); /* read image SPH */ printf( "Reading image SPH...\n\n" ); sphPtr = ( char * ) malloc( sizeof( char ) * mph.sphSize ); if ( sphPtr == NULL ){ printf( "ERROR - sph allocation memory\n" ); exit( -1 ); } if ( (fread( sphPtr, sizeof( char ), mph.sphSize, imFilePtr ) ) != mph.sphSize ){ printf( "ERROR - sph read error\n\n" ); exit( -1 ); } sph = readSph( sphPtr, printImSphIfZero, mph ); /* extract information from SPH */ free ( sphPtr ); /* read image MDSR from file */ printf( "Reading and decoding image MDSR...\n\n" ); bytesRead = 0; for ( i = 0; i < sph.dsd[ 0 ].numDsr; i++ ) { if ( (i+1)%1000 == 0 ) printf( "Line %5d\n", i+1 ); modePacketCountOld = modePacketCount; /* sensing time added by Level 0 processor, as converted from Satellite Binary Time (SBT) counter embedded in each ISP */ /** * Represents a binary time value field in ENVISAT records. * * <p> Refer to ENVISAT documentation for the exact definition of * this data type. */ /* long days; ulong seconds; ulong microseconds; */ bytesRead = bytesRead + 4 * fread( &mdsrDsrTimeDays, 4, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_long, &mdsrDsrTimeDays, 1); } /* header added to the ISP by the Front End Processor (FEP) */ bytesRead = bytesRead + 4 * fread( &mdsrDsrTimeSeconds, 4, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ulong, &mdsrDsrTimeSeconds, 1); } bytesRead = bytesRead + 4 * fread( &mdsrDsrTimeMicroseconds, 4, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ulong, &mdsrDsrTimeMicroseconds, 1); } /* jng . save the pulsetiming in a aux file. same day in year and microsec in day * modified to be able to compute a more precise sensingStart */ dateAux[0] = 1.*(mdsrDsrTimeDays - daysToRemove);//day is in Mod Gregorian 2000. we only need days in the year, so remove day since 2000 dateAux[1] = 1000000.*mdsrDsrTimeSeconds + mdsrDsrTimeMicroseconds; fwrite(dateAux,sizeof(double),2,dsrfp); bytesRead = bytesRead + 4 * fread( &mdsrGsrtTimeDays, 4, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_long, &mdsrGsrtTimeDays, 1); } bytesRead = bytesRead + 4 * fread( &mdsrGsrtTimeSeconds, 4, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ulong, &mdsrGsrtTimeSeconds, 1); } bytesRead = bytesRead + 4 * fread( &mdsrGsrtTimeMicroseconds, 4, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ulong, &mdsrGsrtTimeMicroseconds, 1); } bytesRead = bytesRead + 2 * fread( &mdsrIspLength, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrIspLength, 1); } bytesRead = bytesRead + 2 * fread( &mdsrCrcErrs, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrCrcErrs, 1); } bytesRead = bytesRead + 2 * fread( &mdsrRsErrs, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrRsErrs, 1); } bytesRead = bytesRead + 2 * fread( &mdsrSpare1, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrSpare1, 1); } /* 6-byte ISP Packet Header */ bytesRead = bytesRead + 2 * fread( &mdsrPacketIdentification, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrPacketIdentification, 1); } bytesRead = bytesRead + 2 * fread( &mdsrPacketSequenceControl, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrPacketSequenceControl, 1); } bytesRead = bytesRead + 2 * fread( &mdsrPacketLength, 2, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrPacketLength, 1); } /* 30-byte Data Field Header in Packet Data Field */ bytesRead = bytesRead + 30 * fread( &mdsrPacketDataHeader, 30, 1, imFilePtr ); if (is_littlendian) { swap_endian_order(e_tid_ushort, &mdsrPacketDataHeader, 15); } priCodewordOldOld = priCodewordOld; windowStartTimeCodewordOldOld = windowStartTimeCodewordOld; priCodewordOld = priCodeword; windowStartTimeCodewordOld = windowStartTimeCodeword; dataFieldHeaderLength = mdsrPacketDataHeader[ 0 ]; modeID = mdsrPacketDataHeader[ 1 ]; onBoardTimeMSW = mdsrPacketDataHeader[ 2 ]; onBoardTimeLSW = mdsrPacketDataHeader[ 3 ]; onBoardTimeLSB = (unsigned char) ( ( mdsrPacketDataHeader[ 4 ] >> 8 ) & 255); modePacketCount = mdsrPacketDataHeader[ 5 ]*256 + ((mdsrPacketDataHeader[ 6 ] >> 8 ) & 255); antennaBeamSetNumber = (unsigned char) ( ( mdsrPacketDataHeader[ 6 ] >> 2 ) & 63); compressionRatio = (unsigned char) ( ( mdsrPacketDataHeader[ 6 ] ) & 3); /* 1 is 8/4 compression */ echoFlag = (unsigned char) ( ( mdsrPacketDataHeader[ 7 ] >> 15 ) & 1); noiseFlag = (unsigned char) ( ( mdsrPacketDataHeader[ 7 ] >> 14 ) & 1); calFlag = (unsigned char) ( ( mdsrPacketDataHeader[ 7 ] >> 13 ) & 1); calType = (unsigned char) ( ( mdsrPacketDataHeader[ 7 ] >> 12 ) & 1); cyclePacketCount = ( mdsrPacketDataHeader[ 7 ] & 4095); priCodeword = mdsrPacketDataHeader[ 8 ]; windowStartTimeCodeword = mdsrPacketDataHeader[ 9 ]; windowLengthCodeword = mdsrPacketDataHeader[ 10 ]; upConverterLevel = (short) ( ( mdsrPacketDataHeader[ 11 ] >> 12 ) & 15); downConverterLevel = (short) ( ( mdsrPacketDataHeader[ 11 ] >> 7 ) & 31); TxPolarization = (unsigned char) ( ( mdsrPacketDataHeader[ 11 ] >> 6 ) & 1); RxPolarization = (unsigned char) ( ( mdsrPacketDataHeader[ 11 ] >> 5 ) & 1); calibrationRowNumber = (unsigned char) ( ( mdsrPacketDataHeader[ 11 ] ) & 31); TxPulseLengthCodeword = (unsigned short)( ( mdsrPacketDataHeader[ 12 ] >> 6 ) & 1023); beamAdjDeltaCodeword = (unsigned char) ( ( mdsrPacketDataHeader[ 12 ] ) & 63); chirpPulseBandwidthCodeword = (unsigned char) ( ( mdsrPacketDataHeader[ 13 ] >> 8 ) & 255); auxTxMonitorLevel = (unsigned char) ( ( mdsrPacketDataHeader[ 13 ] ) & 255); resamplingFactor = mdsrPacketDataHeader[ 14 ]; if ( printImMdsrIfZero == 0 ) { onBoardTimeIntegerSeconds = (unsigned int) (onBoardTimeMSW*256 + ( ( onBoardTimeLSW >> 8 ) & 255 ) ); onBoardTimeFractionalSecondsInt = (unsigned short) ((onBoardTimeLSW & 255)*256 + onBoardTimeLSB); /* onBoardTimeFractionalSeconds = (double) ((double)onBoardTimeFractionalSecondsInt/65536.); */ printf( "%6d %2u %2x %8d %5d %d %d %d %d %d %d %d %4d %5d %5d %5d %2d %2d %1d %1d %2u %4d %2d %3d %3d %5d\n", i+1, dataFieldHeaderLength, modeID, onBoardTimeIntegerSeconds, onBoardTimeFractionalSecondsInt, modePacketCount, antennaBeamSetNumber, compressionRatio, echoFlag, noiseFlag, calFlag, calType, cyclePacketCount, priCodeword, windowStartTimeCodeword, windowLengthCodeword, upConverterLevel, downConverterLevel, TxPolarization, RxPolarization, calibrationRowNumber, TxPulseLengthCodeword, beamAdjDeltaCodeword, chirpPulseBandwidthCodeword, auxTxMonitorLevel, resamplingFactor ); } if (( modePacketCount == modePacketCountOld+1 ) || ( firstTimeEqualsZero == 0 )) { /* write out data */ if ( (echoFlag == 1) && (noiseFlag == 0) && (calFlag == 0) ){ if ( firstTimeEqualsZero == 0 ){ outSamples = ((mdsrIspLength+1-30)/64)*63 + ((mdsrIspLength+1-30)%64)-1; if ( windowStartTimeCodeword0 == 0 ) windowStartTimeCodeword0 = windowStartTimeCodeword; else if ( windowStartTimeCodeword0 != windowStartTimeCodeword ) printf( "Line %5d : windowStartTimeCodeword %5d : shifting this and subsequent data to %5d\n", i+1, windowStartTimeCodeword, windowStartTimeCodeword0 ); windowStartTimeCodewordOld = windowStartTimeCodeword; firstTimeEqualsZero = 1; } /* check a few things - still need to check TxPulseLength, chirpPulseBandwidthCodeword, beamAdjDeltaCodeword */ if ( ( i != 0 ) && ( priCodeword != priCodewordOld ) ) { printf( "Line %5d : priCodeword changes from %5d to %5d : no action taken\n", i+1, priCodewordOld, priCodeword ); } if ( windowStartTimeCodeword != windowStartTimeCodewordOld ) { printf( "Line %5d : windowStartTimeCodeword changes from %5d to %5d : shifting this and subsequent data to %5d\n", i+1, windowStartTimeCodewordOld, windowStartTimeCodeword, windowStartTimeCodeword0 ); } /* read 64-byte blocks */ for ( j = 0; j < (mdsrIspLength+1-30)/64; j++ ) { fread( &mdsrBlockId[ j ], sizeof( char ), 1, imFilePtr ); fread( &mdsrCheck, sizeof( char ), 63, imFilePtr ); bytesRead = bytesRead + 64; for ( k = 0; k < 63; k++ ) { mdsrLine[ 2*63*j+2*k ] = LUTi[ 256*(15-((mdsrCheck[ k ] >> 4) & 15))+mdsrBlockId[ j ] ]; mdsrLine[ 2*63*j+2*k+1 ] = LUTq[ 256*(15-( mdsrCheck[ k ] & 15))+mdsrBlockId[ j ] ]; /* if ( i == 0 ) { printf( "k,sample,blockId,i_in,q_in,i_out,q_out: %2d %4d %3d %2d %2d %15f %15f\n", k, 63*j+k, mdsrBlockId[ j ], ((mdsrCheck[ k ] >> 4) & 15), ( mdsrCheck[ k ] & 15), mdsrLine[ 2*k ], mdsrLine[ 2*k+1 ] ); } */ } } /* read partial last block */ fread( &mdsrBlockId[ j ], sizeof( char ), 1, imFilePtr ); fread( &mdsrCheck, sizeof( char ), ((mdsrIspLength+1-30)%64)-1, imFilePtr ); bytesRead = bytesRead + (mdsrIspLength+1-30)%64; for ( k = 0; k < ((mdsrIspLength+1-30)%64)-1; k++ ) { mdsrLine[ 2*63*j+2*k ] = LUTi[ 256*(15-((mdsrCheck[ k ] >> 4) & 15))+mdsrBlockId[ j ] ]; mdsrLine[ 2*63*j+2*k+1 ] = LUTq[ 256*(15-( mdsrCheck[ k ] & 15))+mdsrBlockId[ j ] ]; /* if ( i == 0 ) { printf( "k,sample,blockId,i_in,q_in,i_out,q_out: %2d %4d %3d %2d %2d %15f %15f\n", k, 63*j+k, mdsrBlockId[ j ], ((mdsrCheck[ k ] >> 4) & 15), ( mdsrCheck[ k ] & 15), mdsrLine[ 2*k ], mdsrLine[ 2*k+1 ] ); } */ } if ( windowStartTimeCodeword != windowStartTimeCodeword0 ) { sampleShift = windowStartTimeCodeword - windowStartTimeCodeword0; if ( sampleShift < 0 ) { for ( k = 0; k < outSamples+sampleShift; k++ ) { mdsrLine[ 2*k ] = mdsrLine[ 2*(k-sampleShift) ]; mdsrLine[ 2*k+1 ] = mdsrLine[ 2*(k-sampleShift)+1 ]; } for ( k = outSamples+sampleShift; k < outSamples; k++ ) { mdsrLine[ 2*k ] = 0.; mdsrLine[ 2*k+1 ] = 0.; } } else { for ( k = outSamples-1; k >= sampleShift; k-- ) { mdsrLine[ 2*k ] = mdsrLine[ 2*(k-sampleShift) ]; mdsrLine[ 2*k+1 ] = mdsrLine[ 2*(k-sampleShift)+1 ]; } for ( k = sampleShift-1; k >= 0; k-- ) { mdsrLine[ 2*k ] = 0.; mdsrLine[ 2*k+1 ] = 0.; } } } } else { /* skip ahead and write out previous line as a placeholder */ fseek( imFilePtr, mdsrIspLength+1-30, SEEK_CUR ); bytesRead = bytesRead + mdsrIspLength+1-30; } if ( printBlockIdIfZero == 0 ) { if ( (fwrite( &mdsrBlockId, sizeof( unsigned char ), outSamples/63+1, blockIdFilePtr ) ) != outSamples/63+1 ){ printf( "ERROR - blockIdFile write error\n\n" ); exit( -1 ); } } if ( outType == 1 ) { for ( k = 0; k < 2*outSamples; k++ ) { mdsrLineInt = (mdsrLine[ k ]*127.5+127.5) + .5; /* 5 for rounding */ if ( mdsrLineInt < 0 ) mdsrLineInt = 0; if ( mdsrLineInt > 255 ) mdsrLineInt = 255; mdsrLineChar[ k ] = mdsrLineInt; } if ( (fwrite( &mdsrLineChar, 2*sizeof( unsigned char ), outSamples, outFilePtr ) ) != outSamples ){ printf( "ERROR - outFile write error\n\n" ); exit( -1 ); } } else { if ( (fwrite( &mdsrLine, 2*sizeof( float ), outSamples, outFilePtr ) ) != outSamples ){ printf( "ERROR - outFile write error\n\n" ); exit( -1 ); } } outLines = outLines + 1; } else if ( modePacketCount > modePacketCountOld+1 ) { /* printf( "Line %5d : missing line - no action taken - %d %d\n", i+1, modePacketCount, modePacketCountOld ); fseek( imFilePtr, mdsrIspLength+1-30, SEEK_CUR ); bytesRead = bytesRead + mdsrIspLength+1-30; */ printf( "Line %5d : missing line(s) - filling with zeroes - %d %d\n", i+1, modePacketCount, modePacketCountOld ); for ( j = 0; j < (modePacketCount-modePacketCountOld-1); j++ ) { if ( outType == 1 ) { for ( k = 0; k < 2*outSamples; k++ ) { mdsrLineChar[ k ] = 128; /* (0.*127.5+127.5) + .5 */ } if ( (fwrite( &mdsrLineChar, 2*sizeof( unsigned char ), outSamples, outFilePtr ) ) != outSamples ){ printf( "ERROR - outFile write error\n\n" ); exit( -1 ); } } else { for ( k = 0; k < 2*outSamples; k++ ) { mdsrLine[ k ] = 0.; } if ( (fwrite( &mdsrLine, 2*sizeof( float ), outSamples, outFilePtr ) ) != outSamples ){ printf( "ERROR - outFile write error\n\n" ); exit( -1 ); } } outLines = outLines + 1; } modePacketCountOld = modePacketCount - 1; /* set up to re-read header and decode current line */ fseek( imFilePtr, -68, SEEK_CUR ); bytesRead = bytesRead - 68; modePacketCountOld = modePacketCountOld - 1; modePacketCount = modePacketCount - 1; priCodewordOld = priCodewordOldOld; priCodeword = priCodewordOld; windowStartTimeCodewordOld = windowStartTimeCodewordOldOld; windowStartTimeCodeword = windowStartTimeCodewordOld; i = i - 1; } else if ( modePacketCount < modePacketCountOld+1 ) { printf( "Line %5d : duplicate line\n", i+1 ); fseek( imFilePtr, mdsrIspLength+1-30, SEEK_CUR ); bytesRead = bytesRead + mdsrIspLength+1-30; modePacketCount = modePacketCountOld; } else { printf( "Line %5d : error - %d %d\n", i+1, modePacketCount, modePacketCountOld ); exit( -1 ); } } if ( (i-1+1)%1000 != 0 ) printf( "Line %5d\n\n", i-1+1 ); /* write out a few things */ /* pri = priCodeword / insGads.sampRate; windowStartTime = windowStartTimeCodeword0 / insGads.sampRate; TxPulseLength = TxPulseLengthCodeword / insGads.sampRate; chirpPulseBandwidth = (double)chirpPulseBandwidthCodeword*16.e6/255.; windowLength = windowLengthCodeword / insGads.sampRate; beamAdjDelta = (double)(beamAdjDeltaCodeword-32)*360./4096.; printf( "%s%d\n", "swathNum: ", insGads.timelineIm.swathNums[ antennaBeamSetNumber-1 ] ); printf( "%s%d\n", "mValue: ", insGads.timelineIm.mValues[ antennaBeamSetNumber-1 ] ); printf( "%s%d\n", "rValue: ", insGads.timelineIm.rValues[ antennaBeamSetNumber-1 ] ); printf( "%s%d\n", "gValue: ", insGads.timelineIm.gValues[ antennaBeamSetNumber-1 ] ); printf( "%s%.9g\n", "(rank*pri+windowStartTime)*c/2 (m): ", (insGads.timelineIm.rValues[ antennaBeamSetNumber-1 ]*pri+windowStartTime)*c/2. ); printf( "%s%.9g\n", "(last)windowStartTime*c/2 (m): ", windowStartTime*c/2. ); printf( "%s%.9g\n", "windowLength*c/2 (m): ", windowLength*c/2. ); printf( "%s%.9g\n", "rangeGateBias*c/2 (m): ", insGads.rangeGateBias*c/2. ); printf( "\nOutput information:\n\n" ); printf( "%s%d\n", "number of output samples: ", outSamples ); printf( "%s%d\n", "number of output lines: ", outLines ); printf( "%s%.9g\n", "chirp pulse bandwidth (Hz): ", chirpPulseBandwidth ); printf( "%s%.9g\n", "prf (Hz): ", 1./pri ); printf( "%s%.9g\n", "range sampling frequency (Hz): ", insGads.sampRate ); printf( "%s%.9g\n", "range sample spacing (m): ", c/(2.*insGads.sampRate)); printf( "%s%.9g\n", "chirp slope (Hz/s): ", chirpPulseBandwidth/TxPulseLength ); printf( "%s%.9g\n", "pulse length (s): ", TxPulseLength ); printf( "%s%.9g\n", "radar frequency (Hz): ", insGads.radarFrequency ); printf( "%s%.9g\n", "wavelength (m): ", c/insGads.radarFrequency ); printf( "%s%.9g\n", "starting range (m): ", (insGads.timelineIm.rValues[ antennaBeamSetNumber-1 ]*pri+windowStartTime)*c/2. ); printf( "\n" ); */ fclose( imFilePtr ); } /* write out a few things */ pri = priCodeword / insGads.sampRate; windowStartTime = windowStartTimeCodeword0 / insGads.sampRate; TxPulseLength = TxPulseLengthCodeword / insGads.sampRate; chirpPulseBandwidth = (double)chirpPulseBandwidthCodeword*16.e6/255.; /*//debug */ printf( "%s%d\n", "priCodeword=: ", priCodeword ); printf( "%s%.12f\n", "insGads.sampRate=: ", insGads.sampRate ); printf( "%s%.12f\n", "pri=: ", pri ); printf( "%s%d\n", "windowStartTimeCodeword0=:", windowStartTimeCodeword0); printf( "%s%.12f\n", "windowStartTime=: ", windowStartTime ); printf( "%s%.12f\n", "TxPulseLength=: ", TxPulseLength ); printf( "%s%.12f\n", "chirpPulseBandwidth=: ", chirpPulseBandwidth ); /* //end of debug */ printf( "\nOutput information:\n\n" ); printf( "%s%d\n", "number of output samples: ", outSamples ); printf( "%s%d\n", "number of output lines: ", outLines ); printf( "%s%.9g\n", "chirp pulse bandwidth (Hz): ", chirpPulseBandwidth ); printf( "%s%.9g\n", "prf (Hz): ", 1./pri ); printf( "%s%.9g\n", "range sampling frequency (Hz): ", insGads.sampRate ); printf( "%s%.9g\n", "range sample spacing (m): ", c/(2.*insGads.sampRate)); printf( "%s%.9g\n", "chirp slope (Hz/s): ", chirpPulseBandwidth/TxPulseLength ); printf( "%s%.9g\n", "pulse length (s): ", TxPulseLength ); printf( "%s%.9g\n", "radar frequency (Hz): ", insGads.radarFrequency ); printf( "%s%.9g\n", "wavelength (m): ", c/insGads.radarFrequency ); printf( "%s%.9g\n", "starting range (m): ", (insGads.timelineIm.rValues[ antennaBeamSetNumber-1 ]*pri+windowStartTime)*c/2. ); printf( "%s%.9g\n", "rangeGateBias*c/2 (m): ", insGads.rangeGateBias*c/2. ); printf( "\n" ); *samples = outSamples; *lines = outLines; /* end program */ //fclose(blockIdFilePtr); fclose( outFilePtr ); fclose( dsrfp ); printf( "\nDone.\n\n" ); return; // return imageOutput; } /* end main */ /**********************************************************************************************************************************/ struct mphStruct readMph( const char *mphPtr, const int printMphIfZero ) { struct mphStruct mph; if ( 1 == 0 ) { printf( "check:\n%s\n", mphPtr+1247 ); } memcpy( mph.product, mphPtr+ 0+ 9, 62 ); memcpy( mph.procStage, mphPtr+ 73+11, 1 ); memcpy( mph.refDoc, mphPtr+ 86+ 9, 23 ); memcpy( mph.spare1, mphPtr+ 120+ 0, 40 ); memcpy( mph.acquisitionStation, mphPtr+ 161+21, 20 ); memcpy( mph.procCenter, mphPtr+ 204+13, 6 ); memcpy( mph.procTime, mphPtr+ 225+11, 27 ); memcpy( mph.softwareVer, mphPtr+ 265+14, 14 ); memcpy( mph.spare2, mphPtr+ 295+ 0, 40 ); memcpy( mph.sensingStart, mphPtr+ 336+15, 27 ); memcpy( mph.sensingStop, mphPtr+ 380+14, 27 ); memcpy( mph.spare3, mphPtr+ 423+ 0, 40 ); memcpy( mph.phase, mphPtr+ 464+ 6, 1 ); mph.cycle = atoi( ( char * ) strchr( mphPtr+ 472+ 0, '=' )+1 ); mph.relOrbit = atoi( ( char * ) strchr( mphPtr+ 483+ 0, '=' )+1 ); mph.absOrbit = atoi( ( char * ) strchr( mphPtr+ 500+ 0, '=' )+1 ); memcpy( mph.stateVectorTime, mphPtr+ 517+19, 27 ); mph.deltaUt1 = atof( ( char * ) strchr( mphPtr+ 565+ 0, '=' )+1 ); mph.xPosition = atof( ( char * ) strchr( mphPtr+ 587+ 0, '=' )+1 ); mph.yPosition = atof( ( char * ) strchr( mphPtr+ 614+ 0, '=' )+1 ); mph.zPosition = atof( ( char * ) strchr( mphPtr+ 641+ 0, '=' )+1 ); mph.xVelocity = atof( ( char * ) strchr( mphPtr+ 668+ 0, '=' )+1 ); mph.yVelocity = atof( ( char * ) strchr( mphPtr+ 697+ 0, '=' )+1 ); mph.zVelocity = atof( ( char * ) strchr( mphPtr+ 726+ 0, '=' )+1 ); memcpy( mph.vectorSource, mphPtr+ 755+15, 2 ); memcpy( mph.spare4, mphPtr+ 774+ 0, 40 ); memcpy( mph.utcSbtTime, mphPtr+ 815+14, 27 ); mph.satBinaryTime = atoi( ( char * ) strchr( mphPtr+ 858+ 0, '=' )+1 ); mph.clockStep = atoi( ( char * ) strchr( mphPtr+ 886+ 0, '=' )+1 ); memcpy( mph.spare5, mphPtr+ 913+ 0, 32 ); memcpy( mph.leapUtc, mphPtr+ 946+10, 27 ); mph.leapSign = atoi( ( char * ) strchr( mphPtr+ 985+ 0, '=' )+1 ); mph.leapErr = atoi( ( char * ) strchr( mphPtr+1000+ 0, '=' )+1 ); memcpy( mph.spare6, mphPtr+1011+ 0, 40 ); mph.productErr = atoi( ( char * ) strchr( mphPtr+1052+ 0, '=' )+1 ); mph.totSize = atoi( ( char * ) strchr( mphPtr+1066+ 0, '=' )+1 ); mph.sphSize = atoi( ( char * ) strchr( mphPtr+1104+ 0, '=' )+1 ); mph.numDsd = atoi( ( char * ) strchr( mphPtr+1132+ 0, '=' )+1 ); mph.dsdSize = atoi( ( char * ) strchr( mphPtr+1152+ 0, '=' )+1 ); mph.numDataSets = atoi( ( char * ) strchr( mphPtr+1180+ 0, '=' )+1 ); memcpy( mph.spare7, mphPtr+1206+ 0, 40 ); if ( printMphIfZero == 0 ) { printf( "%s%.62s\n", "product: ", mph.product ); printf( "%s%.1s\n", "procStage: ", mph.procStage ); printf( "%s%.23s\n", "refDoc: ", mph.refDoc ); printf( "%s%.40s\n", "spare1: ", mph.spare1 ); printf( "%s%.20s\n", "acquisitionStation: ", mph.acquisitionStation ); printf( "%s%.6s\n", "procCenter: ", mph.procCenter ); printf( "%s%.27s\n", "procTime: ", mph.procTime ); printf( "%s%.14s\n", "softwareVer: ", mph.softwareVer ); printf( "%s%.40s\n", "spare2: ", mph.spare2 ); printf( "%s%.27s\n", "sensingStart: ", mph.sensingStart ); printf( "%s%.27s\n", "sensingStop: ", mph.sensingStop ); printf( "%s%.40s\n", "spare3: ", mph.spare3 ); printf( "%s%.1s\n", "phase: ", mph.phase ); printf( "%s%d\n", "cycle: ", mph.cycle ); printf( "%s%d\n", "relOrbit: ", mph.relOrbit ); printf( "%s%d\n", "absOrbit: ", mph.absOrbit ); printf( "%s%.27s\n", "stateVectorTime: ", mph.stateVectorTime ); printf( "%s%f\n", "deltaUt1: ", mph.deltaUt1 ); printf( "%s%f\n", "xPosition: ", mph.xPosition ); printf( "%s%f\n", "yPosition: ", mph.yPosition ); printf( "%s%f\n", "zPosition: ", mph.zPosition ); printf( "%s%f\n", "xVelocity: ", mph.xVelocity ); printf( "%s%f\n", "yVelocity: ", mph.yVelocity ); printf( "%s%f\n", "zVelocity: ", mph.zVelocity ); printf( "%s%.2s\n", "vectorSource: ", mph.vectorSource ); printf( "%s%.40s\n", "spare4: ", mph.spare4 ); printf( "%s%.27s\n", "utcSbtTime: ", mph.utcSbtTime ); printf( "%s%u\n", "satBinaryTime: ", mph.satBinaryTime ); printf( "%s%u\n", "clockStep: ", mph.clockStep ); printf( "%s%.32s\n", "spare5: ", mph.spare5 ); printf( "%s%.27s\n", "leapUtc: ", mph.leapUtc ); printf( "%s%d\n", "leapSign: ", mph.leapSign ); printf( "%s%d\n", "leapErr: ", mph.leapErr ); printf( "%s%.40s\n", "spare6: ", mph.spare6 ); printf( "%s%d\n", "productErr: ", mph.productErr ); printf( "%s%d\n", "totSize: ", mph.totSize ); printf( "%s%d\n", "sphSize: ", mph.sphSize ); printf( "%s%d\n", "numDsd: ", mph.numDsd ); printf( "%s%d\n", "dsdSize: ", mph.dsdSize ); printf( "%s%d\n", "numDataSets: ", mph.numDataSets ); printf( "%s%.40s\n", "spare7: ", mph.spare7 ); printf( "\n" ); } return mph; } /* end readMph */ /**********************************************************************************************************************************/ /**********************************************************************************************************************************/ struct sphStruct readSph( const char *sphPtr, const int printSphIfZero, const struct mphStruct mph ) { struct sphStruct sph; int i; memcpy( sph.sphDescriptor, sphPtr+ 0+16, 28 ); sph.startLat = atof( ( char * ) strchr( sphPtr+ 46+ 0, '=' )+1 ) * 1.e-6; sph.startLon = atof( ( char * ) strchr( sphPtr+ 78+ 0, '=' )+1 ) * 1.e-6; sph.stopLat = atof( ( char * ) strchr( sphPtr+111+ 0, '=' )+1 ) * 1.e-6; sph.stopLon = atof( ( char * ) strchr( sphPtr+142+ 0, '=' )+1 ) * 1.e-6; sph.satTrack = atof( ( char * ) strchr( sphPtr+174+ 0, '=' )+1 ); memcpy( sph.spare1, sphPtr+205+ 0, 50 ); sph.ispErrorsSignificant = atoi( ( char * ) strchr( sphPtr+256+ 0, '=' )+1 ); sph.missingIspsSignificant = atoi( ( char * ) strchr( sphPtr+281+ 0, '=' )+1 ); sph.ispDiscardedSignificant = atoi( ( char * ) strchr( sphPtr+308+ 0, '=' )+1 ); sph.rsSignificant = atoi( ( char * ) strchr( sphPtr+336+ 0, '=' )+1 ); memcpy( sph.spare2, sphPtr+353+ 0, 50 ); sph.numErrorIsps = atoi( ( char * ) strchr( sphPtr+404+ 0, '=' )+1 ); sph.errorIspsThresh = atof( ( char * ) strchr( sphPtr+431+ 0, '=' )+1 ); sph.numMissingIsps = atoi( ( char * ) strchr( sphPtr+468+ 0, '=' )+1 ); sph.missingIspsThresh = atof( ( char * ) strchr( sphPtr+497+ 0, '=' )+1 ); sph.numDiscardedIsps = atoi( ( char * ) strchr( sphPtr+536+ 0, '=' )+1 ); sph.discardedIspsThresh = atof( ( char * ) strchr( sphPtr+567+ 0, '=' )+1 ); sph.numRsIsps = atoi( ( char * ) strchr( sphPtr+608+ 0, '=' )+1 ); sph.rsThresh = atof( ( char * ) strchr( sphPtr+632+ 0, '=' )+1 ); memcpy( sph.spare3, sphPtr+661+ 0, 100 ); memcpy( sph.txRxPolar, sphPtr+762+13, 5 ); memcpy( sph.swath, sphPtr+782+ 7, 3 ); memcpy( sph.spare4, sphPtr+794+ 0, 41 ); if ( 1 == 0 ) { printf( "check:\n%s\n", sphPtr+836+ 0 ); } if ( printSphIfZero == 0 ) { printf( "%s%.28s\n", "sphDescriptor: ", sph.sphDescriptor ); printf( "%s%f\n", "startLat: ", sph.startLat ); printf( "%s%f\n", "startLon: ", sph.startLon ); printf( "%s%f\n", "stopLat: ", sph.stopLat ); printf( "%s%f\n", "stopLon: ", sph.stopLon ); printf( "%s%f\n", "satTrack: ", sph.satTrack ); printf( "%s%.50s\n", "spare1: ", sph.spare1 ); printf( "%s%d\n", "ispErrorsSignificant: ", sph.ispErrorsSignificant ); printf( "%s%d\n", "missingIspsSignificant: ", sph.missingIspsSignificant ); printf( "%s%d\n", "ispDiscardedSignificant: ", sph.ispDiscardedSignificant ); printf( "%s%d\n", "rsSignificant: ", sph.rsSignificant ); printf( "%s%.50s\n", "spare2: ", sph.spare2 ); printf( "%s%d\n", "numErrorIsps: ", sph.numErrorIsps ); printf( "%s%f\n", "errorIspsThresh: ", sph.errorIspsThresh ); printf( "%s%d\n", "numMissingIsps: ", sph.numMissingIsps ); printf( "%s%f\n", "missingIspsThresh: ", sph.missingIspsThresh ); printf( "%s%d\n", "numDiscardedIsps: ", sph.numDiscardedIsps ); printf( "%s%f\n", "discardedIspsThresh: ", sph.discardedIspsThresh ); printf( "%s%d\n", "numRsIsps: ", sph.numRsIsps ); printf( "%s%f\n", "rsThresh: ", sph.rsThresh ); printf( "%s%.100s\n", "spare3: ", sph.spare3 ); printf( "%s%.5s\n", "txRxPolar: ", sph.txRxPolar ); printf( "%s%.3s\n", "swath: ", sph.swath ); printf( "%s%.41s\n", "spare4: ", sph.spare4 ); } for ( i = 0; i < mph.numDsd; i++ ){ /* extract DSDs from SPH */ if ( i != 3 ) { /* fourth is a spare DSD - see pdf page 537 */ if (1 == 0) { printf( "check:\n%s\n", sphPtr+836+mph.dsdSize*i+ 0+ 0 ); } memcpy( sph.dsd[ i ].dsName, sphPtr+836+mph.dsdSize*i+ 0+ 9, 28 ); memcpy( sph.dsd[ i ].dsType, sphPtr+836+mph.dsdSize*i+ 39+ 8, 1 ); memcpy( sph.dsd[ i ].filename, sphPtr+836+mph.dsdSize*i+ 49+10, 62 ); sph.dsd[ i ].dsOffset = atoi( ( char * ) strchr( sphPtr+836+mph.dsdSize*i+123+ 0, '=' )+1 ); sph.dsd[ i ].dsSize = atoi( ( char * ) strchr( sphPtr+836+mph.dsdSize*i+162+ 0, '=' )+1 ); sph.dsd[ i ].numDsr = atoi( ( char * ) strchr( sphPtr+836+mph.dsdSize*i+199+ 0, '=' )+1 ); sph.dsd[ i ].dsrSize = atoi( ( char * ) strchr( sphPtr+836+mph.dsdSize*i+219+ 0, '=' )+1 ); /* write out a few things */ if ( printSphIfZero == 0 ) { printf( "%s%d%s%.28s\n", "dsd[ ", i, " ].dsName: ", sph.dsd[ i ].dsName ); printf( "%s%d%s%.1s\n", "dsd[ ", i, " ].dsType: ", sph.dsd[ i ].dsType ); printf( "%s%d%s%.62s\n", "dsd[ ", i, " ].filename: ", sph.dsd[ i ].filename ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].dsOffset: ", sph.dsd[ i ].dsOffset ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].dsSize: ", sph.dsd[ i ].dsSize ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].numDsr: ", sph.dsd[ i ].numDsr ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].dsrSize: ", sph.dsd[ i ].dsrSize ); } } } if ( printSphIfZero == 0 ) { printf( "\n" ); } return sph; } /* end readSph */ /**********************************************************************************************************************************/ /**********************************************************************************************************************************/ struct sphAuxStruct readSphAux( const char *sphPtr, const int printSphIfZero, const struct mphStruct mph ) { struct sphAuxStruct sph; int i; memcpy( sph.sphDescriptor, sphPtr+ 0+16, 28 ); memcpy( sph.spare1, sphPtr+46+ 0, 51 ); if ( printSphIfZero == 0 ) { printf( "%s%.28s\n", "sphDescriptor: ", sph.sphDescriptor ); printf( "%s%.51s\n", "spare1: ", sph.spare1 ); } for ( i = 0; i < mph.numDsd; i++ ){ /* extract DSDs from SPH */ memcpy( sph.dsd[ i ].dsName, sphPtr+ 98+mph.dsdSize*i+ 0+ 9, 28 ); memcpy( sph.dsd[ i ].dsType, sphPtr+ 98+mph.dsdSize*i+ 39+ 8, 1 ); memcpy( sph.dsd[ i ].filename, sphPtr+ 98+mph.dsdSize*i+ 49+10, 62 ); sph.dsd[ i ].dsOffset = atoi( ( char * ) strchr( sphPtr+ 98+mph.dsdSize*i+123+ 0, '=' )+1 ); sph.dsd[ i ].dsSize = atoi( ( char * ) strchr( sphPtr+ 98+mph.dsdSize*i+162+ 0, '=' )+1 ); sph.dsd[ i ].numDsr = atoi( ( char * ) strchr( sphPtr+ 98+mph.dsdSize*i+199+ 0, '=' )+1 ); sph.dsd[ i ].dsrSize = atoi( ( char * ) strchr( sphPtr+ 98+mph.dsdSize*i+219+ 0, '=' )+1 ); /* write out a few things */ if ( printSphIfZero == 0 ) { printf( "%s%d%s%.28s\n", "dsd[ ", i, " ].dsName: ", sph.dsd[ i ].dsName ); printf( "%s%d%s%.1s\n", "dsd[ ", i, " ].dsType: ", sph.dsd[ i ].dsType ); printf( "%s%d%s%.62s\n", "dsd[ ", i, " ].filename: ", sph.dsd[ i ].filename ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].dsOffset: ", sph.dsd[ i ].dsOffset ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].dsSize: ", sph.dsd[ i ].dsSize ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].numDsr: ", sph.dsd[ i ].numDsr ); printf( "%s%d%s%d\n", "dsd[ ", i, " ].dsrSize: ", sph.dsd[ i ].dsrSize ); } } if ( printSphIfZero == 0 ) { printf( "\n" ); } return sph; } /* end readSphAux */ /**********************************************************************************************************************************/ /**********************************************************************************************************************************/ void printInsGads( const struct insGadsStruct insGads ) { int i; printf( "%s%d\n", "dsrTime.days: ", insGads.dsrTime.days ); printf( "%s%d\n", "dsrTime.seconds: ", insGads.dsrTime.seconds ); printf( "%s%d\n", "dsrTime.microseconds: ", insGads.dsrTime.microseconds ); printf( "%s%d\n", "dsrLength: ", insGads.dsrLength ); printf( "%s%.9g\n", "radarFrequency: ", insGads.radarFrequency ); printf( "%s%.9g\n", "sampRate: ", insGads.sampRate ); printf( "%s%.9g\n", "offsetFreq: ", insGads.offsetFreq ); printf( "%s%.9g\n", "rangeGateBias: ", insGads.rangeGateBias ); printf( "%s%.9g\n", "rangeGateBiasGm: ", insGads.rangeGateBiasGm ); printf( "%s%f\n", "refElevAngleIs1: ", insGads.refElevAngleIs1 ); printf( "%s%f\n", "refElevAngleIs2: ", insGads.refElevAngleIs2 ); printf( "%s%f\n", "refElevAngleIs3Ss2: ", insGads.refElevAngleIs3Ss2 ); printf( "%s%f\n", "refElevAngleIs4Ss3: ", insGads.refElevAngleIs4Ss3 ); printf( "%s%f\n", "refElevAngleIs5Ss4: ", insGads.refElevAngleIs5Ss4 ); printf( "%s%f\n", "refElevAngleIs6Ss5: ", insGads.refElevAngleIs6Ss5 ); printf( "%s%f\n", "refElevAngleIs7: ", insGads.refElevAngleIs7 ); printf( "%s%f\n", "refElevAngleSs1: ", insGads.refElevAngleSs1 ); printf( "%s%.9g\n", "swstCalP2: ", insGads.swstCalP2 ); printf( "%s%u\n", "perCalWindowsEc: ", insGads.perCalWindowsEc ); printf( "%s%u\n", "perCalWindowsMs: ", insGads.perCalWindowsMs ); printf( "%s%u\n", "initCalBeamSetWv: ", insGads.initCalBeamSetWv ); printf( "%s%u\n", "beamSetEc: ", insGads.beamSetEc ); printf( "%s%u\n", "beamSetMs: ", insGads.beamSetMs ); printf( "%s%u\n", "mEc: ", insGads.mEc ); printf( ".\n" ); printf( ".\n" ); printf( ".\n" ); for ( i = 0; i < 4096; i++ ) printf( "%s%4d%s%15f %15f %15f\n", "fbaq4LutI,Q,NoAdc[ ", i, " ]: ", insGads.fbaq4LutI[ i ], insGads.fbaq4LutQ[ i ], insGads.fbaq4NoAdc[ i ] ); printf( ".\n" ); printf( ".\n" ); printf( ".\n" ); printf( "\n" ); /* exit( 0 ); */ return; } /* end printInsGads */ /**********************************************************************************************************************************/ /**********************************************************************************************************************************/ /********************************************************** ** Function: byte_swap_InsGads ** ** Purpose: Convert the bytes of struct insGadsStruct for a little endian order machine ** ** Comment: struct testStruct should be redefined in the future! ** ** Author: <NAME> at UCL ** ** Created: 17/02/2005 ** ** Modified: ** ;**********************************************************/ void byte_swap_InsGads( struct insGadsStruct* InsGads ) { swap_endian_order(e_tid_long, &(*InsGads).dsrTime, 3); swap_endian_order(e_tid_ulong, &(*InsGads).dsrLength, 1); swap_endian_order(e_tid_float, &(*InsGads).radarFrequency, 1); swap_endian_order(e_tid_float, &(*InsGads).sampRate, 1); swap_endian_order(e_tid_float, &(*InsGads).offsetFreq, 1); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0TxH1, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0TxV1, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0TxH1a, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0TxV1a, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0RxH2, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0RxV2, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0H3, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseIm0V3, 64); swap_endian_order(e_tid_float, &(*InsGads).calPulseImTxH1, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImTxV1, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImTxH1a, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImTxV1a, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImRxH2, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImRxV2, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImH3, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseImV3, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApTxH1, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApTxV1, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApTxH1a, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApTxV1a, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApRxH2, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApRxV2, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApH3, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseApV3, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvTxH1, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvTxV1, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvTxH1a, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvTxV1a, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvRxH2, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvRxV2, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvH3, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWvV3, 448); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsTxH1, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsTxV1, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsTxH1a, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsTxV1a, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsRxH2, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsRxV2, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsH3, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseWsV3, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmTxH1, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmTxV1, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmTxH1a, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmTxV1a, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmRxH2, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmRxV2, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmH3, 320); swap_endian_order(e_tid_float, &(*InsGads).calPulseGmV3, 320); swap_endian_order(e_tid_float, &(*InsGads).nomPulseIm, 63); swap_endian_order(e_tid_float, &(*InsGads).nomPulseAp, 63); swap_endian_order(e_tid_float, &(*InsGads).nomPulseWv, 63); swap_endian_order(e_tid_float, &(*InsGads).nomPulseWs, 45); swap_endian_order(e_tid_float, &(*InsGads).nomPulseGm, 45); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs1, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs2, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs3Ss2, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs4Ss3, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs5Ss4, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs6Ss5, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternIs7, 101); swap_endian_order(e_tid_float, &(*InsGads).azPatternSs1, 101); swap_endian_order(e_tid_float, &(*InsGads).rangeGateBias, 1); swap_endian_order(e_tid_float, &(*InsGads).rangeGateBiasGm, 1); swap_endian_order(e_tid_float, &(*InsGads).adcLutI, 255); swap_endian_order(e_tid_float, &(*InsGads).adcLutQ, 255); swap_endian_order(e_tid_float, &(*InsGads).full8LutI, 256); swap_endian_order(e_tid_float, &(*InsGads).full8LutQ, 256); swap_endian_order(e_tid_float, &(*InsGads).fbaq4LutI, 4096); swap_endian_order(e_tid_float, &(*InsGads).fbaq3LutI, 2048); swap_endian_order(e_tid_float, &(*InsGads).fbaq2LutI, 1024); swap_endian_order(e_tid_float, &(*InsGads).fbaq4LutQ, 4096); swap_endian_order(e_tid_float, &(*InsGads).fbaq3LutQ, 2048); swap_endian_order(e_tid_float, &(*InsGads).fbaq2LutQ, 1024); swap_endian_order(e_tid_float, &(*InsGads).fbaq4NoAdc, 4096); swap_endian_order(e_tid_float, &(*InsGads).fbaq3NoAdc, 2048); swap_endian_order(e_tid_float, &(*InsGads).fbaq2NoAdc, 1024); swap_endian_order(e_tid_float, &(*InsGads).smLutI, 16); swap_endian_order(e_tid_float, &(*InsGads).smLutQ, 16); swap_endian_order(e_tid_ushort, &(*InsGads).swathConfigIm, 28); swap_endian_order(e_tid_float, &(*InsGads).swathConfigIm.resampleFactor, 7); swap_endian_order(e_tid_ushort, &(*InsGads).swathConfigAp, 28); swap_endian_order(e_tid_float, &(*InsGads).swathConfigAp.resampleFactor, 7); swap_endian_order(e_tid_ushort, &(*InsGads).swathConfigWs, 28); swap_endian_order(e_tid_float, &(*InsGads).swathConfigWs.resampleFactor, 7); swap_endian_order(e_tid_ushort, &(*InsGads).swathConfigGm, 28); swap_endian_order(e_tid_float, &(*InsGads).swathConfigGm.resampleFactor, 7); swap_endian_order(e_tid_ushort, &(*InsGads).swathConfigWv, 28); swap_endian_order(e_tid_float, &(*InsGads).swathConfigWv.resampleFactor, 7); swap_endian_order(e_tid_ushort, &(*InsGads).perCalWindowsEc, 1); swap_endian_order(e_tid_ushort, &(*InsGads).perCalWindowsMs, 1); swap_endian_order(e_tid_ushort, &(*InsGads).swathIdIm, 14); swap_endian_order(e_tid_ushort, &(*InsGads).swathIdAp, 14); swap_endian_order(e_tid_ushort, &(*InsGads).swathIdWs, 14); swap_endian_order(e_tid_ushort, &(*InsGads).swathIdGm, 14); swap_endian_order(e_tid_ushort, &(*InsGads).swathIdWv, 14); swap_endian_order(e_tid_ushort, &(*InsGads).initCalBeamSetWv, 1); swap_endian_order(e_tid_ushort, &(*InsGads).beamSetEc, 1); swap_endian_order(e_tid_ushort, &(*InsGads).beamSetMs, 1); swap_endian_order(e_tid_ushort, &(*InsGads).calSeq, 32); swap_endian_order(e_tid_ushort, &(*InsGads).timelineIm, 28); swap_endian_order(e_tid_ushort, &(*InsGads).timelineAp, 28); swap_endian_order(e_tid_ushort, &(*InsGads).timelineWs, 28); swap_endian_order(e_tid_ushort, &(*InsGads).timelineGm, 28); swap_endian_order(e_tid_ushort, &(*InsGads).timelineWv, 28); swap_endian_order(e_tid_ushort, &(*InsGads).mEc, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs1, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs2, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs3Ss2, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs4Ss3, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs5Ss4, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs6Ss5, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleIs7, 1); swap_endian_order(e_tid_float, &(*InsGads).refElevAngleSs1, 1); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs1, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs2, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs3Ss2, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs4Ss3, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs5Ss4, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs6Ss5, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefIs7, 128); swap_endian_order(e_tid_float, &(*InsGads).calLoopRefSs1, 128); //struct testStruct should be redefined in the future. swap_endian_order(e_tid_float, &(*InsGads).im, 17); swap_endian_order(e_tid_float, &(*InsGads).ap, 17); swap_endian_order(e_tid_float, &(*InsGads).ws, 17); swap_endian_order(e_tid_float, &(*InsGads).gm, 17); swap_endian_order(e_tid_float, &(*InsGads).wv, 17); swap_endian_order(e_tid_float, &(*InsGads).swstCalP2, 1); } /********************************************************** ** Function: is_bigendian ** ** Purpose: Test whether it is a bigendian machine ** ** Return values: true: 1, false: 0 ** ** Comment: ** ** Author: <NAME> at JPL ** ** Created: ** ** Modified: ** ;**********************************************************/ int is_bigendian() { int bigendian, littleendian, test; unsigned char t[4]; littleendian=256; bigendian=256*256; t[0]=0; t[1]=1; t[2]=0; t[3]=0; memcpy(&test, &t[0], 4); /* printf("test: %i\n",test); */ if(test==bigendian)return(1); if(test==littleendian)return(0); printf("Error in endian test, test= %i ********\n",test); } /* * Function: byte_swap_short.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS two-byte words, * starting at address BUFFER. * * @param buffer the one element typed buffer * to convert for a little endian order machine * * @param number_of_swaps number of elements to convert * */ void byte_swap_short(short *buffer, uint number_of_swaps) { short* temp = buffer; uint swap_loop; for (swap_loop = 0, temp = buffer; swap_loop < number_of_swaps; swap_loop++, temp++) { *temp = (short)(((*temp & 0x00ff) << 8) | ((*temp & 0xff00) >> 8)); } } /* Function: byte_swap_long.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS four-byte words, * starting at address BUFFER. * * */ void byte_swap_long(long *buffer, uint number_of_swaps) { long *temp = buffer; uint swap_loop; for (swap_loop = 0, temp = buffer; swap_loop < number_of_swaps; swap_loop++, temp++) { *temp = ((*temp & 0x000000ff) << 24) | ((*temp & 0x0000ff00) << 8) | ((*temp & 0x00ff0000) >> 8) | ((*temp & 0xff000000) >> 24); } } /* ADDED THESE LINES TO TEST THE 4-BYTE INT TYPE ON 64 BIT */ /* Function: byte_swap_int.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS four-byte words, * starting at address BUFFER. * * */ void byte_swap_int(int *buffer, uint number_of_swaps) { int *temp = buffer; uint swap_loop; for (swap_loop = 0, temp = buffer; swap_loop < number_of_swaps; swap_loop++, temp++) { *temp = ((*temp & 0x000000ff) << 24) | ((*temp & 0x0000ff00) << 8) | ((*temp & 0x00ff0000) >> 8) | ((*temp & 0xff000000) >> 24); } } /* Function: byte_swap_uint.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS four-byte words, * starting at address BUFFER. * * */ void byte_swap_uint(uint *buffer, uint number_of_swaps) { uint *temp = buffer; uint swap_loop; for (swap_loop = 0, temp = buffer; swap_loop < number_of_swaps; swap_loop++, temp++) { *temp = ((*temp & 0x000000ff) << 24) | ((*temp & 0x0000ff00) << 8) | ((*temp & 0x00ff0000) >> 8) | ((*temp & 0xff000000) >> 24); } } /* ADDDED NEW LINES ABOVE */ /* ************************************************************************** */ /* Function: byte_swap_short.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS two-byte words, * starting at address BUFFER. * * @param buffer the one element typed buffer * to convert for a little endian order machine * * @param number_of_swaps number of elements to convert * */ void byte_swap_ushort(ushort* buffer, uint number_of_swaps) { byte_swap_short((short*) buffer, number_of_swaps); } /* * Function: byte_swap_ulong.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS four-byte words, * starting at address BUFFER. * * @param buffer the one element typed buffer * to convert for a little endian order machine * * @param number_of_swaps number of elements to convert * */ void byte_swap_ulong(ulong* buffer, uint number_of_swaps) { byte_swap_long((long*) buffer, number_of_swaps); } /* * Function: byte_swap_long.c */ /** * * Swaps bytes within NUMBER_OF_SWAPS four-byte words, * starting at address BUFFER. * * @param buffer the one element typed buffer * to convert for a little endian order machine * * @param number_of_swaps number of elements to convert * */ void byte_swap_float(float* buffer, uint number_of_swaps) { byte_swap_int((int*) buffer, number_of_swaps); } /* Function: epr_swap_endian_order Access: public API Changelog: 2002/02/04 mp nitial version */ /** * Converts bytes for a little endian order machine * * @param field the pointer at data reading in * */ void swap_endian_order(EPR_EDataTypeId data_type_id, void* elems, uint num_elems) { switch (data_type_id) { case e_tid_uchar: case e_tid_char: case e_tid_string: /* no conversion required */ break; case e_tid_time: byte_swap_uint((uint*)elems, 3); break; case e_tid_spare: /* no conversion required */ break; case e_tid_ushort: byte_swap_ushort((ushort*) elems, num_elems); break; case e_tid_short: byte_swap_short((short*) elems, num_elems); break; case e_tid_ulong: byte_swap_uint((uint*) elems, num_elems); break; case e_tid_long: byte_swap_int((int*) elems, num_elems); break; case e_tid_float: byte_swap_float((float*) elems, num_elems); break; case e_tid_double: printf( "swap_endian_order: DOUBLE type was not yet processed\n" ); break; default: printf( "swap_endian_order: unknown data type\n" ); } }
40,608
852
import FWCore.ParameterSet.Config as cms hfnoseNumberingInitialize = cms.ESProducer("HGCalNumberingInitialization", Name = cms.untracked.string("HGCalHFNoseSensitive") )
102
453
<reponame>codyd51/axle /* FUNCTION <<isxdigit>>, <<isxdigit_l>>---hexadecimal digit predicate INDEX isxdigit INDEX isxdigit_l SYNOPSIS #include <ctype.h> int isxdigit(int <[c]>); #include <ctype.h> int isxdigit_l(int <[c]>, locale_t <[locale]>); DESCRIPTION <<isxdigit>> is a macro which classifies singlebyte charset values by table lookup. It is a predicate returning non-zero for hexadecimal digits, and <<0>> for other characters. It is defined only if <[c]> is representable as an unsigned char or if <[c]> is EOF. <<isxdigit_l>> is like <<isxdigit>> but performs the check based on the locale specified by the locale object locale. If <[locale]> is LC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined. You can use a compiled subroutine instead of the macro definition by undefining the macro using `<<#undef isxdigit>>' or `<<#undef isxdigit_l>>'. RETURNS <<isxdigit>>, <<isxdigit_l>> return non-zero if <[c]> is a hexadecimal digit (<<0>>--<<9>>, <<a>>--<<f>>, or <<A>>--<<F>>). PORTABILITY <<isxdigit>> is ANSI C. <<isxdigit_l>> is POSIX-1.2008. No supporting OS subroutines are required. */ #include <_ansi.h> #include <ctype.h> #undef isxdigit int _DEFUN(isxdigit,(c),int c) { return(__CTYPE_PTR[c+1] & ((_X)|(_N))); }
492
3,609
#ifndef __TRACYSOURCETOKENIZER_HPP__ #define __TRACYSOURCETOKENIZER_HPP__ #include <stdint.h> #include <vector> namespace tracy { class Tokenizer { public: enum class TokenColor : uint8_t { Default, Comment, Preprocessor, String, CharacterLiteral, Keyword, Number, Punctuation, Type, Special }; struct Token { const char* begin; const char* end; TokenColor color; }; struct Line { const char* begin; const char* end; std::vector<Token> tokens; }; Tokenizer(); std::vector<Token> Tokenize( const char* begin, const char* end ); private: TokenColor IdentifyToken( const char*& begin, const char* end ); bool m_isInComment; bool m_isInPreprocessor; }; } #endif
400
438
<reponame>Pocoyo-dev/Discord-Bot<filename>src/languages/ru-RU/searcher/r6.json { "DESCRIPTION": "Gets statistics on a Rainbow 6 Account.", "USAGE": "r6 <user> [pc / xbox / ps4] [eu / na / as]", "UNKNOWN_USER": "This username was unable to be found.", "DESC": "Stats for the **{{REGION}}** region on **{{PLATFORM}}**", "GENERAL": "General: ", "GEN_DATA": "**Level:** {{LVL}} ({{XP}} xp) \n**Rank:** {{NAME}} (Max: {{MAX_NAME}}) \n**MMR:** {{MMR}}", "STATS": "Statistics: ", "STAT_DATA": "**Wins:** {{WIN}} \n**Losses:** {{LOSS}} \n**Win/Loss ratio:** {{WL}} \n**Kills** {{KILL}} \n**Deaths:** {{DEATH}} \n**K/D Ratio** {{KD}} \n**Playtime:** {{TIME}} hours", "TERRORIST": "Terrorist Hunt: " }
302
665
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.testdomain.util.event; import javax.inject.Inject; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import org.apache.isis.applib.events.lifecycle.AbstractLifecycleEvent; import org.apache.isis.commons.collections.Can; import org.apache.isis.testdomain.jpa.entities.JpaBook; import org.apache.isis.testdomain.util.dto.BookDto; import org.apache.isis.testdomain.util.kv.KVStoreForTesting; import lombok.RequiredArgsConstructor; import lombok.val; import lombok.extern.log4j.Log4j2; @Service @RequiredArgsConstructor(onConstructor_ = {@Inject}) @Log4j2 public class LifecycleEventSubscriberJpaForTesting { private final KVStoreForTesting kvStore; // -- JPA LIFECYCLE EVENTS @EventListener(JpaBook.CreatedLifecycleEvent.class) public void on(final JpaBook.CreatedLifecycleEvent ev) { storeJpaEvent(ev); } @EventListener(JpaBook.PersistingLifecycleEvent.class) public void on(final JpaBook.PersistingLifecycleEvent ev) { storeJpaEvent(ev); } @EventListener(JpaBook.PersistedLifecycleEvent.class) public void on(final JpaBook.PersistedLifecycleEvent ev) { storeJpaEvent(ev); } @EventListener(JpaBook.LoadedLifecycleEvent.class) public void on(final JpaBook.LoadedLifecycleEvent ev) { storeJpaEvent(ev); } @EventListener(JpaBook.UpdatingLifecycleEvent.class) public void on(final JpaBook.UpdatingLifecycleEvent ev) { storeJpaEvent(ev); } @EventListener(JpaBook.UpdatedLifecycleEvent.class) public void on(final JpaBook.UpdatedLifecycleEvent ev) { storeJpaEvent(ev); } @EventListener(JpaBook.RemovingLifecycleEvent.class) public void on(final JpaBook.RemovingLifecycleEvent ev) { storeJpaEvent(ev); } // -- UTILITY public static void clearPublishedEvents(final KVStoreForTesting kvStore) { kvStore.clear(LifecycleEventSubscriberJpaForTesting.class); } public static Can<BookDto> getPublishedEventsJpa( final KVStoreForTesting kvStore, final Class<? extends AbstractLifecycleEvent<JpaBook>> eventClass) { return kvStore.getAll(LifecycleEventSubscriberJpaForTesting.class, eventClass.getName()) .map(BookDto.class::cast); } // -- HELPER private void storeJpaEvent(final AbstractLifecycleEvent<JpaBook> ev) { val eventType = ev.getClass().getName(); log.debug("on {}", eventType); val bookDto = BookDto.from(ev.getSource()); kvStore.append(this, eventType, bookDto); } }
1,251
465
<filename>pycharm2020.1.3/script/core/util/UtilApi.py from __future__ import annotations import asyncio # from asyncio import AbstractEventLoop import functools import json import random from typing import Callable, Union, Optional # from TcpServer import ev_loop # import typing import aiohttp import typing from common.service_const import ETCD_TAG_DISPATCHER_SERVICE if typing.TYPE_CHECKING: from ConnMgr import ConnMgr from TcpServer import TcpServer from common import gv # from core.mobilelog.LogManager import LogManager from core.util import EnhancedJson # from concurrent.futures.thread import ThreadPoolExecutor server_singletons = {} def add_server_singleton(entity, postfix=''): """添加一个GameServer内唯一的entity""" server_singletons[entity.__class__.__name__ + postfix] = entity def get_server_singleton(entity_name): return server_singletons.get(entity_name, None) class Singleton: def __init__(self, decorated_cls): self._decorated_cls = decorated_cls def instance(self): try: return self._instance except AttributeError: self._instance = self._decorated_cls() add_server_singleton(self._instance) return self._instance def __call__(self): raise TypeError('Singletons must be accessed through `instance()`.') def __instancecheck__(self, inst): return isinstance(inst, self._decorated_cls) def async_lock(f): lock = asyncio.Lock() @functools.wraps(f) async def _wrapped(*args, **kwargs): async with lock: return await f(*args, **kwargs) return _wrapped def wait_or_not(concurrency_limit=888): """ 此装饰器能让一个async的函数在被调用的时候无需await, 但是如果你需要这个函数的return结果的话, 依然可以await, 所以脚wait or not :param concurrency_limit: :return: """ # Bind the default event loop # print("a bousennnnnn") # sem = asyncio.BoundedSemaphore(concurrency_limit) sem = asyncio.BoundedSemaphore(concurrency_limit, loop=gv.get_ev_loop()) # LogManager.set_log_tag("tcp_client_" + str(1)) # LogManager.set_log_path("../bin/win/log/") # logger = LogManager.get_logger() # logger.info(f"b bousennnnnn {id(sem._loop)=}") # logger.info(f"b bousennnnnn{id(sem)=}") def wait_or_not_without_limit(f): @functools.wraps(f) def _wrapped(*args, **kwargs): # logger.info(f"b withold {id(gv.get_ev_loop())=}") return gv.get_ev_loop().create_task(f(*args, **kwargs)) return _wrapped def executor(f): assert(asyncio.iscoroutinefunction(f)) @functools.wraps(f) @wait_or_not_without_limit async def wrapped(*args, **kwargs): async with sem: return await f(*args, **kwargs) return wrapped return executor # _async_wrap_tp_executor = ThreadPoolExecutor() def async_wrap(func: Callable): # TODO: 貌似和long polling 不和, 不适合用在 cpu bound 之处 """ usage: r = await AioApi.async_wrap(lambda: requests.request("GET", 'http://baidu.com', timeout=2)) lambda关键字不可少 """ if not callable(func): raise Exception(f"{func=} is not callable") # dv_loop = gv.get_ev_loop() # print(f"{id(gv.get_ev_loop())=}") # print(f"{(gv.get_ev_loop()._default_executor)=}") # print(f"{id(gv.get_ev_loop()._default_executor)=}") return gv.get_ev_loop().run_in_executor(None, func) async def async_http_requests( method: str, url: str, session: aiohttp.ClientSession = None, response_as_json=False, **kwargs) -> (Union[str, dict], dict): method = method.lower() assert(method in ("get", "put", "post", "delete")) async def _async_http_requests_impl(_method, _url, _session, **_kwargs): async with getattr(_session, _method)(_url, **_kwargs) as response: # type: aiohttp.ClientResponse r_body = await response.text() if response_as_json: r_body = json.loads(r_body) return r_body, response.headers if session is None: async with aiohttp.ClientSession() as session: return await _async_http_requests_impl(method, url, session, **kwargs) else: return await _async_http_requests_impl(method, url, session, **kwargs) def get_global_entity_mailbox(entity_unique_name): return gv.etcd_service_node.get_entity_info(entity_unique_name) def get_lowest_load_service_info(service_tag) -> Optional[typing.Tuple[str, str, int]]: """ :param service_tag: :return: 一个元组 (server_name, ip, port) """ if gv.etcd_service_node is None: return None return gv.etcd_service_node.get_lowest_load_service_addr(service_tag) def register_entity_globally(): pass def register_entity_to_etcd(entity, name, tag=None): # ip = gr.local_ip # port = gr.local_port pass def unregister_entity_from_etcd(name): pass def parse_json_conf(json_conf_path): # with open(r"../bin/win/conf/battle_server.json") as conf_file: with open(json_conf_path) as conf_file: # data = file.read() # _name = r'../bin/win/conf/battle_server.json' # file_name = r'D:\Documents\github\realtime-server\pycharm2020.1.3\bin\win\conf\battle_server.json' # file_name = r'C:\Users\b\Documents\github\realtime-server\pycharm2020.1.3\bin\win\conf\battle_server.json' # conf_file = open(file_name) json_conf = EnhancedJson.load(conf_file) # conf_file.close() gv.game_json_conf = json_conf # file_name = r'../bin/win/conf/battle_server.json' # # file_name = r'D:\Documents\github\realtime-server\pycharm2020.1.3\bin\win\conf\battle_server.json' # # file_name = r'C:\Users\b\Documents\github\realtime-server\pycharm2020.1.3\bin\win\conf\battle_server.json' # conf_file = open(file_name) # json_conf = json.load(conf_file) # conf_file.close() # gr.game_json_conf = json_conf return json_conf def get_cur_server() -> TcpServer: return get_server_singleton("TcpServer") def get_conn_mgr() -> ConnMgr: return get_server_singleton("ConnMgr") def get_rand_dispatcher_addr() -> typing.Tuple[str, int]: rand_dispatcher_service_addr = get_lowest_load_service_info(ETCD_TAG_DISPATCHER_SERVICE) if rand_dispatcher_service_addr is None: dispatcher_json_conf_path = r"../bin/win/conf/dispatcher_service.json" with open(dispatcher_json_conf_path) as conf_file: dispatcher_json_conf = EnhancedJson.load(conf_file) cnt = len(dispatcher_json_conf.items()) * 6 while cnt > 0: # _svr_name = random.choice((dispatcher_json_conf.items())) _svr_name, _svr_info = random.choice(list(dispatcher_json_conf.items())) if type(_svr_info) is dict and _svr_name.startswith("dispatcher"): rand_dispatcher_service_addr = (_svr_info["ip"], _svr_info["port"]) break cnt -= 1 else: rand_dispatcher_service_addr = rand_dispatcher_service_addr[1:] return rand_dispatcher_service_addr
3,123
1,156
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import numpy.testing as npt from reagent.core.parameters import ProblemDomain from reagent.gym.envs import Gym from reagent.gym.envs.wrappers.simple_minigrid import SimpleObsWrapper from reagent.gym.utils import create_df_from_replay_buffer from reagent.preprocessing.sparse_to_dense import PythonSparseToDenseProcessor from reagent.test.base.horizon_test_base import HorizonTestBase logger = logging.getLogger(__name__) class TestEnv(SimpleObsWrapper): """ Wrap Gym environment in TestEnv to save the MiniGrid's observation, action, reward and terminal in a list so that we can check if replay buffer is working correctly """ def __init__(self, env): self.env = env self.action_space = self.env.action_space # mdp_id, sequence_number, state, action, reward, terminal self.sart = [] self.mdp_id = -1 self.sequence_number = 0 def seed(self, *args, **kwargs): return self.env.seed(*args, **kwargs) def reset(self, **kwargs): self.mdp_id += 1 self.sequence_number = 0 res = self.env.reset(**kwargs) self.sart.append([self.mdp_id, self.sequence_number, res, None, None, None]) return res def step(self, action): res = self.env.step(action) ( _, _, last_state, last_action, last_reward, last_terminal, ) = self.sart[-1] assert ( last_state is not None and last_action is None and last_reward is None and last_terminal is None ) next_state, reward, terminal, _ = res self.sart[-1][3] = action self.sart[-1][4] = reward self.sart[-1][5] = terminal self.sequence_number += 1 self.sart.append( [self.mdp_id, self.sequence_number, next_state, None, None, None] ) return res class TestGymReplayBuffer(HorizonTestBase): def test_create_df_from_replay_buffer(self): env_name = "MiniGrid-Empty-5x5-v0" env = Gym(env_name=env_name) state_dim = env.observation_space.shape[0] # Wrap env in TestEnv env = TestEnv(env) problem_domain = ProblemDomain.DISCRETE_ACTION DATASET_SIZE = 1000 multi_steps = None DS = "2021-09-16" # Generate data df = create_df_from_replay_buffer( env=env, problem_domain=problem_domain, desired_size=DATASET_SIZE, multi_steps=multi_steps, ds=DS, shuffle_df=False, ) self.assertEqual(len(df), DATASET_SIZE) # Check data preprocessor = PythonSparseToDenseProcessor(list(range(state_dim))) for idx, row in df.iterrows(): df_mdp_id = row["mdp_id"] env_mdp_id = str(env.sart[idx][0]) self.assertEqual(df_mdp_id, env_mdp_id) df_seq_num = row["sequence_number"] env_seq_num = env.sart[idx][1] self.assertEqual(df_seq_num, env_seq_num) df_state = preprocessor.process([row["state_features"]])[0][0].numpy() env_state = env.sart[idx][2] npt.assert_array_equal(df_state, env_state) df_action = row["action"] env_action = str(env.sart[idx][3]) self.assertEqual(df_action, env_action) df_terminal = row["next_action"] == "" env_terminal = env.sart[idx][5] self.assertEqual(df_terminal, env_terminal) if not df_terminal: df_reward = float(row["reward"]) env_reward = float(env.sart[idx][4]) npt.assert_allclose(df_reward, env_reward) df_next_state = preprocessor.process([row["next_state_features"]])[0][ 0 ].numpy() env_next_state = env.sart[idx + 1][2] npt.assert_array_equal(df_next_state, env_next_state) df_next_action = row["next_action"] env_next_action = str(env.sart[idx + 1][3]) self.assertEqual(df_next_action, env_next_action) else: del env.sart[idx + 1]
2,169
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package complex.cellRanges; import com.sun.star.container.XIndexAccess; // import complexlib.ComplexTestCase; import com.sun.star.lang.XMultiServiceFactory; // import com.sun.star.sheet.CellFlags; import com.sun.star.sheet.XCellRangesQuery; import com.sun.star.sheet.XSheetCellRanges; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.sheet.XSpreadsheets; import com.sun.star.table.CellAddress; // import com.sun.star.table.XColumnRowRange; // import com.sun.star.table.XTableColumns; // import com.sun.star.table.XTableRows; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; // import java.io.PrintWriter; import com.sun.star.util.XCloseable; import util.SOfficeFactory; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.openoffice.test.OfficeConnection; import static org.junit.Assert.*; /** * Check the XCellRangesQuery interface on the SheetCell service. test was * created for bug i20044. */ public class CheckXCellRangesQuery /* extends ComplexTestCase */ { XSpreadsheetDocument m_xSheetDoc = null; XCellRangesQuery m_xCell = null; XSpreadsheet m_xSpreadSheet = null; /** * Get all test methods. * @return The test methods. */ // public String[] getTestMethodNames() { // return new String[] {"checkEmptyCell", "checkFilledCell"}; // } /** * Creates Spreadsheet document and the test object, * before the actual test starts. */ @Before public void before() { // create a calc document // SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)param.getMSF() ); final XMultiServiceFactory xMsf = UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager()); SOfficeFactory SOF = SOfficeFactory.getFactory(xMsf); try { System.out.println( "creating a Spreadsheet document" ); m_xSheetDoc = SOF.createCalcDoc(null); } catch ( com.sun.star.uno.Exception e ) { // Some exception occured.FAILED e.printStackTrace( ); fail( "Couldn?t create document"); } XInterface oObj = null; try { System.out.println("Getting spreadsheet") ; XSpreadsheets oSheets = m_xSheetDoc.getSheets() ; XIndexAccess oIndexSheets = UnoRuntime.queryInterface(XIndexAccess.class, oSheets); m_xSpreadSheet = (XSpreadsheet) AnyConverter.toObject( new Type(XSpreadsheet.class),oIndexSheets.getByIndex(0)); // get the cell System.out.println("Getting a cell from sheet") ; oObj = m_xSpreadSheet.getCellByPosition(2, 3); m_xCell = UnoRuntime.queryInterface(XCellRangesQuery.class, oObj); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(); fail("Error getting cell object from spreadsheet document"); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); fail("Error getting cell object from spreadsheet document"); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(); fail("Error getting cell object from spreadsheet document"); } // set one value for comparison. try { m_xSpreadSheet.getCellByPosition(1, 1).setValue(15); m_xSpreadSheet.getCellByPosition(1, 3).setValue(5); m_xSpreadSheet.getCellByPosition(2, 1).setFormula("=B2+B4"); /* m_xSpreadSheet.getCellByPosition(2, 1).setFormula("=B2+B3"); m_xSpreadSheet.getCellByPosition(3, 2).setFormula(""); m_xSpreadSheet.getCellByPosition(3, 3).setFormula(""); */ } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); fail("Could not fill cell (1, 1) with a value."); } } /* * this method closes a calc document and resets the corresponding class variable xSheetDoc */ protected boolean closeSpreadsheetDocument() { boolean worked = true; System.out.println(" disposing xSheetDoc "); try { XCloseable oCloser = UnoRuntime.queryInterface( XCloseable.class, m_xSheetDoc); oCloser.close(true); } catch (com.sun.star.util.CloseVetoException e) { worked = false; System.out.println("Couldn't close document"); } catch (com.sun.star.lang.DisposedException e) { worked = false; System.out.println("Document already disposed"); } catch (java.lang.NullPointerException e) { worked = false; System.out.println("Couldn't get XCloseable"); } m_xSheetDoc = null; return worked; } @After public void after() { closeSpreadsheetDocument(); } /** * Perform some tests on an empty cell: * <ol> * <li>compare an empty cell with a cell with a value in the same column</li> * <li>compare an empty cell with a cell with a value in the same row</li> * <li>query for empty cells</li> * <ol> */ @Test public void checkEmptyCell() { System.out.println("Checking an empty cell..."); // compare an empty cell with a cell with a value assertTrue("\tQuery column differences did not return the correct value.", _queryColumnDifferences("Sheet1.C4")); // compare an empty cell with a cell with a value assertTrue("\tQuery column differences did not return the correct value.", _queryRowDifferences("Sheet1.C4")); // try to get this cell // assertTrue("\tQuery empty cells did not return the correct value.", _queryEmptyCells("Sheet1.C4")); System.out.println("...done"); } /** * Perform some tests on a filled cell: * <ol> * <li>compare an cell with value 5 with a cell with value 15 in the same column</li> * <li>compare an cell with value 5 with a cell with value 15 in the same row</li> * <li>query for an empty cell.</li> * <ol> */ @Test public void checkFilledCell() { System.out.println("Checking a filled cell..."); // fill the cell with a value try { m_xSpreadSheet.getCellByPosition(2, 3).setValue(15); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); fail("Could not fill cell (2, 3) with a value."); } // compare an cell with value 5 with a cell with value 15 assertTrue("\tQuery column differences did not return the correct value.", _queryColumnDifferences("Sheet1.C4")); // compare an cell with value 5 with a cell with value 15 assertTrue("\tQuery column differences did not return the correct value.", _queryRowDifferences("Sheet1.C4")); // try to get nothing assertTrue("\tQuery empty cells did not return the correct value.", _queryEmptyCells("")); System.out.println("...done"); } /** * Query column differences between my cell(2,3) and (1,1). * @param expected The expected outcome value. * @return True, if the result equals the expected result. */ public boolean _queryColumnDifferences(String expected) { System.out.println("\tQuery column differences"); XSheetCellRanges ranges = m_xCell.queryColumnDifferences( new CellAddress((short) 0, 1, 1)); String getting = ranges.getRangeAddressesAsString(); if (!getting.equals(expected)) { System.out.println("\tGetting: " + getting); System.out.println("\tShould have been: " + expected); return false; } return true; } /** * Query for an empty cell. * @param expected The expected outcome value. * @return True, if the result equals the expected result. */ public boolean _queryEmptyCells(String expected) { System.out.println("\tQuery empty cells"); XSheetCellRanges ranges = m_xCell.queryEmptyCells(); String getting = ranges.getRangeAddressesAsString(); if (!getting.equals(expected)) { System.out.println("\tGetting: " + getting); System.out.println("\tShould have been: " + expected); return false; } return true; } /** * Query row differences between my cell(2,3) and (1,1). * @param expected The expected outcome value. * @return True, if the result equals the expected result. */ public boolean _queryRowDifferences(String expected) { System.out.println("\tQuery row differences"); XSheetCellRanges ranges = m_xCell.queryRowDifferences( new CellAddress((short) 0, 1, 1)); String getting = ranges.getRangeAddressesAsString(); if (!getting.equals(expected)) { System.out.println("\tGetting: " + getting); System.out.println("\tShould have been: " + expected); return false; } return true; } @BeforeClass public static void setUpConnection() throws Exception { connection.setUp(); } @AfterClass public static void tearDownConnection() throws InterruptedException, com.sun.star.uno.Exception { connection.tearDown(); } private static final OfficeConnection connection = new OfficeConnection(); }
4,226
795
package com.yydcdut.markdowndemo.controller; import android.widget.Toast; import com.yydcdut.markdown.MarkdownEditText; import com.yydcdut.markdown.span.MDOrderListSpan; import com.yydcdut.markdown.span.MDUnOrderListSpan; /** * Created by yuyidong on 16/7/15. */ public class ListController { private MarkdownEditText mRxMDEditText; public ListController(MarkdownEditText rxMDEditText) { mRxMDEditText = rxMDEditText; } public void doUnOrderList() { int start = mRxMDEditText.getSelectionStart(); int end = mRxMDEditText.getSelectionEnd(); if (start == end) { MDUnOrderListSpan mdUnOrderListSpan = Utils.getSpans(mRxMDEditText, start, end, MDUnOrderListSpan.class); int position = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1; if (mdUnOrderListSpan != null) { if (mdUnOrderListSpan.getNested() == 0) { mRxMDEditText.getText().delete(position, position + "* ".length()); // mRxMDEditText.getText().removeSpan(mdUnOrderListSpan); return; } mRxMDEditText.getText().delete(position, position + 1); // mRxMDEditText.getText().removeSpan(mdUnOrderListSpan); return; } mRxMDEditText.getText().insert(position, "* "); } else { int position0 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1; int position00 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), end) + 1; if (position0 != position00) { Toast.makeText(mRxMDEditText.getContext(), "无法操作多行", Toast.LENGTH_SHORT).show(); return; } // int selectedStart = mRxMDEditText.getSelectionStart(); // int selectedEnd = mRxMDEditText.getSelectionEnd(); MDUnOrderListSpan mdUnOrderListSpan = Utils.getSpans(mRxMDEditText, start, end, MDUnOrderListSpan.class); if (mdUnOrderListSpan != null) { if (mdUnOrderListSpan.getNested() == 0) { mRxMDEditText.getText().delete(position0, position0 + "* ".length()); // mRxMDEditText.setSelection(selectedStart - "* ".length(), selectedEnd - "* ".length()); return; } mRxMDEditText.getText().delete(position0, position0 + 1); // mRxMDEditText.setSelection(selectedStart - 1, selectedEnd - 1); return; } mRxMDEditText.getText().insert(position0, "* "); // mRxMDEditText.setSelection(selectedStart + "* ".length(), selectedEnd + "* ".length()); } } public void doOrderList() { int start = mRxMDEditText.getSelectionStart(); int end = mRxMDEditText.getSelectionEnd(); if (start == end) { MDOrderListSpan mdOrderListSpan = Utils.getSpans(mRxMDEditText, start, end, MDOrderListSpan.class); int position = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1; if (mdOrderListSpan != null) { mRxMDEditText.getText().delete(position, position + mdOrderListSpan.getNested() + (mdOrderListSpan.getNumber() / 10 + 1) + ". ".length()); return; } if (position == 0) { mRxMDEditText.getText().insert(position, "1. "); } else { MDOrderListSpan mdBeforeLineOrderListSpan = Utils.getSpans(mRxMDEditText, position - 1, position - 1, MDOrderListSpan.class); if (mdBeforeLineOrderListSpan != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mdBeforeLineOrderListSpan.getNested(); i++) { sb.append(" "); } sb.append((mdBeforeLineOrderListSpan.getNumber() + 1)).append(". "); mRxMDEditText.getText().insert(position, sb.toString()); } else { mRxMDEditText.getText().insert(position, "1. "); } } } else { int position0 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1; int position00 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), end) + 1; if (position0 != position00) { Toast.makeText(mRxMDEditText.getContext(), "无法操作多行", Toast.LENGTH_SHORT).show(); return; } // int selectedStart = mRxMDEditText.getSelectionStart(); // int selectedEnd = mRxMDEditText.getSelectionEnd(); MDOrderListSpan mdOrderListSpan = Utils.getSpans(mRxMDEditText, start, end, MDOrderListSpan.class); if (mdOrderListSpan != null) { if (mdOrderListSpan.getNested() == 0) { int deleteLength = position0 + mdOrderListSpan.getNested() + (mdOrderListSpan.getNumber() / 10 + 1) + ". ".length(); mRxMDEditText.getText().delete(position0, deleteLength); // mRxMDEditText.setSelection(selectedStart - deleteLength, selectedEnd - deleteLength); return; } mRxMDEditText.getText().delete(position0, position0 + 1); // mRxMDEditText.setSelection(selectedStart - 1, selectedEnd - 1); return; } if (position0 == 0) { mRxMDEditText.getText().insert(position0, "1. "); } else { MDOrderListSpan mdBeforeLineOrderListSpan = Utils.getSpans(mRxMDEditText, position0 - 1, position0 - 1, MDOrderListSpan.class); if (mdBeforeLineOrderListSpan != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mdBeforeLineOrderListSpan.getNested(); i++) { sb.append(" "); } sb.append((mdBeforeLineOrderListSpan.getNumber() + 1)).append(". "); mRxMDEditText.getText().insert(position0, sb.toString()); // mRxMDEditText.setSelection(selectedStart + sb.length(), selectedEnd + sb.length()); } else { mRxMDEditText.getText().insert(position0, "1. "); // mRxMDEditText.setSelection(selectedStart + "1. ".length(), selectedEnd + "1. ".length()); } } } } }
3,333
810
from .stream51 import Stream51
8
416
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #ifndef VSNRAY_MATH_AXIS_H #define VSNRAY_MATH_AXIS_H 1 #include <cstddef> #include "config.h" #include "vector.h" namespace MATH_NAMESPACE { template <size_t Dim> class cartesian_axis; template <> class cartesian_axis<2> { public: enum label { X, Y }; MATH_FUNC /* implicit */ cartesian_axis(label l) : val_(l) {} MATH_FUNC operator label() const { return val_; } private: label val_; }; template <> class cartesian_axis<3> { public: enum label { X, Y, Z }; MATH_FUNC /* implicit */ cartesian_axis(label l) : val_(l) {} MATH_FUNC operator label() const { return val_; } private: label val_; }; template <size_t Dim> MATH_FUNC vector<Dim, float> to_vector(cartesian_axis<Dim> const& a) { vector<Dim, float> result(0.0f); result[(typename cartesian_axis<Dim>::label)(a)] = 1.0f; return result; } } // MATH_NAMESPACE #endif // VSNRAY_MATH_AXIS_H
418
5,362
<reponame>timgates42/PokemonGo-Bot from pokemongo_bot import inventory from pokemongo_bot.base_task import BaseTask from pokemongo_bot.worker_result import WorkerResult class UpdateWebInventory(BaseTask): SUPPORTED_TASK_API_VERSION = 1 def work(self): inventory.update_web_inventory() return WorkerResult.SUCCESS
119
645
<reponame>sleepingAnt/viewfinder<filename>backend/base/test/message_test.py # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Test message validation and migration. """ __author__ = '<EMAIL> (<NAME>)' from copy import deepcopy from tornado.ioloop import IOLoop from viewfinder.backend.base import testing from viewfinder.backend.base.message import Message, MessageMigrator, BadMessageException, REQUIRED_MIGRATORS class RenameTestMigrator(MessageMigrator): """Rename a field in the message.""" def __init__(self): MessageMigrator.__init__(self, Message.TEST_VERSION) def MigrateForward(self, client, message, callback): assert message.dict['headers'] message.dict['renamed-scalar'] = message.dict['scalar'] del message.dict['scalar'] callback() def MigrateBackward(self, client, message, callback): assert message.dict['headers'] message.dict['scalar'] = message.dict['renamed-scalar'] del message.dict['renamed-scalar'] IOLoop.current().add_callback(callback) class MessageTestCase(testing.BaseTestCase): SCHEMA_NO_VERSION = { 'description': 'test schema', 'type': 'object', 'properties': { 'scalar': {'type': 'string', 'blank': True}, 'list': { 'type': 'array', 'items': {'type': 'any'}, }, 'sub-dict': { 'description': 'nested dictionary', 'required': False, 'type': 'object', 'properties': { 'none': {'type': 'null'}, 'sub-scalar': {'type': 'string'}, 'sub-list': { 'type': 'array', 'items': { 'description': 'dictionary in list', 'type': 'object', 'properties': { 'value': {'type': 'number'} }, }, }, }, }, }, } SCHEMA_WITH_VERSION = deepcopy(SCHEMA_NO_VERSION) SCHEMA_WITH_VERSION['properties']['headers'] = { 'description': 'defines required version field', 'required': False, 'type': 'object', 'properties': { 'version': {'type': 'number', 'minimum': Message.ADD_HEADERS_VERSION}, }, } RENAMED_SCHEMA_WITH_VERSION = deepcopy(SCHEMA_WITH_VERSION) del RENAMED_SCHEMA_WITH_VERSION['properties']['scalar'] RENAMED_SCHEMA_WITH_VERSION['properties']['renamed-scalar'] = {'type': 'string'} MSG_NO_VERSION = { 'scalar': 'Simple scalar field', 'list': [10, 'list item', []], 'sub-dict': { 'none': None, 'sub-scalar': 'Simple scalar field within sub-dict', 'sub-list': [{'value': 20, 'extra': 'extra field that does not appear in schema'}], 'extra': 'extra field that does not appear in schema', }, 'extra': 'extra field that does not appear in schema', } MSG_WITH_VERSION = deepcopy(MSG_NO_VERSION) MSG_WITH_VERSION['headers'] = dict(version=Message.ADD_HEADERS_VERSION) def testMessage(self): """Basic tests of the Message class.""" # Message with no version, no schema. self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION) # Message with version, no schema. self._TestMessage(MessageTestCase.MSG_WITH_VERSION, original_version=Message.ADD_HEADERS_VERSION) # Default version. self._TestMessage(MessageTestCase.MSG_NO_VERSION, default_version=Message.ADD_HEADERS_VERSION, original_version=Message.ADD_HEADERS_VERSION) message_dict = deepcopy(MessageTestCase.MSG_NO_VERSION) message_dict['headers'] = {} self._TestMessage(message_dict, default_version=Message.ADD_HEADERS_VERSION, original_version=Message.ADD_HEADERS_VERSION) # ERROR: Message version not present. message_dict = deepcopy(MessageTestCase.MSG_WITH_VERSION) del message_dict['headers']['version'] self.assertRaises(BadMessageException, self._TestMessage, message_dict) # ERROR: Message version was present, but anachronistic (i.e. try to use headers in version # that didn't support them). message_dict = deepcopy(MessageTestCase.MSG_WITH_VERSION) message_dict['headers']['version'] = Message.INITIAL_VERSION self.assertRaises(BadMessageException, self._TestMessage, message_dict) # ERROR: Message version not high enough to be supported. message_dict = deepcopy(MessageTestCase.MSG_WITH_VERSION) message_dict['headers']['version'] = -1 self.assertRaises(BadMessageException, self._TestMessage, message_dict) self.assertRaises(BadMessageException, self._TestMessage, MessageTestCase.MSG_WITH_VERSION, min_supported_version=Message.TEST_VERSION) # ERROR: Message version not low enough to be supported. message_dict = deepcopy(MessageTestCase.MSG_WITH_VERSION) message_dict['headers']['version'] = Message.ADD_HEADERS_VERSION self.assertRaises(BadMessageException, self._TestMessage, message_dict, max_supported_version=Message.INITIAL_VERSION) # Min required version specified in the message. message_dict = deepcopy(MessageTestCase.MSG_WITH_VERSION) message_dict['headers']['version'] = 1000 message_dict['headers']['min_required_version'] = Message.ADD_HEADERS_VERSION self._TestMessage(message_dict, original_version=Message.MAX_VERSION) message_dict['headers']['version'] = Message.ADD_HEADERS_VERSION self._TestMessage(message_dict, original_version=Message.ADD_HEADERS_VERSION) # ERROR: Min required version specified in the message, but greater than max supported version. message_dict['headers']['version'] = 3 message_dict['headers']['min_required_version'] = Message.TEST_VERSION self.assertRaises(BadMessageException, self._TestMessage, message_dict, max_supported_version=Message.ADD_HEADERS_VERSION) # ERROR: Min required version specified in the message, but less than min required message version. message_dict['headers']['version'] = Message.TEST_VERSION message_dict['headers']['min_required_version'] = Message.ADD_HEADERS_VERSION self.assertRaises(BadMessageException, self._TestMessage, message_dict, min_supported_version=1000, max_supported_version=Message.ADD_HEADERS_VERSION) # ERROR: Min required version specified in the message, but greater than version. message_dict = deepcopy(MessageTestCase.MSG_WITH_VERSION) message_dict['headers']['min_required_version'] = 100 self.assertRaises(BadMessageException, self._TestMessage, message_dict) # Message with sanitize + schema. self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION, schema=MessageTestCase.SCHEMA_NO_VERSION, sanitize=True) # Message with allow_extra_fields=True. self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION, schema=MessageTestCase.SCHEMA_NO_VERSION, allow_extra_fields=True) # ERROR: Message violates schema due to extra fields. self.assertRaises(BadMessageException, self._TestMessage, MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION, schema=MessageTestCase.SCHEMA_NO_VERSION) # Visit message. def _TestVisitor(key, value): """Remove extra fields, replace "list" field.""" if key == 'extra': return () elif key == 'list': return ('new-field', 'new value') message = Message(deepcopy(MessageTestCase.MSG_NO_VERSION)) message.Visit(_TestVisitor) message.Visit(self._TestExtraField) self.assertTrue(message.dict.has_key('scalar')) self.assertTrue(message.dict.has_key('new-field')) self.assertFalse(message.dict.has_key('list')) def testMigrate(self): """Test version migration functionality on the Message class.""" # Migrate message with no header to have a header. message = self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION, max_supported_version=Message.INITIAL_VERSION, schema=MessageTestCase.SCHEMA_WITH_VERSION, allow_extra_fields=True, migrate_version=Message.ADD_HEADERS_VERSION) # Migrate message with header to have no header. message = self._TestMessage(message.dict, sanitize=True, schema=MessageTestCase.SCHEMA_NO_VERSION, original_version=Message.ADD_HEADERS_VERSION, migrate_version=Message.INITIAL_VERSION) # Add a migrator to the list of migrators and migrate from initial version. message = self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION, sanitize=True, schema=MessageTestCase.RENAMED_SCHEMA_WITH_VERSION, migrate_version=Message.TEST_VERSION, migrators=[RenameTestMigrator()]) renamed_dict = message.dict # Migrate message with renamed field all the way back to initial version. message = self._TestMessage(renamed_dict, original_version=Message.TEST_VERSION, schema=MessageTestCase.SCHEMA_NO_VERSION, migrate_version=Message.INITIAL_VERSION, migrators=[RenameTestMigrator()]) # Migrate message with renamed field back to add headers version (not all the way). message = self._TestMessage(renamed_dict, original_version=Message.TEST_VERSION, schema=MessageTestCase.SCHEMA_WITH_VERSION, migrate_version=Message.ADD_HEADERS_VERSION, migrators=[RenameTestMigrator()]) # Migrate message with renamed field back to initial version. message = self._TestMessage(message.dict, original_version=Message.ADD_HEADERS_VERSION, schema=MessageTestCase.SCHEMA_NO_VERSION, migrate_version=Message.INITIAL_VERSION, migrators=[RenameTestMigrator()]) # No migration necessary. message = self._TestMessage(message.dict, original_version=Message.INITIAL_VERSION, schema=MessageTestCase.SCHEMA_NO_VERSION, migrate_version=Message.INITIAL_VERSION, migrators=[RenameTestMigrator()]) def _TestMessage(self, message_dict, original_version=None, default_version=Message.INITIAL_VERSION, min_supported_version=Message.INITIAL_VERSION, max_supported_version=Message.MAX_VERSION, schema=None, allow_extra_fields=False, sanitize=False, migrate_version=None, migrators=None): # Create the message. message_dict = deepcopy(message_dict) message = Message(message_dict, default_version=default_version, min_supported_version=min_supported_version, max_supported_version=max_supported_version) self.assertEqual(message.dict, message_dict) self.assertEqual(message.original_version, original_version) self.assertEqual(message.version, original_version) self.assertTrue(message.version == Message.INITIAL_VERSION or message.dict['headers'].has_key('version')) # Migrate the message to "migrate_version". if migrate_version is not None: migrators = None if migrators is None else sorted(REQUIRED_MIGRATORS + migrators) message.Migrate(None, migrate_version, lambda message: self.stop(message), migrators) self.assert_(self.wait() is message) self.assertEqual(message.version, migrate_version) # Sanitize the message if requested. if sanitize: message.Validate(schema, True) message.Sanitize() message.Visit(self._TestExtraField) # Validate the message according to "schema". if schema: message.Validate(schema, allow_extra_fields) self.assertEqual(message.schema, schema) if not allow_extra_fields: message.Visit(self._TestExtraField) return message def _TestExtraField(self, key, value): self.assertNotEqual(key, 'extra')
5,157
647
<filename>trick_source/er7_utils/integration/rkf45/include/rkf45_butcher_tableau.hh /** * @if Er7UtilsUseGroups * @addtogroup Er7Utils * @{ * @addtogroup Integration * @{ * @endif */ /** * @file * Defines Butcher tableau for Runge Kutta Fehlberg 4/5. */ /* Purpose: () */ #ifndef ER7_UTILS_RKF45_BUTCHER_TABLEAU_HH #define ER7_UTILS_RKF45_BUTCHER_TABLEAU_HH namespace er7_utils { /** * Contains the Runge Kutta Fehlberg 4/5 Butcher Tableau. * This is a class rather than a namespace because of swig issues. */ class RKFehlberg45ButcherTableau { public: static const double RKa[6][6]; /**< trick_units(--) @n * Runge Kutta Fehlberg 4/5 Butcher tableau 'a' elements. */ static const double RKb5[6]; /**< trick_units(--) @n * Runge Kutta Fehlberg 4/5 Butcher tableau fifth order 'b' elements. */ static const double RKb4[6]; /**< trick_units(--) @n * Runge Kutta Fehlberg 4/5 Butcher tableau fourth order 'b' elements. */ static const double RKc[6]; /**< trick_units(--) @n Runge Kutta Fehlberg 4/5 Butcher tableau 'c' elements. */ private: /** * Not implemented. */ RKFehlberg45ButcherTableau (); /** * Not implemented. */ ~RKFehlberg45ButcherTableau (); /** * Not implemented. */ RKFehlberg45ButcherTableau (const RKFehlberg45ButcherTableau &); /** * Not implemented. */ RKFehlberg45ButcherTableau & operator= ( const RKFehlberg45ButcherTableau &); }; } #endif /** * @if Er7UtilsUseGroups * @} * @} * @endif */
624
839
<filename>rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/impl/tl/ThreadLocalInvocationHandlerTest.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxrs.impl.tl; import java.lang.annotation.AnnotationFormatError; import java.lang.reflect.Proxy; import java.net.SocketException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ThreadLocalInvocationHandlerTest { private static final String CHECKED_EXCEPTION_MSG = "Throwing a checked exception."; private static final String UNCHECKED_EXCEPTION_MSG = "Throwing an unchecked exception."; private static final String ERROR_MSG = "Throwing an error."; private static final String THROWABLE_MSG = "Throwing a throwable."; private TestIface testIface; private ExpectedException expectedException = ExpectedException.none(); @Rule public ExpectedException getExpectedExceptionRule() { return expectedException; } @Before public void setUp() throws Exception { ThreadLocalInvocationHandler<TestClass> subject = new ThreadLocalInvocationHandler<>(); subject.set(new TestClass()); testIface = (TestIface) Proxy.newProxyInstance(ThreadLocalInvocationHandler.class.getClassLoader(), new Class[] {TestIface.class}, subject); } @Test public void testCheckedExceptionPropagation() throws Exception { expectedException.expect(SocketException.class); expectedException.expectMessage(CHECKED_EXCEPTION_MSG); testIface.throwCheckedException(); } @Test public void testUncheckedExceptionPropagation() { expectedException.expect(IndexOutOfBoundsException.class); expectedException.expectMessage(UNCHECKED_EXCEPTION_MSG); testIface.throwUncheckedException(); } @Test public void testErrorPropagation() { expectedException.expect(AnnotationFormatError.class); expectedException.expectMessage(ERROR_MSG); testIface.throwError(); } @Test public void testThrowablePropagation() throws Throwable { expectedException.expect(Throwable.class); expectedException.expectMessage(THROWABLE_MSG); testIface.throwThrowable(); } private interface TestIface { void throwCheckedException() throws Exception; void throwUncheckedException(); void throwError(); void throwThrowable() throws Throwable; } private class TestClass implements TestIface { @Override public void throwCheckedException() throws Exception { throw new SocketException(CHECKED_EXCEPTION_MSG); } @Override public void throwUncheckedException() { throw new IndexOutOfBoundsException(UNCHECKED_EXCEPTION_MSG); } @Override public void throwError() { throw new AnnotationFormatError(ERROR_MSG); } @Override public void throwThrowable() throws Throwable { throw new Throwable(THROWABLE_MSG); } } }
1,322
445
<reponame>andreasbossard/deutschland """ Auswärtiges Amt OpenData Schnittstelle Dies ist die Beschreibung für die Schnittstelle zum Zugriff auf die Daten des [Auswärtigen Amtes](https://www.auswaertiges-amt.de/de/) im Rahmen der [OpenData](https://www.auswaertiges-amt.de/de/open-data-schnittstelle/736118) Initiative. ## Deaktivierung Die Schnittstelle kann deaktiviert werden, in dem Fall wird ein leeres JSON-Objekt zurückgegeben. ## Fehlerfall Im Fehlerfall wird ein leeres JSON-Objekt zurückgegeben. ## Nutzungsbedingungen Die Nutzungsbedingungen sind auf der [OpenData-Schnittstelle](https://www.auswaertiges-amt.de/de/open-data-schnittstelle/736118) des Auswärtigen Amtes zu finden. ## Änderungen ### version 1.0.1 (September 2021) * `content` (-> Details des Reise- und Sicherheitshinweis) wurde von [`/travelwarning`](#operations-default-getTravelwarning) entfernt -> bitte ab jetzt [`/travelwarning/{contentId}`](#operations-default-getSingleTravelwarning) nutzen um `content` abzufragen # noqa: E501 The version of the OpenAPI document: 1.0.1 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from deutschland.travelwarning.api_client import ApiClient from deutschland.travelwarning.api_client import Endpoint as _Endpoint from deutschland.travelwarning.model.response_address import ResponseAddress from deutschland.travelwarning.model.response_download import ResponseDownload from deutschland.travelwarning.model.response_warning import ResponseWarning from deutschland.travelwarning.model.response_warnings import ResponseWarnings from deutschland.travelwarning.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, datetime, file_type, none_type, validate_and_convert_types, ) class DefaultApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client self.get_healthcare_endpoint = _Endpoint( settings={ "response_type": (ResponseDownload,), "auth": [], "endpoint_path": "/healthcare", "operation_id": "get_healthcare", "http_method": "GET", "servers": None, }, params_map={ "all": [], "required": [], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": {}, "attribute_map": {}, "location_map": {}, "collection_format_map": {}, }, headers_map={ "accept": ["application/json"], "content_type": [], }, api_client=api_client, ) self.get_representatives_country_endpoint = _Endpoint( settings={ "response_type": (ResponseAddress,), "auth": [], "endpoint_path": "/representativesInCountry", "operation_id": "get_representatives_country", "http_method": "GET", "servers": None, }, params_map={ "all": [], "required": [], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": {}, "attribute_map": {}, "location_map": {}, "collection_format_map": {}, }, headers_map={ "accept": ["text/json;charset=UTF-8"], "content_type": [], }, api_client=api_client, ) self.get_representatives_germany_endpoint = _Endpoint( settings={ "response_type": (ResponseAddress,), "auth": [], "endpoint_path": "/representativesInGermany", "operation_id": "get_representatives_germany", "http_method": "GET", "servers": None, }, params_map={ "all": [], "required": [], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": {}, "attribute_map": {}, "location_map": {}, "collection_format_map": {}, }, headers_map={ "accept": ["text/json;charset=UTF-8"], "content_type": [], }, api_client=api_client, ) self.get_single_travelwarning_endpoint = _Endpoint( settings={ "response_type": (ResponseWarning,), "auth": [], "endpoint_path": "/travelwarning/{contentId}", "operation_id": "get_single_travelwarning", "http_method": "GET", "servers": None, }, params_map={ "all": [ "content_id", ], "required": [ "content_id", ], "nullable": [], "enum": [], "validation": [ "content_id", ], }, root_map={ "validations": { ("content_id",): { "inclusive_minimum": 1, }, }, "allowed_values": {}, "openapi_types": { "content_id": (int,), }, "attribute_map": { "content_id": "contentId", }, "location_map": { "content_id": "path", }, "collection_format_map": {}, }, headers_map={ "accept": ["text/json;charset=UTF-8"], "content_type": [], }, api_client=api_client, ) self.get_state_names_endpoint = _Endpoint( settings={ "response_type": (ResponseDownload,), "auth": [], "endpoint_path": "/stateNames", "operation_id": "get_state_names", "http_method": "GET", "servers": None, }, params_map={ "all": [], "required": [], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": {}, "attribute_map": {}, "location_map": {}, "collection_format_map": {}, }, headers_map={ "accept": ["application/json"], "content_type": [], }, api_client=api_client, ) self.get_travelwarning_endpoint = _Endpoint( settings={ "response_type": (ResponseWarnings,), "auth": [], "endpoint_path": "/travelwarning", "operation_id": "get_travelwarning", "http_method": "GET", "servers": None, }, params_map={ "all": [], "required": [], "nullable": [], "enum": [], "validation": [], }, root_map={ "validations": {}, "allowed_values": {}, "openapi_types": {}, "attribute_map": {}, "location_map": {}, "collection_format_map": {}, }, headers_map={ "accept": ["text/json;charset=UTF-8"], "content_type": [], }, api_client=api_client, ) def get_healthcare(self, **kwargs): """Gibt die Merkblätter des Gesundheitsdienstes zurück # noqa: E501 Merkblätter des Gesundheitsdienstes als Link auf ein PDF # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_healthcare(async_req=True) >>> result = thread.get() Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: ResponseDownload If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index") return self.get_healthcare_endpoint.call_with_http_info(**kwargs) def get_representatives_country(self, **kwargs): """Gibt eine Liste der deutschen Vertretungen im Ausland zurück # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_representatives_country(async_req=True) >>> result = thread.get() Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: ResponseAddress If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index") return self.get_representatives_country_endpoint.call_with_http_info(**kwargs) def get_representatives_germany(self, **kwargs): """Gibt eine Liste der ausländischen Vertretungen in Deutschland zurück # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_representatives_germany(async_req=True) >>> result = thread.get() Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: ResponseAddress If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index") return self.get_representatives_germany_endpoint.call_with_http_info(**kwargs) def get_single_travelwarning(self, content_id, **kwargs): """Gibt einen Reise- und Sicherheitshinweis zurück # noqa: E501 Gibt den vollständigen Datensatz eines Reise- und Sicherheitshinweises zurück. Benötigt die jeweilige ID siehe /travelwarning # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_single_travelwarning(content_id, async_req=True) >>> result = thread.get() Args: content_id (int): Die ID des Reise- und Sicherheitshinweises, IDs siehe /travelwarning Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: ResponseWarning If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index") kwargs["content_id"] = content_id return self.get_single_travelwarning_endpoint.call_with_http_info(**kwargs) def get_state_names(self, **kwargs): """Gibt das Verzeichnis der Staatennamen zurück # noqa: E501 Verzeichnis der Staatennamen als Link auf eine XML- oder CSV-Datei. Eine PDF-Datei mit Nutzungshinweisen wird ebenfalls zurückgegeben. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_state_names(async_req=True) >>> result = thread.get() Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: ResponseDownload If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index") return self.get_state_names_endpoint.call_with_http_info(**kwargs) def get_travelwarning(self, **kwargs): """Gibt alle Reise- und Sicherheitshinweise zurück # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_travelwarning(async_req=True) >>> result = thread.get() Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: ResponseWarnings If the method is called asynchronously, returns the request thread. """ kwargs["async_req"] = kwargs.get("async_req", False) kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) kwargs["_preload_content"] = kwargs.get("_preload_content", True) kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) kwargs["_host_index"] = kwargs.get("_host_index") return self.get_travelwarning_endpoint.call_with_http_info(**kwargs)
10,949
6,215
{ "documentationUrl": "https://docs.airbyte.io/integrations/sources/looker", "connectionSpecification": { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Looker Spec", "type": "object", "required": ["domain", "client_id", "client_secret"], "additionalProperties": false, "properties": { "domain": { "type": "string", "examples": [ "domainname.looker.com", "looker.clientname.com", "172.16.17.32:8000" ], "description": "Domain for your Looker account, e.g. airbyte.cloud.looker.com,looker.[clientname].com,IP address" }, "client_id": { "title": "Client ID", "type": "string", "description": "The Client ID is first part of an API3 key that is specific to each Looker user. See the <a href=\"https://docs.airbyte.io/integrations/sources/looker\">docs</a> for more information on how to generate this key." }, "client_secret": { "title": "Client Secret", "type": "string", "description": "The Client Secret is second part of an API3 key." }, "run_look_ids": { "title": "Look IDs to Run", "type": "array", "items": { "type": "string", "pattern": ["^[0-9]*$"] }, "description": "The IDs of any Looks to run (optional)" } } } }
614
2,231
/** * Copyright (c) 2007-2009, JAGaToo Project Group all rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the 'Xith3D Project Group' nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) A * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE */ package org.jagatoo.loaders.models.collada.stax; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * A float element. * Used in ShadingParameters. * * @author <NAME> (aka BlueSky) * @author <NAME> (aka qbproger) */ public class XMLFloat { public float _float; public void parse( XMLStreamReader parser, String endTag ) throws XMLStreamException { for ( int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next() ) { switch ( event ) { case XMLStreamConstants.START_ELEMENT: { if ( parser.getLocalName().equals( "float" ) ) { try { _float = Float.parseFloat( parser.getElementText() ); } catch (NumberFormatException e) { // Defold-fix: // Some Collada exporters (such the default one in Maya) sometimes output "-1.#IND00" as float entries. // We need to catch the format exception and simply "parse" it as a zero. // In the future we might want to log a build (and Editor 2) warning here, issue; DEF-2917 _float = 0.0f; } } break; } case XMLStreamConstants.END_ELEMENT: { if ( parser.getLocalName().equals( endTag ) ) return; break; } } } } }
1,342
325
/* * The MIT License (MIT) * * Copyright (c) 2014-2018, <NAME> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * This file is part of the Simba project. */ #include "simba.h" #define IP 192.168.0.7 static struct http_server_t server; THRD_STACK(listener_stack, 1024); THRD_STACK(connection_stack, 1500); static int request_index(struct http_server_connection_t *connection_p, struct http_server_request_t *request_p); static struct http_server_route_t routes[] = { { .path_p = "/index.html", .callback = request_index }, { .path_p = NULL, .callback = NULL } }; static struct http_server_listener_t listener = { .address_p = STRINGIFY(IP), .port = 80, .thrd = { .name_p = "http_listener", .stack = { .buf_p = listener_stack, .size = sizeof(listener_stack) } } }; static struct http_server_connection_t connections[] = { { .thrd = { .name_p = "http_conn_0", .stack = { .buf_p = connection_stack, .size = sizeof(connection_stack) } } }, { .thrd = { .name_p = NULL } } }; /** * Handler for the index request. */ static int request_index(struct http_server_connection_t *connection_p, struct http_server_request_t *request_p) { static const char index_html[] = "<!DOCTYPE HTML>\n" "<html>\n" " <body>\n" " Hello from Simba!\n" " </body>\n" "</html>\n"; struct http_server_response_t response; std_printf(FSTR("/index.html requested\r\n")); /* Only the GET action is supported. */ if (request_p->action != http_server_request_action_get_t) { return (-1); } /* Create the response. */ response.code = http_server_response_code_200_ok_t; response.content.type = http_server_content_type_text_html_t; response.content.buf_p = index_html; response.content.size = strlen(response.content.buf_p); return (http_server_response_write(connection_p, request_p, &response)); } /** * Default page handler. */ static int no_route(struct http_server_connection_t *connection_p, struct http_server_request_t *request_p) { struct http_server_response_t response; /* Create the response. */ response.code = http_server_response_code_404_not_found_t; response.content.type = http_server_content_type_text_html_t; response.content.buf_p = NULL; response.content.size = 0; return (http_server_response_write(connection_p, request_p, &response)); } int main() { sys_start(); /* Create the HTTPS server. */ if (http_server_init(&server, &listener, connections, NULL, routes, no_route) != 0) { std_printf(FSTR("http_server_init() failed\r\n")); return (-1); } if (http_server_start(&server) != 0) { std_printf(FSTR("http_server_start() failed\r\n")); return (-1); } std_printf(FSTR("HTTP server running. " "Enter URL 'http://" STRINGIFY(IP) "/index.html' " "in your web browser.\r\n")); thrd_suspend(NULL); return (0); }
1,986
348
/* * Copyright (c) 2010-2017, ALICE project, Inria * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ALICE Project-Team nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: <NAME> * * <EMAIL> * http://www.loria.fr/~levy * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ #ifndef GEOGRAM_VORONOI_RVD_CALLBACK #define GEOGRAM_VORONOI_RVD_CALLBACK #include <geogram/basic/common.h> #include <geogram/voronoi/generic_RVD_vertex.h> #include <geogram/mesh/mesh.h> #include <geogram/basic/numeric.h> #include <geogram/basic/attributes.h> namespace GEOGen { class SymbolicVertex; class Polygon; class ConvexCell; } namespace GEO { class RVDVertexMap; class Mesh; namespace Process { class SpinLockArray; } } /** * \file geogram/voronoi/RVD_callback.h * \brief Declaration of base types for implementing user-defined * code that queries the cells of a restricted Voronoi diagram. */ namespace GEO { /***************************************************************/ /** * \brief Baseclass for user functions called for each * element (polygon or polyhedron) of a restricted Voronoi * diagram traversal. */ class GEOGRAM_API RVDCallback { public: /** * \brief RVDCallback constructor. */ RVDCallback(); /** * \brief RVDCallback destructor. */ virtual ~RVDCallback(); /** * \brief Called at the beginning of the RVD traversal. */ virtual void begin(); /** * \brief Called at the end of the RVD traversal. */ virtual void end(); /** * \brief Gets the index of the seed that corresponds to the current * polygon/polyhedron. * \return The index of the seed that corresponds to the * current polygon/polyhedron. * \details The current polygon/polyhedron is the intersection * between a Voronoi cell (associted with a seed) and a simplex. */ index_t seed() const { return seed_; } /** * \brief Gets the index of the simplex that corresponds to the * current polygon/polyhedron. * \return The index of the simplex that corresponds to the * current polygon/polyhedron. Points to a simplex in the mesh that the * Voronoi diagram is restricted to. * \details The current polygon/polyhedron is the intersection between * a Voronoi cell and a simplex. */ index_t simplex() const { return simplex_; } /** * \brief Sets the spinlocks array. * \details In multithreading mode, a spinlocks array can * be used to manage concurrent accesses. * \param[in] spinlocks a pointer to the Process::SpinLockArray * or nullptr if no spinlocks are used. */ void set_spinlocks(Process::SpinLockArray* spinlocks) { spinlocks_ = spinlocks; } protected: index_t seed_; index_t simplex_; Process::SpinLockArray* spinlocks_; }; /***************************************************************/ /** * \brief Baseclass for user functions called for each * polygon of a surfacic restricted Voronoi diagram. * \details A surfacic restricted Voronoi diagram is the * intersection between Voronoi cells and the triangles of * a given triangulated mesh. The member functions of this * class are called for each intersection between a Voronoi * cell and a triangle. */ class GEOGRAM_API RVDPolygonCallback : public RVDCallback { public: /** * \brief PolyhedronCallback constructor. */ RVDPolygonCallback(); /** * \brief PolyhedronCallback destructor. */ ~RVDPolygonCallback() override; /** * \copydoc RVDCallback::begin() */ void begin() override; /** * \copydoc RVDCallback::end() */ void end() override; /** * \brief The default callback called for each polygon * \param[in] v index of current Delaunay seed * \param[in] t index of current mesh triangle * \param[in] C intersection between current mesh triangle * and the Voronoi cell of \p v */ virtual void operator() ( index_t v, index_t t, const GEOGen::Polygon& C ) const; }; /***************************************************************/ /** * \brief Baseclass for user functions called for each * polyhedron of a volumetric restricted Voronoi diagram. * \details A volumetric restricted Voronoi diagram is the * intersection between Voronoi cells and the tetrahedra of * a given tetrahedral mesh. The member functions of this * class are called for each intersection between a Voronoi * cell and a tetrahedron. */ class GEOGRAM_API RVDPolyhedronCallback : public RVDCallback { public: /** * \brief PolyhedronCallback constructor. */ RVDPolyhedronCallback(); /** * \brief PolyhedronCallback destructor. */ ~RVDPolyhedronCallback() override; /** * \copydoc RVDCallback::begin() */ void begin() override; /** * \copydoc RVDCallback::end() */ void end() override; /** * \brief The default callback called for each polyhedron * \details This default implementation routes the callback to the * begin_polyhedron_internal(), end_polyhedron_internal(), * begin_facet_internal(), end_facet_internal() and vertex_internal() * functions (that in turn route the callbacks to their without * "_internal" counterparts). * \param[in] v index of current Delaunay seed * \param[in] t index of current mesh tetrahedron * \param[in] C intersection between current mesh tetrahedron * and the Voronoi cell of \p v */ virtual void operator() ( index_t v, index_t t, const GEOGen::ConvexCell& C ) const; /** * \brief Called at the beginning of each intersection polyhedron. * \details Each intersection polyhedron is defined as the intersection * between a Voronoi cell and a tetrahedron. * \param[in] seed index of the seed associated with the Voronoi cell * \param[in] tetrahedron index of the tetrahedron */ virtual void begin_polyhedron(index_t seed, index_t tetrahedron); /** * \brief Called at the beginning of each facet of each intersection * polyhedron. * \details A facet can be a subset of either a bisector (defined by * two seeds), or it can be a subset of a facet of a tetrahedron. * \param[in] facet_seed if the facet corresponds to a bisector, * the index of the seed that defines the bisector, or index_t(-1) * otherwise * \param[in] facet_tet if the facet corresponds to a facet * of the current tetrahedron, the index of the tetrahedron * adjacent to that facet, or index_t(-1) otherwise */ virtual void begin_facet(index_t facet_seed, index_t facet_tet); /** * \brief Called for each vertex of the current facet. * \param[in] geometry a pointer to the coordinates of the vertex * \param[in] symb the symbolic representation of the vertex */ virtual void vertex( const double* geometry, const GEOGen::SymbolicVertex& symb ); /** * \brief Called at the end of each polyhedron facet. */ virtual void end_facet(); /** * \brief Called at the end of each polyhedron. */ virtual void end_polyhedron(); /** * \brief Gets the index of the tetrahedron that corresponds to the * current polyhedron. * \return The index of the tetrahedron that corresponds to the * current polyhedron. * \details The current polyhedron is the intersection between a Voronoi * cell and a tetrahedron. */ index_t tet() const { return simplex(); } /** * \brief Gets the index of the seed that defines the bisector on which * the current facet lies, or index_t(-1). * \return The index of the seed that defines the bisector on which * the current facet lies, or index_t(-1). * \details Each facet is either on a bisector or on a tetrahedron * facet. If the current facet is on a bisector, it is defined by * seed() and facet_seed(), otherwise facet_seed() returns index_t(-1). */ index_t facet_seed() const { return facet_seed_; } /** * \brief Gets the index of the tetrahedron adjacent to the current * facet or index_t(-1) if there is no such facet. * \return the index of the tetrahedron adjacent to the current * facet or index_t(-1). * \details Each facet is either on a bisector or on a tetrahedron * facet. If the current facet is on a tetrahedron facet, then it * is defined by tet() and facet_tet(), otherwise * facet_tet() returns index_t(-1). */ index_t facet_tet() const { return facet_tet_; } /** * \brief Specifies whether internal tetrahedron facets should be * removed. * \details If set, a single polyhedron is generated for each * (connected component) of the restricted Voronoi cells. If not * set (default), each tetrahedron-Voronoi cell intersection * generates a new polyhedron. * \param[in] x true if internal facets should be removed, false * otherwise */ void set_simplify_internal_tet_facets(bool x) { simplify_internal_tet_facets_ = x; } /** * \brief Specifies whether Voronoi facets should be simplified. * \details By default, the computed Voronoi facets are composed * of multiple polyhedra that correspond to the intersection with * the tetrahedra of the input volume mesh. They can be simplified * and replaced by a single polygon. This implies simplifying the * internal tetrahedron facets and using a mesh. * \param[in] x true if Voronoi facets should be simplified, * false otherwise. */ void set_simplify_voronoi_facets(bool x) { simplify_voronoi_facets_ = x; if(x) { set_simplify_internal_tet_facets(true); set_use_mesh(true); } } /** * \brief Specifies whether boundary facets should be simplified. * \details By default, the intersection between a Voronoi cell and * the boundary is possibly composed of multiple polygons, that * correspond to the initial polygons of the boundary. They can be * simplified as a single polygon per Voronoi cell. This implies * simplifying the internal tetrahedron facets, simplifying the * Voronoi facets and using a mesh. * \param[in] x true if boundary facets should be simplified, * false otherwise. * \param[in] angle_threshold an edge shared by two adjacent facets * is suppressed if the angle between the facet normals is smaller * than \p angle_threshold */ void set_simplify_boundary_facets(bool x, double angle_threshold=45.0) { simplify_boundary_facets_ = x; if(x) { set_simplify_voronoi_facets(true); simplify_boundary_facets_angle_threshold_ = angle_threshold; } else { simplify_boundary_facets_angle_threshold_ = 0.0; } } /** * \brief Specifies whether non-convex facets should be tessellated. * \param[in] x true if non-convex facets should be tessellated, * false otherwise. * \details Only taken into account if set_use_mesh(true) was called. */ void set_tessellate_non_convex_facets(bool x) { tessellate_non_convex_facets_ = x; } /** * \brief Specifies whether a mesh should be built for each * traversed polyhedron. * \details The build mesh can then be modified (e.g., simplified) * by overloading process_mesh(). * \param[in] x true if a mesh should be build, false otherwise */ void set_use_mesh(bool x); /** * \brief Sets the dimension of the internal mesh if need be. * \details This function is called automatically by * RestrictedVoronoiDiagram::for_each_polyhedron(). * \param[in] dim the dimension of the mesh (3 for 3d). */ void set_dimension(index_t dim) { if(use_mesh_) { mesh_.vertices.set_dimension(dim); } } protected: /** * \brief Filters callbacks between operator() and client callbacks. * \details This is used to implement cells simplifications (remove * internal boundaries and intersections with tetrahedra). * \see begin_polyhedron() */ virtual void begin_polyhedron_internal( index_t seed, index_t tetrahedron ); /** * \brief Filters callbacks between operator() and client callbacks. * \details This is used to implement cells simplifications (remove * internal boundaries and intersections with tetrahedra). * \see begin_facet() */ virtual void begin_facet_internal( index_t facet_seed, index_t facet_tet ); /** * \brief Filters callbacks between operator() and client callbacks. * \details This is used to implement cells simplifications (remove * internal boundaries and intersections with tetrahedra). * \see vertex() */ virtual void vertex_internal( const double* geometry, const GEOGen::SymbolicVertex& symb ); /** * \brief Filters callbacks between operator() and client callbacks. * \details This is used to implement cells simplifications (remove * internal boundaries and intersections with tetrahedra). * \see end_facet() */ virtual void end_facet_internal(); /** * \brief Filters callbacks between operator() and client callbacks. * \details This is used to implement cells simplifications (remove * internal boundaries and intersections with tetrahedra). * \see end_polyhedron() */ virtual void end_polyhedron_internal(); /** * \brief If use_mesh is set, then this function is called for * each generated mesh. * \details Default implementation simplifies the mesh based on * sipmlify_xxx flags, then it calls user callbacks * begin_facet(), end_facet(), vertex() for each facet of the mesh, * as well as begin_polyhedron() and end_polyhedron() once per mesh. * Derived classes may modify (e.g., simplify) the mesh before calling * user callbacks. */ virtual void process_polyhedron_mesh(); protected: index_t facet_seed_; index_t facet_tet_; index_t last_seed_; bool simplify_internal_tet_facets_; bool simplify_voronoi_facets_; bool simplify_boundary_facets_; double simplify_boundary_facets_angle_threshold_; bool tessellate_non_convex_facets_; bool use_mesh_; bool facet_is_skipped_; Mesh mesh_; Attribute<GEOGen::SymbolicVertex> mesh_vertex_sym_; Attribute<index_t> mesh_facet_seed_; Attribute<index_t> mesh_facet_tet_; RVDVertexMap* vertex_map_; vector<index_t> base_current_facet_; }; /***************************************************************/ /** * \brief Constructs a polyhedral mesh from a restricted Voronoi diagram. * \details Its member functions are called for each RVD polyhedron, * i.e. the intersections between the volumetric mesh tetrahedra and * the Voronoi cells. Based on set_simplify_xxx(), a smaller number of * polyhedra can be generated. */ class GEOGRAM_API BuildRVDMesh : public RVDPolyhedronCallback { public: /** * \brief BuildRVDMesh constructor. * \param[out] output_mesh a reference to the generated mesh */ BuildRVDMesh(Mesh& output_mesh); /** * \brief BuildRVDMesh destructor. */ ~BuildRVDMesh() override; /** * \brief Specifies whether ids should be generated. * \details If enabled, unique vertex ids, seed ids and cell ids are * generated and attached to the mesh vertices ("vertex_id" attribute) * and mesh facets ("seed_id" and "cell_id" attributes) respectively. * There is a cell_id per generated polyhedron, and seed_id refers to * the Voronoi seed (the point that the Voronoi cell is associated * with). * \param[in] x true if ids should be generated, false * otherwise (default) */ void set_generate_ids(bool x); /** * \brief Defines the optional shrink factor for cells. * \param[in] x shrink factor, 0.0 means no shrink, 1.0 means * maximum shrink (cell reduced to a point). */ void set_shrink(double x); /** * \brief Called at the beginning of RVD traversal. */ void begin() override; /** * \brief Called at the end of RVD traversal. */ void end() override; /** * \brief Called at the beginning of each RVD polyhedron. * \param[in] seed , tetrahedron the (seed,tetrahedron) pair that * defines the RVD polyhedron, as the intersection between the Voronoi * cell of the seed and the tetrahedron. */ void begin_polyhedron(index_t seed, index_t tetrahedron) override; /** * \copydoc RVDPolyhedronCallback::begin_facet() */ void begin_facet(index_t facet_seed, index_t facet_tet_facet) override; /** * \copydoc RVDPolyhedronCallback::vertex() */ void vertex( const double* geometry, const GEOGen::SymbolicVertex& symb ) override; /** * \copydoc RVDPolyhedronCallback::end_facet() */ void end_facet() override; /** * \copydoc RVDPolyhedronCallback::end_polyhedron() */ void end_polyhedron() override; /** * \copydoc RVDPolyhedronCallback::process_polyhedron_mesh() */ void process_polyhedron_mesh() override; private: vector<index_t> current_facet_; Mesh& output_mesh_; RVDVertexMap* global_vertex_map_; RVDVertexMap* cell_vertex_map_; double shrink_; bool generate_ids_; Attribute<int> cell_id_; Attribute<int> seed_id_; Attribute<int> vertex_id_; Attribute<int> facet_seed_id_; index_t current_cell_id_; }; /***************************************************************/ } #endif
6,333
2,528
<reponame>fjavierv/react-md<gh_stars>1000+ { "out": "./packages/documentation/public/tsdocs", "entryPoints": [ "packages/alert/src/index.ts", "packages/app-bar/src/index.ts", "packages/autocomplete/src/index.ts", "packages/avatar/src/index.ts", "packages/badge/src/index.ts", "packages/button/src/index.ts", "packages/card/src/index.ts", "packages/chip/src/index.ts", "packages/dialog/src/index.ts", "packages/divider/src/index.ts", "packages/expansion-panel/src/index.ts", "packages/form/src/index.ts", "packages/icon/src/index.ts", "packages/layout/src/index.ts", "packages/link/src/index.ts", "packages/list/src/index.ts", "packages/media/src/index.ts", "packages/menu/src/index.ts", "packages/overlay/src/index.ts", "packages/portal/src/index.ts", "packages/progress/src/index.ts", "packages/sheet/src/index.ts", "packages/states/src/index.ts", "packages/table/src/index.ts", "packages/tabs/src/index.ts", "packages/tooltip/src/index.ts", "packages/transition/src/index.ts", "packages/tree/src/index.ts", "packages/typography/src/index.ts", "packages/utils/src/index.ts" ], "tsconfig": "./tsconfig.typedoc.json", "readme": "packages/react-md/README.md", "listInvalidSymbolLinks": true }
564
1,248
<reponame>mario-renau-alstom/atlas<filename>intg/src/main/java/org/apache/atlas/model/notification/AtlasNotificationStringMessage.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.notification; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class AtlasNotificationStringMessage extends AtlasNotificationBaseMessage { private String message = null; public AtlasNotificationStringMessage() { super(MessageVersion.CURRENT_VERSION); } public AtlasNotificationStringMessage(String message) { super(MessageVersion.CURRENT_VERSION); this.message = message; } public AtlasNotificationStringMessage(String message, String msgId, CompressionKind compressionKind) { super(MessageVersion.CURRENT_VERSION, msgId, compressionKind); this.message = message; } public AtlasNotificationStringMessage(String message, String msgId, CompressionKind compressionKind, int msgSplitIdx, int msgSplitCount) { super(MessageVersion.CURRENT_VERSION, msgId, compressionKind, msgSplitIdx, msgSplitCount); this.message = message; } public AtlasNotificationStringMessage(byte[] encodedBytes, String msgId, CompressionKind compressionKind) { super(MessageVersion.CURRENT_VERSION, msgId, compressionKind); this.message = AtlasNotificationBaseMessage.getStringUtf8(encodedBytes); } public AtlasNotificationStringMessage(byte[] encodedBytes, int offset, int length, String msgId, CompressionKind compressionKind, int msgSplitIdx, int msgSplitCount) { super(MessageVersion.CURRENT_VERSION, msgId, compressionKind, msgSplitIdx, msgSplitCount); this.message = new String(encodedBytes, offset, length); } public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }
1,049
511
<reponame>SenthilKumarGS/TizenRT<filename>external/iotivity/iotivity_1.2-rel/resource/csdk/connectivity/util/src/camanager/bt_le_manager/android/camanagerleutil.c /* **************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include <jni.h> #include "cacommon.h" #include "logger.h" #include "cacommonutil.h" #include "camanagerleutil.h" #include "caleclient.h" #include "caleutils.h" #define TAG "OIC_CA_MANAGER_UTIL" static const char CLASSPATH_CONTENT_PREF[] = "android/content/SharedPreferences"; static const char CLASSPATH_CONTENT_PREF_EDITOR[] = "android/content/SharedPreferences$Editor"; static const char CLASSPATH_CONTEXT[] = "android/content/Context"; static const char PREF_NAME_CONNECTED_DEVICE[] = "PREF_NAME_CONNECTED_DEVICE"; static const char PREF_KEY_CONNECTED_DEVICE[] = "PREF_KEY_CONNECTED_DEVICE"; static const char METHODID_BOOLEAN_RET_STRING_PARAM[] = "(Ljava/lang/String;)Z"; static jobject CAManagerGetAdapterContext(JNIEnv *env) { OIC_LOG(DEBUG, TAG, "CAManagerGetAdapterContext"); VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null"); return NULL; } jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM); if (!jni_mid_getDefaultAdapter) { OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null"); return NULL; } jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter); if (!jni_obj_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null"); return NULL; } return jni_obj_BTAdapter; } jobject CAManagerGetRemoteDevice(JNIEnv *env, jstring address) { OIC_LOG(DEBUG, TAG, "IN - CAManagerGetRemoteDevice"); VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); VERIFY_NON_NULL_RET(address, TAG, "address is null", NULL); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null"); return NULL; } // get remote bt adapter method jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM); if (!jni_mid_getDefaultAdapter) { OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null"); return NULL; } // gat bt adapter object jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter); if (!jni_obj_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null"); return NULL; } jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getRemoteDevice", METHODID_BT_REMOTE_DEVICE); if (!jni_mid_getRemoteDevice) { OIC_LOG(ERROR, TAG, "jni_mid_getRemoteDevice is null"); return NULL; } jobject jni_obj_device = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getRemoteDevice, address); if (!jni_obj_device) { OIC_LOG(ERROR, TAG, "jni_obj_device is null"); return NULL; } OIC_LOG(DEBUG, TAG, "OUT - CAManagerGetRemoteDevice"); return jni_obj_device; } bool CAManagerIsDeviceBonded(JNIEnv *env, jobject btDevice) { OIC_LOG(DEBUG, TAG, "IN - CAManagerIsDeviceBonded"); VERIFY_NON_NULL(env, TAG, "env is null"); VERIFY_NON_NULL(btDevice, TAG, "btDevice is null"); jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE); if (!jni_cid_BTDevice) { OIC_LOG(ERROR, TAG, "jni_cid_BTDevice is null"); return false; } jmethodID jni_mid_getBondState = (*env)->GetMethodID(env, jni_cid_BTDevice, "getBondState", "()I"); if (!jni_mid_getBondState) { OIC_LOG(ERROR, TAG, "jni_mid_getBondState is null"); return false; } jint jni_bond_state = (*env)->CallIntMethod(env, btDevice, jni_mid_getBondState); OIC_LOG_V(DEBUG, TAG, "bond state is %d", jni_bond_state); // BOND_BONDED - Constant value : 12 (0x0000000c) jfieldID id_bonded = (*env)->GetStaticFieldID(env, jni_cid_BTDevice, "BOND_BONDED", "I"); if (!id_bonded) { OIC_LOG(ERROR, TAG, "id_bonded is null"); return false;; } jint jni_bonded_const = (*env)->GetStaticIntField(env, jni_cid_BTDevice, id_bonded); if (jni_bond_state == jni_bonded_const) { OIC_LOG(INFO, TAG, "it is not bonded to each other"); return false; } OIC_LOG(DEBUG, TAG, "OUT - CAManagerIsDeviceBonded"); return true; } bool CAManagerControlAdapter(JNIEnv *env, bool control_flag) { OIC_LOG(DEBUG, TAG, "IN - CAManagerControlAdapter"); VERIFY_NON_NULL_RET(env, TAG, "env", false); jobject jni_obj_BTAdapter = CAManagerGetAdapterContext(env); if (!jni_obj_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null"); return false; } jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null"); return NULL; } OIC_LOG_V(DEBUG, TAG, "change adapter : %d", control_flag); jmethodID jni_mid_control = NULL; if (control_flag) { // enable() jni_mid_control = (*env)->GetMethodID(env, jni_cid_BTAdapter, "enable", "()Z"); } else { // disable() jni_mid_control = (*env)->GetMethodID(env, jni_cid_BTAdapter, "disable", "()Z"); } if (!jni_mid_control) { OIC_LOG(ERROR, TAG, "jni_mid_control is null"); return false; } OIC_LOG(DEBUG, TAG, "CALL API - Adapter Will be Changed"); jboolean jni_res = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_control); return jni_res; } CAResult_t CAManagerReadRemoteRssi(JNIEnv *env, jobject bluetoothGatt) { VERIFY_NON_NULL(env, TAG, "env is null"); VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null"); if (!CALEIsEnableBTAdapter(env)) { OIC_LOG(INFO, TAG, "BT adapter is not enabled"); return CA_ADAPTER_NOT_ENABLED; } // get BluetoothGatt class jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT); if (!jni_cid_BluetoothGatt) { OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null"); return CA_STATUS_FAILED; } jmethodID jni_mid_readRemoteRssi = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "readRemoteRssi", "()Z"); if (!jni_mid_readRemoteRssi) { OIC_LOG(ERROR, TAG, "jni_mid_readRemoteRssi is null"); return CA_STATUS_FAILED; } // call disconnect gatt method jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_readRemoteRssi); if (!ret) { OIC_LOG(ERROR, TAG, "readremoteRssi has not been called"); return CA_STATUS_FAILED; } return CA_STATUS_OK; } jobject CAManagerGetSharedPreference(JNIEnv *env, jobject context, jstring prefName) { VERIFY_NON_NULL_RET(env, TAG, "env", NULL); VERIFY_NON_NULL_RET(context, TAG, "context", NULL); VERIFY_NON_NULL_RET(prefName, TAG, "prefName", NULL); jclass jni_cls_context = (*env)->FindClass(env, CLASSPATH_CONTEXT); if (!jni_cls_context) { OIC_LOG(ERROR, TAG, "jni_cls_context is null"); return NULL; } // getSharedPreferences jmethodID jni_mid_getPref = (*env)->GetMethodID(env, jni_cls_context, "getSharedPreferences", "(Ljava/lang/String;I)" "Landroid/content/SharedPreferences;"); if (!jni_mid_getPref) { OIC_LOG(ERROR, TAG, "jni_mid_getPref is null"); return NULL; } jobject jni_obj_sharedPref = (*env)->CallObjectMethod(env, context, jni_mid_getPref, prefName, 0); if (!jni_obj_sharedPref) { OIC_LOG(ERROR, TAG, "jni_obj_sharedPref is null"); return NULL; } return jni_obj_sharedPref; } jobject CAManagerGetPrefEditObject(JNIEnv *env, jobject context) { OIC_LOG(DEBUG, TAG, "IN-CAManagerGetPrefEditObject"); VERIFY_NON_NULL_RET(env, TAG, "env", NULL); VERIFY_NON_NULL_RET(context, TAG, "context", NULL); jstring jni_str_prefName = (*env)->NewStringUTF(env, PREF_NAME_CONNECTED_DEVICE); if (!jni_str_prefName) { OIC_LOG(ERROR, TAG, "jni_str_prefName is null"); return NULL; } jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE); if (!jni_str_prefKey) { OIC_LOG(ERROR, TAG, "jni_str_prefKey is null"); return NULL; } // get SharedPreference jobject jni_obj_pref = CAManagerGetSharedPreference(env, context, jni_str_prefName); if (!jni_obj_pref) { OIC_LOG(ERROR, TAG, "jni_obj_pref is null"); return NULL; } // edit() jobject jni_cls_pref = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF); if (!jni_cls_pref) { OIC_LOG(ERROR, TAG, "jni_cls_pref is null"); return NULL; } jmethodID jni_mid_prefEdit = (*env)->GetMethodID(env, jni_cls_pref, "edit", "()Landroid/content/SharedPreferences$Editor;"); if (!jni_mid_prefEdit) { OIC_LOG(ERROR, TAG, "jni_mid_prefEdit is null"); return NULL; } jobject jni_obj_prefEdit = (*env)->CallObjectMethod(env, jni_obj_pref, jni_mid_prefEdit); if (!jni_obj_prefEdit) { OIC_LOG(ERROR, TAG, "jni_obj_prefEdit is null"); return NULL; } OIC_LOG(DEBUG, TAG, "OUT-CAManagerGetPrefEditObject"); return jni_obj_prefEdit; } bool CAManagerUpdatePrefStringSet(JNIEnv *env, jobject context, jobject set) { OIC_LOG(DEBUG, TAG, "IN-CAManagerUpdatePrefStringSet"); VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(context, TAG, "context", false); VERIFY_NON_NULL_RET(set, TAG, "set", false); jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE); if (!jni_str_prefKey) { OIC_LOG(ERROR, TAG, "jni_str_prefKey is null"); return false; } jobject jni_obj_prefEdit = CAManagerGetPrefEditObject(env, context); if (!jni_obj_prefEdit) { OIC_LOG(ERROR, TAG, "jni_obj_prefEdit is null"); return false; } // putString() jobject jni_cls_edit = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF_EDITOR); if (!jni_cls_edit) { OIC_LOG(ERROR, TAG, "jni_cls_edit is null"); return false; } // get putString method interface jmethodID jni_mid_PrefPutStringSet = (*env)->GetMethodID(env, jni_cls_edit, "putStringSet", "(Ljava/lang/String;Ljava/util/Set;)" "Landroid/content/SharedPreferences" "$Editor;"); if (!jni_mid_PrefPutStringSet) { OIC_LOG(ERROR, TAG, "jni_mid_PrefPutStringSet is null"); return false; } jobject gSetString = (jobject)(*env)->NewGlobalRef(env, set); if (!gSetString) { OIC_LOG(ERROR, TAG, "gAddress is null"); return false; } OIC_LOG(DEBUG, TAG, "CALL API - request putString for SharedPreferences.Editor"); (*env)->CallObjectMethod(env, jni_obj_prefEdit, jni_mid_PrefPutStringSet, jni_str_prefKey, gSetString); // get commit method interface jmethodID jni_mid_PrefCommit = (*env)->GetMethodID(env, jni_cls_edit, "commit", "()Z"); if (!jni_mid_PrefCommit) { OIC_LOG(ERROR, TAG, "jni_mid_PrefCommit is null"); return false; } jboolean res = (*env)->CallBooleanMethod(env, jni_obj_prefEdit, jni_mid_PrefCommit); OIC_LOG(DEBUG, TAG, "OUT-CAManagerUpdatePrefStringSet"); return res; } jobject CAManagerGetPrefStringSet(JNIEnv *env, jobject context) { OIC_LOG(DEBUG, TAG, "CAManagerGetPrefStringSet"); VERIFY_NON_NULL_RET(env, TAG, "env", NULL); VERIFY_NON_NULL_RET(context, TAG, "context", NULL); jstring jni_str_prefName = (*env)->NewStringUTF(env, PREF_NAME_CONNECTED_DEVICE); if (!jni_str_prefName) { OIC_LOG(ERROR, TAG, "jni_str_prefName is null"); return NULL; } jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE); if (!jni_str_prefKey) { OIC_LOG(ERROR, TAG, "jni_str_prefKey is null"); return NULL; } // get SharedPreference jobject jni_obj_pref = CAManagerGetSharedPreference(env, context, jni_str_prefName); if (!jni_obj_pref) { OIC_LOG(ERROR, TAG, "jni_obj_pref is null"); return NULL; } // contains(String key) jobject jni_cls_pref = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF); if (!jni_cls_pref) { OIC_LOG(ERROR, TAG, "jni_cls_pref is null"); return NULL; } jmethodID jni_mid_getStringSet = (*env)->GetMethodID(env, jni_cls_pref, "getStringSet", "(Ljava/lang/String;Ljava/util/Set;)" "Ljava/util/Set;"); if (!jni_mid_getStringSet) { OIC_LOG(ERROR, TAG, "jni_mid_getStringSet is null"); return NULL; } jobject jni_defSet = CAManagerCreateSetString(env); if (!jni_defSet) { OIC_LOG(ERROR, TAG, "jni_defSet is null"); return NULL; } jobject value = (*env)->CallObjectMethod(env, jni_obj_pref, jni_mid_getStringSet, jni_str_prefKey, jni_defSet); return value; } bool CAManagerContainsPrefStringSet(JNIEnv *env, jobject context) { OIC_LOG(DEBUG, TAG, "CAManagerContainsPrefStringSet"); VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(context, TAG, "context", false); jstring jni_str_prefName = (*env)->NewStringUTF(env, PREF_NAME_CONNECTED_DEVICE); if (!jni_str_prefName) { OIC_LOG(ERROR, TAG, "jni_str_prefName is null"); return false; } jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE); if (!jni_str_prefKey) { OIC_LOG(ERROR, TAG, "jni_str_prefKey is null"); return false; } // get SharedPreference jobject jni_obj_pref = CAManagerGetSharedPreference(env, context, jni_str_prefName); if (!jni_obj_pref) { OIC_LOG(ERROR, TAG, "jni_obj_pref is null"); return false; } // contains(String key) jobject jni_cls_pref = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF); if (!jni_cls_pref) { OIC_LOG(ERROR, TAG, "jni_cls_pref is null"); return false; } jmethodID jni_mid_prefContains = (*env)->GetMethodID(env, jni_cls_pref, "contains", METHODID_BOOLEAN_RET_STRING_PARAM); if (!jni_mid_prefContains) { OIC_LOG(ERROR, TAG, "jni_mid_prefContains is null"); return false; } jboolean res = (*env)->CallBooleanMethod(env, jni_obj_pref, jni_mid_prefContains, jni_str_prefKey); OIC_LOG_V(DEBUG, TAG, "Preference - contains (%d)", res); return res; } bool CAManagerRemovePrefStringSet(JNIEnv *env, jobject context) { OIC_LOG(DEBUG, TAG, "CAManagerRemovePrefStringSet"); VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(context, TAG, "context", false); jstring jni_str_prefKey = (*env)->NewStringUTF(env, PREF_KEY_CONNECTED_DEVICE); if (!jni_str_prefKey) { OIC_LOG(ERROR, TAG, "jni_str_prefKey is null"); return false; } jobject jni_obj_prefEdit = CAManagerGetPrefEditObject(env, context); if (!jni_obj_prefEdit) { OIC_LOG(ERROR, TAG, "jni_obj_prefEdit is null"); return false; } // putString() jobject jni_cls_edit = (*env)->FindClass(env, CLASSPATH_CONTENT_PREF_EDITOR); if (!jni_cls_edit) { OIC_LOG(ERROR, TAG, "jni_cls_edit is null"); return false; } // get remove method interface jmethodID jni_mid_PrefRemove = (*env)->GetMethodID(env, jni_cls_edit, "remove", "(Ljava/lang/String;)" "Landroid/content/SharedPreferences" "$Editor;"); if (!jni_mid_PrefRemove) { OIC_LOG(ERROR, TAG, "jni_mid_PrefRemove is null"); return false; } OIC_LOG(DEBUG, TAG, "CALL API - request remove for SharedPreferences.Editor"); (*env)->CallObjectMethod(env, jni_obj_prefEdit, jni_mid_PrefRemove, jni_str_prefKey); // get commit method interface jmethodID jni_mid_PrefCommit = (*env)->GetMethodID(env, jni_cls_edit, "commit", "()Z"); if (!jni_mid_PrefCommit) { OIC_LOG(ERROR, TAG, "jni_mid_PrefCommit is null"); return false; } jboolean res = (*env)->CallBooleanMethod(env, jni_obj_prefEdit, jni_mid_PrefCommit); OIC_LOG(DEBUG, TAG, "OUT-CAManagerAddConnectedDeviceAddress"); return res; } bool CAManagerAddConnectedDeviceAddress(JNIEnv *env, jobject context, jstring address, jobject set) { OIC_LOG(DEBUG, TAG, "IN-CAManagerAddConnectedDeviceAddress"); VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(context, TAG, "context", false); VERIFY_NON_NULL_RET(address, TAG, "address", false); VERIFY_NON_NULL_RET(set, TAG, "set", false); if (CAManagerCallFuncSetString(env, address, set, CM_CONTAINS)) { OIC_LOG(DEBUG, TAG, "it's already done"); return true; } if (!CAManagerCallFuncSetString(env, address, set, CM_ADD)) { OIC_LOG(ERROR, TAG, "CAManagerAddSetString has failed"); return false; } return CAManagerUpdatePrefStringSet(env, context, set); } bool CAManagerIsConnectedDeviceAddress(JNIEnv *env, jobject context, jstring address, jobject set) { VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(context, TAG, "context", false); return CAManagerCallFuncSetString(env, address, set, CM_CONTAINS); } jobject CAManagerGetConnectedDeviceAddress(JNIEnv *env, jobject context) { OIC_LOG(DEBUG, TAG, "CAManagerGetConnectedDeviceAddress"); if (!CAManagerContainsPrefStringSet(env, context)) { OIC_LOG(DEBUG, TAG, "there is no set data"); return NULL; } return CAManagerGetPrefStringSet(env, context); } bool CAManagerRemoveConnectedDeviceAddress(JNIEnv *env, jobject context, jstring address, jobject set) { OIC_LOG(DEBUG, TAG, "CAManagerRemoveConnectedDeviceAddress"); VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(context, TAG, "context", false); VERIFY_NON_NULL_RET(address, TAG, "address", false); VERIFY_NON_NULL_RET(set, TAG, "set", false); if (!CAManagerCallFuncSetString(env, address, set, CM_CONTAINS)) { OIC_LOG(DEBUG, TAG, "it's already done"); return true; } if (!CAManagerCallFuncSetString(env, address, set, CM_REMOVE)) { OIC_LOG(ERROR, TAG, "CAManagerAddSetString has failed"); return false; } return CAManagerUpdatePrefStringSet(env, context, set); } jboolean CAManagerCheckBTAddress(JNIEnv *env, jstring address) { OIC_LOG(DEBUG, TAG, "CAManagerCheckBTAddress"); VERIFY_NON_NULL_RET(env, TAG, "env is null", JNI_FALSE); VERIFY_NON_NULL_RET(address, TAG, "address is null", JNI_FALSE); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null"); return JNI_FALSE; } // get remote bt adapter method jmethodID jni_mid_checkBTAddress = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "checkBluetoothAddress", METHODID_BOOLEAN_RET_STRING_PARAM); if (!jni_mid_checkBTAddress) { OIC_LOG(ERROR, TAG, "jni_mid_checkBTAddress is null"); return JNI_FALSE; } jboolean jni_obj_isAddress = (*env)->CallStaticBooleanMethod(env, jni_cid_BTAdapter, jni_mid_checkBTAddress, address); return jni_obj_isAddress; } jobject CAManagerCreateSetString(JNIEnv *env) { OIC_LOG(DEBUG, TAG, "CAManagerCallFuncSetString"); VERIFY_NON_NULL_RET(env, TAG, "env", NULL); jclass jclazzMap = (*env)->FindClass(env, "java/util/HashSet" ); if (!jclazzMap) { OIC_LOG(ERROR, TAG, "jclazzMap is null"); return NULL; } jmethodID jinitMap = (*env)->GetMethodID(env, jclazzMap, "<init>", "()V"); if (!jinitMap) { OIC_LOG(ERROR, TAG, "jinitMap is null"); return NULL; } jobject jpropertyMap = (*env)->NewObject(env, jclazzMap, jinitMap); if (!jpropertyMap) { OIC_LOG(ERROR, TAG, "jpropertyMap is null"); return NULL; } return jpropertyMap; } bool CAManagerCallFuncSetString(JNIEnv *env, jstring address, jobject set, CASetMethod_t method_type) { VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(address, TAG, "address", false); VERIFY_NON_NULL_RET(set, TAG, "set", false); jclass jni_cls_set = (*env)->FindClass(env, "java/util/HashSet"); if (!jni_cls_set) { OIC_LOG(ERROR, TAG, "jni_cls_set is null"); return false; } jmethodID jni_mid_setMethod = NULL; switch (method_type) { case CM_CONTAINS: jni_mid_setMethod = (*env)->GetMethodID(env, jni_cls_set, "contains", "(Ljava/lang/Object;)Z"); break; case CM_ADD: jni_mid_setMethod = (*env)->GetMethodID(env, jni_cls_set, "add", "(Ljava/lang/Object;)Z"); break; case CM_REMOVE: jni_mid_setMethod = (*env)->GetMethodID(env, jni_cls_set, "remove", "(Ljava/lang/Object;)Z"); break; default: break; } if (!jni_mid_setMethod) { OIC_LOG(ERROR, TAG, "jni_mid_setMethod is null"); return false; } jboolean res = (*env)->CallBooleanMethod(env, set, jni_mid_setMethod, address); return res; }
12,595
441
<reponame>dsrw/godot // Copyright 2009-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once #include "quadi.h" #include "quad_intersector_moeller.h" #include "quad_intersector_pluecker.h" namespace embree { namespace isa { /*! Intersects M quads with 1 ray */ template<int M, bool filter> struct QuadMiIntersector1Moeller { typedef QuadMi<M> Primitive; typedef QuadMIntersector1MoellerTrumbore<M,filter> Precalculations; /*! Intersect a ray with the M quads and updates the hit. */ static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); pre.intersect(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of M quads. */ static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); return pre.occluded(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& quad) { return PrimitivePointQuery1<Primitive>::pointQuery(query, context, quad); } }; /*! Intersects M triangles with K rays. */ template<int M, int K, bool filter> struct QuadMiIntersectorKMoeller { typedef QuadMi<M> Primitive; typedef QuadMIntersectorKMoellerTrumbore<M,K,filter> Precalculations; /*! Intersects K rays with M triangles. */ static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { Scene* scene = context->scene; for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),K); const Vec3vf<K> p0 = quad.template getVertex<0>(i,scene); const Vec3vf<K> p1 = quad.template getVertex<1>(i,scene); const Vec3vf<K> p2 = quad.template getVertex<2>(i,scene); const Vec3vf<K> p3 = quad.template getVertex<3>(i,scene); pre.intersectK(valid_i,ray,p0,p1,p2,p3,IntersectKEpilogM<M,K,filter>(ray,context,quad.geomID(),quad.primID(),i)); } } /*! Test for K rays if they are occluded by any of the M triangles. */ static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { Scene* scene = context->scene; vbool<K> valid0 = valid_i; for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid0),K); const Vec3vf<K> p0 = quad.template getVertex<0>(i,scene); const Vec3vf<K> p1 = quad.template getVertex<1>(i,scene); const Vec3vf<K> p2 = quad.template getVertex<2>(i,scene); const Vec3vf<K> p3 = quad.template getVertex<3>(i,scene); if (pre.intersectK(valid0,ray,p0,p1,p2,p3,OccludedKEpilogM<M,K,filter>(valid0,ray,context,quad.geomID(),quad.primID(),i))) break; } return !valid0; } /*! Intersect a ray with M triangles and updates the hit. */ static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf4 v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); pre.intersect1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of the M triangles. */ static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf4 v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); return pre.occluded1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } }; /*! Intersects M quads with 1 ray */ template<int M, bool filter> struct QuadMiIntersector1Pluecker { typedef QuadMi<M> Primitive; typedef QuadMIntersector1Pluecker<M,filter> Precalculations; /*! Intersect a ray with the M quads and updates the hit. */ static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); pre.intersect(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of M quads. */ static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); return pre.occluded(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& quad) { return PrimitivePointQuery1<Primitive>::pointQuery(query, context, quad); } }; /*! Intersects M triangles with K rays. */ template<int M, int K, bool filter> struct QuadMiIntersectorKPluecker { typedef QuadMi<M> Primitive; typedef QuadMIntersectorKPluecker<M,K,filter> Precalculations; /*! Intersects K rays with M triangles. */ static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { Scene* scene = context->scene; for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),K); const Vec3vf<K> p0 = quad.template getVertex<0>(i,scene); const Vec3vf<K> p1 = quad.template getVertex<1>(i,scene); const Vec3vf<K> p2 = quad.template getVertex<2>(i,scene); const Vec3vf<K> p3 = quad.template getVertex<3>(i,scene); pre.intersectK(valid_i,ray,p0,p1,p2,p3,IntersectKEpilogM<M,K,filter>(ray,context,quad.geomID(),quad.primID(),i)); } } /*! Test for K rays if they are occluded by any of the M triangles. */ static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { Scene* scene = context->scene; vbool<K> valid0 = valid_i; for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid0),K); const Vec3vf<K> p0 = quad.template getVertex<0>(i,scene); const Vec3vf<K> p1 = quad.template getVertex<1>(i,scene); const Vec3vf<K> p2 = quad.template getVertex<2>(i,scene); const Vec3vf<K> p3 = quad.template getVertex<3>(i,scene); if (pre.intersectK(valid0,ray,p0,p1,p2,p3,OccludedKEpilogM<M,K,filter>(valid0,ray,context,quad.geomID(),quad.primID(),i))) break; } return !valid0; } /*! Intersect a ray with M triangles and updates the hit. */ static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf4 v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); pre.intersect1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of the M triangles. */ static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf4 v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene); return pre.occluded1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } }; /*! Intersects M motion blur quads with 1 ray */ template<int M, bool filter> struct QuadMiMBIntersector1Moeller { typedef QuadMi<M> Primitive; typedef QuadMIntersector1MoellerTrumbore<M,filter> Precalculations; /*! Intersect a ray with the M quads and updates the hit. */ static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()); pre.intersect(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of M quads. */ static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()); return pre.occluded(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& quad) { return PrimitivePointQuery1<Primitive>::pointQuery(query, context, quad); } }; /*! Intersects M motion blur quads with K rays. */ template<int M, int K, bool filter> struct QuadMiMBIntersectorKMoeller { typedef QuadMi<M> Primitive; typedef QuadMIntersectorKMoellerTrumbore<M,K,filter> Precalculations; /*! Intersects K rays with M quads. */ static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),K); Vec3vf<K> v0,v1,v2,v3; quad.gather(valid_i,v0,v1,v2,v3,i,context->scene,ray.time()); pre.intersectK(valid_i,ray,v0,v1,v2,v3,IntersectKEpilogM<M,K,filter>(ray,context,quad.geomID(),quad.primID(),i)); } } /*! Test for K rays if they are occluded by any of the M quads. */ static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { vbool<K> valid0 = valid_i; for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid0),K); Vec3vf<K> v0,v1,v2,v3; quad.gather(valid_i,v0,v1,v2,v3,i,context->scene,ray.time()); if (pre.intersectK(valid0,ray,v0,v1,v2,v3,OccludedKEpilogM<M,K,filter>(valid0,ray,context,quad.geomID(),quad.primID(),i))) break; } return !valid0; } /*! Intersect a ray with M quads and updates the hit. */ static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()[k]); pre.intersect1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of the M quads. */ static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()[k]); return pre.occluded1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } }; /*! Intersects M motion blur quads with 1 ray */ template<int M, bool filter> struct QuadMiMBIntersector1Pluecker { typedef QuadMi<M> Primitive; typedef QuadMIntersector1Pluecker<M,filter> Precalculations; /*! Intersect a ray with the M quads and updates the hit. */ static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()); pre.intersect(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of M quads. */ static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()); return pre.occluded(ray,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& quad) { return PrimitivePointQuery1<Primitive>::pointQuery(query, context, quad); } }; /*! Intersects M motion blur quads with K rays. */ template<int M, int K, bool filter> struct QuadMiMBIntersectorKPluecker { typedef QuadMi<M> Primitive; typedef QuadMIntersectorKPluecker<M,K,filter> Precalculations; /*! Intersects K rays with M quads. */ static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),K); Vec3vf<K> v0,v1,v2,v3; quad.gather(valid_i,v0,v1,v2,v3,i,context->scene,ray.time()); pre.intersectK(valid_i,ray,v0,v1,v2,v3,IntersectKEpilogM<M,K,filter>(ray,context,quad.geomID(),quad.primID(),i)); } } /*! Test for K rays if they are occluded by any of the M quads. */ static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const QuadMi<M>& quad) { vbool<K> valid0 = valid_i; for (size_t i=0; i<QuadMi<M>::max_size(); i++) { if (!quad.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid0),K); Vec3vf<K> v0,v1,v2,v3; quad.gather(valid_i,v0,v1,v2,v3,i,context->scene,ray.time()); if (pre.intersectK(valid0,ray,v0,v1,v2,v3,OccludedKEpilogM<M,K,filter>(valid0,ray,context,quad.geomID(),quad.primID(),i))) break; } return !valid0; } /*! Intersect a ray with M quads and updates the hit. */ static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()[k]); pre.intersect1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } /*! Test if the ray is occluded by one of the M quads. */ static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const QuadMi<M>& quad) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,context->scene,ray.time()[k]); return pre.occluded1(ray,k,context,v0,v1,v2,v3,quad.geomID(),quad.primID()); } }; } }
7,548
1,602
<filename>third-party/hwloc/hwloc-src/tests/ports/include/cuda/cuda.h<gh_stars>1000+ /* * Copyright © 2015 Inria. All rights reserved. * See COPYING in top-level directory. */ #ifndef HWLOC_PORT_CUDA_CUDA_H #define HWLOC_PORT_CUDA_CUDA_H #define CUDA_VERSION 4000 #endif /* HWLOC_PORT_CUDA_CUDA_H */
124
755
package com.hjq.xtoast.draggable; import android.annotation.SuppressLint; import android.view.MotionEvent; import android.view.View; /** * author : <NAME> * github : https://github.com/getActivity/XToast * time : 2019/01/04 * desc : 移动拖拽处理实现类 */ public class MovingDraggable extends BaseDraggable { /** 手指按下的坐标 */ private float mViewDownX; private float mViewDownY; /** 触摸移动标记 */ private boolean mMoveTouch; @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 记录按下的位置(相对 View 的坐标) mViewDownX = event.getX(); mViewDownY = event.getY(); mMoveTouch = false; break; case MotionEvent.ACTION_MOVE: // 记录移动的位置(相对屏幕的坐标) float rawMoveX = event.getRawX() - getWindowInvisibleWidth(); float rawMoveY = event.getRawY() - getWindowInvisibleHeight(); // 更新移动的位置 updateLocation(rawMoveX - mViewDownX, rawMoveY - mViewDownY); if (!mMoveTouch && isTouchMove(mViewDownX, event.getX(), mViewDownY, event.getY())) { // 如果用户移动了手指,那么就拦截本次触摸事件,从而不让点击事件生效 mMoveTouch = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: return mMoveTouch; default: break; } return false; } }
974
539
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for generating basis set default parameters. """ # pylint: disable=no-self-use import pytest from pennylane import numpy as np from pennylane import qchem class TestBasis: """Tests for generating basis set default parameters""" @pytest.mark.parametrize( ("basis_name", "atom_name", "l", "alpha", "coeff", "r"), [ ( "sto-3g", "H", (0, 0, 0), # data manually copied from https://www.basissetexchange.org/ [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], [0.0000000000e00, 0.0000000000e00, -0.694349000e00], ), ], ) def test_basisfunction(self, basis_name, atom_name, l, alpha, coeff, r): """Test that BasisFunction class creates basis function objects correctly.""" basis_function = qchem.BasisFunction(l, alpha, coeff, r) assert np.allclose(np.array(basis_function.alpha), np.array(alpha)) assert np.allclose(np.array(basis_function.coeff), np.array(coeff)) assert np.allclose(np.array(basis_function.r), np.array(r)) assert np.allclose(basis_function.params[0], alpha) assert np.allclose(basis_function.params[1], coeff) assert np.allclose(basis_function.params[2], r) @pytest.mark.parametrize( ("basis_name", "atom_name", "params_ref"), [ # data manually copied from https://www.basissetexchange.org/ ( "sto-3g", "H", ( [ ( (0, 0, 0), # l [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], # alpha [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], # coeff ) ] ), ), ( "6-31g", "H", ( ( (0, 0, 0), # l [0.1873113696e02, 0.2825394365e01, 0.6401216923e00], # alpha [0.3349460434e-01, 0.2347269535e00, 0.8137573261e00], # coeff ), ( (0, 0, 0), # l [0.1612777588e00], # alpha [1.0000000], # coeff ), ), ), ( "6-31g", "O", ( ( (0, 0, 0), # l [ 0.5484671660e04, 0.8252349460e03, 0.1880469580e03, 0.5296450000e02, 0.1689757040e02, 0.5799635340e01, ], # alpha [ 0.1831074430e-02, 0.1395017220e-01, 0.6844507810e-01, 0.2327143360e00, 0.4701928980e00, 0.3585208530e00, ], # coeff ), ( (0, 0, 0), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [-0.1107775495e00, -0.1480262627e00, 0.1130767015e01], # coeff ), ( (1, 0, 0), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( (0, 1, 0), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( (0, 0, 1), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( (0, 0, 0), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( (1, 0, 0), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( (0, 1, 0), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( (0, 0, 1), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ), ), ], ) def test_atom_basis_data(self, basis_name, atom_name, params_ref): """Test that correct basis set parameters are generated for a given atom.""" params = qchem.atom_basis_data(basis_name, atom_name) l = [p[0] for p in params] l_ref = [p[0] for p in params_ref] alpha = [p[1] for p in params] alpha_ref = [p[1] for p in params_ref] coeff = [p[2] for p in params] coeff_ref = [p[2] for p in params_ref] assert l == l_ref assert alpha == alpha_ref assert coeff == coeff_ref basis_data_HF = [ ( "sto-3g", ["H", "F"], [1, 5], ( ( (0, 0, 0), [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], ), ( (0, 0, 0), [0.1666791340e03, 0.3036081233e02, 0.8216820672e01], [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], ), ( (0, 0, 0), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [-0.9996722919e-01, 0.3995128261e00, 0.7001154689e00], ), ( (1, 0, 0), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [0.1559162750e00, 0.6076837186e00, 0.3919573931e00], ), ( (0, 1, 0), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [0.1559162750e00, 0.6076837186e00, 0.3919573931e00], ), ( (0, 0, 1), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [0.1559162750e00, 0.6076837186e00, 0.3919573931e00], ), ), ) ] @pytest.mark.parametrize("basis_data", basis_data_HF) def test_mol_basis_data(self, basis_data): """Test that correct basis set parameters are generated for a given molecule represented as a list of atoms.""" basis, symbols, n_ref, params_ref = basis_data n_basis, params = qchem.mol_basis_data(basis, symbols) assert n_basis == n_ref assert np.allclose(params, params_ref)
5,286
3,055
<reponame>Linghhh/u8g2 /* Fontname: -Cronyx-Courier-Medium-R-Normal--10-100-75-75-M-60-RAWIN-R Copyright: Copyright (C) 1990, 1991 EWT Consulting, Portions Copyright (C) 1994 Cronyx Ltd. Glyphs: 18/224 BBX Build Mode: 2 */ const uint8_t u8g2_font_crox2c_mn[290] U8G2_FONT_SECTION("u8g2_font_crox2c_mn") = "\22\2\4\2\4\4\1\1\5\11\16\0\377\15\375\15\375\0\0\0\0\1\5 \7\351\345\347\317\0*\17" "\351\345g\242P\215\6\203\320J\241'\4+\16\351\345g\24\254\32\14R\301z\34\0,\11\351\345\347" "\353\231\21\0-\11\351\345\347|\260g\1.\10\351\345\347k\235\30/\12\351\345'\317\365{(\0\60" "\27\351\345'\30\204jB\231P&\224\11eB\231P&\24\32d\1\61\13\351\345'\211\15\373\331@" "\12\62\15\351\345'\30\204\12\353z\70\230\2\63\20\351\345'\30\204\12\253\226\301\232Ph\220\5\64\23" "\351\345\247\311\311\22\261D*\22\312\204\6\273`n\12\65\21\351\345\207\17\66\301\302\201\62X\23\12\15" "\262\0\66\23\351\345\247X\345\202\25#MQ&\224\11\205\6Y\0\67\21\351\345\207\17\66\241\134\60\27" "\314\5s\301\70\0\70\26\351\345'\30\204jB\231Ph\20\252\11eB\231Ph\220\5\71\23\351\345" "'\30\204jB\231P&#Z\4\353Rc\0:\13\351\345g\255\323\23\351\304\0\0\0\0\4\377\377" "\0";
678
1,821
<reponame>shinny-yangyang/perspective ################################################################################ # # Copyright (c) 2019, the Perspective Authors. # # This file is part of the Perspective library, distributed under the terms of # the Apache License 2.0. The full license can be found in the LICENSE file. # from datetime import date import pandas as pd import numpy as np from perspective import Table, PerspectiveWidget from ..common import superstore DF = superstore(200) class TestWidgetPandas: def test_widget_load_table_df(self): table = Table(DF) widget = PerspectiveWidget(table) assert widget.table.schema() == {'index': int, 'Country': str, 'Region': str, 'Category': str, 'City': str, 'Customer ID': str, 'Discount': float, 'Order Date': date, 'Order ID': str, 'Postal Code': str, 'Product ID': str, 'Profit': float, 'Quantity': int, 'Row ID': int, 'Sales': int, 'Segment': str, 'Ship Date': date, 'Ship Mode': str, 'State': str, 'Sub-Category': str} assert sorted(widget.columns) == sorted(['index', 'Category', 'City', 'Country', 'Customer ID', 'Discount', 'Order Date', 'Order ID', 'Postal Code', 'Product ID', 'Profit', 'Quantity', 'Region', 'Row ID', 'Sales', 'Segment', 'Ship Date', 'Ship Mode', 'State', 'Sub-Category']) view = widget.table.view() assert view.num_rows() == len(DF) assert view.num_columns() == len(DF.columns) + 1 # index def test_widget_load_data_df(self): widget = PerspectiveWidget(DF) assert sorted(widget.columns) == sorted(['index', 'Category', 'City', 'Country', 'Customer ID', 'Discount', 'Order Date', 'Order ID', 'Postal Code', 'Product ID', 'Profit', 'Quantity', 'Region', 'Row ID', 'Sales', 'Segment', 'Ship Date', 'Ship Mode', 'State', 'Sub-Category']) view = widget.table.view() assert view.num_rows() == len(DF) assert view.num_columns() == 20 def test_widget_load_series(self): series = pd.Series(DF["Profit"].values, name="profit") widget = PerspectiveWidget(series) assert widget.table.schema() == {'index': int, 'profit': float} assert sorted(widget.columns) == sorted(["index", "profit"]) view = widget.table.view() assert view.num_rows() == len(DF) assert view.num_columns() == 2 def test_widget_load_pivot_table(self): pivot_table = pd.pivot_table(DF, values='Discount', index=['Country', 'Region'], columns=['Category', 'Segment']) widget = PerspectiveWidget(pivot_table) assert widget.group_by == ['Country', 'Region'] assert widget.split_by == ['Category', 'Segment'] assert widget.columns == ['value'] # table should host flattened data view = widget.table.view() assert view.num_rows() == 60 assert view.num_columns() == 6 def test_widget_load_pivot_table_with_user_pivots(self): pivot_table = pd.pivot_table(DF, values='Discount', index=['Country', 'Region'], columns='Category') widget = PerspectiveWidget(pivot_table, group_by=["Category", "Segment"]) assert widget.group_by == ['Category', 'Segment'] assert widget.split_by == [] assert widget.columns == ['index', 'Country', 'Region', 'Financials', 'Industrials', 'Technology'] # table should host flattened data view = widget.table.view() assert view.num_rows() == 5 assert view.num_columns() == 6 def test_widget_load_group_by(self): df_pivoted = DF.set_index(['Country', 'Region']) widget = PerspectiveWidget(df_pivoted) assert widget.group_by == ['Country', 'Region'] assert widget.split_by == [] assert sorted(widget.columns) == sorted(['index', 'Category', 'Country', 'City', 'Customer ID', 'Discount', 'Order Date', 'Order ID', 'Postal Code', 'Product ID', 'Profit', 'Quantity', 'Region', 'Row ID', 'Sales', 'Segment', 'Ship Date', 'Ship Mode', 'State', 'Sub-Category']) assert widget.table.size() == 200 view = widget.table.view() assert view.num_rows() == len(DF) assert view.num_columns() == len(DF.columns) + 1 # index def test_widget_load_group_by_with_user_pivots(self): df_pivoted = DF.set_index(['Country', 'Region']) widget = PerspectiveWidget(df_pivoted, group_by=["Category", "Segment"]) assert widget.group_by == ['Category', 'Segment'] assert widget.split_by == [] assert sorted(widget.columns) == sorted(['index', 'Category', 'Country', 'City', 'Customer ID', 'Discount', 'Order Date', 'Order ID', 'Postal Code', 'Product ID', 'Profit', 'Quantity', 'Region', 'Row ID', 'Sales', 'Segment', 'Ship Date', 'Ship Mode', 'State', 'Sub-Category']) assert widget.table.size() == 200 view = widget.table.view() assert view.num_rows() == len(DF) assert view.num_columns() == len(DF.columns) + 1 # index def test_widget_load_split_by(self): arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo', 'foo', 'foo', 'qux', 'qux', 'qux', 'qux']), np.array(['one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two']), np.array(['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'])] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second', 'third']) df_both = pd.DataFrame(np.random.randn(3, 16), index=['A', 'B', 'C'], columns=index) widget = PerspectiveWidget(df_both) assert widget.columns == ['value'] assert widget.split_by == ['first', 'second', 'third'] assert widget.group_by == ['index'] def test_widget_load_split_by_preserve_user_settings(self): arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo', 'foo', 'foo', 'qux', 'qux', 'qux', 'qux']), np.array(['one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two']), np.array(['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'])] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second', 'third']) df_both = pd.DataFrame(np.random.randn(3, 16), index=['A', 'B', 'C'], columns=index) widget = PerspectiveWidget(df_both, columns=["first", "third"]) assert widget.columns == ['first', "third"] assert widget.split_by == ['first', 'second', 'third'] assert widget.group_by == ['index'] def test_pivottable_values_index(self): arrays = {'A':['bar', 'bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo', 'foo', 'foo', 'qux', 'qux', 'qux', 'qux'], 'B':['one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two'], 'C':['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'], 'D':np.arange(16)} df = pd.DataFrame(arrays) df_pivot = df.pivot_table(values=['D'], index=['A'], columns=['B','C'], aggfunc={'D':'count'}) widget = PerspectiveWidget(df_pivot) assert widget.columns == ['value'] assert widget.split_by == ['B', 'C'] assert widget.group_by == ['A'] def test_pivottable_multi_values(self): pt = pd.pivot_table(DF, values = ['Discount','Sales'], index=['Country','Region'],aggfunc={'Discount':'count','Sales':'sum'},columns=["State","Quantity"]) widget = PerspectiveWidget(pt) assert widget.columns == ['Discount', 'Sales'] assert widget.split_by == ['State', 'Quantity'] assert widget.group_by == ['Country', 'Region']
3,679
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.core.multitabs.prefs; import org.netbeans.core.windows.options.TabsOptionsPanelController; import org.netbeans.core.windows.options.TabsPanel; /** * * @author <NAME> */ public final class MultiTabsOptionsPanelController extends TabsOptionsPanelController { private MultiTabsPanel panel; @Override protected void changed(Object isChanged, Object isChangedInnerTabsPanel) { super.changed(isChanged, isChangedInnerTabsPanel); } @Override protected TabsPanel getPanel() { if (panel == null) { panel = new MultiTabsPanel(this); } return panel; } }
438
14,668
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.gcore; import static junit.framework.Assert.assertEquals; /** Spying mock for ConnectedTask. */ class MockConnectedTask<T extends ChromeGoogleApiClient> extends ConnectedTask<T> { private int mDoWhenConnectedCount; private int mCleanUpCount; private int mRescheduleCount; public MockConnectedTask(T client) { super(client); } @Override protected final String getName() { return "MockConnectedTask"; } @Override protected final void doWhenConnected(T client) { mDoWhenConnectedCount++; } @Override protected final void cleanUp() { mCleanUpCount++; } @Override protected final void retry(Runnable task, long delayMs) { mRescheduleCount++; } public void assertDoWhenConnectedCalled(int times) { assertEquals(times, mDoWhenConnectedCount); mDoWhenConnectedCount = 0; } public void assertCleanUpCalled(int times) { assertEquals(times, mCleanUpCount); mCleanUpCount = 0; } public void assertRescheduleCalled(int times) { assertEquals(times, mRescheduleCount); mRescheduleCount = 0; } public void assertNoOtherMethodsCalled() { assertEquals(0, mDoWhenConnectedCount + mCleanUpCount + mRescheduleCount); } }
561
5,169
<reponame>Gantios/Specs { "name": "Inspector", "version": "0.0.1", "summary": "An elegant Object-Oriented objc runtime wrapper for Swift.", "description": "An elegant Object-Oriented objc runtime wrapper for Swift.\n1. Elegant\n2. OOP\n3. Inspect\n4. runtime\n5. Wrapper", "homepage": "https://github.com/0xxd0/Inspector", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "0xxd0": "<EMAIL>" }, "platforms": { "ios": "8.0", "osx": "10.9", "watchos": "2.0", "tvos": "9.0" }, "source": { "git": "https://github.com/0xxd0/Inspector.git", "tag": "0.0.1" }, "source_files": "Sources/*.{swift}", "pushed_with_swift_version": "3.2" }
327
5,411
<filename>vendor/chromium/base/trace_event/log_message.cc<gh_stars>1000+ // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/trace_event/log_message.h" #include <stdint.h> #include <string> #include "base/json/string_escape.h" #include "base/strings/stringprintf.h" namespace base { namespace trace_event { LogMessage::LogMessage(const char* file, base::StringPiece message, int line) : file_(file), message_(message), line_number_(line) {} LogMessage::~LogMessage() = default; void LogMessage::AppendAsTraceFormat(std::string* out) const { out->append("{"); out->append(base::StringPrintf("\"line\":\"%d\",", line_number_)); out->append("\"message\":"); base::EscapeJSONString(message_, true, out); out->append(","); out->append(base::StringPrintf("\"file\":\"%s\"", file_)); out->append("}"); } void LogMessage::EstimateTraceMemoryOverhead( TraceEventMemoryOverhead* overhead) { overhead->Add(TraceEventMemoryOverhead::kOther, sizeof(this)); overhead->AddString(message_); } bool LogMessage::AppendToProto(ProtoAppender* appender) { // LogMessage is handled in a special way in // track_event_thread_local_event_sink.cc in the function |AddTraceEvent|, so // this call should never happen. NOTREACHED(); return false; } } // namespace trace_event } // namespace base
479
445
import os import sys py3 = sys.version_info.major >= 3 py36 = sys.version_info[0:2] >= (3, 6) if py3: def isStringType(t): return isinstance(t, str) if py36: from pathlib import Path def isPath(f): return isinstance(f, (bytes, str, Path)) else: def isPath(f): return isinstance(f, (bytes, str)) else: def isStringType(t): return isinstance(t, basestring) # noqa: F821 def isPath(f): return isinstance(f, basestring) # noqa: F821 # Checks if an object is a string, and that it points to a directory. def isDirectory(f): return isPath(f) and os.path.isdir(f) class deferred_error(object): def __init__(self, ex): self.ex = ex def __getattr__(self, elt): raise self.ex
360
1,418
<reponame>Watch-Later/recipes #include "InetAddress.h" #include "TcpStream.h" #include <limits> #include <memory> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <vector> int64_t kNanos = 1e9; int64_t clock_diff(struct timespec x, struct timespec y) { return (x.tv_sec - y.tv_sec) * kNanos + x.tv_nsec - y.tv_nsec; } struct timespec get_time() { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return now; } struct Sample { int index; int64_t start_nano; int64_t rtt_nano; }; std::vector<Sample> run(const char* host, int delay_ms, int length_s, int batch, int payload_size, bool silent) { const struct timespec start = get_time(); std::vector<Sample> rtts; InetAddress addr; if (!InetAddress::resolve(host, 3007, &addr)) { printf("Unable to resolve %s\n", host); return rtts; } // printf("connecting to %s\n", addr.toIpPort().c_str()); TcpStreamPtr stream(TcpStream::connect(addr)); if (!stream) { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); return rtts; } std::unique_ptr<char[]> payload(new char[payload_size]); int64_t count = 0, sum_rtt = 0; int64_t min_rtt = std::numeric_limits<int64_t>::max(), max_rtt = 0; while (true) { const struct timespec batch_start = get_time(); double elapsed_s = (double)clock_diff(batch_start, start) / kNanos; if (elapsed_s >= length_s) { if (silent && count > 0) { printf("count %ld, avg rtt %.2fus, min %.2fus, max %.2fus\n", count, sum_rtt / 1e3 / count, min_rtt / 1e3, max_rtt / 1e3); } break; } for (int i = 0; i < batch; ++i) { const struct timespec before = get_time(); int nw = stream->sendAll(payload.get(), payload_size); if (nw != payload_size) return rtts; int nr = stream->receiveAll(payload.get(), payload_size); if (nr != payload_size) return rtts; const struct timespec after = get_time(); int64_t rtt = clock_diff(after, before); ++count; sum_rtt += rtt; if (rtt > max_rtt) max_rtt = rtt; if (rtt < min_rtt) min_rtt = rtt; Sample s = { .index = i, .rtt_nano = rtt, }; if (i == 0) s.start_nano = clock_diff(before, start); else s.start_nano = clock_diff(before, batch_start); if (!silent) rtts.push_back(s); } if (delay_ms > 0) { ::usleep(delay_ms * 1000); } } return rtts; } int main(int argc, char* argv[]) { int opt; int delay = 0, length = 3, batch = 4, payload = 1; bool silent = false; while ((opt = getopt(argc, argv, "b:d:l:p:s")) != -1) { switch (opt) { case 'b': batch = atoi(optarg); break; case 'd': delay = atoi(optarg); break; case 'l': length = atoi(optarg); break; case 'p': payload = atoi(optarg); break; case 's': silent = true; break; default: ; } } if (optind >= argc) { fprintf(stderr, "Usage:\nroundtrip_tcp [-b batch_size] [-d delay_ms] [-l length_in_seconds] echo_server_host\n"); return 1; } if (batch < 1) { batch = 1; } if (delay < 0) { delay = 0; } if (payload < 1) { payload = 1; } std::vector<Sample> rtts = run(argv[optind], delay, length, batch, payload, silent); if (!silent) { printf("index start rtt\n"); for (Sample s : rtts) { printf("%d %ld %ld\n", s.index, s.start_nano, s.rtt_nano); } } }
1,699
1,080
<reponame>wandaitzuchen/pelikan<gh_stars>1000+ import errno import socket import unittest # implementation based on pymemcache: https://pypi.python.org/pypi/pymemcache class TCPClient(object): DEFAULT_TIMEOUT = 1.0 RECV_SIZE = 1024 * 1024 def __init__(self, server, connect_timeout=DEFAULT_TIMEOUT, request_timeout=DEFAULT_TIMEOUT, recv_size=RECV_SIZE): """Constructor: setting and connecting to the remote.""" self.server = server self.connect_timeout = connect_timeout self.request_timeout = request_timeout self.recv_size = recv_size self.connect() def connect(self): """Connect to a TCP host:port endpoint, return socket""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self.connect_timeout) sock.connect(self.server) sock.settimeout(self.request_timeout) self.sock = sock def close(self): """Close the socket""" if self.sock is not None: try: self.sock.close() except Exception: pass self.sock = None def recvall(self): """recv until no data outstanding on the socket""" self.sock.setblocking(False) data = '' while True: try: seg = self.sock.recv(self.recv_size) if seg == '': self.close() else: data += seg except (IOError, socket.error) as e: err = e.args[0] if err == errno.EINTR: continue if err == errno.EAGAIN or err == errno.EWOULDBLOCK: if len(data) == 0: continue else: break else: raise self.sock.setblocking(True) return data def send(self, data): """send req until all data is sent, or an error occurs""" if not self.sock: self.connect() try: self.sock.sendall(data) except Exception: self.close() raise class DataClient(TCPClient): DELIM = '\r\n' def request(self, req): """send a (multi-line) request, req should be of a sequence type""" for line in req: self.send(line + DataClient.DELIM) def response(self): """receive a response, which will be split by delimiter (retained)""" buf = self.recvall() rsp = buf.split(DataClient.DELIM) if rsp[-1] == '': rsp.pop() else: raise Exception("response not terminated by " + DataClient.DELIM) return rsp class AdminClient(TCPClient): DELIM = '\r\n' STATS_CMD = 'stats' def stats(self): self.send(AdminClient.STATS_CMD + AdminClient.DELIM) buf = self.recvall() rsp = buf.split(AdminClient.DELIM) if rsp[-1] == '': rsp.pop() else: raise Exception("response not terminated by " + DataClient.DELIM) if rsp[-1] == 'END': rsp.pop() else: raise Exception('ending not detected, found {} instead'.format(rsp[-1])) return dict(line.split(' ')[1:] for line in rsp)
1,327
1,694
<filename>header6.6.1/RTMPDownloader.h // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "TXIStreamDownloader.h" @class NSLock, NSMutableArray, TXCRecvThread; @interface RTMPDownloader : TXIStreamDownloader { TXCRecvThread *_currentThread; NSLock *_threadMutex; NSMutableArray *_arrayUrls; _Bool _hasTcpStreamUrl; } - (void).cxx_destruct; - (id)getDownloadStats; - (void)stopDownload; - (void)startDownload:(id)arg1; - (void)reconnectServer:(_Bool)arg1; - (void)connectServer:(double)arg1; - (void)sendNotifyEvent:(unsigned long long)arg1; - (void)dealloc; - (id)init; @end
297
488
/** * \file NameGenerator.cc * \brief Class to generate numbered names. */ // tps (12/09/2009) : Playing with precompiled headers in Windows. Requires rose.h as the first line in source files. #include <sstream> #include "NameGenerator.hh" #include <ROSE_ASSERT.h> using namespace std; NameGenerator::NameGenerator (size_t first_id) : cur_id_ (first_id) { } NameGenerator::NameGenerator (const string& pre, size_t first_id, const string& suf) : cur_id_ (first_id), prefix_ (pre), suffix_ (suf) { } size_t NameGenerator::id (void) const { return cur_id_; } string NameGenerator::prefix (void) const { return prefix_; } string NameGenerator::suffix (void) const { return suffix_; } string NameGenerator::current (void) const { stringstream s; s << prefix () << id () << suffix (); return s.str (); } string NameGenerator::next (void) { ++cur_id_; return current (); } // eof
394
522
package algs.model.tests.convexhull; import org.junit.Test; import algs.model.IPoint; import algs.model.problems.convexhull.slowhull.SlowHull; import algs.model.twod.TwoDPoint; import junit.framework.TestCase; public class SlowHullTest extends TestCase { @Test public void testTwoPoints() { IPoint[] points = new TwoDPoint[]{ new TwoDPoint(10, 40), new TwoDPoint(10, 10), }; IPoint hull[]= new SlowHull().compute(points); assertEquals (2, hull.length); assertEquals (new TwoDPoint(10,40), hull[0]); assertEquals (new TwoDPoint(10,10), hull[1]); } @Test public void testBox() { IPoint[] points = new TwoDPoint[]{ new TwoDPoint(1, 1), new TwoDPoint(1, 3), new TwoDPoint(2, 1), // this point threw off the computations before we updated internal check. new TwoDPoint(3, 1), new TwoDPoint(3, 3), }; IPoint hull[]= new SlowHull().compute(points); assertEquals (4, hull.length); assertEquals (new TwoDPoint(1,1), hull[0]); assertEquals (new TwoDPoint(1,3), hull[1]); } @Test public void testVerticalLineFirst() { IPoint[] points = new TwoDPoint[]{ new TwoDPoint(10, 10), // min first new TwoDPoint(10, 30), new TwoDPoint(10, 40), new TwoDPoint(10, 20), }; IPoint hull[]= new SlowHull().compute(points); assertEquals (2, hull.length); assertEquals (new TwoDPoint(10,10), hull[0]); assertEquals (new TwoDPoint(10,40), hull[1]); } @Test public void testVerticalLine() { IPoint[] points = new TwoDPoint[]{ new TwoDPoint(10, 30), new TwoDPoint(10, 40), new TwoDPoint(10, 20), new TwoDPoint(10, 10), // min not first }; IPoint hull[]= new SlowHull().compute(points); assertEquals (2, hull.length); assertEquals (new TwoDPoint(10,10), hull[0]); assertEquals (new TwoDPoint(10,40), hull[1]); } @Test public void testSlowHull() { TwoDPoint p1,p2,p3,p4; IPoint[] points = new TwoDPoint[]{ p3=new TwoDPoint(20, 10), p2=new TwoDPoint(13, 40), p4=new TwoDPoint(7, -2), p1=new TwoDPoint(5, 20), }; IPoint hull[]= new SlowHull().compute(points); assertEquals (4, hull.length); assertEquals (p1, hull[0]); assertEquals (p2, hull[1]); assertEquals (p3, hull[2]); assertEquals (p4, hull[3]); } @Test public void testHorizontalLine() { IPoint[] points = new TwoDPoint[]{ new TwoDPoint(10, 10), new TwoDPoint(40, 10), new TwoDPoint(30, 10), new TwoDPoint(20, 10), }; IPoint hull[]= new SlowHull().compute(points); assertEquals (2, hull.length); assertEquals (new TwoDPoint(10,10), hull[0]); assertEquals (new TwoDPoint(40,10), hull[1]); } @Test public void testDiagonalLine() { IPoint[] points = new TwoDPoint[]{ new TwoDPoint(30, 30), new TwoDPoint(10, 10), // min and max are neither first nor last new TwoDPoint(50, 50), new TwoDPoint(20, 20), }; IPoint hull[]= new SlowHull().compute(points); assertEquals (2, hull.length); assertEquals (new TwoDPoint(10,10), hull[0]); assertEquals (new TwoDPoint(50,50), hull[1]); } }
1,356
538
package com.google.u2f.server.impl.attestation.android; import com.google.gson.JsonObject; import com.google.u2f.server.impl.attestation.X509ExtensionParsingUtil; import org.apache.commons.codec.binary.Hex; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Objects; /** * Parses and contains an Android KeyStore attestation. */ public class AndroidKeyStoreAttestation { private static final String KEY_DESCRIPTION_OID = "1.3.6.1.4.1.11129.2.1.17"; // Indexes for data in KeyDescription sequence private static final int DESCRIPTION_LENGTH = 4; private static final int DESCRIPTION_VERSION_INDEX = 0; private static final int DESCRIPTION_CHALLENGE_INDEX = 1; private static final int DESCRIPTION_SOFTWARE_ENFORCED_INDEX = 2; private static final int DESCRIPTION_TEE_ENFORCED_INDEX = 3; // Tags for Authorization List private static final int AUTHZ_PURPOSE_TAG = 1; private static final int AUTHZ_ALGORITHM_TAG = 2; private static final int AUTHZ_KEY_SIZE_TAG = 3; private static final int AUTHZ_BLOCK_MODE_TAG = 4; private final int keymasterVersion; private final byte[] attestationChallenge; private final AuthorizationList softwareAuthorizationList; private final AuthorizationList teeAuthorizationList; private AndroidKeyStoreAttestation(Integer keymasterVersion, byte[] attestationChallenge, AuthorizationList softwareAuthorizationList, AuthorizationList teeAuthorizationList) { this.keymasterVersion = keymasterVersion; this.attestationChallenge = attestationChallenge; this.softwareAuthorizationList = softwareAuthorizationList; this.teeAuthorizationList = teeAuthorizationList; } /** * Parses the key description extension. Note that this method only parses the description * extension in the leaf cert. It *does not* validate the certificate (or any chain). * * TODO(aczeskis): Add chain validation and remove/clarify the above comment. * * Expected format of the description extension is: * KeyDescription ::= SEQUENCE { * keymasterVersion INTEGER, * attestationChallenge OCTET_STRING, * softwareEnforced AuthorizationList, * teeEnforced AuthorizationList, * uniqueId OCTET_STRING OPTIONAL, * } * * AuthorizationList ::= SEQUENCE { * -- See keymaster_purpose_t for purpose values. * purpose [1] EXPLICIT SET OF INTEGER OPTIONAL, * -- See keymaster_algorithm_t for algorithm values. * algorithm [2] EXPLICIT INTEGER OPTIONAL, * -- keySize is measured in bits, not bytes, and the value must be * -- positive and less than than 2^32, though realistic values are * -- much smaller. * keySize [3] EXPLICIT INTEGER OPTIONAL, * -- See keymaster_block_mode_t for blockMode values. * blockMode [4] EXPLICIT SET OF INTEGER OPTIONAL, * -- See keymaster_digest_t for digest values. * digest [5] EXPLICIT SET OF INTEGER OPTIONAL, * -- See keymaster_padding_t for padding values. * padding [6] EXPLICIT SET OF INTEGER OPTIONAL, * callerNonce [7] EXPLICIT NULL OPTIONAL, * -- minMacLength values must be positive and less than 2^32. * minMacLength [8] EXPLICIT INTEGER OPTIONAL, * -- See keymaster_kdf_t for kdf values. * kdf [9] EXPLICIT SEQUENCE OF INTEGER OPTIONAL, * -- See keymaster_ec_curve_t for ecCurve values * ecCurve [10] EXPLICIT INTEGER OPTIONAL, * -- rsaPublicExponent must be a valid RSA public exponent less * -- than 2^64. * rsaPublicExponent [200] EXPLICIT INTEGER OPTIONAL, * eciesSingleHashMode [201] EXPLICIT NULL OPTIONAL, * includeUniqueId [202] EXPLICIT NULL OPTIONAL, * -- See keymaster_key_blob_usage_requirements for * -- blobUsageRequirement values. * blobUsageRequirement [301] EXPLICIT INTEGER OPTIONAL, * bootloaderOnly [302] EXPLICIT NULL OPTIONAL, * -- activeDateTime must be a 64-bit Java date/time value. * activeDateTime [400] EXPLICIT INTEGER OPTIONAL * -- originationExpireDateTime must be a 64-bit Java date/time * -- value. * originationExpireDateTime [401] EXPLICIT INTEGER OPTIONAL * -- usageExpireDateTime must be a 64-bit Java date/time value. * usageExpireDateTime [402] EXPLICIT INTEGER OPTIONAL * -- minSecondsBetweenOps must be non-negative and less than 2^32. * minSecondsBetweenOps [403] EXPLICIT INTEGER OPTIONAL, * -- maxUsesPerBoot must be positive and less than 2^32. * maxUsesPerBoot [404] EXPLICIT INTEGER OPTIONAL, * noAuthRequired [503] EXPLICIT NULL OPTIONAL, * -- See hw_authenticator_type_t for userAuthType values. Note * -- this field is a bitmask; multiple authenticator types may be * -- ORed together. * userAuthType [504] EXPLICIT INTEGER OPTIONAL, * -- authTimeout, if present, must be positive and less than 2^32. * authTimeout [505] EXPLICIT INTEGER OPTIONAL, * allApplications [600] EXPLICIT NULL OPTIONAL, * applicationId [601] EXPLICIT OCTET_STRING OPTIONAL, * applicationData [700] EXPLICIT OCTET_STRING OPTIONAL, * -- creationDateTime must be a 64-bit Java date/time value. * creationDateTime [701] EXPLICIT INTEGER OPTIONAL, * -- See keymaster_origin_t for origin values. * origin [702] EXPLICIT INTEGER OPTIONAL, * rollbackResistant [703] EXPLICIT NULL OPTIONAL, * -- rootOfTrust is included only if bootloader is not locked. * rootOfTrust [704] EXPLICIT RootOfTrust OPTIONAL * osVersion [705] EXPLICIT INTEGER OPTIONAL, * patchLevel [706] EXPLICIT INTEGER OPTIONAL, * uniqueId [707] EXPLICIT NULL OPTIONAL, * } * * RootOfTrust ::= SEQUENCE { * verifiedBootKey OCTET_STRING, * osVersion INTEGER, * patchMonthYear INTEGER, * } */ public static AndroidKeyStoreAttestation Parse(X509Certificate cert) throws CertificateParsingException { // Extract the extension from the certificate ASN1OctetString extensionValue = X509ExtensionParsingUtil.extractExtensionValue(cert, KEY_DESCRIPTION_OID); if (extensionValue == null) { return null; } // Get the KeyDescription sequence ASN1Sequence keyDescriptionSequence = getKeyDescriptionSequence(extensionValue); // Extract version Integer keymasterVersion = getKeymasterVersion(keyDescriptionSequence); // Extract challenge byte[] challenge = getAttestationChallenge(keyDescriptionSequence); // Extract the software authorization list ASN1Sequence softwareEnforcedSequence = getSoftwareEncodedSequence(keyDescriptionSequence); AuthorizationList softwareAuthorizationList = extractAuthorizationList(softwareEnforcedSequence); // Extract the tee authorization list ASN1Sequence teeEnforcedSequence = getTeeEncodedSequence(keyDescriptionSequence); AuthorizationList teeAuthorizationList = extractAuthorizationList(teeEnforcedSequence); return new AndroidKeyStoreAttestation( keymasterVersion, challenge, softwareAuthorizationList, teeAuthorizationList); } /** * @return parsed keymaster version */ public Integer getKeyMasterVersion() { return keymasterVersion; } /** * @return parsed software authorization list */ public AuthorizationList getSoftwareAuthorizationList() { return softwareAuthorizationList; } /** * @return the parsed attestation challenge */ public byte[] getAttestationChallenge() { return attestationChallenge; } /** * @return the parsed TEE authorization list */ public AuthorizationList getTeeAuthorizationList() { return teeAuthorizationList; } @Override public int hashCode() { return Objects.hash( attestationChallenge, keymasterVersion, softwareAuthorizationList, teeAuthorizationList); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AndroidKeyStoreAttestation other = (AndroidKeyStoreAttestation) obj; return Objects.equals(attestationChallenge, other.attestationChallenge) && Objects.equals(keymasterVersion, other.keymasterVersion) && Objects.equals(softwareAuthorizationList, other.softwareAuthorizationList) && Objects.equals(teeAuthorizationList, other.teeAuthorizationList); } @Override public String toString() { StringBuilder attestation = new StringBuilder(); attestation.append("[\n keymasterVersion: " + keymasterVersion); if (attestationChallenge != null && attestationChallenge.length > 0) { attestation.append("\n attestationChallenge: 0x"); attestation.append(Hex.encodeHexString(attestationChallenge)); } if (softwareAuthorizationList != null) { attestation.append("\n softwareEnforced: "); attestation.append(softwareAuthorizationList.toString().replaceAll("\n", "\n ")); } if (teeAuthorizationList != null) { attestation.append("\n teeEnforced: "); attestation.append(teeAuthorizationList.toString().replaceAll("\n", "\n ")); } attestation.append("\n]"); return attestation.toString(); } public JsonObject toJson() { JsonObject json = new JsonObject(); json.addProperty("keymaster_version", keymasterVersion); json.addProperty("attestation_challenge", Hex.encodeHexString(attestationChallenge)); json.add("software_encoded", softwareAuthorizationList.toJson()); json.add("tee_encoded", teeAuthorizationList.toJson()); return json; } private static ASN1Sequence getKeyDescriptionSequence(ASN1OctetString octet) throws CertificateParsingException { // Read out the Sequence ASN1Object asn1Object = X509ExtensionParsingUtil.getAsn1Object(octet.getOctets()); if (asn1Object == null || !(asn1Object instanceof ASN1Sequence)) { throw new CertificateParsingException("Expected KeyDescription Sequence."); } ASN1Sequence sequence = (ASN1Sequence) asn1Object; if (sequence.size() != DESCRIPTION_LENGTH) { throw new CertificateParsingException("KeyDescription Sequence has " + sequence.size() + " elements. Expected " + DESCRIPTION_LENGTH + " elements "); } return sequence; } private static ASN1Sequence getSoftwareEncodedSequence(ASN1Sequence keyDescriptionSequence) throws CertificateParsingException { ASN1Encodable asn1Encodable = keyDescriptionSequence.getObjectAt(DESCRIPTION_SOFTWARE_ENFORCED_INDEX); if (asn1Encodable == null || !(asn1Encodable instanceof ASN1Sequence)) { throw new CertificateParsingException("Expected softwareEnforced ASN1Sequence."); } return (ASN1Sequence) asn1Encodable; } private static ASN1Sequence getTeeEncodedSequence(ASN1Sequence keyDescriptionSequence) throws CertificateParsingException { ASN1Encodable asn1Encodable = keyDescriptionSequence.getObjectAt(DESCRIPTION_TEE_ENFORCED_INDEX); if (asn1Encodable == null || !(asn1Encodable instanceof ASN1Sequence)) { throw new CertificateParsingException("Expected teeEnforced ASN1Sequence."); } return (ASN1Sequence) asn1Encodable; } private static int getKeymasterVersion(ASN1Sequence keyDescriptionSequence) throws CertificateParsingException { ASN1Encodable asn1Encodable = keyDescriptionSequence.getObjectAt(DESCRIPTION_VERSION_INDEX); return X509ExtensionParsingUtil.getInt(asn1Encodable); } private static byte[] getAttestationChallenge(ASN1Sequence keyDescriptionSequence) throws CertificateParsingException { ASN1Encodable asn1Encodable = keyDescriptionSequence.getObjectAt(DESCRIPTION_CHALLENGE_INDEX); return X509ExtensionParsingUtil.getByteArray(asn1Encodable); } private static List<Purpose> getPurpose(HashMap<Integer, ASN1Primitive> taggedObjects) throws CertificateParsingException { return getListFromTaggedObjectSet(taggedObjects, AUTHZ_PURPOSE_TAG, Purpose.class); } private static Algorithm getAlgorithm(HashMap<Integer, ASN1Primitive> taggedObjects) throws CertificateParsingException { ASN1Primitive asn1Primitive = taggedObjects.get(AUTHZ_ALGORITHM_TAG); if (asn1Primitive == null) { // No algorithm found return null; } return Algorithm.fromValue(X509ExtensionParsingUtil.getInt(asn1Primitive)); } private static Integer getKeySize(HashMap<Integer, ASN1Primitive> taggedObjects) throws CertificateParsingException { ASN1Primitive asn1Primitive = taggedObjects.get(AUTHZ_KEY_SIZE_TAG); if (asn1Primitive == null) { // No key size found return null; } return X509ExtensionParsingUtil.getInt(asn1Primitive); } private static List<BlockMode> getBlockMode( HashMap<Integer, ASN1Primitive> softwareEnforcedTaggedObjects) throws CertificateParsingException { return getListFromTaggedObjectSet( softwareEnforcedTaggedObjects, AUTHZ_BLOCK_MODE_TAG, BlockMode.class); } // TODO(aczeskis): There is a cleaner way of doing this in Java 8. In Java 8, we can make Purpose // & BlockMode implement an interface (so the function could call .fromInt() on the // parameterized type). Unfortunately, Java 7 does not allow interfaces to have static methods! // This decision was fixed in Java 8. private static <T> List<T> getListFromTaggedObjectSet( HashMap<Integer, ASN1Primitive> taggedObjects, int tag, Class<T> type) throws CertificateParsingException { ASN1Primitive asn1Primitive = taggedObjects.get(tag); if (asn1Primitive == null) { // No tagged object mode found return null; } if (!(asn1Primitive instanceof ASN1Set)) { throw new CertificateParsingException("Expected ASN1Set"); } ASN1Set set = (ASN1Set) asn1Primitive; List<T> list = new ArrayList<T>(); for (ASN1Encodable asn1Encodable : set.toArray()) { list.add(buildTypeFromInt(X509ExtensionParsingUtil.getInt(asn1Encodable), type)); } return list; } @SuppressWarnings("unchecked") private static <T> T buildTypeFromInt(int value, Class<T> type) throws CertificateParsingException { if (type == Purpose.class) { return (T) Purpose.fromValue(value); } else if (type == BlockMode.class) { return (T) BlockMode.fromValue(value); } else { throw new CertificateParsingException("Cannot build type " + type.getSimpleName()); } } private static AuthorizationList extractAuthorizationList(ASN1Sequence authorizationSequence) throws CertificateParsingException { HashMap<Integer, ASN1Primitive> taggedObjects = X509ExtensionParsingUtil.extractTaggedObjects(authorizationSequence); return new AuthorizationList.Builder() .setPurpose(getPurpose(taggedObjects)) .setAlgorithm(getAlgorithm(taggedObjects)) .setKeySize(getKeySize(taggedObjects)) .setBlockMode(getBlockMode(taggedObjects)) .build(); } }
5,701
2,379
// Copyright (c) by respective owners including Yahoo!, Microsoft, and // individual contributors. All rights reserved. Released under a BSD (revised) // license as described in the file LICENSE. #include <sstream> #include <cfloat> #include "reductions.h" #include "vw.h" #include "shared_data.h" #include "io/logger.h" using namespace VW::config; struct multi_oaa { size_t k = 0; bool probabilities = false; std::string link = ""; VW::io::logger logger; explicit multi_oaa(VW::io::logger logger) : logger(std::move(logger)) {} }; template <bool is_learn> void predict_or_learn(multi_oaa& o, VW::LEARNER::single_learner& base, example& ec) { MULTILABEL::labels multilabels = ec.l.multilabels; MULTILABEL::labels preds = ec.pred.multilabels; preds.label_v.clear(); ec.l.simple = {FLT_MAX}; ec._reduction_features.template get<simple_label_reduction_features>().reset_to_default(); uint32_t multilabel_index = 0; for (uint32_t i = 0; i < o.k; i++) { if (is_learn) { ec.l.simple.label = -1.f; if (multilabels.label_v.size() > multilabel_index && multilabels.label_v[multilabel_index] == i) { ec.l.simple.label = 1.f; multilabel_index++; } base.learn(ec, i); } else base.predict(ec, i); if ((o.link == "logistic" && ec.pred.scalar > 0.5) || (o.link != "logistic" && ec.pred.scalar > 0.0)) { preds.label_v.push_back(i); } if (o.probabilities) { ec.pred.scalars.push_back(std::move(ec.pred.scalar)); } } if (is_learn) { if (multilabel_index < multilabels.label_v.size()) { o.logger.out_error( "label {0} is not in {{0,{1}}} This won't work right.", multilabels.label_v[multilabel_index], o.k - 1); } } if (!o.probabilities) { ec.pred.multilabels = preds; ec.l.multilabels = multilabels; } } void finish_example(VW::workspace& all, multi_oaa& o, example& ec) { if (o.probabilities) { // === Print probabilities for all classes std::ostringstream outputStringStream; for (uint32_t i = 0; i < o.k; i++) { if (i > 0) outputStringStream << ' '; if (all.sd->ldict) { outputStringStream << all.sd->ldict->get(i); } else outputStringStream << i; outputStringStream << ':' << ec.pred.scalars[i]; } const auto ss_str = outputStringStream.str(); for (auto& sink : all.final_prediction_sink) all.print_text_by_ref(sink.get(), ss_str, ec.tag, all.logger); } MULTILABEL::output_example(all, ec); VW::finish_example(all, ec); } VW::LEARNER::base_learner* multilabel_oaa_setup(VW::setup_base_i& stack_builder) { options_i& options = *stack_builder.get_options(); VW::workspace& all = *stack_builder.get_all_pointer(); auto data = VW::make_unique<multi_oaa>(all.logger); option_group_definition new_options("Multilabel One Against All"); new_options .add(make_option("multilabel_oaa", data->k).keep().necessary().help("One-against-all multilabel with <k> labels")) .add(make_option("probabilities", data->probabilities).help("Predict probabilities of all classes")) .add(make_option("link", data->link) .default_value("identity") .keep() .one_of({"identity", "logistic", "glf1", "poisson"}) .help("Specify the link function")); if (!options.add_parse_and_check_necessary(new_options)) return nullptr; std::string name_addition; VW::prediction_type_t pred_type; size_t ws = data->k; if (data->probabilities) { // Unlike oaa and csoaa_ldf (which always remove --logistic link and apply logic manually for probabilities), // multilabel_oaa will always add logistic link and apply logic in base (scorer) reduction if (data->link != "logistic") { options.replace("link", "logistic"); data->link = "logistic"; } pred_type = VW::prediction_type_t::scalars; auto loss_function_type = all.loss->getType(); if (loss_function_type != "logistic") all.logger.out_warn( "--probabilities should be used only with --loss_function=logistic, currently using: {}", loss_function_type); // the three boolean template parameters are: is_learn, print_all and scores name_addition = "-prob"; } else { name_addition = ""; pred_type = VW::prediction_type_t::multilabels; } auto* l = make_reduction_learner(std::move(data), as_singleline(stack_builder.setup_base_learner()), predict_or_learn<true>, predict_or_learn<false>, stack_builder.get_setupfn_name(multilabel_oaa_setup) + name_addition) .set_params_per_weight(ws) .set_learn_returns_prediction(true) .set_input_label_type(VW::label_type_t::multilabel) .set_output_prediction_type(pred_type) .set_finish_example(finish_example) .build(); all.example_parser->lbl_parser = MULTILABEL::multilabel; return make_base(*l); }
2,039
575
<filename>chrome/browser/ui/app_list/search/arc/recommend_apps_fetcher.cc<gh_stars>100-1000 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/search/arc/recommend_apps_fetcher.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/app_list/search/arc/recommend_apps_fetcher_impl.h" #include "content/public/browser/storage_partition.h" namespace app_list { // static std::unique_ptr<RecommendAppsFetcher> RecommendAppsFetcher::Create( RecommendAppsFetcherDelegate* delegate) { return std::make_unique<RecommendAppsFetcherImpl>( delegate, content::BrowserContext::GetDefaultStoragePartition( ProfileManager::GetActiveUserProfile()) ->GetURLLoaderFactoryForBrowserProcess() .get()); } } // namespace app_list
361
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ #import <OfficeImport/XXUnknownSuperclass.h> #import <OfficeImport/EDKeyedObject.h> @class CHDErrorBar, EDCollection, CHDFormula, EDKeyedCollection, CHDChart, CHDChartType, CHDData, CHDDataLabel, OADGraphicProperties, CHDDataValue; __attribute__((visibility("hidden"))) @interface CHDSeries : XXUnknownSuperclass <EDKeyedObject> { @private CHDChart *mChart; // 4 = 0x4 CHDChartType *mChartType; // 8 = 0x8 int mOrder; // 12 = 0xc int mStyleIndex; // 16 = 0x10 CHDFormula *mName; // 20 = 0x14 CHDDataValue *mLastCachedName; // 24 = 0x18 CHDData *mValueData; // 28 = 0x1c CHDData *mCategoryData; // 32 = 0x20 EDKeyedCollection *mDataValuePropertiesCollection; // 36 = 0x24 EDCollection *mTrendlinesCollection; // 40 = 0x28 CHDErrorBar *mErrorBarX; // 44 = 0x2c CHDErrorBar *mErrorBarY; // 48 = 0x30 CHDDataLabel *mDefaultDataLabel; // 52 = 0x34 OADGraphicProperties *mGraphicProperties; // 56 = 0x38 bool mDateTimeFormattingFlag; // 60 = 0x3c bool mHiddenFlag; // 61 = 0x3d } @property(retain) id chartType; // G=0x1eba65; S=0x16ece5; converted property @property(assign) int order; // G=0x266305; S=0x16d499; converted property @property(assign) int styleIndex; // G=0x16e8ed; S=0x16e501; converted property @property(retain) id lastCachedName; // G=0x16ee85; S=0x171f75; converted property @property(retain) id name; // G=0x16ee75; S=0x16da6d; converted property @property(retain) id valueData; // G=0x16ef99; S=0x16e10d; converted property @property(retain) id categoryData; // G=0x171b65; S=0x16e281; converted property @property(retain) id dataValuePropertiesCollection; // G=0x16e3b9; S=0x1fecb1; converted property @property(retain) id trendlinesCollection; // G=0x1ebc01; S=0x1ebc11; converted property @property(retain) id errorBarXAxis; // G=0x1ebc59; S=0x1ebc69; converted property @property(retain) id errorBarYAxis; // G=0x16f309; S=0x16f751; converted property @property(retain) id defaultDataLabel; // G=0x16e6b9; S=0x1eb321; converted property @property(retain) id graphicProperties; // G=0x16e8fd; S=0x16e671; converted property @property(assign, getter=isDateTimeFormattingFlag) bool dateTimeFormattingFlag; // G=0x175761; S=0x175751; converted property + (id)seriesWithChart:(id)chart; // 0x1e317d - (id)initWithChart:(id)chart; // 0x16cf59 - (id)shallowCopy; // 0x1ebb21 - (void)clearBackPointers; // 0x1ecdc9 - (void)dealloc; // 0x17aa81 // converted property getter: - (id)chartType; // 0x1eba65 - (id)chart; // 0x16f319 // converted property setter: - (void)setChartType:(id)type; // 0x16ece5 - (unsigned)key; // 0x16ee65 // converted property getter: - (int)order; // 0x266305 // converted property setter: - (void)setOrder:(int)order; // 0x16d499 // converted property getter: - (int)styleIndex; // 0x16e8ed // converted property setter: - (void)setStyleIndex:(int)index; // 0x16e501 // converted property getter: - (id)lastCachedName; // 0x16ee85 // converted property setter: - (void)setLastCachedName:(id)name; // 0x171f75 // converted property getter: - (id)name; // 0x16ee75 // converted property setter: - (void)setName:(id)name; // 0x16da6d // converted property getter: - (id)valueData; // 0x16ef99 // converted property setter: - (void)setValueData:(id)data; // 0x16e10d // converted property getter: - (id)categoryData; // 0x171b65 // converted property setter: - (void)setCategoryData:(id)data; // 0x16e281 // converted property getter: - (id)dataValuePropertiesCollection; // 0x16e3b9 // converted property setter: - (void)setDataValuePropertiesCollection:(id)collection; // 0x1fecb1 // converted property getter: - (id)trendlinesCollection; // 0x1ebc01 // converted property setter: - (void)setTrendlinesCollection:(id)collection; // 0x1ebc11 - (void)setErrorBar:(id)bar; // 0x16f609 // converted property getter: - (id)errorBarXAxis; // 0x1ebc59 // converted property setter: - (void)setErrorBarXAxis:(id)axis; // 0x1ebc69 // converted property getter: - (id)errorBarYAxis; // 0x16f309 // converted property setter: - (void)setErrorBarYAxis:(id)axis; // 0x16f751 // converted property getter: - (id)defaultDataLabel; // 0x16e6b9 // converted property setter: - (void)setDefaultDataLabel:(id)label; // 0x1eb321 // converted property getter: - (id)graphicProperties; // 0x16e8fd // converted property setter: - (void)setGraphicProperties:(id)properties; // 0x16e671 // converted property setter: - (void)setDateTimeFormattingFlag:(bool)flag; // 0x175751 // converted property getter: - (bool)isDateTimeFormattingFlag; // 0x175761 - (bool)isHidden; // 0x16ecd5 - (void)setHiddenFlag:(bool)flag; // 0x1fbb4d - (id)defaultSeriesNameForIndex:(int)index; // 0x172ff1 - (bool)isEmpty; // 0x170099 @end
1,838
526
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.analyticsmodeling.test.synchronization; import org.testng.annotations.Test; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; import org.odpi.openmetadata.accessservices.analyticsmodeling.synchronization.IdMap; import org.odpi.openmetadata.accessservices.analyticsmodeling.synchronization.model.MetadataItem; import org.odpi.openmetadata.accessservices.analyticsmodeling.test.utils.JsonMocks; import org.odpi.openmetadata.accessservices.analyticsmodeling.test.utils.TestUtilities; import org.odpi.openmetadata.accessservices.analyticsmodeling.utils.QualifiedNameUtils; class MetadataItemTest { private static final String FOLDER_MASTER = "/src/test/resources/synchronization/master/"; @Test void testBuildMetadataItem() throws IOException { MetadataItem obj = new MetadataItem(); String id = "qiID"; // from Referenceable obj.setQualifiedName(QualifiedNameUtils.buildQualifiedName("PARENT", IdMap.SCHEMA_ATTRIBUTE_TYPE_NAME, id)); Map<String, String> props = new TreeMap<>(); props.put("p1", "v1"); props.put("p2", "v2"); obj.setAdditionalProperties(props); // from SchemaElement obj.setDisplayName("displayName"); obj.setDescription("Query Item description"); // from SchemaAttribute obj.setElementPosition(1); // from QueryItem obj.setIdentifier(id); obj.setExpression("qiExpression"); obj.setDataType("VARCHAR"); obj.setSourceGuid(Arrays.asList("guid1", "guid2")); obj.setSourceId(Arrays.asList("uid1", "uid2")); TestUtilities.assertObjectJson(obj, TestUtilities.readJsonFile(FOLDER_MASTER, "item")); } @Test void testMetadataItemFromJson() throws IOException { MetadataItem obj = TestUtilities.readObjectJson( JsonMocks.getItem("PARENT::(SchemaAttribute)=qiID", "displayName", "qiID", "qiExpression", "VARCHAR"), MetadataItem.class); TestUtilities.assertObjectJson(obj, TestUtilities.readJsonFile(FOLDER_MASTER, "itemPartial")); } }
743
432
/* Copyright (c) 2015, bugyo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* \summary: Network Service Header (NSH) printer */ /* specification: draft-ietf-sfc-nsh-01 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" static const char tstr[] = " [|NSH]"; static const struct tok nsh_flags [] = { { 0x20, "O" }, { 0x10, "C" }, { 0, NULL } }; #define NSH_BASE_HDR_LEN 4 #define NSH_SERVICE_PATH_HDR_LEN 4 #define NSH_HDR_WORD_SIZE 4U void nsh_print(netdissect_options *ndo, const u_char *bp, u_int len) { int n, vn; uint8_t ver; uint8_t flags; uint8_t length; uint8_t md_type; uint8_t next_protocol; uint32_t service_path_id; uint8_t service_index; uint32_t ctx; uint16_t tlv_class; uint8_t tlv_type; uint8_t tlv_len; u_int next_len; /* print Base Header and Service Path Header */ if (len < NSH_BASE_HDR_LEN + NSH_SERVICE_PATH_HDR_LEN) goto trunc; ND_TCHECK2(*bp, NSH_BASE_HDR_LEN + NSH_SERVICE_PATH_HDR_LEN); ver = (uint8_t)(*bp >> 6); flags = *bp; bp += 1; length = *bp; bp += 1; md_type = *bp; bp += 1; next_protocol = *bp; bp += 1; service_path_id = EXTRACT_24BITS(bp); bp += 3; service_index = *bp; bp += 1; ND_PRINT((ndo, "NSH, ")); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "ver %d, ", ver)); } ND_PRINT((ndo, "flags [%s], ", bittok2str_nosep(nsh_flags, "none", flags))); if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, "length %d, ", length)); ND_PRINT((ndo, "md type 0x%x, ", md_type)); } if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "next-protocol 0x%x, ", next_protocol)); } ND_PRINT((ndo, "service-path-id 0x%06x, ", service_path_id)); ND_PRINT((ndo, "service-index 0x%x", service_index)); /* Make sure we have all the headers */ if (len < length * NSH_HDR_WORD_SIZE) goto trunc; ND_TCHECK2(*bp, length * NSH_HDR_WORD_SIZE); /* * length includes the lengths of the Base and Service Path headers. * That means it must be at least 2. */ if (length < 2) goto trunc; /* * Print, or skip, the Context Headers. * (length - 2) is the length of those headers. */ if (ndo->ndo_vflag > 2) { if (md_type == 0x01) { for (n = 0; n < length - 2; n++) { ctx = EXTRACT_32BITS(bp); bp += NSH_HDR_WORD_SIZE; ND_PRINT((ndo, "\n Context[%02d]: 0x%08x", n, ctx)); } } else if (md_type == 0x02) { n = 0; while (n < length - 2) { tlv_class = EXTRACT_16BITS(bp); bp += 2; tlv_type = *bp; bp += 1; tlv_len = *bp; bp += 1; ND_PRINT((ndo, "\n TLV Class %d, Type %d, Len %d", tlv_class, tlv_type, tlv_len)); n += 1; if (length - 2 < n + tlv_len) { ND_PRINT((ndo, " ERROR: invalid-tlv-length")); return; } for (vn = 0; vn < tlv_len; vn++) { ctx = EXTRACT_32BITS(bp); bp += NSH_HDR_WORD_SIZE; ND_PRINT((ndo, "\n Value[%02d]: 0x%08x", vn, ctx)); } n += tlv_len; } } else { ND_PRINT((ndo, "ERROR: unknown-next-protocol")); return; } } else { bp += (length - 2) * NSH_HDR_WORD_SIZE; } ND_PRINT((ndo, ndo->ndo_vflag ? "\n " : ": ")); /* print Next Protocol */ next_len = len - length * NSH_HDR_WORD_SIZE; switch (next_protocol) { case 0x1: ip_print(ndo, bp, next_len); break; case 0x2: ip6_print(ndo, bp, next_len); break; case 0x3: ether_print(ndo, bp, next_len, ndo->ndo_snapend - bp, NULL, NULL); break; default: ND_PRINT((ndo, "ERROR: unknown-next-protocol")); return; } return; trunc: ND_PRINT((ndo, "%s", tstr)); }
2,719
3,710
#pragma once //----------------------------------------------------------------------------- // tellipticbrush.h: interface for the TEllipticBrush class. //----------------------------------------------------------------------------- #if !defined(TELLIPTIC_BRUSH_H) #define TELLIPTIC_BRUSH_H #ifdef PER_VECCHIO_ELLIPTIC_BRUSH #include "tbrush.h" #undef DVAPI #undef DVVAR #ifdef TVRENDER_EXPORTS #define DVAPI DV_EXPORT_API #define DVVAR DV_EXPORT_VAR #else #define DVAPI DV_IMPORT_API #define DVVAR DV_IMPORT_VAR #endif //============================================================================= // forward declaration class TStroke; //============================================================================= /*! | / __b__ / \ angle in degree / | \ | ----|---o---a--|-- > \__|__/ | N.B. Imp manages angle in radiant. */ //============================================================================= class DVAPI TEllipticBrush : public TBrush { struct Imp; Imp *m_imp; public: // TEllipticBrush(double a = 1,double b = 1, double angleInDegree = 0); // // per brush ellittico TEllipticBrush(); TEllipticBrush(const TEllipticBrush &brush); virtual ~TEllipticBrush(); void makeOutline(const TStroke &stroke, TStrokeOutline &outline, const OutlineParameter &param); void draw(); /* // per brush ellittico void setAngle(double angleInDegree); double getAngle() const; double getSemiAxisA() const; void setSemiAxisA(double); double getSemiAxisB() const; void setSemiAxisB(double); */ TBrush *clone(); private: // not implemented TEllipticBrush &operator=(const TEllipticBrush &brush); }; #endif // PER_VECCHIO_ELLIPTIC_BRUSH #endif // !defined(TELLIPTIC_BRUSH_H) //----------------------------------------------------------------------------- // End Of File //-----------------------------------------------------------------------------
649
4,802
#ifndef TOBOOT_INTERNAL_H_ #define TOBOOT_INTERNAL_H_ #include <stdint.h> /// This describes the structure that allows the OS to communicate /// with the bootloader. It keeps track of how many times we've /// tried booting, as well as a magic value that tells us to enter /// the bootloader instead of booting the app. /// It also keeps track of the board model. __attribute__((section(".boot_token"))) extern struct toboot_runtime boot_token; enum bootloader_reason { NOT_ENTERING_BOOTLOADER = 0, BOOT_TOKEN_PRESENT = 1, BOOT_FAILED_TOO_MANY_TIMES = 2, NO_PROGRAM_PRESENT = 3, BUTTON_HELD_DOWN = 4, COLD_BOOT_CONFIGURATION_FLAG = 5, }; extern enum bootloader_reason bootloader_reason; /// Legacy Toboot V1 configuration values #ifndef TOBOOT_V1_CFG_FLAGS #define TOBOOT_V1_CFG_FLAGS 0 #endif #define TOBOOT_V1_CFG_MAGIC_MASK 0xffff #define TOBOOT_V1_CFG_MAGIC 0x70b0 #ifndef TOBOOT_V1_APP_FLAGS #define TOBOOT_V1_APP_FLAGS 0 #endif #define TOBOOT_V1_APP_MAGIC_MASK 0xffff #define TOBOOT_V1_APP_MAGIC 0x6fb0 #define TOBOOT_V1_APP_PAGE_MASK 0x00ff0000 #define TOBOOT_V1_APP_PAGE_SHIFT 16 uint32_t tb_first_free_address(void); uint32_t tb_first_free_sector(void); const struct toboot_configuration *tb_get_config(void); uint32_t tb_config_hash(const struct toboot_configuration *cfg); void tb_sign_config(struct toboot_configuration *cfg); uint32_t tb_generation(const struct toboot_configuration *cfg); int tb_valid_signature_at_page(uint32_t page); #endif /* TOBOOT_INTERNAL_H_ */
596
1,564
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.modelmapper.spi; import org.modelmapper.Converter; import org.modelmapper.config.Configuration; /** * Conditionally converts matching source objects to instances of destination type {@code D}. * * @param <S> source type * @param <D> destination type * @author <NAME> */ public interface ConditionalConverter<S, D> extends Converter<S, D> { public enum MatchResult { /** Indicates that the source and destination types were matched. */ FULL, /** Indicates that only the destination type was matched. */ PARTIAL, /** Indicates that the destination type was not matched. */ NONE; } /** * Determines whether the converter matches and supports conversion from {@code sourceType} to * {@code destinationType}. * <p> * In the case of a partial match, the converter is indicating that it does not recognise the * source type but that it may still be capable performing the conversion implicitly by parsing the * result of calling {@link Object#toString()} or by some other means which similarly does not * require knowledge of the type at compile time. * <p> * Implicit conversion may result in conversions which are susceptible to unexpected failure when * property types or formats change. Conversion of properties with partially matched types can be * disabled via {@link Configuration#setFullTypeMatchingRequired(boolean)}. * * @param sourceType to match * @param destinationType to match * @return <ul> * <li>{@link MatchResult#FULL} if {@code sourceType} and {@code destinationType} are * matched</li> * <li>{@link MatchResult#PARTIAL} if {@code destinationType} is matched</li> * <li>{@link MatchResult#NONE} if {@code destinationType} is not matched</li> * </ul> */ MatchResult match(Class<?> sourceType, Class<?> destinationType); }
796
474
<reponame>ILGO0413/Javacord package org.javacord.core.interaction; import com.fasterxml.jackson.databind.JsonNode; import org.apache.logging.log4j.Logger; import org.javacord.api.DiscordApi; import org.javacord.api.entity.channel.Channel; import org.javacord.api.entity.channel.ServerChannel; import org.javacord.api.entity.channel.TextChannel; import org.javacord.api.entity.server.Server; import org.javacord.api.entity.user.User; import org.javacord.api.interaction.Interaction; import org.javacord.api.interaction.InteractionType; import org.javacord.api.interaction.callback.InteractionFollowupMessageBuilder; import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder; import org.javacord.api.interaction.callback.InteractionOriginalResponseUpdater; import org.javacord.core.DiscordApiImpl; import org.javacord.core.entity.message.InteractionCallbackType; import org.javacord.core.entity.server.ServerImpl; import org.javacord.core.entity.user.MemberImpl; import org.javacord.core.entity.user.UserImpl; import org.javacord.core.util.logging.LoggerUtil; import org.javacord.core.util.rest.RestEndpoint; import org.javacord.core.util.rest.RestMethod; import org.javacord.core.util.rest.RestRequest; import java.util.Optional; import java.util.concurrent.CompletableFuture; public abstract class InteractionImpl implements Interaction { private static final Logger logger = LoggerUtil.getLogger(InteractionImpl.class); private static final String RESPOND_LATER_BODY = "{\"type\": " + InteractionCallbackType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE.getId() + "}"; private final DiscordApiImpl api; private final TextChannel channel; private final long id; private final long applicationId; private final UserImpl user; private final String token; private final int version; /** * Class constructor. * * @param api The api instance. * @param channel The channel in which the interaction happened. Can be {@code null}. * @param jsonData The json data of the interaction. */ public InteractionImpl(DiscordApiImpl api, TextChannel channel, JsonNode jsonData) { this.api = api; this.channel = channel; id = jsonData.get("id").asLong(); applicationId = jsonData.get("application_id").asLong(); if (jsonData.hasNonNull("member")) { MemberImpl member = new MemberImpl( api, (ServerImpl) getServer().orElseThrow(AssertionError::new), jsonData.get("member"), null ); user = (UserImpl) member.getUser(); } else if (jsonData.hasNonNull("user")) { user = new UserImpl(api, jsonData.get("user"), (MemberImpl) null, null); } else { user = null; logger.error("Received interaction without a member AND without a user field"); } token = jsonData.get("token").asText(); version = jsonData.get("version").asInt(); } @Override public DiscordApi getApi() { return api; } @Override public long getId() { return id; } @Override public long getApplicationId() { return applicationId; } @Override public abstract InteractionType getType(); @Override public InteractionImmediateResponseBuilder createImmediateResponder() { return new InteractionImmediateResponseBuilderImpl(this); } @Override public CompletableFuture<InteractionOriginalResponseUpdater> respondLater() { return new RestRequest<InteractionOriginalResponseUpdater>(this.api, RestMethod.POST, RestEndpoint.INTERACTION_RESPONSE) .setUrlParameters(getIdAsString(), token) .setBody(RESPOND_LATER_BODY) .execute(result -> new InteractionOriginalResponseUpdaterImpl(this)); } @Override public InteractionFollowupMessageBuilder createFollowupMessageBuilder() { return new InteractionFollowupMessageBuilderImpl(this); } @Override public Optional<Server> getServer() { return getChannel().flatMap(Channel::asServerChannel).map(ServerChannel::getServer); } @Override public Optional<TextChannel> getChannel() { return Optional.ofNullable(channel); } @Override public User getUser() { return user; } @Override public String getToken() { return token; } @Override public int getVersion() { return version; } }
1,761
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_SOFTWARE_OUTPUT_DEVICE_CLIENT_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_SOFTWARE_OUTPUT_DEVICE_CLIENT_H_ namespace gfx { struct CALayerParams; } // namespace gfx namespace viz { class SoftwareOutputDeviceClient { public: virtual ~SoftwareOutputDeviceClient() {} // Specify the CALayer parameters used to display the content drawn by this // device on macOS. virtual void SoftwareDeviceUpdatedCALayerParams( const gfx::CALayerParams& ca_layer_params) = 0; }; } // namespace viz #endif // COMPONENTS_VIZ_SERVICE_DISPLAY_SOFTWARE_OUTPUT_DEVICE_CLIENT_H_
259
4,071
package com.github.ompc.greys.core.command; import com.github.ompc.greys.core.advisor.AdviceListener; import com.github.ompc.greys.core.server.Session; import com.github.ompc.greys.core.util.PointCut; import com.github.ompc.greys.core.util.affect.RowAffect; import java.lang.instrument.Instrumentation; /** * 命令 * Created by <EMAIL> on 15/5/18. */ public interface Command { /** * 信息发送者 * * @author <EMAIL> */ interface Printer { /** * 发送信息 * * @param isF 是否结束打印 * @param message 发送信息内容 */ Printer print(boolean isF, String message); /** * 发送信息 * * @param message 发送信息内容 */ Printer print(String message); /** * 换行发送信息 * * @param isF 是否结束打印 * @param message 发送信息内容 */ Printer println(boolean isF, String message); /** * 换行发送信息 * * @param message 发送信息内容 */ Printer println(String message); /** * 结束打印 */ void finish(); } /** * 类增强 */ interface GetEnhancer { /** * 获取增强功能点 * @return */ PointCut getPointCut(); /** * 获取监听器 * * @return 返回监听器 */ AdviceListener getAdviceListener(); } /** * 命令动作 */ interface Action { } /** * 类增强动作 */ interface GetEnhancerAction extends Action { /** * 执行动作 * * @param session 会话 * @param inst inst * @param printer 信息发送者 * @return 类增强 * @throws Throwable 动作执行出错 */ GetEnhancer action(Session session, Instrumentation inst, Printer printer) throws Throwable; } /** * 安静命令动作 */ interface SilentAction extends Action { /** * 安静的执行动作 * * @param session 会话 * @param inst inst * @param printer 信息发送者 * @throws Throwable 动作执行出错 */ void action(Session session, Instrumentation inst, Printer printer) throws Throwable; } /** * 影响动作 */ interface RowAction extends Action { /** * 安静的执行动作 * * @param session 会话 * @param inst inst * @param printer 信息发送者 * @return 影响范围 * @throws Throwable 动作执行出错 */ RowAffect action(Session session, Instrumentation inst, Printer printer) throws Throwable; } /** * 获取命令动作 * * @return 返回命令所对应的命令动作 */ Action getAction(); }
1,690
1,123
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #pragma once #include <quic/codec/Types.h> #include <quic/state/StateData.h> namespace quic { /** * Processes a Datagram frame */ void handleDatagram(QuicConnectionStateBase& conn, DatagramFrame& frame); } // namespace quic
133
743
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.guacamole.auth.jdbc.base; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A search term for querying historical records of arbitrary activities. This * will contain a the search term in string form and, if that string appears to * be a date. a corresponding date range. */ public class ActivityRecordSearchTerm { /** * A pattern that can match a year, year and month, or year and month and * day. */ private static final Pattern DATE_PATTERN = Pattern.compile("(\\d+)(?:-(\\d+)?(?:-(\\d+)?)?)?"); /** * The index of the group within <code>DATE_PATTERN</code> containing the * year number. */ private static final int YEAR_GROUP = 1; /** * The index of the group within <code>DATE_PATTERN</code> containing the * month number, if any. */ private static final int MONTH_GROUP = 2; /** * The index of the group within <code>DATE_PATTERN</code> containing the * day number, if any. */ private static final int DAY_GROUP = 3; /** * The start of the date range for records that should be retrieved, if the * provided search term appears to be a date. */ private final Date startDate; /** * The end of the date range for records that should be retrieved, if the * provided search term appears to be a date. */ private final Date endDate; /** * The string that should be searched for. */ private final String term; /** * Parse the given string as an integer, returning the provided default * value if the string is null. * * @param str * The string to parse as an integer. * * @param defaultValue * The value to return if <code>str</code> is null. * * @return * The parsed value, or the provided default value if <code>str</code> * is null. */ private static int parseInt(String str, int defaultValue) { if (str == null) return defaultValue; return Integer.parseInt(str); } /** * Returns a new calendar representing the last millisecond of the same * year as <code>calendar</code>. * * @param calendar * The calendar defining the year whose end (last millisecond) is to be * returned. * * @return * A new calendar representing the last millisecond of the same year as * <code>calendar</code>. */ private static Calendar getEndOfYear(Calendar calendar) { // Get first day of next year Calendar endOfYear = Calendar.getInstance(); endOfYear.clear(); endOfYear.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1); // Transform into the last millisecond of the given year endOfYear.add(Calendar.MILLISECOND, -1); return endOfYear; } /** * Returns a new calendar representing the last millisecond of the same * month and year as <code>calendar</code>. * * @param calendar * The calendar defining the month and year whose end (last millisecond) * is to be returned. * * @return * A new calendar representing the last millisecond of the same month * and year as <code>calendar</code>. */ private static Calendar getEndOfMonth(Calendar calendar) { // Copy given calender only up to given month Calendar endOfMonth = Calendar.getInstance(); endOfMonth.clear(); endOfMonth.set(Calendar.YEAR, calendar.get(Calendar.YEAR)); endOfMonth.set(Calendar.MONTH, calendar.get(Calendar.MONTH)); // Advance to the last millisecond of the given month endOfMonth.add(Calendar.MONTH, 1); endOfMonth.add(Calendar.MILLISECOND, -1); return endOfMonth; } /** * Returns a new calendar representing the last millisecond of the same * year, month, and day as <code>calendar</code>. * * @param calendar * The calendar defining the year, month, and day whose end * (last millisecond) is to be returned. * * @return * A new calendar representing the last millisecond of the same year, * month, and day as <code>calendar</code>. */ private static Calendar getEndOfDay(Calendar calendar) { // Copy given calender only up to given month Calendar endOfMonth = Calendar.getInstance(); endOfMonth.clear(); endOfMonth.set(Calendar.YEAR, calendar.get(Calendar.YEAR)); endOfMonth.set(Calendar.MONTH, calendar.get(Calendar.MONTH)); endOfMonth.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)); // Advance to the last millisecond of the given day endOfMonth.add(Calendar.DAY_OF_MONTH, 1); endOfMonth.add(Calendar.MILLISECOND, -1); return endOfMonth; } /** * Creates a new ActivityRecordSearchTerm representing the given string. * If the given string appears to be a date, the start and end dates of the * implied date range will be automatically determined and made available * via getStartDate() and getEndDate() respectively. * * @param term * The string that should be searched for. */ public ActivityRecordSearchTerm(String term) { // Search terms absolutely must not be null if (term == null) throw new NullPointerException("Search terms may not be null"); this.term = term; // Parse start/end of date range if term appears to be a date Matcher matcher = DATE_PATTERN.matcher(term); if (matcher.matches()) { // Retrieve date components from term String year = matcher.group(YEAR_GROUP); String month = matcher.group(MONTH_GROUP); String day = matcher.group(DAY_GROUP); // Parse start date from term Calendar startCalendar = Calendar.getInstance(); startCalendar.clear(); startCalendar.set( Integer.parseInt(year), parseInt(month, 1) - 1, parseInt(day, 1) ); Calendar endCalendar; // Derive end date from start date if (month == null) { endCalendar = getEndOfYear(startCalendar); } else if (day == null) { endCalendar = getEndOfMonth(startCalendar); } else { endCalendar = getEndOfDay(startCalendar); } // Convert results back into dates this.startDate = startCalendar.getTime(); this.endDate = endCalendar.getTime(); } // The search term doesn't look like a date else { this.startDate = null; this.endDate = null; } } /** * Returns the start of the date range for records that should be retrieved, * if the provided search term appears to be a date. * * @return * The start of the date range. */ public Date getStartDate() { return startDate; } /** * Returns the end of the date range for records that should be retrieved, * if the provided search term appears to be a date. * * @return * The end of the date range. */ public Date getEndDate() { return endDate; } /** * Returns the string that should be searched for. * * @return * The search term. */ public String getTerm() { return term; } @Override public int hashCode() { return term.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof ActivityRecordSearchTerm)) return false; return ((ActivityRecordSearchTerm) obj).getTerm().equals(getTerm()); } }
3,540
357
<gh_stars>100-1000 /* * Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ package com.vmware.identity.rest.idm.server.mapper; import com.vmware.identity.idm.LockoutPolicy; import com.vmware.identity.rest.idm.data.LockoutPolicyDTO; /** * Mapper for LockoutPolicy * * @author <NAME> * @author <NAME> */ public class LockoutPolicyMapper { public static LockoutPolicyDTO getLockoutPolicyDTO(LockoutPolicy policy) { return LockoutPolicyDTO.builder() .withDescription(policy.getDescription()) .withFailedAttemptIntervalSec(policy.getFailedAttemptIntervalSec()) .withMaxFailedAttempts(policy.getMaxFailedAttempts()) .withAutoUnlockIntervalSec(policy.getAutoUnlockIntervalSec()) .build(); } public static LockoutPolicy getLockoutPolicy(LockoutPolicyDTO lockoutPolicyDTO) { return new LockoutPolicy(lockoutPolicyDTO.getDescription(), lockoutPolicyDTO.getFailedAttemptIntervalSec(), lockoutPolicyDTO.getMaxFailedAttempts(), lockoutPolicyDTO.getAutoUnlockIntervalSec()); } }
734
575
<reponame>sarang-apps/darshan_browser<filename>chromeos/components/drivefs/drivefs_mojom_traits.cc // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/drivefs/drivefs_mojom_traits.h" namespace mojo { drivefs::mojom::FileError EnumTraits<drivefs::mojom::FileError, drive::FileError>::ToMojom( drive::FileError input) { switch (input) { case drive::FILE_ERROR_OK: return drivefs::mojom::FileError::kOk; case drive::FILE_ERROR_FAILED: return drivefs::mojom::FileError::kFailed; case drive::FILE_ERROR_IN_USE: return drivefs::mojom::FileError::kInUse; case drive::FILE_ERROR_EXISTS: return drivefs::mojom::FileError::kExists; case drive::FILE_ERROR_NOT_FOUND: return drivefs::mojom::FileError::kNotFound; case drive::FILE_ERROR_ACCESS_DENIED: return drivefs::mojom::FileError::kAccessDenied; case drive::FILE_ERROR_TOO_MANY_OPENED: return drivefs::mojom::FileError::kTooManyOpened; case drive::FILE_ERROR_NO_MEMORY: return drivefs::mojom::FileError::kNoMemory; case drive::FILE_ERROR_NO_SERVER_SPACE: return drivefs::mojom::FileError::kNoServerSpace; case drive::FILE_ERROR_NOT_A_DIRECTORY: return drivefs::mojom::FileError::kNotADirectory; case drive::FILE_ERROR_INVALID_OPERATION: return drivefs::mojom::FileError::kInvalidOperation; case drive::FILE_ERROR_SECURITY: return drivefs::mojom::FileError::kSecurity; case drive::FILE_ERROR_ABORT: return drivefs::mojom::FileError::kAbort; case drive::FILE_ERROR_NOT_A_FILE: return drivefs::mojom::FileError::kNotAFile; case drive::FILE_ERROR_NOT_EMPTY: return drivefs::mojom::FileError::kNotEmpty; case drive::FILE_ERROR_INVALID_URL: return drivefs::mojom::FileError::kInvalidUrl; case drive::FILE_ERROR_NO_CONNECTION: return drivefs::mojom::FileError::kNoConnection; case drive::FILE_ERROR_NO_LOCAL_SPACE: return drivefs::mojom::FileError::kNoLocalSpace; case drive::FILE_ERROR_SERVICE_UNAVAILABLE: return drivefs::mojom::FileError::kServiceUnavailable; } return drivefs::mojom::FileError::kFailed; } bool EnumTraits<drivefs::mojom::FileError, drive::FileError>::FromMojom( drivefs::mojom::FileError input, drive::FileError* output) { switch (input) { case drivefs::mojom::FileError::kOk: *output = drive::FILE_ERROR_OK; return true; case drivefs::mojom::FileError::kFailed: *output = drive::FILE_ERROR_FAILED; return true; case drivefs::mojom::FileError::kInUse: *output = drive::FILE_ERROR_IN_USE; return true; case drivefs::mojom::FileError::kExists: *output = drive::FILE_ERROR_EXISTS; return true; case drivefs::mojom::FileError::kNotFound: *output = drive::FILE_ERROR_NOT_FOUND; return true; case drivefs::mojom::FileError::kAccessDenied: *output = drive::FILE_ERROR_ACCESS_DENIED; return true; case drivefs::mojom::FileError::kTooManyOpened: *output = drive::FILE_ERROR_TOO_MANY_OPENED; return true; case drivefs::mojom::FileError::kNoMemory: *output = drive::FILE_ERROR_NO_MEMORY; return true; case drivefs::mojom::FileError::kNoServerSpace: *output = drive::FILE_ERROR_NO_SERVER_SPACE; return true; case drivefs::mojom::FileError::kNotADirectory: *output = drive::FILE_ERROR_NOT_A_DIRECTORY; return true; case drivefs::mojom::FileError::kInvalidOperation: *output = drive::FILE_ERROR_INVALID_OPERATION; return true; case drivefs::mojom::FileError::kSecurity: *output = drive::FILE_ERROR_SECURITY; return true; case drivefs::mojom::FileError::kAbort: *output = drive::FILE_ERROR_ABORT; return true; case drivefs::mojom::FileError::kNotAFile: *output = drive::FILE_ERROR_NOT_A_FILE; return true; case drivefs::mojom::FileError::kNotEmpty: *output = drive::FILE_ERROR_NOT_EMPTY; return true; case drivefs::mojom::FileError::kInvalidUrl: *output = drive::FILE_ERROR_INVALID_URL; return true; case drivefs::mojom::FileError::kNoConnection: *output = drive::FILE_ERROR_NO_CONNECTION; return true; case drivefs::mojom::FileError::kNoLocalSpace: *output = drive::FILE_ERROR_NO_LOCAL_SPACE; return true; case drivefs::mojom::FileError::kServiceUnavailable: *output = drive::FILE_ERROR_SERVICE_UNAVAILABLE; return true; } return false; } } // namespace mojo
1,934
852
#ifndef MaxLostHitsTrajectoryFilter_H #define MaxLostHitsTrajectoryFilter_H #include "TrackingTools/TrajectoryFiltering/interface/TrajectoryFilter.h" class MaxLostHitsTrajectoryFilter final : public TrajectoryFilter { public: explicit MaxLostHitsTrajectoryFilter(int maxHits = 0) : theMaxLostHits(maxHits) {} explicit MaxLostHitsTrajectoryFilter(const edm::ParameterSet& pset, edm::ConsumesCollector& iC) : theMaxLostHits(pset.getParameter<int>("maxLostHits")) {} bool qualityFilter(const Trajectory& traj) const override { return TrajectoryFilter::qualityFilterIfNotContributing; } bool qualityFilter(const TempTrajectory& traj) const override { return TrajectoryFilter::qualityFilterIfNotContributing; } bool toBeContinued(TempTrajectory& traj) const override { return TBC<TempTrajectory>(traj); } bool toBeContinued(Trajectory& traj) const override { return TBC<Trajectory>(traj); } std::string name() const override { return "MaxLostHitsTrajectoryFilter"; } protected: template <class T> bool TBC(T& traj) const { bool ret = traj.lostHits() <= theMaxLostHits; if (!ret) traj.setStopReason(StopReason::MAX_LOST_HITS); return ret; } int theMaxLostHits; }; #endif
421
5,133
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.conversion.nativetypes; public class IntWrapperSource { private Integer b; private Integer bb; private Integer s; private Integer ss; private Integer i; private Integer ii; private Integer l; private Integer ll; private Integer f; private Integer ff; private Integer d; private Integer dd; public Integer getB() { return b; } public void setB(Integer b) { this.b = b; } public Integer getBb() { return bb; } public void setBb(Integer bb) { this.bb = bb; } public Integer getS() { return s; } public void setS(Integer s) { this.s = s; } public Integer getSs() { return ss; } public void setSs(Integer ss) { this.ss = ss; } public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } public Integer getIi() { return ii; } public void setIi(Integer ii) { this.ii = ii; } public Integer getL() { return l; } public void setL(Integer l) { this.l = l; } public Integer getLl() { return ll; } public void setLl(Integer ll) { this.ll = ll; } public Integer getF() { return f; } public void setF(Integer f) { this.f = f; } public Integer getFf() { return ff; } public void setFf(Integer ff) { this.ff = ff; } public Integer getD() { return d; } public void setD(Integer d) { this.d = d; } public Integer getDd() { return dd; } public void setDd(Integer dd) { this.dd = dd; } }
881
808
<filename>lite/backends/arm/math/conv_transpose_depthwise.cc // Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/backends/arm/math/conv_transpose_depthwise.h" #include "lite/backends/arm/math/funcs.h" #include "lite/core/parallel_defines.h" namespace paddle { namespace lite { namespace arm { namespace math { template <> void conv_transpose_depthwise_s1<float>(const float* dst, const float* weights, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h0, const int pad_h1, const int pad_w0, const int pad_w1, const int dilation_h, const int dilation_w, float* src, ARMContext* ctx) { memset(src, 0, height * width * channels * sizeof(float)); const int output_h = (height + pad_h0 + pad_h1 - (dilation_h * (kernel_h - 1) + 1)) + 1; const int output_w = (width + pad_w0 + pad_w1 - (dilation_w * (kernel_w - 1) + 1)) + 1; float* zero_ptr = ctx->workspace_data<float>(); memset(zero_ptr, 0, width * sizeof(float)); const int ic_plane_size = height * width; const int oc_plane_size = output_h * output_w; const int rr_plane_size = kernel_h * kernel_w; LITE_PARALLEL_BEGIN(c, tid, channels) { int dst_z = c * oc_plane_size; int weight_z = c * rr_plane_size; int src_z = c * ic_plane_size; for (int ky = 0; ky < kernel_h; ky++) { int weight_y = ky * kernel_w; for (int kx = 0; kx < kernel_w; kx++) { int weight_offset = weight_z + weight_y + kx; const float* weight_addr = weights + weight_offset; for (int ih = -pad_h0 + ky * dilation_h, oh = 0; oh < output_h; ih += 4, oh += 4) { int src_y = ih * width; int dst_y = oh * output_w; bool boundary_y0 = ((ih >= 0) && (ih < height)) && (oh < output_h); bool boundary_y1 = ((ih + 1) >= 0) && ((ih + 1) < height) && ((oh + 1) < output_h); bool boundary_y2 = ((ih + 2) >= 0) && ((ih + 2) < height) && ((oh + 2) < output_h); bool boundary_y3 = ((ih + 3) >= 0) && ((ih + 3) < height) && ((oh + 3) < output_h); float* src_addr_h0 = boundary_y0 ? (src + src_z + src_y) : zero_ptr; float* src_addr_h1 = boundary_y1 ? (src + src_z + width + src_y) : zero_ptr; float* src_addr_h2 = boundary_y2 ? (src + src_z + width * 2 + src_y) : zero_ptr; float* src_addr_h3 = boundary_y3 ? (src + src_z + width * 3 + src_y) : zero_ptr; int iw = -pad_w0 + kx * dilation_w; int i = 0; if (iw < 0) { i = -iw; iw = 0; } for (; i + 7 < output_w && iw + 7 < width; i += 8, iw += 8) { int dst_offset = dst_z + dst_y + i; const float* dst_addr = dst + dst_offset; if (boundary_y0) { float32x4_t src_v0 = vmlaq_f32(vld1q_f32(src_addr_h0 + iw), vld1q_f32(dst_addr), vld1q_dup_f32(weight_addr)); float32x4_t src_v1 = vmlaq_f32(vld1q_f32(src_addr_h0 + iw + 4), vld1q_f32(dst_addr + 4), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h0 + iw, src_v0); vst1q_f32(src_addr_h0 + iw + 4, src_v1); } if (boundary_y1) { float32x4_t src_v2 = vmlaq_f32(vld1q_f32(src_addr_h1 + iw), vld1q_f32(dst_addr + output_w), vld1q_dup_f32(weight_addr)); float32x4_t src_v3 = vmlaq_f32(vld1q_f32(src_addr_h1 + iw + 4), vld1q_f32(dst_addr + output_w + 4), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h1 + iw, src_v2); vst1q_f32(src_addr_h1 + iw + 4, src_v3); } if (boundary_y2) { float32x4_t src_v4 = vmlaq_f32(vld1q_f32(src_addr_h2 + iw), vld1q_f32(dst_addr + output_w * 2), vld1q_dup_f32(weight_addr)); float32x4_t src_v5 = vmlaq_f32(vld1q_f32(src_addr_h2 + iw + 4), vld1q_f32(dst_addr + output_w * 2 + 4), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h2 + iw, src_v4); vst1q_f32(src_addr_h2 + iw + 4, src_v5); } if (boundary_y3) { float32x4_t src_v6 = vmlaq_f32(vld1q_f32(src_addr_h3 + iw), vld1q_f32(dst_addr + output_w * 3), vld1q_dup_f32(weight_addr)); float32x4_t src_v7 = vmlaq_f32(vld1q_f32(src_addr_h3 + iw + 4), vld1q_f32(dst_addr + output_w * 3 + 4), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h3 + iw, src_v6); vst1q_f32(src_addr_h3 + iw + 4, src_v7); } } for (; i + 3 < output_w && iw + 3 < width; i += 4, iw += 4) { int dst_offset = dst_z + dst_y + i; const float* dst_addr = dst + dst_offset; if (boundary_y0) { float32x4_t src_v0 = vmlaq_f32(vld1q_f32(src_addr_h0 + iw), vld1q_f32(dst_addr), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h0 + iw, src_v0); } if (boundary_y1) { float32x4_t src_v1 = vmlaq_f32(vld1q_f32(src_addr_h1 + iw), vld1q_f32(dst_addr + output_w), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h1 + iw, src_v1); } if (boundary_y2) { float32x4_t src_v2 = vmlaq_f32(vld1q_f32(src_addr_h2 + iw), vld1q_f32(dst_addr + output_w * 2), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h2 + iw, src_v2); } if (boundary_y3) { float32x4_t src_v3 = vmlaq_f32(vld1q_f32(src_addr_h3 + iw), vld1q_f32(dst_addr + output_w * 3), vld1q_dup_f32(weight_addr)); vst1q_f32(src_addr_h3 + iw, src_v3); } } for (; i < output_w; i++, iw++) { bool boundary_x = ((iw >= 0) && (iw < width)); int src_offset = src_z + src_y + iw; int dst_offset = dst_z + dst_y + i; if (boundary_x && boundary_y0) src[src_offset] += dst[dst_offset] * weights[weight_offset]; if (boundary_x && boundary_y1) src[src_offset + width] += dst[dst_offset + output_w] * weights[weight_offset]; if (boundary_x && boundary_y2) src[src_offset + width * 2] += dst[dst_offset + output_w * 2] * weights[weight_offset]; if (boundary_x && boundary_y3) src[src_offset + width * 3] += dst[dst_offset + output_w * 3] * weights[weight_offset]; } } } } } LITE_PARALLEL_END() } template <> void conv_transpose_depthwise_s2<float>(const float* dst, const float* weights, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h0, const int pad_h1, const int pad_w0, const int pad_w1, const int dilation_h, const int dilation_w, float* src, ARMContext* ctx) { memset(src, 0, height * width * channels * sizeof(float)); const int output_h = (height + pad_h0 + pad_h1 - (dilation_h * (kernel_h - 1) + 1)) / 2 + 1; const int output_w = (width + pad_w0 + pad_w1 - (dilation_w * (kernel_w - 1) + 1)) / 2 + 1; float* zero_ptr = ctx->workspace_data<float>(); memset(zero_ptr, 0, width * sizeof(float)); const int ic_plane_size = height * width; const int oc_plane_size = output_h * output_w; const int rr_plane_size = kernel_h * kernel_w; LITE_PARALLEL_BEGIN(c, tid, channels) { int dst_z = c * oc_plane_size; int weight_z = c * rr_plane_size; int src_z = c * ic_plane_size; for (int ky = 0; ky < kernel_h; ky++) { int weight_y = ky * kernel_w; for (int kx = 0; kx < kernel_w; kx++) { int weight_offset = weight_z + weight_y + kx; const float* weight_addr = weights + weight_offset; for (int ih = -pad_h0 + ky * dilation_h, oh = 0; oh < output_h; ih += 8, oh += 4) { int src_y = ih * width; int dst_y = oh * output_w; bool boundary_y0 = ((ih >= 0) && (ih < height)) && (oh < output_h); bool boundary_y1 = ((ih + 2) >= 0) && ((ih + 2) < height) && ((oh + 1) < output_h); bool boundary_y2 = ((ih + 4) >= 0) && ((ih + 4) < height) && ((oh + 2) < output_h); bool boundary_y3 = ((ih + 6) >= 0) && ((ih + 6) < height) && ((oh + 3) < output_h); float* src_addr_h0 = boundary_y0 ? (src + src_z + src_y) : zero_ptr; float* src_addr_h1 = boundary_y1 ? (src + src_z + width * 2 + src_y) : zero_ptr; float* src_addr_h2 = boundary_y2 ? (src + src_z + width * 4 + src_y) : zero_ptr; float* src_addr_h3 = boundary_y3 ? (src + src_z + width * 6 + src_y) : zero_ptr; int iw = -pad_w0 + kx * dilation_w; int i = 0; if (iw < 0) { i = ((-iw % 2) - iw) / 2; iw = -iw % 2; } for (; i + 7 < output_w && iw + 14 < width; i += 8, iw += 16) { int dst_offset = dst_z + dst_y + i; const float* dst_addr = dst + dst_offset; if (boundary_y0) { float32x4x2_t src_vv0 = vld2q_f32(src_addr_h0 + iw); src_vv0.val[0] = vmlaq_f32(src_vv0.val[0], vld1q_f32(dst_addr), vld1q_dup_f32(weight_addr)); float32x4x2_t src_vv1 = vld2q_f32(src_addr_h0 + iw + 8); src_vv1.val[0] = vmlaq_f32(src_vv1.val[0], vld1q_f32(dst_addr + 4), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h0 + iw, src_vv0); vst2q_f32(src_addr_h0 + iw + 8, src_vv1); } if (boundary_y1) { float32x4x2_t src_vv2 = vld2q_f32(src_addr_h1 + iw); src_vv2.val[0] = vmlaq_f32(src_vv2.val[0], vld1q_f32(dst_addr + output_w), vld1q_dup_f32(weight_addr)); float32x4x2_t src_vv3 = vld2q_f32(src_addr_h1 + iw + 8); src_vv3.val[0] = vmlaq_f32(src_vv3.val[0], vld1q_f32(dst_addr + output_w + 4), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h1 + iw, src_vv2); vst2q_f32(src_addr_h1 + iw + 8, src_vv3); } if (boundary_y2) { float32x4x2_t src_vv4 = vld2q_f32(src_addr_h2 + iw); src_vv4.val[0] = vmlaq_f32(src_vv4.val[0], vld1q_f32(dst_addr + output_w * 2), vld1q_dup_f32(weight_addr)); float32x4x2_t src_vv5 = vld2q_f32(src_addr_h2 + iw + 8); src_vv5.val[0] = vmlaq_f32(src_vv5.val[0], vld1q_f32(dst_addr + output_w * 2 + 4), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h2 + iw, src_vv4); vst2q_f32(src_addr_h2 + iw + 8, src_vv5); } if (boundary_y3) { float32x4x2_t src_vv6 = vld2q_f32(src_addr_h3 + iw); src_vv6.val[0] = vmlaq_f32(src_vv6.val[0], vld1q_f32(dst_addr + output_w * 3), vld1q_dup_f32(weight_addr)); float32x4x2_t src_vv7 = vld2q_f32(src_addr_h3 + iw + 8); src_vv7.val[0] = vmlaq_f32(src_vv7.val[0], vld1q_f32(dst_addr + output_w * 3 + 4), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h3 + iw, src_vv6); vst2q_f32(src_addr_h3 + iw + 8, src_vv7); } } for (; i + 3 < output_w && iw + 6 < width; i += 4, iw += 8) { int dst_offset = dst_z + dst_y + i; const float* dst_addr = dst + dst_offset; if (boundary_y0) { float32x4x2_t src_vv0 = vld2q_f32(src_addr_h0 + iw); src_vv0.val[0] = vmlaq_f32(src_vv0.val[0], vld1q_f32(dst_addr), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h0 + iw, src_vv0); } if (boundary_y1) { float32x4x2_t src_vv1 = vld2q_f32(src_addr_h1 + iw); src_vv1.val[0] = vmlaq_f32(src_vv1.val[0], vld1q_f32(dst_addr + output_w), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h1 + iw, src_vv1); } if (boundary_y2) { float32x4x2_t src_vv2 = vld2q_f32(src_addr_h2 + iw); src_vv2.val[0] = vmlaq_f32(src_vv2.val[0], vld1q_f32(dst_addr + output_w * 2), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h2 + iw, src_vv2); } if (boundary_y3) { float32x4x2_t src_vv3 = vld2q_f32(src_addr_h3 + iw); src_vv3.val[0] = vmlaq_f32(src_vv3.val[0], vld1q_f32(dst_addr + output_w * 3), vld1q_dup_f32(weight_addr)); vst2q_f32(src_addr_h3 + iw, src_vv3); } } for (; i < output_w; i++, iw += 2) { bool boundary_x = ((iw >= 0) && (iw < width)); int src_offset = src_z + src_y + iw; int dst_offset = dst_z + dst_y + i; if (boundary_x && boundary_y0) src[src_offset] += dst[dst_offset] * weights[weight_offset]; if (boundary_x && boundary_y1) src[src_offset + width * 2] += dst[dst_offset + output_w] * weights[weight_offset]; if (boundary_x && boundary_y2) src[src_offset + width * 4] += dst[dst_offset + output_w * 2] * weights[weight_offset]; if (boundary_x && boundary_y3) src[src_offset + width * 6] += dst[dst_offset + output_w * 3] * weights[weight_offset]; } } } } } LITE_PARALLEL_END() } } // namespace math } // namespace arm } // namespace lite } // namespace paddle
10,916
2,727
<reponame>jiangkang/ndk-samples /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <memory> #include "ImageViewEngine.h" /* * Create Rendering Context */ bool ImageViewEngine::InitializeDisplay(void) { EnableWelcomeUI(); bool status = CreateWideColorCtx(); ASSERT(status, "CreateWideColorContext() failed"); status = program_.createProgram(); ASSERT(status, "CreateShaderProgram Failed"); status = CreateTextures(); ASSERT(status, "LoadTextures() Failed") // Other GL States glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, renderTargetWidth_, renderTargetHeight_); EnableRenderUI(); return true; } bool ImageViewEngine::GetAnimationStatus(void) { return animating_; } void ImageViewEngine::EnableAnimation(bool enable) { animating_ = enable; } /* * Draw quad(s) to view texture */ void ImageViewEngine::DrawFrame(void) { if (display_ == NULL) { return; } const GLfloat leftQuadVertices[] = { -1.f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f }; const GLfloat rightQuadVertices[] = { 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }; // Just fill the screen with a color. glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(program_.getProgram()); glVertexAttribPointer(program_.getAttribLocation(), 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, leftQuadVertices); glEnableVertexAttribArray(program_.getAttribLocation()); glVertexAttribPointer(program_.getAttribLocationTex(), 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, leftQuadVertices + 2); glEnableVertexAttribArray(program_.getAttribLocationTex()); int32_t texIdx = textureIdx_; if(renderModeBits_ & RENDERING_P3) { glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, textures_[texIdx]->P3TexId()); glUniform1i(program_.getSamplerLoc(), 0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } if (renderModeBits_ & RENDERING_SRGB) { glVertexAttribPointer(program_.getAttribLocation(), 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, rightQuadVertices); glVertexAttribPointer(program_.getAttribLocationTex(), 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, rightQuadVertices + 2); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, textures_[texIdx]->SRGBATexId()); glUniform1i(program_.getSamplerLoc(), 1); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } eglSwapBuffers(display_, surface_); } /** * Tear down the EGL context currently associated with the display. */ void ImageViewEngine::TerminateDisplay(void) { animating_ = 0; if(display_ == EGL_NO_DISPLAY) return; DestroyWideColorCtx(); glDeleteProgram(program_.getProgram()); DeleteTextures(); } /* * Initialize the application engine */ ImageViewEngine::ImageViewEngine(struct android_app* app) : app_(app), animating_(0), textureIdx_(0) { textures_.resize(0); renderModeBits_ = RENDERING_P3 | RENDERING_SRGB; eglContext_ = EGL_NO_CONTEXT; surface_ = EGL_NO_SURFACE; display_ = EGL_NO_DISPLAY; }
1,629
3,710
#include "locatorpopup.h" // TnzLib includes #include "toonz/txshlevelhandle.h" #include "toonz/tframehandle.h" #include "toonz/preferences.h" #include "toonz/stage2.h" // Tnz6 includes #include "tapp.h" #include "sceneviewer.h" #include <QVBoxLayout> LocatorPopup::LocatorPopup(QWidget *parent) : QDialog(parent), m_initialZoom(true) { m_viewer = new SceneViewer(NULL); m_viewer->setParent(parent); m_viewer->setIsLocator(); //---- layout QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setMargin(0); mainLayout->addWidget(m_viewer, 1); setLayout(mainLayout); bool ret = true; // When zoom changed, change window title. ret = connect(m_viewer, SIGNAL(onZoomChanged()), SLOT(changeWindowTitle())); ret = ret && connect(m_viewer, SIGNAL(previewToggled()), SLOT(changeWindowTitle())); assert(ret); resize(400, 400); } //----------------------------------------------------------------------------- void LocatorPopup::onChangeViewAff(const TPointD &pos) { TAffine curAff = m_viewer->getSceneMatrix(); TAffine newAff(curAff.a11, 0, -pos.x * curAff.a11, 0, curAff.a22, -pos.y * curAff.a22); m_viewer->setViewMatrix(newAff, 0); m_viewer->setViewMatrix(newAff, 1); m_viewer->update(); } //----------------------------------------------------------------------------- void LocatorPopup::showEvent(QShowEvent *) { // zoom the locator for the first time if (m_initialZoom) { for (int z = 0; z < 4; z++) m_viewer->zoomQt(true, false); m_initialZoom = false; } TApp *app = TApp::instance(); TFrameHandle *frameHandle = app->getCurrentFrame(); TXshLevelHandle *levelHandle = app->getCurrentLevel(); bool ret = true; ret = ret && connect(frameHandle, SIGNAL(frameSwitched()), this, SLOT(changeWindowTitle())); ret = ret && connect(levelHandle, SIGNAL(xshLevelSwitched(TXshLevel *)), this, SLOT(changeWindowTitle())); assert(ret); changeWindowTitle(); } //----------------------------------------------------------------------------- void LocatorPopup::hideEvent(QHideEvent *) { TApp *app = TApp::instance(); disconnect(app->getCurrentLevel()); disconnect(app->getCurrentFrame()); } //----------------------------------------------------------------------------- void LocatorPopup::changeWindowTitle() { TApp *app = TApp::instance(); // put the titlebar texts in this string QString name = tr("Locator"); bool showZoomFactor = false; // if the frame type is "scene editing" if (app->getCurrentFrame()->isEditingScene()) { if (m_viewer->isPreviewEnabled()) showZoomFactor = true; // If the current level exists and some option is set in the preference, // set the zoom value to the current level's dpi else if (Preferences::instance() ->isActualPixelViewOnSceneEditingModeEnabled() && app->getCurrentLevel()->getSimpleLevel() && !CleanupPreviewCheck::instance() ->isEnabled() // cleanup preview must be OFF && !CameraTestCheck::instance() ->isEnabled()) // camera test mode must be OFF neither showZoomFactor = true; } // if the frame type is "level editing" else { TXshLevel *level = app->getCurrentLevel()->getLevel(); if (level) showZoomFactor = true; } if (showZoomFactor) { name = name + " Zoom : " + QString::number((int)(100.0 * sqrt(m_viewer->getViewMatrix().det()) * m_viewer->getDpiFactor())) + "%"; } setWindowTitle(name); }
1,374
804
<gh_stars>100-1000 package com.github.liuweijw.business.wechat.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.github.liuweijw.business.commons.utils.RequestUtil; import com.github.liuweijw.business.wechat.beans.UrlInfoBean; import com.github.liuweijw.business.wechat.beans.WechatNotifyBean; import com.github.liuweijw.business.wechat.config.WechatMpProperties; import com.github.liuweijw.business.wechat.service.UrlInfoService; import com.github.liuweijw.commons.base.R; import com.github.liuweijw.commons.utils.RandomHelper; import com.github.liuweijw.commons.utils.StringHelper; import com.github.liuweijw.commons.utils.WebUtils; import com.github.liuweijw.core.commons.constants.MqQueueConstant; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; /** * 微信公众号授权管理 * * @author liuweijw */ @Slf4j @Controller @RequestMapping("/wechat/auth") public class WxAuthorizeController { @Autowired private WxMpService wxService; @Autowired private UrlInfoService urlInfoService; @Autowired private RabbitTemplate rabbitTemplate; @Autowired private WechatMpProperties properties; // @Autowired // private TaskExecutor taskExecutor; private static final String OPENID = "openId"; // https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 @RequestMapping(value = "/authorize", method = RequestMethod.GET) public String authorize(HttpServletRequest request, @RequestParam("_backUrl") String _backUrl, Integer from, @RequestParam("wechatId") String wechatId, Long t) { long start = System.currentTimeMillis(); log.info("【wxauth.authorize】_backUrl:" + _backUrl); from = null == from || from < 0 ? 0 : from; t = null == t || t < 0 ? 0 : t; String returnUrl = properties.getAuthUrl() + "/wechat/auth/openId?wechatId=" + wechatId + "&from=" + from + "&t=" + t; // from == 1 已经关注(静默登录) from == 0 通过网页(用户授权) String state = WebUtils.buildURLEncoder(_backUrl); log.info("【wxauth.authorize】state:" + state); if (state.length() > 112) { // 微信端最长允许128-16(#wechat_redirect),长度超过改为项目段链接标识替换 state = RandomHelper.randomStringUpper(); UrlInfoBean urlInfoBean = new UrlInfoBean(state, _backUrl); urlInfoService.cacheUrlInfo(urlInfoBean); } String redirectURL = wxService.oauth2buildAuthorizationUrl( returnUrl, from.intValue() == 1 ? WxConsts.OAuth2Scope.SNSAPI_BASE : WxConsts.OAuth2Scope.SNSAPI_USERINFO, state); // 微信默认会发送两次回调请求问题处理 -设置之后还是一样问题暂未解决,目前调用服务端采用其它方式规避此问题 // https://blog.csdn.net/jiangguilong2000/article/details/79416615 // https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=https&response_type=code&scope=snsapi_base&state=xxx#wechat_redirect // if (!redirectURL.contains("connect_redirect=")) { // redirectURL = redirectURL.replace("#wechat_redirect", // "&connect_redirect=1#wechat_redirect"); // } log.info("【wxauth.authorize】redirect:" + redirectURL); long end = System.currentTimeMillis(); log.info("【wxauth.authorize】耗时:" + (end - start)); log.info("【wxauth.authorize】请求从第三方应用到跳转授权开始[" + t + "],耗时:" + (end - t)); return "redirect:" + redirectURL; } // 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE @RequestMapping(value = "/openId", method = RequestMethod.GET) public String openId(HttpServletRequest request, @RequestParam("code") String code, @RequestParam("state") String state, @RequestParam("from") Integer from, @RequestParam("wechatId") String wechatId, @RequestParam("t") Long t) { long start = System.currentTimeMillis(); String openId = ""; try { boolean isSopeBase = from.intValue() == 1; WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code); openId = wxMpOAuth2AccessToken.getOpenId(); log.info("【wxauth.openId】:state|" + state); // 采用异步方式拉取用户信息 // taskExecutor.execute(() -> {}) long mqStart = System.currentTimeMillis(); log.info("【wxauth.openId】发送MQ:" + mqStart); WechatNotifyBean wechatNotifyBean = new WechatNotifyBean(); wechatNotifyBean.setSopeBase(isSopeBase); wechatNotifyBean.setWechatId(wechatId); wechatNotifyBean.setWxMpOAuth2AccessToken(wxMpOAuth2AccessToken); rabbitTemplate.convertAndSend(MqQueueConstant.WECHAT_QUEUE, wechatNotifyBean); log.info("【wxauth.openId】发送MQ耗时:" + (System.currentTimeMillis() - mqStart)); log.info("【wxauth.openId】:openId|" + openId); } catch (WxErrorException ex) { ex.printStackTrace(); log.info("【wxauth.openId】exception:" + ex.getError().getErrorMsg()); } String returnUrl = ""; if (state.length() == 32 && !state.startsWith("http")) { // key UrlInfoBean urlInfoBean = urlInfoService.findFromCacheByUuid(state); returnUrl = urlInfoBean.getUrl(); } else { returnUrl = state; } String redirectUrl = RequestUtil.buildAppendURLParams(RequestUtil.buildURLParams(returnUrl, OPENID), OPENID + "=" + openId, "t=" + t); log.info("【wxauth.openId】:redirect|" + redirectUrl); long end = System.currentTimeMillis(); log.info("【wxauth.openId】耗时:" + (end - start)); log.info("【wxauth.authorize】请求从第三方应用到跳转授权开始[" + t + "],耗时:" + (end - t)); return "redirect:" + redirectUrl; } @RequestMapping(value = "/refreshToken", method = RequestMethod.GET) public R<WxMpOAuth2AccessToken> refreshToken(HttpServletRequest request, @RequestParam("refreshToken") String refreshToken) { if (StringHelper.isBlank(refreshToken)) return new R<WxMpOAuth2AccessToken>().failure("请求参数[refreshToken]不存在!"); log.info("【wxauth】:refreshToken|" + refreshToken); WxMpOAuth2AccessToken wxMpOAuth2AccessToken; try { wxMpOAuth2AccessToken = wxService.oauth2refreshAccessToken(refreshToken); return new R<WxMpOAuth2AccessToken>().data(wxMpOAuth2AccessToken).success(); } catch (WxErrorException e) { e.printStackTrace(); } return new R<WxMpOAuth2AccessToken>().failure("微信refreshToken刷新失败!"); } }
2,795
486
<filename>third_party/edu/tum/cup2/parser/actions/Accept.java package edu.tum.cup2.parser.actions; import edu.tum.cup2.semantics.Action; import java.io.Serializable; /** * LR parser action for "accept". * * @author <NAME> */ public class Accept implements LRAction, Serializable { private static final long serialVersionUID = 1L; public Action getAction() { return null; } @Override public boolean equals(Object obj) { if (obj instanceof Accept) { return true; } return false; } @Override public String toString() { return "acc"; } }
220
669
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. Module Name: qlgavgpool.cpp Abstract: This module implements routines for quantized linear global average pool. --*/ #include "mlasi.h" size_t MLASCALL MlasQLinearSafePaddingElementCount( size_t ElementSize, size_t ElementCount ) { if (!(ElementSize == 1 || ElementSize == 2 || ElementSize == 4 || ElementSize == 8 || ElementSize == 16)) { #ifdef MLAS_NO_EXCEPTION abort(); #else throw std::invalid_argument("ElementSize must be power of 2 and less or equal than 16!"); #endif } return ElementCount + (size_t{256} / ElementSize - 1); } MLAS_FORCEINLINE float CheckQLinearGlobalAveragePoolScaleAndSize( float ScaleInput, float ScaleOutput, size_t ImageSize ) { if (ImageSize >= 0x1000000) { #ifdef MLAS_NO_EXCEPTION abort(); #else throw std::invalid_argument("QLinearGlobalAveragePool ImageSize too large!"); #endif } float scale = ScaleInput / (ScaleOutput * static_cast<float>(ImageSize)); if (scale < 0x1.0p-32f || scale >= 256.0f) { // In first case, the scale is too small, ScaleInput/ScaleOutput < 1/256 no matter what ImageSize // In second case, the scale is too large, ScaleInput/ScaleOutput >= 256 no matter what Image Size // both case make output value constant, and hence not meaningful. #ifdef MLAS_NO_EXCEPTION abort(); #else throw std::invalid_argument("QLinearGlobalAveragePool parameter out of computation range!"); #endif } return scale; } #if defined(MLAS_NEON_INTRINSICS) template <typename T8Bits> void MLASCALL MlasQLinearGlobalAveragePoolNchw( const T8Bits* Input, float ScaleInput, int32_t ZeroPointInput, T8Bits* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Channels, size_t ImageSize, int32_t* AccumulateBuffer ) { float scale = CheckQLinearGlobalAveragePoolScaleAndSize(ScaleInput, ScaleOutput, ImageSize); int32_t bias[] = {-ZeroPointInput * static_cast<int32_t>(ImageSize), 0, 0, 0}; const int32x4_t vbias = vld1q_s32(bias); const int32x4_t vzero = vmovq_n_s32(0); const uint8_t* InputU8 = (const uint8_t*)(Input); int32_t* sum_buffer = AccumulateBuffer; uint8_t tail_buffer[8] = {0, 0, 0, 0, 0, 0, 0, 0}; for (size_t c = Channels; c > 0; c--) { int32x4_t vacc_lo = vbias; int32x4_t vacc_hi = vzero; auto Len = ImageSize; for (; Len >= 32; Len -= 32) { const uint8x8_t vi0 = vld1_u8(InputU8); const uint8x8_t vi1 = vld1_u8(InputU8 + 8); const uint8x8_t vi2 = vld1_u8(InputU8 + 16); const uint8x8_t vi3 = vld1_u8(InputU8 + 24); int16x8_t vsum; if constexpr (std::is_signed<T8Bits>::value) { const int16x8_t vs01 = vaddl_s8(vreinterpret_s8_u8(vi0), vreinterpret_s8_u8(vi1)); const int16x8_t vs23 = vaddl_s8(vreinterpret_s8_u8(vi2), vreinterpret_s8_u8(vi3)); vsum = vaddq_s16(vs01, vs23); } else { const uint16x8_t vs01 = vaddl_u8(vi0, vi1); const uint16x8_t vs23 = vaddl_u8(vi2, vi3); vsum = vreinterpretq_s16_u16(vaddq_u16(vs01, vs23)); } vacc_lo = vaddw_s16(vacc_lo, vget_low_s16(vsum)); vacc_hi = vaddw_s16(vacc_hi, vget_high_s16(vsum)); InputU8 += 32; } for (; Len >= 8; Len -= 8) { int16x8_t vsum; if constexpr (std::is_signed<T8Bits>::value) { vsum = vmovl_s8(vreinterpret_s8_u8(vld1_u8(InputU8))); } else { vsum = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(InputU8))); } vacc_lo = vaddw_s16(vacc_lo, vget_low_s16(vsum)); vacc_hi = vaddw_s16(vacc_hi, vget_high_s16(vsum)); InputU8 += 8; } if (Len > 0) { memcpy(tail_buffer, InputU8, Len); int16x8_t vsum; if constexpr (std::is_signed<T8Bits>::value) { vsum = vmovl_s8(vreinterpret_s8_u8(vld1_u8(tail_buffer))); } else { vsum = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(tail_buffer))); } vacc_lo = vaddw_s16(vacc_lo, vget_low_s16(vsum)); vacc_hi = vaddw_s16(vacc_hi, vget_high_s16(vsum)); InputU8 += Len; } vacc_lo = vaddq_s32(vacc_lo, vacc_hi); int32x2_t vacc = vadd_s32(vget_high_s32(vacc_lo), vget_low_s32(vacc_lo)); *sum_buffer++ = vget_lane_s32(vpadd_s32(vacc, vacc), 0); } MlasRequantizeOutput(AccumulateBuffer, Channels, Output, Channels, nullptr, &scale, false, static_cast<T8Bits>(ZeroPointOutput), 0, 0, 1, Channels); } template <typename T8Bits> MLAS_FORCEINLINE void MlasQLinearGlobalAveragePoolNhwcSingleBatch( const T8Bits* Input, T8Bits* Output, const T8Bits* LastOf8, size_t ImageSize, size_t Channels, size_t Stride, int32_t Bias, float Scale, T8Bits Output_zero_point, int32_t* AccumulateBuffer, const T8Bits* ZeroBuffer ) { #define LOAD_FULL_CHANNELS() \ const uint8x8_t vi0 = vld1_u8(i0); \ i0 += 8; \ const uint8x8_t vi1 = vld1_u8(i1); \ i1 += 8; \ const uint8x8_t vi2 = vld1_u8(i2); \ i2 += 8; \ const uint8x8_t vi3 = vld1_u8(i3); \ i3 += 8; \ const uint8x8_t vi4 = vld1_u8(i4); \ i4 += 8; \ const uint8x8_t vi5 = vld1_u8(i5); \ i5 += 8; \ const uint8x8_t vi6 = vld1_u8(i6); \ i6 += 8 #define CALCULATE_ACCUMULATE_VECTORS() \ int32x4_t vacc_lo = finish_one_pass ? vld1q_s32(acc) : vbias; \ int32x4_t vacc_hi = finish_one_pass ? vld1q_s32(acc + 4) : vbias; \ int16x8_t vsum; \ if constexpr (std::is_signed<T8Bits>::value) { \ const int16x8_t vsum01 = vaddl_s8(vreinterpret_s8_u8(vi0), vreinterpret_s8_u8(vi1)); \ const int16x8_t vsum23 = vaddl_s8(vreinterpret_s8_u8(vi2), vreinterpret_s8_u8(vi3)); \ const int16x8_t vsum45 = vaddl_s8(vreinterpret_s8_u8(vi4), vreinterpret_s8_u8(vi5)); \ const int16x8_t vsum016 = vaddw_s8(vsum01, vreinterpret_s8_u8(vi6)); \ const int16x8_t vsum2345 = vaddq_s16(vsum23, vsum45); \ vsum = vaddq_s16(vsum016, vsum2345); \ } else { \ const uint16x8_t vsum01 = vaddl_u8(vi0, vi1); \ const uint16x8_t vsum23 = vaddl_u8(vi2, vi3); \ const uint16x8_t vsum45 = vaddl_u8(vi4, vi5); \ const uint16x8_t vsum016 = vaddw_u8(vsum01, vi6); \ const uint16x8_t vsum2345 = vaddq_u16(vsum23, vsum45); \ vsum = vreinterpretq_s16_u16(vaddq_u16(vsum016, vsum2345)); \ } \ vacc_lo = vaddw_s16(vacc_lo, vget_low_s16(vsum)); \ vacc_hi = vaddw_s16(vacc_hi, vget_high_s16(vsum)) uint8_t tail[8] = {0, 0, 0, 0, 0, 0, 0, 0}; const int32x4_t vbias = vld1q_dup_s32(&Bias); bool finish_one_pass = false; const size_t step_next_group = 7 * Stride - (Channels & ~size_t{7}); const uint8_t* LastOf8U8 = (const uint8_t*)LastOf8; const uint8_t* i0 = (const uint8_t*)Input; const uint8_t* i1 = i0 + Stride; const uint8_t* i4 = i0 + Stride * 4; const uint8_t* i2 = i1 + Stride; const uint8_t* i5 = i4 + Stride; const uint8_t* i3 = i2 + Stride; const uint8_t* i6 = i5 + Stride; for (; ImageSize > 7; ImageSize -= 7) { int32_t* acc = AccumulateBuffer; size_t c = Channels; for (; c >= 8; c -= 8) { LOAD_FULL_CHANNELS(); CALCULATE_ACCUMULATE_VECTORS(); vst1q_s32(acc, vacc_lo); vst1q_s32(acc + 4, vacc_hi); acc += 8; } if (c > 0) { const uint8x8_t vi0 = vld1_u8(((i0 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i0, c) : i0)); const uint8x8_t vi1 = vld1_u8(((i1 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i1, c) : i1)); const uint8x8_t vi2 = vld1_u8(((i2 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i2, c) : i2)); const uint8x8_t vi3 = vld1_u8(((i3 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i3, c) : i3)); const uint8x8_t vi4 = vld1_u8(((i4 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i4, c) : i4)); const uint8x8_t vi5 = vld1_u8(((i5 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i5, c) : i5)); const uint8x8_t vi6 = vld1_u8(((i6 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i6, c) : i6)); CALCULATE_ACCUMULATE_VECTORS(); vst1q_s32(acc, vacc_lo); vst1q_s32(acc + 4, vacc_hi); } finish_one_pass = true; i0 += step_next_group; i1 += step_next_group; i2 += step_next_group; i3 += step_next_group; i4 += step_next_group; i5 += step_next_group; i6 += step_next_group; } if (ImageSize > 0) { switch (ImageSize) { case 1: i1 = (const uint8_t*)ZeroBuffer; /* fall through */ case 2: i2 = (const uint8_t*)ZeroBuffer; /* fall through */ case 3: i3 = (const uint8_t*)ZeroBuffer; /* fall through */ case 4: i4 = (const uint8_t*)ZeroBuffer; /* fall through */ case 5: i5 = (const uint8_t*)ZeroBuffer; /* fall through */ case 6: i6 = (const uint8_t*)ZeroBuffer; /* fall through */ default: break; } int32_t* acc = AccumulateBuffer; size_t c = Channels; for (; c >= 8; c -= 8) { LOAD_FULL_CHANNELS(); CALCULATE_ACCUMULATE_VECTORS(); vst1q_s32(acc, vacc_lo); vst1q_s32(acc + 4, vacc_hi); acc += 8; } if (c > 0) { const uint8x8_t vi0 = vld1_u8(((i0 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i0, c) : i0)); const uint8x8_t vi1 = vld1_u8( ((1 < ImageSize && i1 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i1, c) : i1)); const uint8x8_t vi2 = vld1_u8( ((2 < ImageSize && i2 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i2, c) : i2)); const uint8x8_t vi3 = vld1_u8( ((3 < ImageSize && i3 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i3, c) : i3)); const uint8x8_t vi4 = vld1_u8( ((4 < ImageSize && i4 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i4, c) : i4)); const uint8x8_t vi5 = vld1_u8( ((5 < ImageSize && i5 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i5, c) : i5)); const uint8x8_t vi6 = vld1_u8( ((6 < ImageSize && i6 >= LastOf8U8) ? (const uint8_t*)memcpy(tail, i6, c) : i6)); CALCULATE_ACCUMULATE_VECTORS(); vst1q_s32(acc, vacc_lo); vst1q_s32(acc + 4, vacc_hi); } } MlasRequantizeOutput(AccumulateBuffer, Channels, Output, Channels, nullptr, &Scale, false, Output_zero_point, 0, 0, 1, Channels); } #elif defined(MLAS_SSE2_INTRINSICS) template <typename T8Bits> void MLASCALL MlasQLinearGlobalAveragePoolNchw( const T8Bits* Input, float ScaleInput, int32_t ZeroPointInput, T8Bits* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Channels, size_t ImageSize, int32_t* AccumulateBuffer ) { float scale = CheckQLinearGlobalAveragePoolScaleAndSize(ScaleInput, ScaleOutput, ImageSize); const int32_t bias[] = {-ZeroPointInput * static_cast<int32_t>(ImageSize), 0, 0, 0}; const auto vbias = _mm_loadu_si128((const __m128i*)&bias); const auto vzero = _mm_setzero_si128(); uint8_t buffer[8] = {0, 0, 0, 0, 0, 0, 0, 0}; int32_t* sum_buffer = AccumulateBuffer; for (size_t c = Channels; c > 0; c--) { __m128i vacc_lo = vbias; __m128i vacc_hi = vzero; auto Len = ImageSize; for (; Len >= 32; Len -= 32) { const __m128i vi0 = _mm_loadl_epi64((const __m128i*)Input); const __m128i vi1 = _mm_loadl_epi64((const __m128i*)(Input + 8)); const __m128i vi2 = _mm_loadl_epi64((const __m128i*)(Input + 16)); const __m128i vi3 = _mm_loadl_epi64((const __m128i*)(Input + 24)); if constexpr (std::is_signed<T8Bits>::value) { const __m128i vxi0 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi0), 8); const __m128i vxi1 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi1), 8); const __m128i vxi2 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi2), 8); const __m128i vxi3 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi3), 8); const __m128i vsum = _mm_add_epi16(_mm_add_epi16(vxi0, vxi1), _mm_add_epi16(vxi2, vxi3)); vacc_lo = _mm_add_epi32(vacc_lo, _mm_srai_epi32(_mm_unpacklo_epi16(vzero, vsum), 16)); vacc_hi = _mm_add_epi32(vacc_hi, _mm_srai_epi32(_mm_unpackhi_epi16(vzero, vsum), 16)); } else { const __m128i vxi0 = _mm_unpacklo_epi8(vi0, vzero); const __m128i vxi1 = _mm_unpacklo_epi8(vi1, vzero); const __m128i vxi2 = _mm_unpacklo_epi8(vi2, vzero); const __m128i vxi3 = _mm_unpacklo_epi8(vi3, vzero); const __m128i vsum = _mm_add_epi16(_mm_add_epi16(vxi0, vxi1), _mm_add_epi16(vxi2, vxi3)); vacc_lo = _mm_add_epi32(vacc_lo, _mm_unpacklo_epi16(vsum, vzero)); vacc_hi = _mm_add_epi32(vacc_hi, _mm_unpackhi_epi16(vsum, vzero)); } Input += 32; } for (; Len >= 8; Len -= 8) { if constexpr (std::is_signed<T8Bits>::value) { const __m128i vsum = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, _mm_loadl_epi64((const __m128i*)Input)), 8); vacc_lo = _mm_add_epi32(vacc_lo, _mm_srai_epi32(_mm_unpacklo_epi16(vzero, vsum), 16)); vacc_hi = _mm_add_epi32(vacc_hi, _mm_srai_epi32(_mm_unpackhi_epi16(vzero, vsum), 16)); } else { const __m128i vsum = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*)Input), vzero); vacc_lo = _mm_add_epi32(vacc_lo, _mm_unpacklo_epi16(vsum, vzero)); vacc_hi = _mm_add_epi32(vacc_hi, _mm_unpackhi_epi16(vsum, vzero)); } Input += 8; } if (Len > 0) { memcpy(buffer, Input, Len); if constexpr (std::is_signed<T8Bits>::value) { const __m128i vsum = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, _mm_loadl_epi64((const __m128i*)buffer)), 8); vacc_lo = _mm_add_epi32(vacc_lo, _mm_srai_epi32(_mm_unpacklo_epi16(vzero, vsum), 16)); vacc_hi = _mm_add_epi32(vacc_hi, _mm_srai_epi32(_mm_unpackhi_epi16(vzero, vsum), 16)); } else { const __m128i vsum = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*)buffer), vzero); vacc_lo = _mm_add_epi32(vacc_lo, _mm_unpacklo_epi16(vsum, vzero)); vacc_hi = _mm_add_epi32(vacc_hi, _mm_unpackhi_epi16(vsum, vzero)); } Input += Len; } __m128i vacc = _mm_add_epi32(vacc_lo, vacc_hi); // [ D C | B A ] __m128i vshuf = _mm_shuffle_epi32(vacc, _MM_SHUFFLE(2, 3, 0, 1)); // [ C D | A B ] __m128i vsums = _mm_add_epi32(vacc, vshuf); // [ D+C C+D | B+A A+B ] vshuf = _mm_shuffle_epi32(vsums, _MM_SHUFFLE(1, 0, 3, 2)); // [ B+A A+B | D+C C+D ] vsums = _mm_add_epi32(vsums, vshuf); *sum_buffer++ = _mm_cvtsi128_si32(vsums); } MlasRequantizeOutput(AccumulateBuffer, Channels, Output, Channels, nullptr, &scale, false, static_cast<T8Bits>(ZeroPointOutput), 0, 0, 1, Channels); } template <typename T8Bits> MLAS_FORCEINLINE void MlasQLinearGlobalAveragePoolNhwcSingleBatch( const T8Bits* Input, T8Bits* Output, const T8Bits* LastOf8, size_t ImageSize, size_t Channels, size_t Stride, int32_t Bias, float Scale, T8Bits Output_zero_point, int32_t* AccumulateBuffer, const T8Bits* ZeroBuffer ) { #if defined(MLAS_TARGET_IX86) constexpr size_t PixelsPerIteration = 4; #define LOAD_FULL_CHANNELS() \ const __m128i vi0 = _mm_loadl_epi64((const __m128i*)i0); \ i0 += 8; \ const __m128i vi1 = _mm_loadl_epi64((const __m128i*)i1); \ i1 += 8; \ const __m128i vi2 = _mm_loadl_epi64((const __m128i*)i2); \ i2 += 8; \ const __m128i vi3 = _mm_loadl_epi64((const __m128i*)i3); \ i3 += 8; #define CALCULATE_ACCUMULATE_VECTORS() \ __m128i vacc_lo = finish_one_pass ? _mm_loadu_si128((__m128i*)acc) : vbias; \ __m128i vacc_hi = finish_one_pass ? _mm_loadu_si128(((__m128i*)acc) + 1) : vbias; \ __m128i vxi0; \ __m128i vxi1; \ __m128i vxi2; \ __m128i vxi3; \ if constexpr (std::is_signed<T8Bits>::value) { \ vxi0 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi0), 8); \ vxi1 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi1), 8); \ vxi2 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi2), 8); \ vxi3 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi3), 8); \ } else { \ vxi0 = _mm_unpacklo_epi8(vi0, vzero); \ vxi1 = _mm_unpacklo_epi8(vi1, vzero); \ vxi2 = _mm_unpacklo_epi8(vi2, vzero); \ vxi3 = _mm_unpacklo_epi8(vi3, vzero); \ } \ __m128i vsum01 = _mm_add_epi16(vxi0, vxi1); \ __m128i vsum23 = _mm_add_epi16(vxi2, vxi3); \ __m128i vsum = _mm_add_epi16(vsum01, vsum23); \ \ if constexpr (std::is_signed<T8Bits>::value) { \ vacc_lo = _mm_add_epi32(vacc_lo, _mm_srai_epi32(_mm_unpacklo_epi16(vzero, vsum), 16)); \ vacc_hi = _mm_add_epi32(vacc_hi, _mm_srai_epi32(_mm_unpackhi_epi16(vzero, vsum), 16)); \ } else { \ vacc_lo = _mm_add_epi32(vacc_lo, _mm_unpacklo_epi16(vsum, vzero)); \ vacc_hi = _mm_add_epi32(vacc_hi, _mm_unpackhi_epi16(vsum, vzero)); \ } #else constexpr size_t PixelsPerIteration = 7; #define LOAD_FULL_CHANNELS() \ const __m128i vi0 = _mm_loadl_epi64((const __m128i*)i0); \ i0 += 8; \ const __m128i vi1 = _mm_loadl_epi64((const __m128i*)i1); \ i1 += 8; \ const __m128i vi2 = _mm_loadl_epi64((const __m128i*)i2); \ i2 += 8; \ const __m128i vi3 = _mm_loadl_epi64((const __m128i*)i3); \ i3 += 8; \ const __m128i vi4 = _mm_loadl_epi64((const __m128i*)i4); \ i4 += 8; \ const __m128i vi5 = _mm_loadl_epi64((const __m128i*)i5); \ i5 += 8; \ const __m128i vi6 = _mm_loadl_epi64((const __m128i*)i6); \ i6 += 8 #define CALCULATE_ACCUMULATE_VECTORS() \ __m128i vacc_lo = finish_one_pass ? _mm_loadu_si128((__m128i*)acc) : vbias; \ __m128i vacc_hi = finish_one_pass ? _mm_loadu_si128(((__m128i*)acc) + 1) : vbias; \ __m128i vxi0; \ __m128i vxi1; \ __m128i vxi2; \ __m128i vxi3; \ __m128i vxi4; \ __m128i vxi5; \ __m128i vxi6; \ if constexpr (std::is_signed<T8Bits>::value) { \ vxi0 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi0), 8); \ vxi1 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi1), 8); \ vxi2 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi2), 8); \ vxi3 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi3), 8); \ vxi4 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi4), 8); \ vxi5 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi5), 8); \ vxi6 = _mm_srai_epi16(_mm_unpacklo_epi8(vzero, vi6), 8); \ } else { \ vxi0 = _mm_unpacklo_epi8(vi0, vzero); \ vxi1 = _mm_unpacklo_epi8(vi1, vzero); \ vxi2 = _mm_unpacklo_epi8(vi2, vzero); \ vxi3 = _mm_unpacklo_epi8(vi3, vzero); \ vxi4 = _mm_unpacklo_epi8(vi4, vzero); \ vxi5 = _mm_unpacklo_epi8(vi5, vzero); \ vxi6 = _mm_unpacklo_epi8(vi6, vzero); \ } \ const __m128i vsum01 = _mm_add_epi16(vxi0, vxi1); \ const __m128i vsum23 = _mm_add_epi16(vxi2, vxi3); \ const __m128i vsum45 = _mm_add_epi16(vxi4, vxi5); \ const __m128i vsum016 = _mm_add_epi16(vsum01, vxi6); \ const __m128i vsum2345 = _mm_add_epi16(vsum23, vsum45); \ const __m128i vsum = _mm_add_epi16(vsum016, vsum2345); \ if constexpr (std::is_signed<T8Bits>::value) { \ vacc_lo = _mm_add_epi32(vacc_lo, _mm_srai_epi32(_mm_unpacklo_epi16(vzero, vsum), 16)); \ vacc_hi = _mm_add_epi32(vacc_hi, _mm_srai_epi32(_mm_unpackhi_epi16(vzero, vsum), 16)); \ } else { \ vacc_lo = _mm_add_epi32(vacc_lo, _mm_unpacklo_epi16(vsum, vzero)); \ vacc_hi = _mm_add_epi32(vacc_hi, _mm_unpackhi_epi16(vsum, vzero)); \ } #endif T8Bits tail[8] = {0, 0, 0, 0, 0, 0, 0, 0}; bool finish_one_pass = false; const __m128i vbias = _mm_set1_epi32(Bias); const __m128i vzero = _mm_setzero_si128(); size_t step_next_group = PixelsPerIteration * Stride - (Channels & ~size_t{7}); const T8Bits* i0 = Input; const T8Bits* i1 = i0 + Stride; const T8Bits* i2 = i1 + Stride; const T8Bits* i3 = i2 + Stride; #if !defined(MLAS_TARGET_IX86) const T8Bits* i4 = i0 + Stride * 4; const T8Bits* i5 = i4 + Stride; const T8Bits* i6 = i5 + Stride; #endif for (; ImageSize > PixelsPerIteration; ImageSize -= PixelsPerIteration) { int32_t* acc = AccumulateBuffer; size_t c = Channels; for (; c >= 8; c -= 8) { LOAD_FULL_CHANNELS(); CALCULATE_ACCUMULATE_VECTORS(); _mm_storeu_si128((__m128i*)acc, vacc_lo); _mm_storeu_si128(((__m128i*)acc) + 1, vacc_hi); acc += 8; } if (c > 0) { const __m128i vi0 = _mm_loadl_epi64((const __m128i*)(i0 >= LastOf8 ? memcpy(tail, i0, c) : i0)); const __m128i vi1 = _mm_loadl_epi64((const __m128i*)(i1 >= LastOf8 ? memcpy(tail, i1, c) : i1)); const __m128i vi2 = _mm_loadl_epi64((const __m128i*)(i2 >= LastOf8 ? memcpy(tail, i2, c) : i2)); const __m128i vi3 = _mm_loadl_epi64((const __m128i*)(i3 >= LastOf8 ? memcpy(tail, i3, c) : i3)); #if !defined(MLAS_TARGET_IX86) const __m128i vi4 = _mm_loadl_epi64((const __m128i*)(i4 >= LastOf8 ? memcpy(tail, i4, c) : i4)); const __m128i vi5 = _mm_loadl_epi64((const __m128i*)(i5 >= LastOf8 ? memcpy(tail, i5, c) : i5)); const __m128i vi6 = _mm_loadl_epi64((const __m128i*)(i6 >= LastOf8 ? memcpy(tail, i6, c) : i6)); #endif CALCULATE_ACCUMULATE_VECTORS(); _mm_storeu_si128((__m128i*)acc, vacc_lo); _mm_storeu_si128(((__m128i*)acc) + 1, vacc_hi); } finish_one_pass = true; i0 += step_next_group; i1 += step_next_group; i2 += step_next_group; i3 += step_next_group; #if !defined(MLAS_TARGET_IX86) i4 += step_next_group; i5 += step_next_group; i6 += step_next_group; #endif } if (ImageSize > 0) { #if defined(MLAS_TARGET_IX86) switch (ImageSize) { case 1: i1 = ZeroBuffer; [[fallthrough]]; case 2: i2 = ZeroBuffer; [[fallthrough]]; case 3: i3 = ZeroBuffer; [[fallthrough]]; default: break; } #else switch (ImageSize) { case 1: i1 = ZeroBuffer; [[fallthrough]]; case 2: i2 = ZeroBuffer; [[fallthrough]]; case 3: i3 = ZeroBuffer; [[fallthrough]]; case 4: i4 = ZeroBuffer; [[fallthrough]]; case 5: i5 = ZeroBuffer; [[fallthrough]]; case 6: i6 = ZeroBuffer; [[fallthrough]]; default: break; } #endif int32_t* acc = AccumulateBuffer; size_t c = Channels; for (; c >= 8; c -= 8) { LOAD_FULL_CHANNELS(); CALCULATE_ACCUMULATE_VECTORS(); _mm_storeu_si128((__m128i*)acc, vacc_lo); _mm_storeu_si128(((__m128i*)acc) + 1, vacc_hi); acc += 8; } if (c > 0) { const __m128i vi0 = _mm_loadl_epi64((const __m128i*)(i0 >= LastOf8 ? memcpy(tail, i0, c) : i0)); const __m128i vi1 = _mm_loadl_epi64( (const __m128i*)(1 < ImageSize && i1 >= LastOf8 ? memcpy(tail, i1, c) : i1)); const __m128i vi2 = _mm_loadl_epi64( (const __m128i*)(2 < ImageSize && i2 >= LastOf8 ? memcpy(tail, i2, c) : i2)); const __m128i vi3 = _mm_loadl_epi64( (const __m128i*)(3 < ImageSize && i3 >= LastOf8 ? memcpy(tail, i3, c) : i3)); #if !defined(MLAS_TARGET_IX86) const __m128i vi4 = _mm_loadl_epi64( (const __m128i*)(4 < ImageSize && i4 >= LastOf8 ? memcpy(tail, i4, c) : i4)); const __m128i vi5 = _mm_loadl_epi64( (const __m128i*)(5 < ImageSize && i5 >= LastOf8 ? memcpy(tail, i5, c) : i5)); const __m128i vi6 = _mm_loadl_epi64( (const __m128i*)(6 < ImageSize && i6 >= LastOf8 ? memcpy(tail, i6, c) : i6)); #endif CALCULATE_ACCUMULATE_VECTORS(); _mm_storeu_si128((__m128i*)acc, vacc_lo); _mm_storeu_si128(((__m128i*)acc) + 1, vacc_hi); } } MlasRequantizeOutput(AccumulateBuffer, Channels, Output, Channels, nullptr, &Scale, false, Output_zero_point, 0, 0, 1, Channels); } #else // Pure C++ Implementation template <typename T8Bits> void MLASCALL MlasQLinearGlobalAveragePoolNchw( const T8Bits* Input, float ScaleInput, int32_t ZeroPointInput, T8Bits* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Channels, size_t ImageSize, int32_t* /* AccumulateBuffer */ ) { float scale = CheckQLinearGlobalAveragePoolScaleAndSize(ScaleInput, ScaleOutput, ImageSize); int32_t bias = -ZeroPointInput * static_cast<int32_t>(ImageSize); for (; Channels > 0; Channels--) { int32_t acc = bias; for (size_t i = 0; i < ImageSize; ++i) { acc += static_cast<int32_t>(*Input++); } int32_t v = static_cast<int32_t>(std::nearbyintf(acc * scale)) + ZeroPointOutput; v = std::min(static_cast<int32_t>(std::numeric_limits<T8Bits>::max()), v); v = std::max(static_cast<int32_t>(std::numeric_limits<T8Bits>::lowest()), v); *Output++ = static_cast<T8Bits>(v); } } template <typename T8Bits> void MLASCALL MlasQLinearGlobalAveragePoolNhwc( const T8Bits* Input, float ScaleInput, int32_t ZeroPointInput, T8Bits* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Batch, size_t ImageSize, size_t Stride, size_t Channels, int32_t* AccumulateBuffer, const T8Bits* /*ZeroBuffer*/ ) { float scale = CheckQLinearGlobalAveragePoolScaleAndSize(ScaleInput, ScaleOutput, ImageSize); int32_t bias = -ZeroPointInput * static_cast<int32_t>(ImageSize); for (; Batch > 0; Batch--) { const T8Bits* batch_input = Input; T8Bits* batch_output = Output; Input += Stride * ImageSize; Output += Stride; std::fill_n(AccumulateBuffer, Channels, bias); for (size_t i = 0; i < ImageSize; ++i) { for (size_t c = 0; c < Channels; ++c) { AccumulateBuffer[c] += static_cast<int>(batch_input[c]); } batch_input += Stride; } for (size_t c = 0; c < Channels; ++c) { int32_t v = static_cast<int32_t>(std::nearbyintf(AccumulateBuffer[c] * scale)) + ZeroPointOutput; v = std::min(static_cast<int32_t>(std::numeric_limits<T8Bits>::max()), v); v = std::max(static_cast<int32_t>(std::numeric_limits<T8Bits>::lowest()), v); *batch_output++ = static_cast<T8Bits>(v); } } } #endif #if defined(MLAS_NEON_INTRINSICS) || defined(MLAS_SSE2_INTRINSICS) template <typename T8Bits> void MLASCALL MlasQLinearGlobalAveragePoolNhwc( const T8Bits* Input, float ScaleInput, int32_t ZeroPointInput, T8Bits* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Batch, size_t ImageSize, size_t Stride, size_t Channels, int32_t* AccumulateBuffer, const T8Bits* ZeroBuffer ) { float scale = CheckQLinearGlobalAveragePoolScaleAndSize(ScaleInput, ScaleOutput, ImageSize); const int32_t bias = -ZeroPointInput * static_cast<int32_t>(ImageSize); const T8Bits* inputLastOf8 = Input + (Batch * ImageSize * Stride - Stride + Channels) - 8; for (; Batch > 0; Batch--) { MlasQLinearGlobalAveragePoolNhwcSingleBatch( Input, Output, inputLastOf8, ImageSize, Channels, Stride, bias, scale, static_cast<T8Bits>(ZeroPointOutput), AccumulateBuffer, ZeroBuffer); Input += ImageSize * Stride; Output += Stride; } } #endif template void MLASCALL MlasQLinearGlobalAveragePoolNchw<int8_t>( const int8_t* Input, float ScaleInput, int32_t ZeroPointInput, int8_t* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Channels, size_t ImageSize, int32_t* AccumulateBuffer ); template void MLASCALL MlasQLinearGlobalAveragePoolNchw<uint8_t>( const uint8_t* Input, float ScaleInput, int32_t ZeroPointInput, uint8_t* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Channels, size_t ImageSize, int32_t* AccumulateBuffer ); template void MLASCALL MlasQLinearGlobalAveragePoolNhwc<int8_t>( const int8_t* Input, float ScaleInput, int32_t ZeroPointInput, int8_t* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Batch, size_t ImageSize, size_t Stride, size_t Channels, int32_t* AccumulateBuffer, const int8_t* ZeroBuffer ); template void MLASCALL MlasQLinearGlobalAveragePoolNhwc<uint8_t>( const uint8_t* Input, float ScaleInput, int32_t ZeroPointInput, uint8_t* Output, float ScaleOutput, int32_t ZeroPointOutput, size_t Batch, size_t ImageSize, size_t Stride, size_t Channels, int32_t* AccumulateBuffer, const uint8_t* ZeroBuffer );
21,064
435
<gh_stars>100-1000 { "description": "Serverside applications are more and more likely to need to run in\ndynamic cloud environments where they can automatically scale as\nrequired. One rightfully popular approach is to run the application\nas a Docker container inside a Kubernetes cluster, giving you a lot of\noperational benefits thanks to the Kubernetes folks.\n\nFor the most part it is rather easy to make your Python application\nwork inside a Docker container. But there are a number of common\npatterns one can follow to save time by delegating more things to the\nruntime environment. Furthermore you can start adding a few simple\nnon-intrusive features to your application which will help improve the\napplication live-cycle in the cluster, ensuring smooth hand-over when\nmigrating the container to different nodes or scaling it up or down.\n\nThis talk will quickly cover the basics of Kubernetes and will then\nstart from a simple program and will discuss the steps to take to make\nit behave well in this environment. Starting with the basics steps\nyou can rely on the runtime for, covering logging and all the way to\nsupporting the service life-cycle, health checking and monitoring in a\nKubernetes environment. You will see that building a cloud-native\napplication is not very hard and something you can gradually\nintroduce.", "duration": 1833, "language": "eng", "recorded": "2017-07-13", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/ZKPMQ-Sfk8Y/hqdefault.jpg", "title": "Cloud Native Python in Kubernetes", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=ZKPMQ-Sfk8Y" } ] }
480
434
package com.amazonaws.services.lambda.runtime.events.transformers.v2.dynamodb; import software.amazon.awssdk.services.dynamodb.model.StreamRecord; public class DynamodbStreamRecordTransformer { public static StreamRecord toStreamRecordV2(final com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord streamRecord) { return StreamRecord.builder() .approximateCreationDateTime( streamRecord.getApproximateCreationDateTime().toInstant() ) .keys( DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getKeys()) ) .newImage( streamRecord.getNewImage() != null ? DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getNewImage()) : null ) .oldImage( streamRecord.getOldImage() != null ? DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getOldImage()) : null ) .sequenceNumber(streamRecord.getSequenceNumber()) .sizeBytes(streamRecord.getSizeBytes()) .streamViewType(streamRecord.getStreamViewType()) .build(); } }
658
7,272
package com.kunal.abstractDemo; public class Main { public static void main(String[] args) { Son son = new Son(30); son.career(); son.normal(); Parent daughter = new Daughter(28); daughter.career(); Parent.hello(); // Parent mom = new Parent(45); } }
138
389
<gh_stars>100-1000 names = ["Jimmy", "Rose", "Max", "Nina", "Phillip"] for name in names: if len(name) != 4: continue print(f"Hello, {name}") if name == "Nina": break print("Done!")
98
1,442
<gh_stars>1000+ # Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== ''' python metric unittest ''' import os from pathlib import Path import tempfile import numpy as np import delta.compat as tf from delta import utils from delta.utils import metrics from delta import PACKAGE_ROOT_DIR #pylint: disable=too-many-instance-attributes class MetricTest(tf.test.TestCase): ''' python metrix unittest ''' def setUp(self): super().setUp() ''' setup ''' package_root = Path(PACKAGE_ROOT_DIR) self.config_file_crf = \ package_root.joinpath('../egs/mock_text_seq_label_data/seq-label/v1/config/seq-label-mock.yml') self.conf_str = ''' solver: metrics: pos_label: 1 # int, same to sklearn cals: - name: AccuracyCal arguments: null - name: ConfusionMatrixCal arguments: null - name: PrecisionCal arguments: average: 'micro' - name: RecallCal arguments: average: 'micro' - name: F1ScoreCal arguments: average: 'micro' ''' self.conf_file = tempfile.mktemp(suffix='metric.yaml') with open(self.conf_file, 'w', encoding='utf-8') as f: #pylint: disable=invalid-name f.write(self.conf_str) self.true_label = np.array([1, 1, 2, 3, 4, 6, 5]) self.pred1 = np.array([1, 1, 2, 3, 4, 6, 5]) self.pred2 = np.array([2, 2, 1, 1, 1, 1, 1]) # config for test token error metircs self.token_conf_str = ''' solver: metrics: pos_label: 1 # int, same to sklearn cals: - name: TokenErrCal arguments: eos_id: 0 ''' self.token_conf_file = tempfile.mktemp(suffix='token.yaml') with open(self.token_conf_file, 'w', encoding='utf-8') as f: #pylint: disable=invalid-name f.write(self.token_conf_str) self.token_true_label = [[1, 1, 1, 1], [1, 3, 4, 5]] self.token_pred1 = [[1, 1, 1, 1], [1, 3, 4, 5]] self.token_pred2 = [[1, 2, 2, 2], [1, 0, 0, 0]] def tearDown(self): ''' tear down ''' if os.path.exists(self.conf_file): os.unlink(self.conf_file) def test_metric(self): ''' test get_metrics function ''' config = utils.load_config(self.conf_file) metrics1 = metrics.get_metrics( config, y_true=self.true_label, y_pred=self.pred1) self.assertEqual(1.0, metrics1['AccuracyCal']) self.assertEqual(1.0, metrics1['PrecisionCal']) self.assertEqual(1.0, metrics1['RecallCal']) self.assertEqual(1.0, metrics1['F1ScoreCal']) metrics2 = metrics.get_metrics( config, y_true=self.true_label, y_pred=self.pred2) self.assertEqual(0.0, metrics2['AccuracyCal']) self.assertEqual(0.0, metrics2['PrecisionCal']) self.assertEqual(0.0, metrics2['RecallCal']) self.assertEqual(0.0, metrics2['F1ScoreCal']) def test_token_err(self): ''' test tooken error rate ''' config = utils.load_config(self.token_conf_file) metrics1 = metrics.get_metrics( config, y_true=self.token_true_label, y_pred=self.token_pred1) self.assertEqual(0.0, metrics1['TokenErrCal']) metrics2 = metrics.get_metrics( config, y_true=self.token_true_label, y_pred=self.token_pred2) self.assertEqual(0.75, metrics2['TokenErrCal']) def test_crf_metrics(self): ''' test crf metrics ''' config = utils.load_config(self.config_file_crf) metrics3 = metrics.get_metrics( config, y_true=[self.true_label], y_pred=[self.pred1]) # metrics3: one string. Text summary of the precision, recall, F1 score for each class. # res3 = metrics3['CrfCal'] # print(res3) # for i, s in enumerate(res3): # print(i, s) self.assertEqual('1.0000', metrics3['CrfCal'][67:73]) metrics4 = metrics.get_metrics( config, y_true=[self.true_label], y_pred=[self.pred2]) self.assertEqual('0.0000', metrics4['CrfCal'][67:73]) if __name__ == "__main__": tf.test.main()
1,970
380
#!/usr/bin/env python # coding: utf-8 # In[1]: #importing the required packages import pandas as pd import seaborn as sns import numpy as np from sklearn.metrics import mean_squared_error, r2_score from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split #reading the data dataset= pd.read_excel("C:/Users/ASUS/Linear Regression.xlsx", sheet_name="Linear Regression") #defined a function to take the independent variables as input def reg(col_name): #gaining insights about the data dataset.head() dataset.isnull().sum() dataset.describe() dataset.corr() print("for", col_name) sns.pairplot(dataset) print('---------------------------------------------------------------') #dividing the data into x and y x=dataset[[col_name]] y=dataset[['price']] #splitting the training data and testing data x_train,x_test,y_train,y_test= train_test_split(x,y,test_size=0.3,random_state=10) reg= LinearRegression() #fitting the model reg.fit(x_train,y_train) #predicting on the unseen data prediction= reg.predict(x_test) #getting the RMSE valuse and r2 value and printing them RMSE=np.sqrt(mean_squared_error(y_test,prediction)) r2=r2_score(y_test, prediction) #print("for", col_name) print("R Sqaure value is", r2) print("Root mean square is ", RMSE) #predicting and priniting the estimated price unseen_pred=reg.predict(np.array([[2]])) print("The estiamted price is",unseen_pred) print('---------------------------------------------------------------') #passing values (the independent varibles) to the function reg('sqft_living') reg('bedrooms') reg('bathrooms') reg('floors') # In[ ]:
633
852
#ifndef CalibTracker_SiStripChannelGain_SiStripGainFromAsciiFile_h #define CalibTracker_SiStripChannelGain_SiStripGainFromAsciiFile_h #include "FWCore/ParameterSet/interface/FileInPath.h" #include "CommonTools/ConditionDBWriter/interface/ConditionDBWriter.h" #include "CondFormats/SiStripObjects/interface/SiStripApvGain.h" #include <vector> #include <memory> #include <unordered_map> class SiStripGainFromAsciiFile : public ConditionDBWriter<SiStripApvGain> { public: explicit SiStripGainFromAsciiFile(const edm::ParameterSet&); ~SiStripGainFromAsciiFile() override; private: std::unique_ptr<SiStripApvGain> getNewObject() override; private: struct ModuleGain { float apv[6]; void soft_reset() { for (int i = 0; i < 6; ++i) if (apv[i] == -1) apv[i] = 1; } void hard_reset(float val) { for (int i = 0; i < 6; ++i) apv[i] = val; } }; std::string Asciifilename_; float referenceValue_; edm::FileInPath fp_; std::unordered_map<unsigned int, ModuleGain> GainsMap; }; #endif
442
1,817
/* * * * * * * * * * * Copyright 2019-2020 the original author or authors. * * * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * * * you may not use this file except in compliance with the License. * * * * You may obtain a copy of the License at * * * * * * * * https://www.apache.org/licenses/LICENSE-2.0 * * * * * * * * Unless required by applicable law or agreed to in writing, software * * * * distributed under the License is distributed on an "AS IS" BASIS, * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * * * See the License for the specific language governing permissions and * * * * limitations under the License. * * * * * * * */ package org.springdoc.data.rest.core; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import com.fasterxml.jackson.annotation.JsonView; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.Content; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.parameters.Parameter; import org.apache.commons.lang3.ArrayUtils; import org.springdoc.core.AbstractRequestService; import org.springdoc.core.DelegatingMethodParameter; import org.springdoc.core.GenericParameterService; import org.springdoc.core.MethodAttributes; import org.springdoc.core.ParameterInfo; import org.springdoc.core.RequestBodyInfo; import org.springdoc.core.RequestBodyService; import org.springdoc.core.SpringDocAnnotationsUtils; import org.springdoc.data.rest.utils.SpringDocDataRestUtils; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.webmvc.PersistentEntityResource; import org.springframework.data.rest.webmvc.support.BackendId; import org.springframework.data.rest.webmvc.support.DefaultedPageable; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; /** * The type Data rest request builder. * @author bnasslahsen */ public class DataRestRequestService { /** * The Local spring doc parameter name discoverer. */ private LocalVariableTableParameterNameDiscoverer localSpringDocParameterNameDiscoverer; /** * The Parameter builder. */ private GenericParameterService parameterBuilder; /** * The Request body builder. */ private RequestBodyService requestBodyService; /** * The Request builder. */ private AbstractRequestService requestBuilder; /** * The Spring doc data rest utils. */ private SpringDocDataRestUtils springDocDataRestUtils; /** * Instantiates a new Data rest request builder. * * @param localSpringDocParameterNameDiscoverer the local spring doc parameter name discoverer * @param parameterBuilder the parameter builder * @param requestBodyService the request body builder * @param requestBuilder the request builder * @param springDocDataRestUtils the spring doc data rest utils */ public DataRestRequestService(LocalVariableTableParameterNameDiscoverer localSpringDocParameterNameDiscoverer, GenericParameterService parameterBuilder, RequestBodyService requestBodyService, AbstractRequestService requestBuilder, SpringDocDataRestUtils springDocDataRestUtils) { this.localSpringDocParameterNameDiscoverer = localSpringDocParameterNameDiscoverer; this.parameterBuilder = parameterBuilder; this.requestBodyService = requestBodyService; this.requestBuilder = requestBuilder; this.springDocDataRestUtils = springDocDataRestUtils; } /** * Build parameters. * * @param openAPI the open api * @param handlerMethod the handler method * @param requestMethod the request method * @param methodAttributes the method attributes * @param operation the operation * @param resourceMetadata the resource metadata * @param dataRestRepository the data rest repository */ public void buildParameters(OpenAPI openAPI, HandlerMethod handlerMethod, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, ResourceMetadata resourceMetadata, DataRestRepository dataRestRepository) { String[] pNames = this.localSpringDocParameterNameDiscoverer.getParameterNames(handlerMethod.getMethod()); MethodParameter[] parameters = handlerMethod.getMethodParameters(); if (!resourceMetadata.isPagingResource()) { Optional<MethodParameter> methodParameterPage = Arrays.stream(parameters).filter(methodParameter -> DefaultedPageable.class.equals(methodParameter.getParameterType())).findFirst(); if (methodParameterPage.isPresent()) parameters = ArrayUtils.removeElement(parameters, methodParameterPage.get()); } String[] reflectionParametersNames = Arrays.stream(handlerMethod.getMethod().getParameters()).map(java.lang.reflect.Parameter::getName).toArray(String[]::new); if (pNames == null || Arrays.stream(pNames).anyMatch(Objects::isNull)) pNames = reflectionParametersNames; buildCommonParameters(openAPI, requestMethod, methodAttributes, operation, pNames, parameters, dataRestRepository); } /** * Build common parameters. * * @param openAPI the open api * @param requestMethod the request method * @param methodAttributes the method attributes * @param operation the operation * @param pNames the p names * @param parameters the parameters * @param dataRestRepository the data rest repository */ public void buildCommonParameters(OpenAPI openAPI, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, String[] pNames, MethodParameter[] parameters, DataRestRepository dataRestRepository) { parameters = DelegatingMethodParameter.customize(pNames, parameters, parameterBuilder.getDelegatingMethodParameterCustomizer()); Class<?> domainType = dataRestRepository.getDomainType(); for (MethodParameter methodParameter : parameters) { final String pName = methodParameter.getParameterName(); ParameterInfo parameterInfo = new ParameterInfo(pName, methodParameter, parameterBuilder); if (isParamToIgnore(methodParameter)) { if (PersistentEntityResource.class.equals(methodParameter.getParameterType())) { Schema<?> schema = SpringDocAnnotationsUtils.resolveSchemaFromType(domainType, openAPI.getComponents(), null, methodParameter.getParameterAnnotations()); parameterInfo.setParameterModel(new Parameter().schema(schema)); } else if (methodParameter.getParameterAnnotation(BackendId.class) != null) { parameterInfo.setParameterModel(new Parameter().name("id").in(ParameterIn.PATH.toString()).schema(new StringSchema())); } Parameter parameter = null; io.swagger.v3.oas.annotations.Parameter parameterDoc = AnnotatedElementUtils.findMergedAnnotation( AnnotatedElementUtils.forAnnotations(methodParameter.getParameterAnnotations()), io.swagger.v3.oas.annotations.Parameter.class); if (parameterDoc != null) { if (parameterDoc.hidden() || parameterDoc.schema().hidden()) continue; parameter = parameterBuilder.buildParameterFromDoc(parameterDoc, openAPI.getComponents(), methodAttributes.getJsonViewAnnotation(), methodAttributes.getLocale()); parameterInfo.setParameterModel(parameter); } if (!ArrayUtils.isEmpty(methodParameter.getParameterAnnotations())) parameter = requestBuilder.buildParams(parameterInfo, parameters.length, openAPI.getComponents(), requestMethod, null); addParameters(openAPI, requestMethod, methodAttributes, operation, methodParameter, parameterInfo, parameter); } } } /** * Build parameter from doc parameter. * * @param parameterDoc the parameter doc * @param components the components * @param jsonViewAnnotation the json view annotation * @param locale the locale * @return the parameter */ public Parameter buildParameterFromDoc(io.swagger.v3.oas.annotations.Parameter parameterDoc, Components components, JsonView jsonViewAnnotation, Locale locale) { return parameterBuilder.buildParameterFromDoc(parameterDoc, components, jsonViewAnnotation, locale); } /** * Is param to ignore boolean. * * @param methodParameter the method parameter * @return the boolean */ private boolean isParamToIgnore(MethodParameter methodParameter) { return !requestBuilder.isParamToIgnore(methodParameter) && !isHeaderToIgnore(methodParameter) && !"property".equals(methodParameter.getParameterName()); } /** * Add parameters. * * @param openAPI the open api * @param requestMethod the request method * @param methodAttributes the method attributes * @param operation the operation * @param methodParameter the method parameter * @param parameterInfo the parameter info * @param parameter the parameter */ private void addParameters(OpenAPI openAPI, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, MethodParameter methodParameter, ParameterInfo parameterInfo, Parameter parameter) { List<Annotation> parameterAnnotations = Arrays.asList(methodParameter.getParameterAnnotations()); if (requestBuilder.isValidParameter(parameter)) { requestBuilder.applyBeanValidatorAnnotations(parameter, parameterAnnotations); operation.addParametersItem(parameter); } else if (!RequestMethod.GET.equals(requestMethod)) { RequestBodyInfo requestBodyInfo = new RequestBodyInfo(); if (operation.getRequestBody() != null) requestBodyInfo.setRequestBody(operation.getRequestBody()); requestBodyService.calculateRequestBodyInfo(openAPI.getComponents(), methodAttributes, parameterInfo, requestBodyInfo); requestBuilder.applyBeanValidatorAnnotations(requestBodyInfo.getRequestBody(), parameterAnnotations, methodParameter.isOptional()); operation.setRequestBody(requestBodyInfo.getRequestBody()); Content content = operation.getRequestBody().getContent(); springDocDataRestUtils.buildTextUriContent(content); operation.getRequestBody().setRequired(true); } } /** * Is header to ignore boolean. * * @param methodParameter the method parameter * @return the boolean */ private boolean isHeaderToIgnore(MethodParameter methodParameter) { RequestHeader requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class); return requestHeader != null && HttpHeaders.ACCEPT.equals(requestHeader.value()); } }
3,159
384
<gh_stars>100-1000 /** * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. */ package com.baidu.jprotobuf.pbrpc.transport; /** * The Class RpcErrorMessage. * * @author xiemalin * @since 3.5.13 */ public class RpcErrorMessage { /** The error code. */ private int errorCode; /** The error message. */ private String errorMessage; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the error message. * * @return the error message */ public String getErrorMessage() { return errorMessage; } /** * Sets the error message. * * @param errorMessage the new error message */ public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } /** * Instantiates a new rpc error. * * @param errorCode the error code * @param errorMessage the error message */ public RpcErrorMessage(int errorCode, String errorMessage) { super(); this.errorCode = errorCode; this.errorMessage = errorMessage; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + errorCode; return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RpcErrorMessage other = (RpcErrorMessage) obj; if (errorCode != other.errorCode) return false; return true; } }
993
1,550
<reponame>ATikhonov2/leo-editor # Leo colorizer control file for fortran mode. # This file is in the public domain. # Properties for fortran mode. properties = { "blockComment": "C", "indentNextLine": "\\s*((if\\s*\\(.*\\)\\s*then|else\\s*|do\\s*)*)", "wordBreakChars": ",+-=<>/?^&*", } # Attributes dict for fortran_main ruleset. fortran_main_attributes_dict = { "default": "null", "digit_re": "", "escape": "", "highlight_digits": "false", "ignore_case": "true", "no_word_sep": "", } # Dictionary of attributes dictionaries for fortran mode. attributesDictDict = { "fortran_main": fortran_main_attributes_dict, } # Keywords dict for fortran_main ruleset. fortran_main_keywords_dict = { ".false.": "keyword1", ".true.": "keyword1", "abs": "keyword1", "acos": "keyword1", "aimag": "keyword1", "aint": "keyword1", "allocatable": "keyword1", "allocate": "keyword1", "allocated": "keyword1", "alog": "keyword1", "alog10": "keyword1", "amax0": "keyword1", "amax1": "keyword1", "amin0": "keyword1", "amin1": "keyword1", "amod": "keyword1", "anint": "keyword1", "asin": "keyword1", "atan": "keyword1", "atan2": "keyword1", "backspace": "keyword1", "cabs": "keyword1", "call": "keyword1", "case": "keyword1", "ccos": "keyword1", "ceiling": "keyword1", "char": "keyword1", "character": "keyword1", "clog": "keyword1", "close": "keyword1", "cmplx": "keyword1", "complex": "keyword1", "conjg": "keyword1", "contains": "keyword1", "continue": "keyword1", "cos": "keyword1", "cosh": "keyword1", "csin": "keyword1", "csqrt": "keyword1", "cycle": "keyword1", "dabs": "keyword1", "dacos": "keyword1", "dasin": "keyword1", "data": "keyword1", "datan": "keyword1", "datan2": "keyword1", "dble": "keyword1", "dcmplx": "keyword1", "dcos": "keyword1", "dcosh": "keyword1", "ddim": "keyword1", "deallocate": "keyword1", "default": "keyword1", "dexp": "keyword1", "dfloat": "keyword1", "dim": "keyword1", "dimension": "keyword1", "dint": "keyword1", "dlog": "keyword1", "dlog10": "keyword1", "dmax1": "keyword1", "dmin1": "keyword1", "dmod": "keyword1", "dnint": "keyword1", "do": "keyword1", "double": "keyword1", "dprod": "keyword1", "dreal": "keyword1", "dsign": "keyword1", "dsin": "keyword1", "dsinh": "keyword1", "dsqrt": "keyword1", "dtan": "keyword1", "dtanh": "keyword1", "else": "keyword1", "elseif": "keyword1", "elsewhere": "keyword1", "end": "keyword1", "enddo": "keyword1", "endfile": "keyword1", "endif": "keyword1", "exit": "keyword1", "exp": "keyword1", "explicit": "keyword1", "float": "keyword1", "floor": "keyword1", "forall": "keyword1", "format": "keyword1", "function": "keyword1", "goto": "keyword1", "iabs": "keyword1", "ichar": "keyword1", "idim": "keyword1", "idint": "keyword1", "idnint": "keyword1", "if": "keyword1", "ifix": "keyword1", "imag": "keyword1", "implicit": "keyword1", "include": "keyword1", "index": "keyword1", "inquire": "keyword1", "int": "keyword1", "integer": "keyword1", "isign": "keyword1", "kind": "keyword1", "len": "keyword1", "lge": "keyword1", "lgt": "keyword1", "lle": "keyword1", "llt": "keyword1", "log": "keyword1", "log10": "keyword1", "logical": "keyword1", "max": "keyword1", "max0": "keyword1", "max1": "keyword1", "min": "keyword1", "min0": "keyword1", "min1": "keyword1", "mod": "keyword1", "module": "keyword1", "modulo": "keyword1", "nint": "keyword1", "none": "keyword1", "open": "keyword1", "parameter": "keyword1", "pause": "keyword1", "precision": "keyword1", "print": "keyword1", "program": "keyword1", "read": "keyword1", "real": "keyword1", "return": "keyword1", "rewind": "keyword1", "select": "keyword1", "sign": "keyword1", "sin": "keyword1", "sinh": "keyword1", "sngl": "keyword1", "sqrt": "keyword1", "stop": "keyword1", "subroutine": "keyword1", "tan": "keyword1", "tanh": "keyword1", "then": "keyword1", "transfer": "keyword1", "use": "keyword1", "where": "keyword1", "while": "keyword1", "write": "keyword1", "zext": "keyword1", } # Dictionary of keywords dictionaries for fortran mode. keywordsDictDict = { "fortran_main": fortran_main_keywords_dict, } # Rules for fortran_main ruleset. def fortran_rule0(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="c", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def fortran_rule1(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="C", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def fortran_rule2(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="!", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def fortran_rule3(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="*", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def fortran_rule4(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="!", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def fortran_rule5(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment2", seq="D", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def fortran_rule6(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def fortran_rule7(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def fortran_rule8(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="<=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule9(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule10(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule11(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="<", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule12(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="&", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule13(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="/=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule14(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="==", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule15(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".lt.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule16(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".gt.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule17(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".eq.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule18(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".ne.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule19(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".le.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule20(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".ge.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule21(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".AND.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule22(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".OR.", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def fortran_rule23(colorer, s, i): return colorer.match_keywords(s, i) # Rules dict for fortran_main ruleset. rulesDict1 = { "!": [fortran_rule2,fortran_rule4,], "\"": [fortran_rule6,], "&": [fortran_rule12,], "'": [fortran_rule7,], "*": [fortran_rule3,], ".": [fortran_rule15,fortran_rule16,fortran_rule17,fortran_rule18,fortran_rule19,fortran_rule20,fortran_rule21,fortran_rule22,fortran_rule23,], "/": [fortran_rule13,], "0": [fortran_rule23,], "1": [fortran_rule23,], "2": [fortran_rule23,], "3": [fortran_rule23,], "4": [fortran_rule23,], "5": [fortran_rule23,], "6": [fortran_rule23,], "7": [fortran_rule23,], "8": [fortran_rule23,], "9": [fortran_rule23,], "<": [fortran_rule8,fortran_rule11,], "=": [fortran_rule14,], ">": [fortran_rule9,fortran_rule10,], "@": [fortran_rule23,], "A": [fortran_rule23,], "B": [fortran_rule23,], "C": [fortran_rule1,fortran_rule23,], "D": [fortran_rule5,fortran_rule23,], "E": [fortran_rule23,], "F": [fortran_rule23,], "G": [fortran_rule23,], "H": [fortran_rule23,], "I": [fortran_rule23,], "J": [fortran_rule23,], "K": [fortran_rule23,], "L": [fortran_rule23,], "M": [fortran_rule23,], "N": [fortran_rule23,], "O": [fortran_rule23,], "P": [fortran_rule23,], "Q": [fortran_rule23,], "R": [fortran_rule23,], "S": [fortran_rule23,], "T": [fortran_rule23,], "U": [fortran_rule23,], "V": [fortran_rule23,], "W": [fortran_rule23,], "X": [fortran_rule23,], "Y": [fortran_rule23,], "Z": [fortran_rule23,], "a": [fortran_rule23,], "b": [fortran_rule23,], "c": [fortran_rule0,fortran_rule23,], "d": [fortran_rule23,], "e": [fortran_rule23,], "f": [fortran_rule23,], "g": [fortran_rule23,], "h": [fortran_rule23,], "i": [fortran_rule23,], "j": [fortran_rule23,], "k": [fortran_rule23,], "l": [fortran_rule23,], "m": [fortran_rule23,], "n": [fortran_rule23,], "o": [fortran_rule23,], "p": [fortran_rule23,], "q": [fortran_rule23,], "r": [fortran_rule23,], "s": [fortran_rule23,], "t": [fortran_rule23,], "u": [fortran_rule23,], "v": [fortran_rule23,], "w": [fortran_rule23,], "x": [fortran_rule23,], "y": [fortran_rule23,], "z": [fortran_rule23,], } # x.rulesDictDict for fortran mode. rulesDictDict = { "fortran_main": rulesDict1, } # Import dict for fortran mode. importDict = {}
5,974
1,025
#import <Foundation/Foundation.h> #import <CDEKit/CDEEntitiesViewController.h> #import <CDEKit/CDEManagedObjectsViewController.h> #import <CDEKit/CDEManagedObjectViewController.h> @interface CDE : NSObject + (instancetype)sharedCoreDataEditor; #pragma mark - Creating a Embedded Core Data Editor - (void)enableEmbeddedCoreDataEditorWithMainContext:(NSManagedObjectContext *)mainContext; @end
132
1,521
<filename>analytical_engine/benchmarks/apps/bfs/property_bfs.h /** Copyright 2020 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANALYTICAL_ENGINE_BENCHMARKS_APPS_BFS_PROPERTY_BFS_H_ #define ANALYTICAL_ENGINE_BENCHMARKS_APPS_BFS_PROPERTY_BFS_H_ #include <limits> #include "grape/grape.h" #include "core/app/parallel_property_app_base.h" #include "core/context/vertex_data_context.h" #include "core/worker/parallel_property_worker.h" namespace gs { namespace benchmarks { template <typename FRAG_T> class PropertyBFSContext : public LabeledVertexDataContext<FRAG_T, int64_t> { public: using depth_type = int64_t; using oid_t = typename FRAG_T::oid_t; using vid_t = typename FRAG_T::vid_t; explicit PropertyBFSContext(const FRAG_T& fragment) : LabeledVertexDataContext<FRAG_T, int64_t>(fragment, true), partial_result(this->data()[0]) {} void Init(ParallelPropertyMessageManager& messages, oid_t src_id) { auto& frag = this->fragment(); source_id = src_id; auto vertices = frag.Vertices(0); partial_result.Init(vertices, std::numeric_limits<depth_type>::max()); } void Output(std::ostream& os) { auto& frag = this->fragment(); auto inner_vertices = frag.InnerVertices(0); for (auto v : inner_vertices) { os << frag.GetId(v) << " " << partial_result[v] << std::endl; } } oid_t source_id; typename FRAG_T::template vertex_array_t<depth_type>& partial_result; grape::DenseVertexSet<vid_t> curr_inner_updated, next_inner_updated; depth_type current_depth = 0; }; template <typename FRAG_T> class PropertyBFS : public ParallelPropertyAppBase<FRAG_T, PropertyBFSContext<FRAG_T>>, public grape::ParallelEngine { public: INSTALL_PARALLEL_PROPERTY_WORKER(PropertyBFS<FRAG_T>, PropertyBFSContext<FRAG_T>, FRAG_T) using vertex_t = typename fragment_t::vertex_t; void PEval(const fragment_t& frag, context_t& ctx, message_manager_t& messages) { using depth_type = typename context_t::depth_type; messages.InitChannels(thread_num(), 2 * 1023 * 64, 2 * 1024 * 64); ctx.current_depth = 1; vertex_t source; bool native_source = frag.GetInnerVertex(0, ctx.source_id, source); auto inner_vertices = frag.InnerVertices(0); auto outer_vertices = frag.OuterVertices(0); // init double buffer which contains updated vertices using bitmap ctx.curr_inner_updated.Init(inner_vertices, GetThreadPool()); ctx.next_inner_updated.Init(inner_vertices, GetThreadPool()); auto& channel_0 = messages.Channels()[0]; if (native_source) { ctx.partial_result[source] = 0; auto oes = frag.GetOutgoingAdjList(source, 0); for (auto& e : oes) { auto u = e.get_neighbor(); if (ctx.partial_result[u] == std::numeric_limits<depth_type>::max()) { ctx.partial_result[u] = 1; if (frag.IsOuterVertex(u)) { channel_0.SyncStateOnOuterVertex<fragment_t>(frag, u); } else { ctx.curr_inner_updated.Insert(u); } } } } messages.ForceContinue(); } void IncEval(const fragment_t& frag, context_t& ctx, message_manager_t& messages) { using depth_type = typename context_t::depth_type; auto& channels = messages.Channels(); depth_type next_depth = ctx.current_depth + 1; int thrd_num = thread_num(); ctx.next_inner_updated.ParallelClear(GetThreadPool()); // process received messages and update depth messages.ParallelProcess<fragment_t, grape::EmptyType>( thrd_num, frag, [&ctx](int tid, vertex_t v, grape::EmptyType) { if (ctx.partial_result[v] == std::numeric_limits<depth_type>::max()) { ctx.partial_result[v] = ctx.current_depth; ctx.curr_inner_updated.Insert(v); } }); // sync messages to other workers ForEach(ctx.curr_inner_updated, [next_depth, &frag, &ctx, &channels]( int tid, vertex_t v) { auto oes = frag.GetOutgoingAdjList(v, 0); for (auto& e : oes) { auto u = e.get_neighbor(); if (ctx.partial_result[u] == std::numeric_limits<depth_type>::max()) { ctx.partial_result[u] = next_depth; if (frag.IsOuterVertex(u)) { channels[tid].SyncStateOnOuterVertex<fragment_t>(frag, u); } else { ctx.next_inner_updated.Insert(u); } } } }); ctx.current_depth = next_depth; if (!ctx.next_inner_updated.Empty()) { messages.ForceContinue(); } ctx.next_inner_updated.Swap(ctx.curr_inner_updated); } }; } // namespace benchmarks } // namespace gs #endif // ANALYTICAL_ENGINE_BENCHMARKS_APPS_BFS_PROPERTY_BFS_H_
2,229
1,006
from .common import EWSAccountService, to_item_id from ..properties import ParentItemId from ..util import create_element, set_xml_value, MNS class CreateAttachment(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/createattachment-operation """ SERVICE_NAME = 'CreateAttachment' element_container_name = '{%s}Attachments' % MNS def call(self, parent_item, items): return self._elems_to_objs(self._chunked_get_elements(self.get_payload, items=items, parent_item=parent_item)) def _elems_to_objs(self, elems): from ..attachments import FileAttachment, ItemAttachment cls_map = {cls.response_tag(): cls for cls in (FileAttachment, ItemAttachment)} for elem in elems: if isinstance(elem, Exception): yield elem continue yield cls_map[elem.tag].from_xml(elem=elem, account=self.account) def get_payload(self, items, parent_item): from ..items import BaseItem payload = create_element('m:%s' % self.SERVICE_NAME) version = self.account.version if isinstance(parent_item, BaseItem): # to_item_id() would convert this to a normal ItemId, but the service wants a ParentItemId parent_item = ParentItemId(parent_item.id, parent_item.changekey) set_xml_value(payload, to_item_id(parent_item, ParentItemId, version=version), version=version) attachments = create_element('m:Attachments') for item in items: set_xml_value(attachments, item, version=self.account.version) if not len(attachments): raise ValueError('"items" must not be empty') payload.append(attachments) return payload
714
589
<filename>inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/editor/preferences/control/SamplingRateControl.java package rocks.inspectit.ui.rcp.editor.preferences.control; import java.util.HashMap; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import rocks.inspectit.ui.rcp.editor.preferences.IPreferenceGroup; import rocks.inspectit.ui.rcp.editor.preferences.IPreferencePanel; import rocks.inspectit.ui.rcp.editor.preferences.PreferenceId; /** * This class creates a control group with a sampling rate slider in the * {@link rocks.inspectit.ui.rcp.editor.preferences.FormPreferencePanel}. * * @author <NAME> * */ public class SamplingRateControl extends AbstractPreferenceControl implements IPreferenceControl { /** * The unique id of this preference control. */ private static final PreferenceId CONTROL_GROUP_ID = PreferenceId.SAMPLINGRATE; /** * The sampling rate slider. */ private Scale slider = null; /** * The radio button for timeframe selection. */ private Button timeframeModeButton = null; /** * The available sensitivity modes. * * @author <NAME> * */ public enum Sensitivity { /** No sensitivity. */ NO_SENSITIVITY(0), /** 'Very fine' sensitivity. */ VERY_FINE(200), /** 'Fine' sensitivity. */ FINE(120), /** 'Medium' sensitivity. */ MEDIUM(75), /** 'Coarse' sensitivity. */ COARSE(30), /** 'Very coarse' sensitivity. */ VERY_COARSE(15); /** * The value. */ private int value; /** * The constructor needing the specific value. * * @param value * The value. */ private Sensitivity(int value) { this.value = value; } /** * Returns the sensitivity value. * * @return The value. */ public int getValue() { return value; } /** * Converts an ordinal into a {@link Sensitivity}. * * @param i * The ordinal. * @return The appropriate column. */ public static Sensitivity fromOrd(int i) { if ((i < 0) || (i >= Sensitivity.values().length)) { throw new IndexOutOfBoundsException("Invalid ordinal"); } return Sensitivity.values()[i]; } } /** * The default sensitivity. */ public static final Sensitivity DEFAULT_SENSITIVITY = Sensitivity.MEDIUM; /** * Default constructor. * * @param preferencePanel * Preference panel. */ public SamplingRateControl(IPreferencePanel preferencePanel) { super(preferencePanel); } /** * {@inheritDoc} */ @Override public Composite createControls(Composite parent, FormToolkit toolkit) { Section section = toolkit.createSection(parent, ExpandableComposite.TITLE_BAR); section.setText("Sampling Rate"); section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); Composite composite = toolkit.createComposite(section); section.setClient(composite); GridLayout layout = new GridLayout(4, false); layout.marginLeft = 10; layout.horizontalSpacing = 10; composite.setLayout(layout); GridData gridData = new GridData(SWT.MAX, SWT.DEFAULT); gridData.grabExcessHorizontalSpace = true; composite.setLayoutData(gridData); final Label sliderLabel = toolkit.createLabel(composite, "no sensitivity selected", SWT.LEFT); GridData data = new GridData(SWT.FILL, SWT.FILL, false, false); data.widthHint = sliderLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; sliderLabel.setLayoutData(data); slider = new Scale(composite, SWT.HORIZONTAL); toolkit.adapt(slider, true, true); slider.setMinimum(0); slider.setMaximum(Sensitivity.values().length - 1); slider.setIncrement(1); slider.setSize(200, 10); slider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); slider.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent event) { Sensitivity sensitivity = Sensitivity.fromOrd(slider.getSelection()); switch (sensitivity) { case NO_SENSITIVITY: sliderLabel.setText("no sensitivity selected"); break; case VERY_FINE: sliderLabel.setText("very fine"); break; case FINE: sliderLabel.setText("fine"); break; case MEDIUM: sliderLabel.setText("medium"); break; case COARSE: sliderLabel.setText("coarse"); break; case VERY_COARSE: sliderLabel.setText("very coarse"); break; default: break; } } }); slider.setSelection(DEFAULT_SENSITIVITY.ordinal()); slider.notifyListeners(SWT.Selection, null); Label modeLabel = toolkit.createLabel(composite, "Sampling Rate Mode: ", SWT.LEFT); modeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); timeframeModeButton = toolkit.createButton(composite, "Timeframe dividing", SWT.RADIO); timeframeModeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); timeframeModeButton.setSelection(true); return composite; } /** * {@inheritDoc} */ @Override public Map<IPreferenceGroup, Object> eventFired() { Sensitivity sensitivity = Sensitivity.fromOrd(slider.getSelection()); Map<IPreferenceGroup, Object> preferenceControlMap = new HashMap<>(); preferenceControlMap.put(PreferenceId.SamplingRate.SLIDER_ID, sensitivity); // get the actual selected divider mode button and set the specific id if (timeframeModeButton.getSelection()) { preferenceControlMap.put(PreferenceId.SamplingRate.DIVIDER_ID, PreferenceId.SamplingRate.TIMEFRAME_DIVIDER_ID); } return preferenceControlMap; } /** * {@inheritDoc} */ @Override public PreferenceId getControlGroupId() { return CONTROL_GROUP_ID; } /** * {@inheritDoc} */ @Override public void dispose() { } }
2,299
540
<reponame>dlee992/sdc # -*- coding: utf-8 -*- # ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** import numpy as np import pandas as pd import unittest from itertools import product from sdc.tests.indexes import ( TestEmptyIndex, TestPositionalIndex, TestRangeIndex, TestInt64Index, ) from sdc.tests.indexes.index_datagens import _generate_index_param_values, get_sample_index from sdc.datatypes.indexes import * class TestIndexes( TestEmptyIndex, TestPositionalIndex, TestRangeIndex, TestInt64Index ): """ This suite combines tests from all concrete index-type suites and also adds tests for common use-cases that need to be checked for all index-types. """ def assert_indexes_equal(self, index1, index2): # for SDC indexes that are represented with arrays (e.g. Uint64Index) supported_pandas_indexes = (pd.RangeIndex, pd.Int64Index, ) if (not isinstance(index1, supported_pandas_indexes) or not isinstance(index2, supported_pandas_indexes)): index1 = np.asarray(index1) index2 = np.asarray(index2) np.testing.assert_array_equal(index1, index2) else: pd.testing.assert_index_equal(index1, index2) @unittest.skip("TODO: support boxing/unboxing and parent ref for Python ranges in Numba") def test_indexes_unbox_data_id_check(self): def test_impl(index): return index sdc_func = self.jit(test_impl) n = 11 indexes_to_test = [ pd.RangeIndex(n, name='abc'), # only this one fails, other pass pd.Int64Index(np.arange(n), name='abc'), ] data_attr_names_map = { pd.RangeIndex: '_range', pd.Int64Index: '_data', } for index in indexes_to_test: with self.subTest(index_type=type(index)): result = sdc_func(index) result_ref = test_impl(index) data1, data2, data3 = map( lambda x: getattr(x, data_attr_names_map[type(x)]), [index, result, result_ref] ) self.assertIs(data1, data3) self.assertIs(data2, data3) @unittest.skip("Needs writable native struct type members in Numba") def test_indexes_named_set_name(self): def test_impl(index): index.name = 'def' return index sdc_func = self.jit(test_impl) n = 11 indexes_to_test = [ pd.RangeIndex(n, name='abc'), pd.Int64Index(np.arange(n), name='abc'), ] for index in indexes_to_test: with self.subTest(index_type=type(index)): index1 = index.copy(deep=True) index2 = index.copy(deep=True) result = sdc_func(index1) result_ref = test_impl(index2) pd.testing.assert_index_equal(result, result_ref) @unittest.skip("Needs writable native struct type members and single common type for name") def test_indexes_unnamed_set_name(self): def test_impl(index): index.name = 'def' return index sdc_func = self.jit(test_impl) n = 11 indexes_to_test = [ pd.RangeIndex(n), pd.Int64Index(np.arange(n)), ] for index in indexes_to_test: with self.subTest(index_type=type(index)): index1 = index.copy(deep=True) index2 = index.copy(deep=True) result = sdc_func(index1) result_ref = test_impl(index2) pd.testing.assert_index_equal(result, result_ref) @unittest.skip("Need support unboxing pandas indexes with parent ref") def test_indexes_operator_is_unbox(self): def test_impl(index1, index2): return index1 is index2 sdc_func = self.jit(test_impl) indexes_to_test = [ pd.RangeIndex(1, 21, 3), pd.Int64Index([1, 2, 3, 5, 6, 3, 4]), ] for index in indexes_to_test: # positive testcase with self.subTest(subtest="same indexes"): index1 = index.copy(deep=True) index2 = index1 result = sdc_func(index1, index2) result_ref = test_impl(index1, index2) self.assertEqual(result, result_ref) self.assertEqual(result, True) # negative testcase with self.subTest(subtest="not same indexes"): index1 = index.copy(deep=True) index2 = index.copy(deep=True) result = sdc_func(index1, index2) result_ref = test_impl(index1, index2) self.assertEqual(result, result_ref) self.assertEqual(result, False) def test_indexes_unbox_series_with_index(self): @self.jit def test_impl(S): # TO-DO: this actually includes calling 'index' attribute overload, should really be S._index, # but this requires separate type (e.g. PositionalIndexType) instead of types.none as default index return S.index n = 11 for index in _generate_index_param_values(n): expected_res = pd.RangeIndex(n) if index is None else index with self.subTest(series_index=index): S = pd.Series(np.ones(n), index=index) result = test_impl(S) self.assert_indexes_equal(result, expected_res) def test_indexes_create_series_with_index(self): @self.jit def test_impl(data, index): S = pd.Series(data=data, index=index) return S.index n = 11 series_data = np.ones(n) for index in _generate_index_param_values(n): expected_res = pd.RangeIndex(n) if index is None else index with self.subTest(series_index=index): result = test_impl(series_data, index) self.assert_indexes_equal(result, expected_res) def test_indexes_box_series_with_index(self): def test_impl(data, index): return pd.Series(data=data, index=index) sdc_func = self.jit(test_impl) n = 11 series_data = np.ones(n) for index in _generate_index_param_values(n): with self.subTest(series_index=index): result = sdc_func(series_data, index) result_ref = test_impl(series_data, index) pd.testing.assert_series_equal(result, result_ref) def test_indexes_get_series_index(self): def test_impl(S): return S.index sdc_func = self.jit(test_impl) n = 11 for index in _generate_index_param_values(n): with self.subTest(series_index=index): S = pd.Series(np.ones(n), index=index) result = sdc_func(S) result_ref = test_impl(S) self.assert_indexes_equal(result, result_ref) def test_indexes_unbox_df_with_index(self): @self.jit def test_impl(df): # TO-DO: this actually includes calling 'index' attribute overload, should really be df._index, # but this requires separate type (e.g. PositionalIndexType) instead of types.none as default index return df.index n = 11 for index in _generate_index_param_values(n): expected_res = pd.RangeIndex(n) if index is None else index with self.subTest(df_index=index): df = pd.DataFrame({'A': np.ones(n), 'B': np.arange(n)}, index=index) result = test_impl(df) self.assert_indexes_equal(result, expected_res) def test_indexes_create_df_with_index(self): @self.jit def test_impl(A, B, index): df = pd.DataFrame({'A': A, 'B': B}, index=index) return df.index n = 11 A, B = np.ones(n), np.arange(n) for index in _generate_index_param_values(n): expected_res = pd.RangeIndex(n) if index is None else index with self.subTest(df_index=index): result = test_impl(A, B, index) self.assert_indexes_equal(result, expected_res) def test_indexes_box_df_with_index(self): def test_impl(A, B, index): return pd.DataFrame({'A': A, 'B': B}, index=index) sdc_func = self.jit(test_impl) n = 11 A, B = np.ones(n), np.arange(n, dtype=np.intp) for index in _generate_index_param_values(n): with self.subTest(df_index=index): result = sdc_func(A, B, index) result_ref = test_impl(A, B, index) pd.testing.assert_frame_equal(result, result_ref) def test_indexes_get_df_index(self): def test_impl(df): return df.index sdc_func = self.jit(test_impl) n = 11 for index in _generate_index_param_values(n): with self.subTest(df_index=index): df = pd.DataFrame({'A': np.ones(n)}, index=index) result = sdc_func(df) result_ref = test_impl(df) self.assert_indexes_equal(result, result_ref) def test_indexes_support_numpy_like_take_by(self): """ Verifies numpy_like.take can handle SDC index types as indices """ from sdc.functions import numpy_like def pyfunc(arr, index): return np.take(arr, index) @self.jit def sdc_func(arr, index): return numpy_like.take(arr, index) n, k = 1000, 200 np.random.seed(0) arr = np.arange(n) * 2 indexes_to_test = [ get_sample_index(k, PositionalIndexType), get_sample_index(k, RangeIndexType), get_sample_index(k, Int64IndexType), ] for index in indexes_to_test: with self.subTest(index=index): result = sdc_func(arr, index) result_ref = pyfunc(arr, index) np.testing.assert_array_equal(result, result_ref) def test_indexes_support_series_operator_add(self): def test_impl(data, index1, index2): S1 = pd.Series(data, index=index1) S2 = pd.Series(2 * data + 1, index=index2) return S1 + S2 sdc_func = self.jit(test_impl) n = 11 series_data = np.arange(n, dtype=np.float64) index_params_to_test = [ None, pd.RangeIndex(0, -n, -1), pd.Int64Index(np.arange(n) * 2), ] for index1, index2 in product(index_params_to_test, repeat=2): with self.subTest(index1=index1, index2=index2): result = sdc_func(series_data, index1, index2) result_ref = test_impl(series_data, index1, index2) pd.testing.assert_series_equal(result, result_ref, check_dtype=False) def test_indexes_support_series_operator_lt(self): def test_impl(data, index1, index2): S1 = pd.Series(data, index=index1) S2 = pd.Series(2 * data + 1, index=index2) return S1 < S2 sdc_func = self.jit(test_impl) n = 11 series_data = np.arange(n, dtype=np.float64) index_params_to_test = [ None, pd.RangeIndex(0, -n, -1), pd.Int64Index(np.arange(n) * 2), ] for index1 in index_params_to_test: index2 = index1 with self.subTest(index1=index1, index2=index2): result = sdc_func(series_data, index1, index2) result_ref = test_impl(series_data, index1, index2) pd.testing.assert_series_equal(result, result_ref, check_dtype=False) def test_indexes_support_series_reindexing(self): from sdc.datatypes.common_functions import sdc_reindex_series def pyfunc(data, index, name, by_index): S = pd.Series(data, index, name=name) return S.reindex(by_index) @self.jit def sdc_func(data, index, name, by_index): return sdc_reindex_series(data, index, name, by_index) n = 17 np.random.seed(0) mask = np.random.choice([True, False], n) name = 'asdf' range_index = pd.RangeIndex(n) int64_index = pd.Int64Index(np.random.choice(range_index.values, n, replace=False)) indexes_combinations = [ (range_index, range_index), (range_index, range_index[::-1]), (range_index[::-1], range_index), (range_index, int64_index), (int64_index, range_index), ] for index1, index2 in indexes_combinations: with self.subTest(index1=index1, index2=index2): result = sdc_func(mask, index1, name, index2) result_ref = pyfunc(mask, index1, name, index2) pd.testing.assert_series_equal(result, result_ref) if __name__ == "__main__": unittest.main()
6,963
310
from abc import ABCMeta import numpy as np from deslib.base import BaseDS from deslib.util.aggregation import (aggregate_proba_ensemble_weighted, sum_votes_per_class, get_weighted_votes) class BaseDES(BaseDS): """Base class for a Dynamic Ensemble Selection (DES). All dynamic ensemble selection techniques should inherit from this class. Warning: This class should not be instantiated directly, use derived classes instead. """ __metaclass__ = ABCMeta def __init__(self, pool_classifiers=None, k=7, DFP=False, with_IH=False, safe_k=None, IH_rate=0.30, mode='selection', voting='hard', needs_proba=False, random_state=None, knn_classifier='knn', knne=False, DSEL_perc=0.5, n_jobs=-1): super(BaseDES, self).__init__(pool_classifiers=pool_classifiers, k=k, DFP=DFP, with_IH=with_IH, safe_k=safe_k, IH_rate=IH_rate, needs_proba=needs_proba, random_state=random_state, knn_classifier=knn_classifier, knne=knne, DSEL_perc=DSEL_perc, n_jobs=n_jobs) self.mode = mode self.voting = voting def classify_with_ds(self, predictions, probabilities=None, competence_region=None, distances=None, DFP_mask=None): """Predicts the label of the corresponding query sample. If self.mode == "selection", the selected ensemble is combined using the majority voting rule If self.mode == "weighting", all base classifiers are used for classification, however their influence in the final decision are weighted according to their estimated competence level. The weighted majority voting scheme is used to combine the decisions of the base classifiers. If self.mode == "hybrid", A hybrid Dynamic selection and weighting approach is used. First an ensemble with the competent base classifiers are selected. Then, their decisions are aggregated using the weighted majority voting rule according to its competence level estimates. Parameters ---------- predictions : array of shape (n_samples, n_classifiers) Predictions of the base classifier for all test examples. probabilities : array of shape (n_samples, n_classifiers, n_classes) Probabilities estimates of each base classifier for all test examples. (For methods that always require probabilities from the base classifiers). competence_region : array of shape (n_samples, n_neighbors) Indices of the k nearest neighbors according for each test sample. distances : array of shape (n_samples, n_neighbors) Distances from the k nearest neighbors to the query DFP_mask : array of shape (n_samples, n_classifiers) Mask containing 1 for the selected base classifier and 0 otherwise. Returns ------- predicted_label : array of shape (n_samples) Predicted class label for each test example. """ probas = self.predict_proba_with_ds(predictions, probabilities, competence_region, distances, DFP_mask) return probas.argmax(axis=1) def predict_proba_with_ds(self, predictions, probabilities=None, competence_region=None, distances=None, DFP_mask=None): """Predicts the posterior probabilities of the corresponding query. If self.mode == "selection", the selected ensemble is used to estimate the probabilities. The average rule is used to give probabilities estimates. If self.mode == "weighting", all base classifiers are used for estimating the probabilities, however their influence in the final decision are weighted according to their estimated competence level. A weighted average method is used to give the probabilities estimates. If self.mode == "Hybrid", A hybrid Dynamic selection and weighting approach is used. First an ensemble with the competent base classifiers are selected. Then, their decisions are aggregated using a weighted average rule to give the probabilities estimates. Parameters ---------- predictions : array of shape (n_samples, n_classifiers) Predictions of the base classifier for all test examples. probabilities : array of shape (n_samples, n_classifiers, n_classes) Probabilities estimates of each base classifier for all samples. competence_region : array of shape (n_samples, n_neighbors) Indices of the k nearest neighbors. distances : array of shape (n_samples, n_neighbors) Distances from the k nearest neighbors to the query DFP_mask : array of shape (n_samples, n_classifiers) Mask containing 1 for the selected base classifier and 0 otherwise. Returns ------- predicted_proba : array = [n_samples, n_classes] The probability estimates for all test examples. """ if self.needs_proba: competences = self.estimate_competence_from_proba( neighbors=competence_region, distances=distances, probabilities=probabilities) else: competences = self.estimate_competence( competence_region=competence_region, distances=distances, predictions=predictions) if self.DFP: # FIRE-DES pruning. competences = competences * DFP_mask if self.mode == "selection": predicted_proba = self._dynamic_selection(competences, predictions, probabilities) elif self.mode == "weighting": predicted_proba = self._dynamic_weighting(competences, predictions, probabilities) else: predicted_proba = self._hybrid(competences, predictions, probabilities) return predicted_proba def _dynamic_selection(self, competences, predictions, probabilities): """ Combine models using dynamic ensemble selection. """ selected_classifiers = self.select(competences) if self.voting == 'hard': votes = np.ma.MaskedArray(predictions, ~selected_classifiers) votes = sum_votes_per_class(votes, self.n_classes_) predicted_proba = votes / votes.sum(axis=1)[:, None] else: masked_proba = self._mask_proba(probabilities, selected_classifiers) predicted_proba = np.mean(masked_proba, axis=1) return predicted_proba def _dynamic_weighting(self, competences, predictions, probabilities): """ Combine models using dynamic weighting. """ if self.voting == 'hard': w_votes, _ = get_weighted_votes(predictions, competences, np.arange(self.n_classes_)) predicted_proba = w_votes / w_votes.sum(axis=1)[:, None] else: predicted_proba = aggregate_proba_ensemble_weighted( probabilities, competences) return predicted_proba def _hybrid(self, competences, predictions, probabilities): """ Combine models using a hybrid dynamic selection + weighting. """ selected_classifiers = self.select(competences) if self.voting == 'hard': votes = np.ma.MaskedArray(predictions, ~selected_classifiers) w_votes, _ = get_weighted_votes(votes, competences, np.arange(self.n_classes_)) predicted_proba = w_votes / w_votes.sum(axis=1)[:, None] else: masked_proba = self._mask_proba(probabilities, selected_classifiers) predicted_proba = aggregate_proba_ensemble_weighted( masked_proba, competences) return predicted_proba @staticmethod def _mask_proba(probabilities, selected_classifiers): # Broadcast the selected classifiers mask # to cover the last axis (n_classes): selected_classifiers = np.expand_dims(selected_classifiers, axis=2) selected_classifiers = np.broadcast_to(selected_classifiers, probabilities.shape) masked_proba = np.ma.MaskedArray(probabilities, ~selected_classifiers) return masked_proba def _validate_parameters(self): super(BaseDES, self)._validate_parameters() if not isinstance(self.mode, str): raise TypeError( 'Parameter "mode" should be a string.' ' Currently "mode" = {}' .format(type(self.mode))) if self.mode not in ['selection', 'hybrid', 'weighting']: raise ValueError( 'Invalid value for parameter "mode".' ' "mode" should be one of these options ' '{selection, hybrid, weighting}') if self.voting not in ['soft', 'hard']: raise ValueError('Invalid value for parameter "voting".' ' "voting" should be one of these options ' '{selection, hybrid, weighting}') if self.voting == 'soft': self._check_predict_proba()
4,766
343
[ { "url": "https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#bitstrings", "description": "Getting Started guide - Bitstrings" }, { "url": "https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%3C%3C%3E%3E/1", "description": "Kernel.SpecialForms.<<>>/1" } ]
130
856
// // Copyright © 2020 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include <armnnUtils/Threads.hpp> #if defined(__linux__) #include <unistd.h> #include <sys/syscall.h> #define gettid() syscall(SYS_gettid) #elif defined(_MSC_VER) #include <common/include/WindowsWrapper.hpp> #elif defined(__APPLE__) #include "AvailabilityMacros.h" #include <pthread.h> #include <sys/syscall.h> #include <sys/time.h> #include <unistd.h> #endif namespace armnnUtils { namespace Threads { int GetCurrentThreadId() { #if defined(__linux__) return static_cast<int>(gettid()); #elif defined(_MSC_VER) return ::GetCurrentThreadId(); #elif defined(__APPLE__) uint64_t threadId; int iRet = pthread_threadid_np(NULL, &threadId); if (iRet != 0) { return 0; } return static_cast<int>(threadId); #endif } } }
358
1,431
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hwpf.usermodel; import java.util.HashMap; import java.util.Map; import org.apache.poi.hwpf.model.NotesTables; /** * Default implementation of {@link Notes} interface */ public class NotesImpl implements Notes { private Map<Integer, Integer> anchorToIndexMap; private final NotesTables notesTables; public NotesImpl( NotesTables notesTables ) { this.notesTables = notesTables; } public int getNoteAnchorPosition( int index ) { return notesTables.getDescriptor( index ).getStart(); } public int getNoteIndexByAnchorPosition( int anchorPosition ) { updateAnchorToIndexMap(); Integer index = anchorToIndexMap .get( Integer.valueOf( anchorPosition ) ); if ( index == null ) return -1; return index.intValue(); } public int getNotesCount() { return notesTables.getDescriptorsCount(); } public int getNoteTextEndOffset( int index ) { return notesTables.getTextPosition( index ).getEnd(); } public int getNoteTextStartOffset( int index ) { return notesTables.getTextPosition( index ).getStart(); } private void updateAnchorToIndexMap() { if ( anchorToIndexMap != null ) return; Map<Integer, Integer> result = new HashMap<>(); for ( int n = 0; n < notesTables.getDescriptorsCount(); n++ ) { int anchorPosition = notesTables.getDescriptor( n ).getStart(); result.put( Integer.valueOf( anchorPosition ), Integer.valueOf( n ) ); } this.anchorToIndexMap = result; } }
876
488
#pragma once #include <boost/bind.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/make_shared.hpp> #include "widgets.h" using namespace dbglog; namespace fuse { // Wrapper for boost:shared_ptr<Type> that can be used as keys in maps because it wraps comparison // operations by forwarding them to the Type's own comparison operations. In contrast, the base // boost::shared_ptr uses pointer equality. template <class Type> class CompSharedPtr : public dbglog::printable { //public: boost::shared_ptr<Type> ptr; public: CompSharedPtr() {} // Wraps a raw pointer of an object that has a dynamic copying method with a comparable shared pointer CompSharedPtr(Type* p) { Type* c = dynamic_cast<Type*>(p->copy()); assert(c); ptr = boost::shared_ptr<Type>(c); } // Copy constructor CompSharedPtr(const CompSharedPtr<Type>& o) : ptr(o.ptr) {} // Constructor for converting across CompSharedPtr wrappers of compatible types template <class OtherType> CompSharedPtr(const CompSharedPtr<OtherType>& o) : ptr(boost::static_pointer_cast<Type>(o.ptr)) {} // Constructor for wrapping boost::shared_ptr with a CompoSharedPtr CompSharedPtr(boost::shared_ptr<Type> ptr) : ptr(ptr) {} template <class OtherType> CompSharedPtr(boost::shared_ptr<OtherType> ptr) : ptr(boost::static_pointer_cast<Type>(ptr)) {} template <class OtherType> friend class CompSharedPtr; CompSharedPtr& operator=(const CompSharedPtr& o) { ptr = o.ptr; return *this; } // If both ptr and o.ptr are != NULL, use their equality operator // If both ptr and o.ptr are == NULL, they are equal // If only one is == NULL but the other is not, order the NULL object as < the non-NULL object bool operator==(const CompSharedPtr<Type> & o) const { if(ptr.get()!=NULL) { if(o.get()!=NULL) return (*ptr.get()) == o; else return false; } else { if(o.get()!=NULL) return false; else return true; } } bool operator< (const CompSharedPtr<Type> & o) const { if(ptr.get()!=NULL) { if(o.get()!=NULL) return (*ptr.get()) < o; else return false; } else { if(o.get()!=NULL) return true; else return false; } } bool operator!=(const CompSharedPtr<Type> & o) const { if(ptr.get()!=NULL) { if(o.get()!=NULL) return (*ptr.get()) != o; else return true; } else { if(o.get()!=NULL) return true; else return false; } } bool operator>=(const CompSharedPtr<Type> & o) const { if(ptr.get()!=NULL) { if(o.get()!=NULL) return (*ptr.get()) >= o; else return true; } else { if(o.get()!=NULL) return false; else return true; } } bool operator<=(const CompSharedPtr<Type> & o) const { if(ptr.get()!=NULL) { if(o.get()!=NULL) return (*ptr.get()) <= o; else return false; } else { if(o.get()!=NULL) return true; else return true; } } bool operator> (const CompSharedPtr<Type> & o) const { if(ptr.get()!=NULL) { if(o.get()!=NULL) return (*ptr.get()) > o; else return true; } else { if(o.get()!=NULL) return false; else return false; } } Type* get() const { return ptr.get(); } const Type* operator->() const { return ptr.get(); } Type* operator->() { return ptr.get(); } operator bool() const { return (bool) ptr.get(); } //PartPtr operator * () { return ptr; } std::string str(std::string indent="") { return ptr->str(indent); } }; // Returns a new instance of a CompSharedPtr that refers to an instance of CompSharedPtr<Type> // GB 2012-09-21: We have created an instance of this function for cases with 0-9 input parameters since that is // what boost::make_shared provides when the compiler doesn't support varyadic types. Support for // varyadic types is future work. template <class Type> CompSharedPtr<Type> makePtr() { return boost::make_shared<Type>(); } template <class Type, class Arg1> CompSharedPtr<Type> makePtr(const Arg1& arg1) { return boost::make_shared<Type>(arg1); } template <class Type, class Arg1, class Arg2> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2) { return boost::make_shared<Type>(arg1, arg2); } template <class Type, class Arg1, class Arg2, class Arg3> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3) { return boost::make_shared<Type>(arg1, arg2, arg3); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4, arg5); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4, arg5, arg6); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4, arg5, arg6, arg7); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8, class Arg9> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8, class Arg9, class Arg10> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9, const Arg10& arg10) { return boost::make_shared<Type>(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8, class Arg9, class Arg10, class Arg11> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9, const Arg10& arg10, const Arg11& arg11) { return boost::shared_ptr<Type>(new Type(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11)); } template <class Type, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8, class Arg9, class Arg10, class Arg11, class Arg12> CompSharedPtr<Type> makePtr(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9, const Arg10& arg10, const Arg11& arg11, const Arg12& arg12) { return boost::shared_ptr<Type>(new Type(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12)); } // Wrapper for boost::dynamic_pointer_cast for CompSharedPtr // Used as: dynamicPtrCast<SomePartImplementation>(objectWithPartPtrType); template <class TargetType, class SourceType> CompSharedPtr<TargetType> dynamicPtrCast(CompSharedPtr<SourceType> s) { if(dynamic_cast<TargetType*>(s.get())) return CompSharedPtr<TargetType>(s); else { CompSharedPtr<TargetType> null; return null; } } template <class TargetType, class SourceType> const CompSharedPtr<TargetType> dynamicConstPtrCast(CompSharedPtr<SourceType> s) { if(dynamic_cast<const TargetType*>(s.get())) return CompSharedPtr<TargetType>(s); else { CompSharedPtr<TargetType> null; return null; } } template <class TargetType, class SourceType> CompSharedPtr<TargetType> staticPtrCast(const CompSharedPtr<SourceType> s) { if(static_cast<TargetType*>(s.get())) return CompSharedPtr<TargetType>(s); else { CompSharedPtr<TargetType> null; return null; } } template <class TargetType, class SourceType> const CompSharedPtr<TargetType> staticConstPtrCast(const CompSharedPtr<SourceType> s) { if(static_cast<const TargetType*>(s.get())) return CompSharedPtr<TargetType>(s); else { CompSharedPtr<TargetType> null; return null; } } // Wrapper for boost::make_shared_from_this. // Used as: makePtrFromThis(make_shared_from_this()); template <class Type> CompSharedPtr<Type> makePtrFromThis(boost::shared_ptr<Type> s) { return CompSharedPtr<Type>(s); } // Initializes a shared pointer from a raw pointer template <class Type> CompSharedPtr<Type> initPtr(Type* p) { return CompSharedPtr<Type>(p); } }; // namespace fuse
3,316
5,139
{ "source" : "czm_material czm_getMaterial(czm_materialInput m) { return czm_getDefaultMaterial(m); }" }
40
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef X2C_HEAP_HXX #define X2C_HEAP_HXX #include "sistr.hxx" class HeapItem; class Heap { public: Heap( unsigned i_nWidth ); ~Heap(); void InsertValue( const char * i_sKey, const char * i_sValue ); HeapItem * ReleaseTop(); /// @return must be deleted by caller of method. private: typedef HeapItem * Column; void IncColumn(); Column & ActiveColumn() { return dpColumnsArray[nActiveColumn]; } Column * dpColumnsArray; unsigned nColumnsArraySize; unsigned nActiveColumn; }; class HeapItem { public: HeapItem( const char * i_sKey, const char * i_sValue ); ~HeapItem( ); bool operator<( const HeapItem & i_rOther ) const; bool operator<=( const HeapItem & i_rOther ) const { return ! (i_rOther < *this); } const Simstr & Value() const; const Simstr & Key() const; HeapItem * Next() const; void SetNext( HeapItem * i_pNext ); private: Simstr sValue; Simstr sKey; HeapItem * pNext; }; #endif
772
4,054
<reponame>Anlon-Burke/vespa // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /** * @author <NAME> * @date 2004/10/01 * @version $Id$ * @file conceptnet.h * @brief Concept network class definition. * */ #pragma once #include <cassert> #include <stdlib.h> #include "file.h" // for FileAccessMethod #include "fsa.h" namespace fsa { // {{{ class ConceptNet /** * @class ConceptNet * @brief Class for compact representation of a concept network. */ class ConceptNet { public: class Handle; // defined in conceptnethandle.h private: static const uint32_t MAGIC = 238579428; /**< Magic number identifying concept net files. */ static const FileAccessMethod _default_file_access_method = FILE_ACCESS_MMAP; /**< Default file access method (read/mmap). */ /** * @struct Header * @brief Concept net data file header. */ struct Header { uint32_t _magic; /**< Magic number. */ uint32_t _version; /**< Version number. (currently not used) */ uint32_t _checksum; /**< Checksum. (currently not used) */ uint32_t _index_size; /**< Size of index structure. */ uint32_t _info_size; /**< Size of info structure. */ uint32_t _catindex_size; /**< Size of category index. */ uint32_t _strings_size; /**< Size of string storage. */ uint32_t _max_freq; /**< Reseved for normalization purposes. */ uint32_t _max_cfreq; /**< Reseved for normalization purposes. */ uint32_t _max_qfreq; /**< Reseved for normalization purposes. */ uint32_t _max_sfreq; /**< Reseved for normalization purposes. */ uint32_t _max_efreq; /**< Reseved for normalization purposes. */ uint32_t _max_afreq; /**< Reseved for normalization purposes. */ uint32_t _dummy[51]; /**< Reserved. */ }; /** * @struct UnitData * @brief Unit data structure. */ struct UnitData { uint32_t _term; /**< Offset of unit string in string storage. */ uint32_t _frq; /**< Unit frequency. */ uint32_t _cfrq; /**< Frequency of the unit as complete query. */ uint32_t _qfrq; /**< Frequency of the unit as part of a query. */ uint32_t _sfrq; /**< Number of queries containing all unit terms. */ uint32_t _exts; /**< If non-zero: offset of extension info in info structure. */ uint32_t _assocs; /**< If non-zero: offset of association info in info structure. */ uint32_t _cats; /**< If non-zero: offset of category info in info structure. */ }; void *_mmap_addr; /**< mmap address, NULL is file has not been mmapped. */ size_t _mmap_length; /**< mmap length. */ FSA _unit_fsa; /**< %FSA containing the units (with hash). */ uint32_t _index_size; /**< Size of the index structure. */ UnitData *_index; /**< Pointer to the index structure in memory. */ uint32_t _info_size; /**< Size of the info structure. */ uint32_t *_info; /**< Pointer to the info structure in memory. */ uint32_t _catindex_size; /**< Size of the catergory index. */ uint32_t *_catindex; /**< Pointer to the category index in memory. */ uint32_t _strings_size; /**< Size of the string storage. */ char *_strings; /**< Pointer to the string storage in memory. */ bool _ok; /**< Flag indicating successful initialization. */ /** * @brief Reset the object. * * Resets the object to an empty %ConceptNet, and releases allocated memory. */ void reset(); /** * @brief Read the concept net data file from disk. * * @param datafile Name of the concept net data file. * @param fam File access mode (read or mmap). If not set, the * global default access mode will be used. * @return True on success. */ bool read(const char *datafile, fsa::FileAccessMethod fam = FILE_ACCESS_UNDEF); /** * @brief Unimplemented private default constructor. */ ConceptNet(); /** * @brief Unimplemented private copy constructor. */ ConceptNet(const ConceptNet&); /** * @brief Unimplemented private assignement operator. */ const ConceptNet& operator=(const ConceptNet&); public: /** * @brief Constructor. * * @param fsafile %FSA file containing the units, with a perfect has * (used for indexing the data file). * @param datafile Concept net data file. * @param fam File access mode (read or mmap). If not set, the * global default access mode will be used. */ ConceptNet(const char *fsafile, const char *datafile=NULL, FileAccessMethod fam = FILE_ACCESS_UNDEF); ConceptNet(const std::string &fsafile, const std::string &datafile, FileAccessMethod fam = FILE_ACCESS_UNDEF); /** * @brief Destructor. */ virtual ~ConceptNet(); /** * @brief Check if initialization was successful. * * @return True if the initialization of the object succeeded. */ bool isOk() const { return _ok; } /** * @brief Get the concept net %FSA. * * Get the concept net %FSA. The object continues to be owned by the * concept net. * * @return The concept net %FSA. */ const FSA& getFSA() const { assert(_ok); return _unit_fsa; } /** * @brief Look up a unit. * * Look up a unit in the concept net, and get its index. * * @param unit Unit string. * @return Index of the unit, or -1 if not found. */ int lookup(const char *unit) const; /** * @brief Look up a unit index. * * Look up a unit index in the concept net, and get the unit string. * * @param idx Unit index. * @return Pointer to the unit string, or NULL if index is out of range. */ const char * lookup(int idx) const; /** * @brief Get the unit frequency of the unit. * * @param idx Unit index. * @return Unit frequency, or -1 if the index is out of range. */ int frq(int idx) const; /** * @brief Get the unit frequency of the unit. * * @param unit Unit string. * @return Unit frequency, or -1 if the unit is not found. */ int frq(const char *unit) const; /** * @brief Get the frequency of the unit as a complete query. * * @param idx Unit index. * @return Unit-C frequency, or -1 if the index is out of range. */ int cFrq(int idx) const; /** * @brief Get the frequency of the unit as a complete query. * * @param unit Unit string. * @return Unit-C frequency, or -1 if the unit is not found. */ int cFrq(const char *unit) const; /** * @brief Get the frequency of the unit as part of a query. * * @param idx Unit index. * @return Unit-Q frequency, or -1 if the index is out of range. */ int qFrq(int idx) const; /** * @brief Get the frequency of the unit as part of a query. * * @param unit Unit string. * @return Unit-Q frequency, or -1 if the unit is not found. */ int qFrq(const char *unit) const; /** * @brief Get the frequency of queries containing all terms of the unit. * * @param idx Unit index. * @return Unit-S frequency, or -1 if the index is out of range. */ int sFrq(int idx) const; /** * @brief Get the frequency of queries containing all terms of the unit. * * @param unit Unit string. * @return Unit-Q frequency, or -1 if the unit is not found. */ int sFrq(const char *unit) const; /** * @brief Get the unit score (100.0*cFrq/qFrq). * * @param idx Unit index. * @return Unit score, or -1.0 if the index is out of range. */ double score(int idx) const; /** * @brief Get the unit score (100.0*cFrq/qFrq). * * @param unit Unit string. * @return Unit score, or -1. if the unit is not found. */ double score(const char *unit) const; /** * @brief Get the unit strength (100.0*qFrq/sFrq). * * @param idx Unit index. * @return Unit strength, or -1.0 if the index is out of range. */ double strength(int idx) const; /** * @brief Get the unit strength (100.0*qFrq/sFrq). * * @param unit Unit string. * @return Unit strength, or -1. if the unit is not found. */ double strength(const char *unit) const; /** * @brief Get the number of extensions for the unit. * * @param idx Unit index. * @return Number of extensions for the unit, -1 if the index is out * of range. */ int numExt(int idx) const; /** * @brief Get the number of associations for the unit. * * @param idx Unit index. * @return Number of associations for the unit, -1 if the index is out * of range. */ int numAssoc(int idx) const; /** * @brief Get the number of categories for the unit. * * @param idx Unit index. * @return Number of categories for the unit, -1 if the index is out * of range. */ int numCat(int idx) const; /** * @brief Get the index of an extension. * * @param idx Unit index. * @param j Number of the extension (extensions of each unit are * sorted by decreasing weight). * @return Extension (unit) index, -1 if idx or j is out * of range. */ int ext(int idx, int j) const; /** * @brief Get the frequency of an extension. * * @param idx Unit index. * @param j Number of the extension (extensions of each unit are * sorted by decreasing weight). * @return Extension frequency, -1 if idx or j is out * of range. */ int extFrq(int idx, int j) const; /** * @brief Get the index of an association. * * @param idx Unit index. * @param j Number of the association (associations of each unit are * sorted by decreasing weight). * @return Association (unit) index, -1 if idx or j is out * of range. */ int assoc(int idx, int j) const; /** * @brief Get the frequency of an association. * * @param idx Unit index. * @param j Number of the association (associations of each unit are * sorted by decreasing weight). * @return Association frequency, -1 if idx or j is out * of range. */ int assocFrq(int idx, int j) const; /** * @brief Get the index of a category. * * @param idx Unit index. * @param j Number of the category. * @return Catergory index, -1 if idx or j is out of range. */ int cat(int idx, int j) const; /** * @brief Get the name of a category. * * @param catIdx Category index. * @return Catergory name, or NULL if catIdx is out of range. */ const char *catName(int catIdx) const; }; // }}} } // namespace fsa
4,384
577
<filename>bugtests/test354.py """ [ 522423 ] cStringIO has no reset() method """ import support import cStringIO s = cStringIO.StringIO("abcdef") s.read(3) s.reset() support.compare(s.read(3), "abc") support.compare(s.read(3), "def")
94
335
<gh_stars>100-1000 { "word": "Drank", "definitions": [ "A drink, especially of alcohol." ], "parts-of-speech": "Noun" }
68
594
<filename>SingleSource/Regression/C/gcc-c-torture/execute/ieee/mzero5.c /* Test gcse handling of IEEE 0/-0 rules. */ static double zero = 0.0; int negzero_check (double d) { if (d == 0) return !!memcmp ((void *)&zero, (void *)&d, sizeof (double)); return 0; } int sub (double d, double e) { if (d == 0.0 && e == 0.0 && negzero_check (d) == 0 && negzero_check (e) == 0) return 1; else return 0; } int main (void) { double minus_zero = -0.0; if (sub (minus_zero, 0)) abort (); return 0; }
231
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.datacatalog.v1beta1.model; /** * Representation of a column within a schema. Columns could be nested inside other columns. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Cloud Data Catalog API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDatacatalogV1beta1ColumnSchema extends com.google.api.client.json.GenericJson { /** * Required. Name of the column. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String column; /** * Optional. Description of the column. Default value is an empty string. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * Optional. A column's mode indicates whether the values in this column are required, nullable, * etc. Only `NULLABLE`, `REQUIRED` and `REPEATED` are supported. Default mode is `NULLABLE`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String mode; /** * Optional. Schema of sub-columns. A column can have zero or more sub-columns. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDatacatalogV1beta1ColumnSchema> subcolumns; /** * Required. Type of the column. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Required. Name of the column. * @return value or {@code null} for none */ public java.lang.String getColumn() { return column; } /** * Required. Name of the column. * @param column column or {@code null} for none */ public GoogleCloudDatacatalogV1beta1ColumnSchema setColumn(java.lang.String column) { this.column = column; return this; } /** * Optional. Description of the column. Default value is an empty string. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * Optional. Description of the column. Default value is an empty string. * @param description description or {@code null} for none */ public GoogleCloudDatacatalogV1beta1ColumnSchema setDescription(java.lang.String description) { this.description = description; return this; } /** * Optional. A column's mode indicates whether the values in this column are required, nullable, * etc. Only `NULLABLE`, `REQUIRED` and `REPEATED` are supported. Default mode is `NULLABLE`. * @return value or {@code null} for none */ public java.lang.String getMode() { return mode; } /** * Optional. A column's mode indicates whether the values in this column are required, nullable, * etc. Only `NULLABLE`, `REQUIRED` and `REPEATED` are supported. Default mode is `NULLABLE`. * @param mode mode or {@code null} for none */ public GoogleCloudDatacatalogV1beta1ColumnSchema setMode(java.lang.String mode) { this.mode = mode; return this; } /** * Optional. Schema of sub-columns. A column can have zero or more sub-columns. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDatacatalogV1beta1ColumnSchema> getSubcolumns() { return subcolumns; } /** * Optional. Schema of sub-columns. A column can have zero or more sub-columns. * @param subcolumns subcolumns or {@code null} for none */ public GoogleCloudDatacatalogV1beta1ColumnSchema setSubcolumns(java.util.List<GoogleCloudDatacatalogV1beta1ColumnSchema> subcolumns) { this.subcolumns = subcolumns; return this; } /** * Required. Type of the column. * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Required. Type of the column. * @param type type or {@code null} for none */ public GoogleCloudDatacatalogV1beta1ColumnSchema setType(java.lang.String type) { this.type = type; return this; } @Override public GoogleCloudDatacatalogV1beta1ColumnSchema set(String fieldName, Object value) { return (GoogleCloudDatacatalogV1beta1ColumnSchema) super.set(fieldName, value); } @Override public GoogleCloudDatacatalogV1beta1ColumnSchema clone() { return (GoogleCloudDatacatalogV1beta1ColumnSchema) super.clone(); } }
1,727
388
<gh_stars>100-1000 """ This module defines the :class:`GenericFunction` class, which is the base for the implementation of spatial functions in GeoAlchemy. This module is also where actual spatial functions are defined. Spatial functions supported by GeoAlchemy are defined in this module. See :class:`GenericFunction` to know how to create new spatial functions. .. note:: By convention the names of spatial functions are prefixed by ``ST_``. This is to be consistent with PostGIS', which itself is based on the ``SQL-MM`` standard. Functions created by subclassing :class:`GenericFunction` can be called in several ways: * By using the ``func`` object, which is the SQLAlchemy standard way of calling a function. For example, without the ORM:: select([func.ST_Area(lake_table.c.geom)]) and with the ORM:: Session.query(func.ST_Area(Lake.geom)) * By applying the function to a geometry column. For example, without the ORM:: select([lake_table.c.geom.ST_Area()]) and with the ORM:: Session.query(Lake.geom.ST_Area()) * By applying the function to a :class:`geoalchemy2.elements.WKBElement` object (:class:`geoalchemy2.elements.WKBElement` is the type into which GeoAlchemy converts geometry values read from the database), or to a :class:`geoalchemy2.elements.WKTElement` object. For example, without the ORM:: conn.scalar(lake['geom'].ST_Area()) and with the ORM:: session.scalar(lake.geom.ST_Area()) Reference --------- """ import re from sqlalchemy import inspect from sqlalchemy.sql import functions from sqlalchemy.sql.elements import ColumnElement from sqlalchemy.ext.compiler import compiles from sqlalchemy.util import with_metaclass from . import elements from ._functions import _FUNCTIONS class _GenericMeta(functions._GenericMeta): """Extend the metaclass mechanism of sqlalchemy to register the functions in a specific registry for geoalchemy2""" _register = False def __init__(cls, clsname, bases, clsdict): # Register the function elements.function_registry.add(clsname.lower()) super(_GenericMeta, cls).__init__(clsname, bases, clsdict) class TableRowElement(ColumnElement): def __init__(self, selectable): self.selectable = selectable @property def _from_objects(self): return [self.selectable] class ST_AsGeoJSON(with_metaclass(_GenericMeta, functions.GenericFunction)): """Special process for the ST_AsGeoJSON() function to be able to work with its feature version introduced in PostGIS 3.""" name = "ST_AsGeoJSON" def __init__(self, *args, **kwargs): expr = kwargs.pop('expr', None) args = list(args) if expr is not None: args = [expr] + args for idx, element in enumerate(args): if isinstance(element, functions.Function): continue elif isinstance(element, elements.HasFunction): if element.extended: func_name = element.geom_from_extended_version func_args = [element.data] else: func_name = element.geom_from func_args = [element.data, element.srid] args[idx] = getattr(functions.func, func_name)(*func_args) else: try: insp = inspect(element) if hasattr(insp, "selectable"): args[idx] = TableRowElement(insp.selectable) except Exception: continue functions.GenericFunction.__init__(self, *args, **kwargs) __doc__ = ( 'Return the geometry as a GeoJSON "geometry" object, or the row as a ' 'GeoJSON feature" object (PostGIS 3 only). (Cf GeoJSON specifications RFC ' '7946). 2D and 3D Geometries are both supported. GeoJSON only support SFS ' '1.1 geometry types (no curve support for example). ' 'See https://postgis.net/docs/ST_AsGeoJSON.html') @compiles(TableRowElement) def _compile_table_row_thing(element, compiler, **kw): # In order to get a name as reliably as possible, noting that some # SQL compilers don't say "table AS name" and might not have the "AS", # table and alias names can have spaces in them, etc., get it from # a column instead because that's what we want to be showing here anyway. compiled = compiler.process(list(element.selectable.columns)[0], **kw) # 1. check for exact name of the selectable is here, use that. # This way if it has dots and spaces and anything else in it, we # can get it w/ correct quoting schema = getattr(element.selectable, "schema", "") name = element.selectable.name pattern = r"(.?%s.?\.)?(.?%s.?)\." % (schema, name) m = re.match(pattern, compiled) if m: return m.group(2) # 2. just split on the dot, assume anonymized name return compiled.split(".")[0] class GenericFunction(with_metaclass(_GenericMeta, functions.GenericFunction)): """ The base class for GeoAlchemy functions. This class inherits from ``sqlalchemy.sql.functions.GenericFunction``, so functions defined by subclassing this class can be given a fixed return type. For example, functions like :class:`ST_Buffer` and :class:`ST_Envelope` have their ``type`` attributes set to :class:`geoalchemy2.types.Geometry`. This class allows constructs like ``Lake.geom.ST_Buffer(2)``. In that case the ``Function`` instance is bound to an expression (``Lake.geom`` here), and that expression is passed to the function when the function is actually called. If you need to use a function that GeoAlchemy does not provide you will certainly want to subclass this class. For example, if you need the ``ST_TransScale`` spatial function, which isn't (currently) natively supported by GeoAlchemy, you will write this:: from geoalchemy2 import Geometry from geoalchemy2.functions import GenericFunction class ST_TransScale(GenericFunction): name = 'ST_TransScale' type = Geometry """ # Set _register to False in order not to register this class in # sqlalchemy.sql.functions._registry. Only its children will be registered. _register = False def __init__(self, *args, **kwargs): expr = kwargs.pop('expr', None) args = list(args) if expr is not None: args = [expr] + args for idx, elem in enumerate(args): if isinstance(elem, elements.HasFunction): if elem.extended: func_name = elem.geom_from_extended_version func_args = [elem.data] else: func_name = elem.geom_from func_args = [elem.data, elem.srid] args[idx] = getattr(functions.func, func_name)(*func_args) functions.GenericFunction.__init__(self, *args, **kwargs) # Iterate through _FUNCTIONS and create GenericFunction classes dynamically for name, type_, doc in _FUNCTIONS: attributes = {'name': name} docs = [] if isinstance(doc, tuple): docs.append(doc[0]) docs.append('see http://postgis.net/docs/{0}.html'.format(doc[1])) elif doc is not None: docs.append(doc) docs.append('see http://postgis.net/docs/{0}.html'.format(name)) if type_ is not None: attributes['type'] = type_ type_str = '{0}.{1}'.format(type_.__module__, type_.__name__) docs.append('Return type: :class:`{0}`.'.format(type_str)) if len(docs) != 0: attributes['__doc__'] = '\n\n'.join(docs) globals()[name] = type(name, (GenericFunction,), attributes) # # Define compiled versions for functions in SpatiaLite whose names don't have # the ST_ prefix. # _SQLITE_FUNCTIONS = { "ST_GeomFromEWKT": "GeomFromEWKT", "ST_GeomFromEWKB": "GeomFromEWKB", "ST_AsBinary": "AsBinary", "ST_AsEWKB": "AsEWKB", "ST_AsGeoJSON": "AsGeoJSON", } # Default handlers are required for SQLAlchemy < 1.1 # See more details in https://github.com/geoalchemy/geoalchemy2/issues/213 def _compiles_default(cls): def _compile_default(element, compiler, **kw): return "{}({})".format(cls, compiler.process(element.clauses, **kw)) compiles(globals()[cls])(_compile_default) def _compiles_sqlite(cls, fn): def _compile_sqlite(element, compiler, **kw): return "{}({})".format(fn, compiler.process(element.clauses, **kw)) compiles(globals()[cls], "sqlite")(_compile_sqlite) for cls, fn in _SQLITE_FUNCTIONS.items(): _compiles_default(cls) _compiles_sqlite(cls, fn)
3,405