max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,102
// RUN: %clang_cc1 -fsyntax-only -verify %s // expected-no-diagnostics extern "C" { extern "C++" { template<class C> C x(); } }
54
1,447
package com.kofigyan.stateprogressbarsample; import android.app.Activity; import android.support.v4.content.ContextCompat; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.kofigyan.stateprogressbar.StateProgressBar; import com.kofigyan.stateprogressbar.components.StateItem; import com.kofigyan.stateprogressbar.listeners.OnStateItemClickListener; /** * Created by <NAME> on 7/22/2016. */ public abstract class BaseActivity extends Activity { protected StateProgressBar stateProgressBar; @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); stateProgressBar = (StateProgressBar) findViewById(R.id.state_progress_bar); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_base, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (stateProgressBar == null) return false; switch (item.getItemId()) { case R.id.color: stateProgressBar.setForegroundColor(ContextCompat.getColor(this, R.color.demo_state_foreground_color)); stateProgressBar.setBackgroundColor(ContextCompat.getColor(this, android.R.color.darker_gray)); stateProgressBar.setStateNumberForegroundColor(ContextCompat.getColor(this, android.R.color.white)); stateProgressBar.setStateNumberBackgroundColor(ContextCompat.getColor(this, android.R.color.background_dark)); break; case R.id.size: stateProgressBar.setStateSize(40f); stateProgressBar.setStateNumberTextSize(20f); break; case R.id.animation: stateProgressBar.enableAnimationToCurrentState(true); break; case R.id.line_thickness: stateProgressBar.setStateLineThickness(10f); break; case R.id.current_state: if (stateProgressBar.getMaxStateNumber() >= StateProgressBar.StateNumber.TWO.getValue()) stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO); else Toast.makeText(getApplicationContext() , getResources().getString(R.string.max_error_message) , Toast.LENGTH_LONG).show(); break; case R.id.max_state: if (stateProgressBar.getCurrentStateNumber() <= StateProgressBar.StateNumber.FOUR.getValue()) stateProgressBar.setMaxStateNumber(StateProgressBar.StateNumber.FOUR); else Toast.makeText(getApplicationContext() , getResources().getString(R.string.max_error_message) , Toast.LENGTH_LONG).show(); break; case R.id.check_state_completed: stateProgressBar.checkStateCompleted(Boolean.TRUE); break; case R.id.enable_all_states_completed: stateProgressBar.setAllStatesCompleted(Boolean.TRUE); break; } return true; } }
1,382
356
<filename>examples/eigenstate solver examples/2D_harmonic_oscillator_magneticfield.py import numpy as np from qmsolve import Hamiltonian, SingleParticle, init_visualization, Å, T , eV #========================================================================================================================================================================== # This example computes the eigenstates of a charged particle in a magnetic field Bz, that points in the z direction. # # Notes: # The example requires to use potential_type = "matrix" in the Hamiltonian constructor, # which allows to use momentum operators (px and py) in the potential term # particle.x, particle.px , particle.y, particle.py, are treated as operators, and they are discretized as matrices. Therefore, for multiplying them, # we use the @ instead of *, because this is the operator that represents matrix multiplication. #========================================================================================================================================================================== #interaction potential def harmonic_and_magnetic_interaction(particle): kx = 2 * 1e-6 ky = 2 * 1e-6 harmonic_interaction = 0.5 * kx * particle.x **2 + 0.5 * ky * particle.y **2 Bz = 30 * T B_dot_L = Bz*(-particle.px @ particle.y + particle.py @ particle.x) 𝜇 = 0.5 # e/(2*m_e) paramagnetic_term = -𝜇 * B_dot_L d = 0.125 # e**2/(8*m_e) diamagnetic_term = d* Bz**2 *(particle.x**2 + particle.y**2) magnetic_interaction = diamagnetic_term + paramagnetic_term return magnetic_interaction + harmonic_interaction H = Hamiltonian(particles = SingleParticle(), potential = harmonic_and_magnetic_interaction, potential_type = "matrix", spatial_ndim = 2, N = 400, extent = 250 * Å) eigenstates = H.solve(max_states = 28) print(eigenstates.energies) visualization = init_visualization(eigenstates) visualization.animate()
594
1,546
<gh_stars>1000+ ///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // unless required by applicable law or agreed to in writing, software distributed under the // license is distributed on an "as is" basis, without warranties or conditions of any kind, // either express or implied. see the license for the specific language governing permissions // and limitations under the license. // ///////////////////////////////////////////////////////////////////////////////////////////////// #include "ContentCache.h" #include "rendering/graphics/Picture.h" namespace pag { ContentCache::ContentCache(Layer* layer) : FrameCache<Content>(layer->startTime, layer->duration), layer(layer) { } void ContentCache::update() { staticTimeRanges = {layer->visibleRange()}; excludeVaryingRanges(&staticTimeRanges); staticTimeRanges = OffsetTimeRanges(staticTimeRanges, -layer->startTime); _contentStatic = !HasVaryingTimeRange(&staticTimeRanges, 0, layer->duration); _hasFilters = (!layer->effects.empty() || !layer->layerStyles.empty() || layer->motionBlur); // 理论上当图层的matrix带了缩放时也不能缓存,会导致图层样式也会跟着缩放。但目前投影等滤镜的效果看起来区别不明显,性能优化考虑暂时忽略。 _cacheFilters = _hasFilters && checkCacheFilters(); if (_cacheFilters) { _cacheEnabled = true; } else { _cacheEnabled = checkCacheEnabled(); } } bool ContentCache::checkCacheFilters() { bool varyingLayerStyle = false; bool varyingEffect = false; bool processVisibleAreaOnly = true; if (!layer->layerStyles.empty()) { std::vector<TimeRange> timeRanges = {layer->visibleRange()}; for (auto& layerStyle : layer->layerStyles) { layerStyle->excludeVaryingRanges(&timeRanges); } timeRanges = OffsetTimeRanges(timeRanges, -layer->startTime); varyingLayerStyle = HasVaryingTimeRange(&timeRanges, 0, layer->duration); } if (!layer->effects.empty()) { std::vector<TimeRange> timeRanges = {layer->visibleRange()}; for (auto& effect : layer->effects) { effect->excludeVaryingRanges(&timeRanges); if (!effect->processVisibleAreaOnly()) { processVisibleAreaOnly = false; } } timeRanges = OffsetTimeRanges(timeRanges, -layer->startTime); varyingEffect = HasVaryingTimeRange(&timeRanges, 0, layer->duration); } // 理论上当图层的matrix带了缩放时也不能缓存,会导致图层样式也会跟着缩放。但目前投影等滤镜的效果看起来区别不明显,性能优化考虑暂时忽略。 return layer->masks.empty() && !layer->motionBlur && processVisibleAreaOnly && !varyingLayerStyle && !varyingEffect; } bool ContentCache::checkCacheEnabled() { auto cacheEnabled = false; if (layer->cachePolicy != CachePolicy::Auto) { cacheEnabled = layer->cachePolicy == CachePolicy::Enable; } else if (!layer->effects.empty() || !layer->layerStyles.empty() || layer->motionBlur) { // 滤镜不缓存到纹理内,但含有滤镜每帧的输入都要求是纹理,开启纹理缓存的性能会更高。 cacheEnabled = true; } else { // PreComposeLayer 和 ImageLayer 在 createContent() 时会创建 // Image,不需要上层额外判断是否需要缓存。 if (layer->type() == LayerType::Text || layer->type() == LayerType::Shape) { auto staticContent = !HasVaryingTimeRange(getStaticTimeRanges(), 0, layer->duration); cacheEnabled = staticContent && layer->duration > 1; } } return cacheEnabled; } Content* ContentCache::createCache(Frame layerFrame) { auto content = createContent(layerFrame); if (_cacheFilters) { auto filterModifier = FilterModifier::Make(layer, layerFrame); content->graphic = Graphic::MakeCompose(content->graphic, filterModifier); } if (_cacheEnabled) { content->graphic = Picture::MakeFrom(getCacheID(), content->graphic); } return content; } } // namespace pag
1,605
4,036
namespace stmtexpr { class C { public: C(int x); ~C(); }; void f(int b) { int i; if (({ C c(1); b; })) 2; else ; } void g(int b) { void *ptr; int i; lab: ptr = &&lab; goto *({ C c(3); ptr; }); } }
232
423
<reponame>haducloc/appslandia-plum // The MIT License (MIT) // Copyright © 2015 AppsLandia. 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, 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 com.appslandia.plum.base; import java.util.Collections; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import com.appslandia.common.base.LruMap; import com.appslandia.common.utils.AssertUtils; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> * */ @ApplicationScoped public class MemRemMeTokenManager implements RemMeTokenManager { final Map<String, RemMeToken> tokenMap = Collections.synchronizedMap(new LruMap<>(100)); @Override public void save(RemMeToken token) { this.tokenMap.put(token.getSeries(), copy(token)); } @Override public RemMeToken load(String series) { RemMeToken obj = this.tokenMap.get(series); return (obj != null) ? copy(obj) : null; } @Override public void reissue(String series, String token, long expiresAt, long issuedAt) { RemMeToken obj = this.tokenMap.get(series); AssertUtils.assertNotNull(obj); obj.setToken(token); obj.setExpiresAt(expiresAt); obj.setIssuedAt(issuedAt); } @Override public void remove(String series) { this.tokenMap.remove(series); } @Override public void removeAll(String hashIdentity) { this.tokenMap.entrySet().removeIf(e -> e.getValue().getHashIdentity().equals(hashIdentity)); } static RemMeToken copy(RemMeToken obj) { RemMeToken copy = new RemMeToken(); copy.setSeries(obj.getSeries()); copy.setToken(obj.getToken()); copy.setHashIdentity(obj.getHashIdentity()); copy.setExpiresAt(obj.getExpiresAt()); copy.setIssuedAt(obj.getIssuedAt()); return copy; } }
848
424
#ifndef TENSOR_POST_META_H #define TENSOR_POST_META_H #include "Fastor/tensor/Tensor.h" #include "Fastor/tensor_algebra/indicial.h" namespace Fastor { /* Classify/specialise Tensor<primitive> as primitive if needed. This specialisation hurts the performance of some specialised kernels like matmul/norm/LU/inv that unroll aggressively unless Tensor<T> is specialised to wrap T only */ //--------------------------------------------------------------------------------------------------------------------// // template<typename T> // struct is_primitive<Tensor<T>> { // static constexpr bool value = is_primitive_v_<T> ? true : false; // }; //--------------------------------------------------------------------------------------------------------------------// /* Find the underlying scalar type of an expression */ //--------------------------------------------------------------------------------------------------------------------// template<class T> struct scalar_type_finder { using type = T; }; template<typename T, size_t ... Rest> struct scalar_type_finder<Tensor<T,Rest...>> { using type = T; }; // This specific specialisation is needed to avoid ambiguity for vectors template<typename T, size_t N> struct scalar_type_finder<Tensor<T,N>> { using type = T; }; template<typename T, size_t ... Rest> struct scalar_type_finder<TensorMap<T,Rest...>> { using type = T; }; // This specific specialisation is needed to avoid ambiguity for vectors template<typename T, size_t N> struct scalar_type_finder<TensorMap<T,N>> { using type = T; }; template<template <class,size_t> class UnaryExpr, typename Expr, size_t DIMS> struct scalar_type_finder<UnaryExpr<Expr,DIMS>> { using type = typename scalar_type_finder<Expr>::type; }; template<template <class,class,size_t> class Expr, typename TLhs, typename TRhs, size_t DIMS> struct scalar_type_finder<Expr<TLhs,TRhs,DIMS>> { using type = typename std::conditional<is_primitive_v_<TLhs>, typename scalar_type_finder<TRhs>::type, typename scalar_type_finder<TLhs>::type>::type; }; template<template<typename,typename,typename,size_t> class TensorFixedViewExpr, typename Expr, typename Seq0, typename Seq1, size_t DIMS> struct scalar_type_finder<TensorFixedViewExpr<Expr,Seq0,Seq1,DIMS>> { using type = typename scalar_type_finder<Expr>::type; }; template<template<typename,size_t...> class TensorType, typename T, size_t ...Rest, typename ... Fseqs> struct scalar_type_finder<TensorConstFixedViewExprnD<TensorType<T,Rest...>,Fseqs...>> { using type = T; }; template<template<typename,size_t...> class TensorType, typename T, size_t ...Rest, typename ... Fseqs> struct scalar_type_finder<TensorFixedViewExprnD<TensorType<T,Rest...>,Fseqs...>> { using type = T; }; //--------------------------------------------------------------------------------------------------------------------// /* Find the underlying tensor type of an expression */ //--------------------------------------------------------------------------------------------------------------------// template<class X> struct tensor_type_finder { using type = Tensor<X>; }; template<typename T, size_t ... Rest> struct tensor_type_finder<Tensor<T,Rest...>> { using type = Tensor<T,Rest...>; }; // This specific specialisation is needed to avoid ambiguity for vectors template<typename T, size_t N> struct tensor_type_finder<Tensor<T,N>> { using type = Tensor<T,N>; }; template<typename T, size_t ... Rest> struct tensor_type_finder<TensorMap<T,Rest...>> { using type = Tensor<T,Rest...>; }; // This specific specialisation is needed to avoid ambiguity for vectors template<typename T, size_t N> struct tensor_type_finder<TensorMap<T,N>> { using type = Tensor<T,N>; }; template<template<typename,size_t> class UnaryExpr, typename Expr, size_t DIM> struct tensor_type_finder<UnaryExpr<Expr,DIM>> { using type = typename tensor_type_finder<Expr>::type; }; template<template<class,class,size_t> class BinaryExpr, typename TLhs, typename TRhs, size_t DIMS> struct tensor_type_finder<BinaryExpr<TLhs,TRhs,DIMS>> { using type = typename std::conditional<is_primitive_v_<TLhs>, typename tensor_type_finder<TRhs>::type, typename tensor_type_finder<TLhs>::type>::type; }; template<template<typename,typename,typename,size_t> class TensorFixedViewExpr, typename Expr, typename Seq0, typename Seq1, size_t DIMS> struct tensor_type_finder<TensorFixedViewExpr<Expr,Seq0,Seq1,DIMS>> { using type = typename tensor_type_finder<Expr>::type; }; template<template<typename,size_t...> class TensorType, typename T, size_t ...Rest, typename ... Fseqs> struct tensor_type_finder<TensorConstFixedViewExprnD<TensorType<T,Rest...>,Fseqs...>> { using type = TensorType<T,Rest...>; }; template<template<typename,size_t...> class TensorType, typename T, size_t ...Rest, typename ... Fseqs> struct tensor_type_finder<TensorFixedViewExprnD<TensorType<T,Rest...>,Fseqs...>> { using type = TensorType<T,Rest...>; }; //--------------------------------------------------------------------------------------------------------------------// /* Is an expression a tensor */ //--------------------------------------------------------------------------------------------------------------------// template<class T> struct is_tensor { static constexpr bool value = false; }; template<class T, size_t ...Rest> struct is_tensor<Tensor<T,Rest...>> { static constexpr bool value = true; }; template<typename T> constexpr bool is_tensor_v = is_tensor<T>::value; //--------------------------------------------------------------------------------------------------------------------// /* Is an expression a abstract tensor */ //--------------------------------------------------------------------------------------------------------------------// template<class T> struct is_abstracttensor { static constexpr bool value = false; }; template<class T, size_t DIMS> struct is_abstracttensor<AbstractTensor<T,DIMS>> { static constexpr bool value = true; }; template<typename T> constexpr bool is_abstracttensor_v = is_abstracttensor<T>::value; //--------------------------------------------------------------------------------------------------------------------// /* Convert a tensor to a bool tensor */ //--------------------------------------------------------------------------------------------------------------------// template <class Tens> struct to_bool_tensor; template <typename T, size_t ... Rest> struct to_bool_tensor<Tensor<T,Rest...>> { using type = Tensor<bool,Rest...>; }; template <class Tens> using to_bool_tensor_t = typename to_bool_tensor<Tens>::type; //--------------------------------------------------------------------------------------------------------------------// /* Concatenate two tensor and make a new tensor type */ //--------------------------------------------------------------------------------------------------------------------// // Do not generalise this, as it leads to all kinds of problems // with binary operator expression involving std::arithmetic template <class X, class Y, class ... Z> struct concat_tensor; template<template<typename,size_t...> class Derived0, template<typename,size_t...> class Derived1, typename T, size_t ... Rest0, size_t ... Rest1> struct concat_tensor<Derived0<T,Rest0...>,Derived1<T,Rest1...>> { using type = Tensor<T,Rest0...,Rest1...>; }; template<template<typename,size_t...> class Derived0, template<typename,size_t...> class Derived1, template<typename,size_t...> class Derived2, typename T, size_t ... Rest0, size_t ... Rest1, size_t ... Rest2> struct concat_tensor<Derived0<T,Rest0...>,Derived1<T,Rest1...>,Derived2<T,Rest2...>> { using type = Tensor<T,Rest0...,Rest1...,Rest2...>; }; template<template<typename,size_t...> class Derived0, template<typename,size_t...> class Derived1, template<typename,size_t...> class Derived2, template<typename,size_t...> class Derived3, typename T, size_t ... Rest0, size_t ... Rest1, size_t ... Rest2, size_t ... Rest3> struct concat_tensor<Derived0<T,Rest0...>,Derived1<T,Rest1...>,Derived2<T,Rest2...>,Derived3<T,Rest3...>> { using type = Tensor<T,Rest0...,Rest1...,Rest2...,Rest3...>; }; template <class X, class Y, class ... Z> using concatenated_tensor_t = typename concat_tensor<X,Y,Z...>::type; //--------------------------------------------------------------------------------------------------------------------// /* Extract the tensor dimension(s) */ //--------------------------------------------------------------------------------------------------------------------// // Return dimensions of tensor as a std::array and Index<Rest...> template<class X> struct get_tensor_dimensions; template<typename T, size_t ... Rest> struct get_tensor_dimensions<Tensor<T,Rest...>> { static constexpr std::array<size_t,sizeof...(Rest)> dims = {Rest...}; static constexpr std::array<int,sizeof...(Rest)> dims_int = {Rest...}; using tensor_to_index = Index<Rest...>; }; template<typename T, size_t ... Rest> constexpr std::array<size_t,sizeof...(Rest)> get_tensor_dimensions<Tensor<T,Rest...>>::dims; template<typename T, size_t ... Rest> constexpr std::array<int,sizeof...(Rest)> get_tensor_dimensions<Tensor<T,Rest...>>::dims_int; // Conditional get tensor dimension // Return tensor dimension if Idx is within range else return Dim template<size_t Idx, size_t Dim, class X> struct if_get_tensor_dimension; template<size_t Idx, size_t Dim, typename T, size_t ... Rest> struct if_get_tensor_dimension<Idx,Dim,Tensor<T,Rest...>> { static constexpr size_t value = (Idx < sizeof...(Rest)) ? get_value<Idx+1,Rest...>::value : 1; }; template<size_t Idx, size_t Dim, class X> static constexpr size_t if_get_tensor_dimension_v = if_get_tensor_dimension<Idx,Dim,X>::value; // Gives one if Idx is outside range template<size_t Idx, class X> static constexpr size_t get_tensor_dimension_v = if_get_tensor_dimension<Idx,1,X>::value; //--------------------------------------------------------------------------------------------------------------------// /* Find if a tensor is uniform */ //--------------------------------------------------------------------------------------------------------------------// template<class T> struct is_tensor_uniform; template<typename T, size_t ... Rest> struct is_tensor_uniform<Tensor<T,Rest...>> { static constexpr bool value = no_of_unique<Rest...>::value == 1 ? true : false; }; // helper function template<class T> static constexpr bool is_tensor_uniform_v = is_tensor_uniform<T>::value; //--------------------------------------------------------------------------------------------------------------------// /* Extract a matrix from a high order tensor */ //--------------------------------------------------------------------------------------------------------------------// // This is used in functions like determinant/inverse of high order tensors // where the last square matrix (last two dimensions) is needed. If Seq is // is the same size as dimensions of tensor, this could also be used as // generic tensor dimension extractor template<class Tens, class Seq> struct last_matrix_extracter; template<typename T, size_t ... Rest, size_t ... ss> struct last_matrix_extracter<Tensor<T,Rest...>,std_ext::index_sequence<ss...>> { static constexpr std::array<size_t,sizeof...(Rest)> dims = {Rest...}; static constexpr std::array<size_t,sizeof...(ss)> values = {dims[ss]...}; static constexpr size_t remaining_product = pack_prod<dims[ss]...>::value; using type = Tensor<T,dims[ss]...>; }; template<typename T, size_t ... Rest, size_t ... ss> constexpr std::array<size_t,sizeof...(ss)> last_matrix_extracter<Tensor<T,Rest...>,std_ext::index_sequence<ss...>>::values; //--------------------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// template <typename T, typename Idx> struct index_to_tensor; template <typename T, size_t ...Idx> struct index_to_tensor <T, Index<Idx...>> { using type = Tensor<T,Idx...>; }; // helper template <typename T, typename Idx> using index_to_tensor_t = typename index_to_tensor<T,Idx>::type; template <typename T, typename Idx> struct index_to_tensor_map; template <typename T, size_t ...Idx> struct index_to_tensor_map <T, Index<Idx...>> { using type = TensorMap<T,Idx...>; }; // helper template <typename T, typename Idx> using index_to_tensor_map_t = typename index_to_tensor_map<T,Idx>::type; //-----------------------------------------------------------------------------------------------------------// } #endif // TENSOR_POST_META_H
3,940
1,968
<gh_stars>1000+ ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// package com.ansca.corona.input; /** * Indicates the type of device that input events come from such as a keyboard, touchscreen, gamepad, etc. * <p> * Instances of this class are immutable. * <p> * You cannot create instances of this class. * Instead, you use the pre-allocated objects from this class' static methods and fields. */ public class InputDeviceType { /** Unique integer ID matching a SOURCE constant in the the Android "InputDevice" class. */ private int fAndroidSourceId; /** Corona's unique integer ID matching a constant in the C++ "InputDeviceType" class. */ private int fCoronaIntegerId; /** Corona's unique string ID matching a constant in the C++ "InputDeviceType" class. */ private String fCoronaStringId; /** Indicates that the device is of an unknown type. */ public static final InputDeviceType UNKNOWN = new InputDeviceType(0, 0, "unknown"); /** Indicates that the device is a keyboard and will provide key events. */ public static final InputDeviceType KEYBOARD = new InputDeviceType(257, 1, "keyboard"); /** Indicates that the device is a mouse and will provide mouse motion events. */ public static final InputDeviceType MOUSE = new InputDeviceType(8194, 2, "mouse"); /** Indicates that the device is a stylus and will provide touch motion events. */ public static final InputDeviceType STYLUS = new InputDeviceType(16386, 3, "stylus"); /** Indicates that the device is a trackball and will provide scroll motion events. */ public static final InputDeviceType TRACKBALL = new InputDeviceType(65540, 4, "trackball"); /** * Indicates that the device is a touchpad and will provide analog motion events. * <p> * Note that the touch coordinates provided will not be in screen coordinates. * An example of this kind of device is the touch surface at the top of an Apple Magic Mouse. */ public static final InputDeviceType TOUCHPAD = new InputDeviceType(1048584, 5, "touchpad"); /** Indicates that the device is a touchscreen and will provide touch motion events. */ public static final InputDeviceType TOUCHSCREEN = new InputDeviceType(4098, 6, "touchscreen"); /** Indicates that the device is a joystick and will provide analog motion and key events. */ public static final InputDeviceType JOYSTICK = new InputDeviceType(16777232, 7, "joystick"); /** Indicates that the device is a gamepad and will provide analog motion and key events. */ public static final InputDeviceType GAMEPAD = new InputDeviceType(1025, 8, "gamepad"); /** Indicates that the device is a direction pad and will provide key events. */ public static final InputDeviceType DPAD = new InputDeviceType(513, 9, "directionalPad"); /** Stores a collection of all known input device types. */ private static ReadOnlyInputDeviceTypeSet sTypeCollection = null; /** Static constructor. */ static { // Create a read-only collection of all pre-allocated device type via reflection. InputDeviceTypeSet collection = new InputDeviceTypeSet(); try { for (java.lang.reflect.Field field : InputDeviceType.class.getDeclaredFields()) { if (field.getType().equals(InputDeviceType.class)) { InputDeviceType deviceType = (InputDeviceType)field.get(null); if (deviceType != null) { collection.add(deviceType); } } } } catch (Exception ex) { } sTypeCollection = new ReadOnlyInputDeviceTypeSet(collection); } /** * Creates a new input device type. * @param androidSourceId Unique integer ID matching a SOURCE constant in Android class "InputDevice". * @param coronaIntegerId Corona's unique integer ID for the input device. * @param coronaStringId Corona's unique string ID for the input device. */ private InputDeviceType(int androidSourceId, int coronaIntegerId, String coronaStringId) { fAndroidSourceId = androidSourceId; fCoronaIntegerId = coronaIntegerId; fCoronaStringId = coronaStringId; } /** * Gets the unique integer ID as defined by one of the SOURCE constants in Android class InputDevice. * @return Returns a unique integer ID matching a SOURCE constant in Android class InputDevice. */ public int toAndroidSourceId() { return fAndroidSourceId; } /** * Gets Corona's unique integer ID for this device type. * @return Returns a unique integer ID used by Corona to identify the device type. */ public int toCoronaIntegerId() { return fCoronaIntegerId; } /** * Gets Corona's unique string ID for this device type such as "keyboard", "mouse", "gamepad", etc. * @return Returns a unique string ID used by Corona's input events such as "keyboard", "mouse", etc. */ public String toCoronaStringId() { return fCoronaStringId; } /** * Gets Corona's unique string ID for this device type such as "keyboard", "mouse", "gamepad", etc. * @return Returns a unique string ID used by Corona's input events in Lua. */ @Override public String toString() { return fCoronaStringId; } /** * Gets an integer hash code for this object. * @return Returns this object's hash code. */ @Override public int hashCode() { return fAndroidSourceId; } /** * Gets a read-only collection of all known input device types. * @return Returns a read-only collection of all known input device types. */ public static ReadOnlyInputDeviceTypeSet getCollection() { return sTypeCollection; } /** * Fetches the type of device that the given input event came from. * @param event The motion event received from an activity or view's onTouchEvent(), onGenericMotionEvent(), * onTrackballevent(), or similar method. * @return Returns the type of input device the event came from, such as KEYBOARD or TOUCHSCREEN. * <p> * Returns null if given a null argument. * <p> * Returns the UNKNOWN type if the event's input source is not known by Corona or Android. */ public static InputDeviceType from(android.view.MotionEvent event) { // Validate argument. if (event == null) { return null; } // Fetch the device type from the given input event. InputDeviceType deviceType; if (android.os.Build.VERSION.SDK_INT >= 9) { // Fetch the device type by the event's source ID. int sourceId = ApiLevel9.getSourceIdFrom(event); deviceType = InputDeviceType.fromAndroidSourceId(sourceId); } else { // For older operating systems, we have to assume that motion events come from a touchscreen. deviceType = InputDeviceType.TOUCHSCREEN; } return deviceType; } /** * Fetches the type of device that the given input event came from. * <p> * Note that buttons on a gamepad or joystick are typically received on Android as key events. * @param event The key event received from an activity or view's onKeyEvent() method. * @return Returns the type of input device the event came from, such as KEYBOARD or GAMEPAD. * <p> * Returns null if given a null argument. * <p> * Returns the UNKNOWN type if the event's input source is not known by Corona or Android. */ public static InputDeviceType from(android.view.KeyEvent event) { // Validate argument. if (event == null) { return null; } // Fetch the device type from the given input event. InputDeviceType deviceType; if (android.os.Build.VERSION.SDK_INT >= 9) { // Fetch the device type by the event's source ID. int sourceId = ApiLevel9.getSourceIdFrom(event); deviceType = InputDeviceType.fromAndroidSourceId(sourceId); } else { // For older operating systems, we have to assume that key events come from a keyboard. deviceType = InputDeviceType.KEYBOARD; } return deviceType; } /** * Fetches the input device type for the given Android source ID. * @param sourceId Unique integer ID matching a SOURCE constant in Android class "InputDevice". * <p> * This ID can also come from a MotionEvent or KeyEvent object's getSource() method. * However, you should never call that method unless you are running API Level 9 or higher. * For lower API Levels, it is better to call this class' other static from() methods instead. * @return Returns an input device type object matching the given source ID. * <p> * Returns UNKNOWN if the given ID is not recognized by Corona or Android. */ public static InputDeviceType fromAndroidSourceId(int sourceId) { // Fetch a pre-allocated object matching the given ID. // Note: A source ID can be made up of multiple device types. // In this case, select a device type having the highest ID value. // This way, a device that is both a GAMEPAD and a KEYBOARD will be returned as a GAMEPAD. InputDeviceType deviceType = InputDeviceType.UNKNOWN; for (InputDeviceType nextDeviceType : sTypeCollection) { if ((nextDeviceType != InputDeviceType.UNKNOWN) && ((sourceId & nextDeviceType.toAndroidSourceId()) == nextDeviceType.toAndroidSourceId()) && (nextDeviceType.toAndroidSourceId() > deviceType.toAndroidSourceId())) { deviceType = nextDeviceType; } } return deviceType; } /** * Fetches a collection of input device types extracted from the given Android sources bit field. * <p> * Note that a sources bit field can flag multiple device types. This sources bit field is returned * by the Android InputDevice.getSources() method. It can also come from the KeyEvent.getSource() * and MotionEvent.getSource() methods, but those methods typically (but not always) return only * one device type. * @param sources Bit field matching SOURCE constants in Android class "InputDevice". * @return Returns a collection of device types found in the given Android sources bit field. * <p> * This collection will never be empty. If the given argument specifies a device type this * class does not recognize, then the collection will contain one UNKNOWN type. */ public static InputDeviceTypeSet collectionFromAndroidSourcesBitField(int sources) { // Add pre-allocated device types to the collection matching the bits found in the given source ID. InputDeviceTypeSet collection = new InputDeviceTypeSet(); for (InputDeviceType deviceType : sTypeCollection) { if ((deviceType != InputDeviceType.UNKNOWN) && ((sources & deviceType.toAndroidSourceId()) == deviceType.toAndroidSourceId())) { collection.add(deviceType); } } // If the collection is empty, then add an UNKNOWN device type to it. if (collection.size() <= 0) { collection.add(InputDeviceType.UNKNOWN); } // Return the collection of device types. return collection; } /** * Provides access to API Level 9 (Gingerbread) features. * Should only be accessed if running on an operating system matching this API Level. * <p> * You cannot create instances of this class. * You are expected to call its static methods instead. */ private static class ApiLevel9 { /** Constructor made private to prevent instances from being made. */ private ApiLevel9() { } /** * Fetches the given event's source ID matching a SOURCE constant in Android class InputDevice. * @param event Reference to the input event to retrieve the source ID from via the getSource() method. * <p> * Cannot be null or else an exception will be thrown. * @return Returns a unique ID such as SOURCE_TOUCHSCREEN, SOURCE_MOUSE, SOURCE_GAMEPAD, etc. */ public static int getSourceIdFrom(android.view.InputEvent event) { if (event == null) { throw new NullPointerException(); } return event.getSource(); } } }
3,602
755
<reponame>N500/WindowsTemplateStudio { "author": "Microsoft", "name": "Background Task", "description": "Aggiungi un'attività in background in-process per eseguire il codice anche quando l'app non è in primo piano.", "identity": "wts.Feat.BackgroundTask" }
94
593
<filename>runner/src/main/java/org/ananas/runner/steprunner/jdbc/mysql/MySQLDialect.java package org.ananas.runner.steprunner.jdbc.mysql; import org.ananas.runner.steprunner.jdbc.JDBCDriver; import org.ananas.runner.steprunner.jdbc.SQLDialect; import org.apache.beam.sdk.schemas.Schema; public class MySQLDialect implements SQLDialect { private MySQLDialect() {} public static SQLDialect of() { return new MySQLDialect(); } @Override public String addColumnStatement(JDBCDriver driver, String tablename, Schema.Field n) { return String.format( "ALTER TABLE %s ADD COLUMN %s %s;", tablename, n.getName(), driver.getDefaultDataType(n.getType()).getDatatypeLiteral()); } @Override public String dropExistingColumnStatement(String tablename, Schema.Field f) { return String.format("ALTER TABLE %s RENAME COLUMN %s TO old_%s;", tablename, f.getName()); } @Override public String dropTableStatement(String tablename) { StringBuilder builder = new StringBuilder(); builder.append("DROP TABLE IF EXISTS "); builder.append(tablename); builder.append(" ;"); return builder.toString(); } @Override public String createTableStatement(JDBCDriver driver, String tablename, Schema schema) { StringBuilder builder = new StringBuilder(); builder.append("CREATE TABLE "); builder.append(tablename); builder.append(" ( "); for (int i = 0; i < schema.getFields().size(); i++) { builder.append(schema.getField(i).getName()); builder.append(" "); builder.append(driver.getDefaultDataType(schema.getField(i).getType()).getDatatypeLiteral()); builder.append(" NULL DEFAULT NULL "); if (i != schema.getFields().size() - 1) { builder.append(","); } } builder.append(");"); return builder.toString(); } @Override public String insertStatement(String tablename, Schema schema) { StringBuilder builder = new StringBuilder(); builder.append("insert into "); builder.append(tablename); builder.append(" "); builder.append("values ("); for (int i = 0; i < schema.getFields().size(); i++) { builder.append("?"); if (i != schema.getFields().size() - 1) { builder.append(","); } } builder.append(")"); return builder.toString(); } @Override public String limit(int limit) { return " LIMIT " + limit; } }
880
1,968
<reponame>agramonte/corona<filename>platform/mac/CoronaCards/CoronaView.h<gh_stars>1000+ ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #import <GLKit/GLKit.h> #import <CoreLocation/CoreLocation.h> typedef enum { kNormal, kMinimized, kMaximized, kFullscreen, } CoronaViewWindowMode; @protocol CoronaViewDelegate; @protocol CLLocationManagerDelegate; // ---------------------------------------------------------------------------- @interface CoronaView : NSView < CLLocationManagerDelegate > @property (nonatomic, assign) id <CoronaViewDelegate> coronaViewDelegate; - (NSInteger)run; - (NSInteger)runWithPath:(NSString*)path parameters:(NSDictionary *)params; - (void)suspend; - (void)resume; - (void)terminate; - (void) handleOpenURL:(NSString *)urlStr; - (void) setScaleFactor:(CGFloat)scaleFactor; - (void) restoreWindowProperties; - (BOOL) settingsIsWindowResizable; - (BOOL) settingsIsWindowCloseButtonEnabled; - (BOOL) settingsIsWindowMinimizeButtonEnabled; - (BOOL) settingsIsWindowMaximizeButtonEnabled; - (int) settingsContentWidth; - (int) settingsContentHeight; - (NSString *) settingsWindowTitle; - (CoronaViewWindowMode) settingsDefaultWindowMode; - (int) settingsMinWindowViewWidth; - (int) settingsMinWindowViewHeight; - (int) settingsDefaultWindowViewWidth; - (int) settingsDefaultWindowViewHeight; - (int) settingsImageSuffixScaleCount; - (double) settingsImageSuffixScaleByIndex:(int) index; - (BOOL) settingsSuspendWhenMinimized; - (BOOL) settingsIsWindowTitleShown; - (id)sendEvent:(NSDictionary *)event; @end // ---------------------------------------------------------------------------- @protocol CoronaViewDelegate <NSObject> @optional - (id)coronaView:(CoronaView *)view receiveEvent:(NSDictionary *)event; @optional - (void)coronaViewWillSuspend:(CoronaView *)view; - (void)coronaViewDidSuspend:(CoronaView *)view; - (void)coronaViewWillResume:(CoronaView *)view; - (void)coronaViewDidResume:(CoronaView *)view; - (void)notifyRuntimeError:(NSString *)message; - (void)didPrepareOpenGLContext:(id)sender; @end // ----------------------------------------------------------------------------
722
511
/**************************************************************************** * include/tinyara/bluetooth/bt_core.h * Bluetooth subsystem core APIs. * * Copyright (C) 2018 <NAME>. All rights reserved. * Author: <NAME> <<EMAIL>> * * Ported from the Intel/Zephyr arduino101_firmware_source-v1.tar package * where the code was released with a compatible 3-clause BSD license: * * Copyright (c) 2016, 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: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __INCLUDE_TINYARA_BLUETOOTH_BT_CORE_H #define __INCLUDE_TINYARA_BLUETOOTH_BT_CORE_H 1 /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <stdio.h> #include <string.h> #include <tinyara/bluetooth/bt_buf.h> #include <tinyara/bluetooth/bt_hci.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* BT_ADDR_STR_LEN * Recommended length of user string buffer for Bluetooth address * * The recommended length guarantee the output of address conversion will not * lose valuable information about address being processed. */ #define BT_ADDR_STR_LEN 18 /* BT_ADDR_LE_STR_LEN * Recommended length of user string buffer for Bluetooth LE address * * The recommended length guarantee the output of address conversion will not * lose valuable information about address being processed. */ #define BT_ADDR_LE_STR_LEN 27 /* BT_LE162HOST * Convert 16-bit integer from little-endian to host endianness. */ #ifdef CONFIG_ENDIAN_BIG #define BT_LE162HOST(le) \ ((((uint16_t)(le) >> 8) & 0xff) | (((uint16_t)(le) & 0xff) << 8)) #else #define BT_LE162HOST(le) (le) #endif /* BT_HOST2LE16 * Convert 16-bit integer from host endianness to little-endian. */ #ifdef CONFIG_ENDIAN_BIG #define BT_HOST2LE16(h) \ ((((uint16_t)(h) >> 8) & 0xff) | (((uint16_t)(h) & 0xff) << 8)) #else #define BT_HOST2LE16(h) (h) #endif /* Unaligned access */ #ifdef CONFIG_ENDIAN_BIG #define BT_GETUINT16(p) \ ((((uint16_t)(((FAR uint8_t *)(p))[1]) >> 8) & 0xff) | \ (((uint16_t)(((FAR uint8_t *)(p))[0]) & 0xff) << 8)) #define BT_PUTUINT16(p, v) \ do { \ ((FAR uint8_t *)(p))[0] = ((uint16_t)(v) >> 8) & 0xff; \ ((FAR uint8_t *)(p))[1] = ((uint16_t)(v) & 0xff) >> 8; \ } while (0) #else #define BT_GETUINT16(p) \ ((((uint16_t)(((FAR uint8_t *)(p))[0]) >> 8) & 0xff) | \ (((uint16_t)(((FAR uint8_t *)(p))[1]) & 0xff) << 8)) #define BT_PUTUINT16(p, v) \ do { \ ((FAR uint8_t *)(p))[0] = ((uint16_t)(v) & 0xff) >> 8; \ ((FAR uint8_t *)(p))[1] = ((uint16_t)(v) >> 8) & 0xff; \ } while (0) #endif /**************************************************************************** * Public Types ****************************************************************************/ /* Advertising API */ struct bt_eir_s { uint8_t len; uint8_t type; uint8_t data[29]; } packed_struct; /**************************************************************************** * Inline Functions ****************************************************************************/ /**************************************************************************** * Name: bt_addr_to_str * * Description: * Converts binary Bluetooth address to string. * * Input Parameters: * addr - Address of buffer containing binary Bluetooth address. * str - Address of user buffer with enough room to store formatted * string containing binary address. * len - Length of data to be copied to user string buffer. Refer to * BT_ADDR_STR_LEN about recommended value. * * Returned Value: * Number of successfully formatted bytes from binary address. * ****************************************************************************/ static inline int bt_addr_to_str(FAR const bt_addr_t *addr, FAR char *str, size_t len) { return snprintf(str, len, "%02X:%02X:%02X:%02X:%02X:%02X", addr->val[0], addr->val[1], addr->val[2], addr->val[3], addr->val[4], addr->val[0]); } /**************************************************************************** * Name: bt_addr_le_to_str * * Description: * Converts binary LE Bluetooth address to string. * * Input Parameters: * addr - Address of buffer containing binary LE Bluetooth address. * user_buf - Address of user buffer with enough room to store * formatted string containing binary LE address. * len - Length of data to be copied to user string buffer. Refer to * BT_ADDR_LE_STR_LEN about recommended value. * * Returned Value: * Number of successfully formatted bytes from binary address. * ****************************************************************************/ static inline int bt_addr_le_to_str(FAR const bt_addr_le_t *addr, char *str, size_t len) { char type[7]; switch (addr->type) { case BT_ADDR_LE_PUBLIC: strncpy(type, "public", 7); break; case BT_ADDR_LE_RANDOM: strncpy(type, "random", 7); break; default: snprintf(type, 7, "0x%02x", addr->type); break; } return snprintf(str, len, "%02X:%02X:%02X:%02X:%02X:%02X (%s)", addr->val[0], addr->val[1], addr->val[2], addr->val[3], addr->val[4], addr->val[5], type); } /**************************************************************************** * Public Function Prototypes ****************************************************************************/ #endif /* __INCLUDE_TINYARA_BLUETOOTH_BT_CORE_H */
2,247
605
""" Tests SBType.IsTypeComplete on C++ types. """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def assertComplete(self, typename): """ Asserts that the type with the given name is complete. """ found_type = self.target().FindFirstType(typename) self.assertTrue(found_type.IsValid()) self.assertTrue(found_type.IsTypeComplete()) def assertCompleteWithVar(self, typename): """ Asserts that the type with the given name is complete. """ found_type = self.target().FindFirstType(typename) self.assertTrue(found_type.IsValid()) self.assertTrue(found_type.IsTypeComplete()) def assertPointeeIncomplete(self, typename, variable): """ Asserts that the pointee type behind the type with the given name is not complete. The variable is used to find the type.""" found_type = self.target().FindFirstType(typename) found_type = self.expect_expr(variable, result_type=typename).GetType() self.assertTrue(found_type.IsPointerType()) pointee_type = found_type.GetPointeeType() self.assertTrue(pointee_type.IsValid()) self.assertFalse(pointee_type.IsTypeComplete()) @no_debug_info_test def test_forward_declarations(self): """ Tests types of declarations that can be forward declared. """ self.build() self.createTestTarget() # Check record types with a definition. self.assertCompleteWithVar("EmptyClass") self.assertCompleteWithVar("DefinedClass") self.assertCompleteWithVar("DefinedClassTypedef") self.assertCompleteWithVar("DefinedTemplateClass<int>") # Record types without a defining declaration are not complete. self.assertPointeeIncomplete("FwdClass *", "fwd_class") self.assertPointeeIncomplete("FwdClassTypedef *", "fwd_class_typedef") self.assertPointeeIncomplete("FwdTemplateClass<> *", "fwd_template_class") # A pointer type is complete even when it points to an incomplete type. fwd_class_ptr = self.expect_expr("fwd_class", result_type="FwdClass *") self.assertTrue(fwd_class_ptr.GetType().IsTypeComplete()) @no_debug_info_test def test_builtin_types(self): """ Tests builtin types and types derived from them. """ self.build() self.createTestTarget() # Void is complete. void_type = self.target().FindFirstType("void") self.assertTrue(void_type.IsValid()) self.assertTrue(void_type.IsTypeComplete()) # Builtin types are also complete. int_type = self.target().FindFirstType("int") self.assertTrue(int_type.IsValid()) self.assertTrue(int_type.IsTypeComplete()) # References to builtin types are also complete. int_ref_type = int_type.GetReferenceType() self.assertTrue(int_ref_type.IsValid()) self.assertTrue(int_ref_type.IsTypeComplete()) # Pointer types to basic types are always complete. int_ptr_type = int_type.GetReferenceType() self.assertTrue(int_ptr_type.IsValid()) self.assertTrue(int_ptr_type.IsTypeComplete())
1,270
4,538
<reponame>wstong999/AliOS-Things /* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include "ucloud_ai_common.h" #include "ulog/ulog.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif #define TAG "uclud_ai_example" #define LOG printf static void ucloud_ai_comp_example(int argc, char **argv) { int model_index = -1; int ret = -1; char *image = NULL; if (argc < 2) { LOG("Please test with command: ucloud_ai_example -m [0~14]\n"); return; } if (!strncmp(argv[1], "init", 4)) { /*init network*/ event_service_init(NULL); netmgr_service_init(NULL); LOG("ucloud_ai comp init successfully!\n"); return; } else if (!strncmp(argv[1], "-m", 2)) { if (argv[2] < 0 && argv[2] > 14) { LOGE(TAG, "range of model value is 0 ~ 14, please try again\n"); return; } } else { LOG("unkown command\n"); return; } model_index = atoi(argv[2]); /*ucloud ai component init*/ ret = ucloud_ai_init(); if (ret < 0) { LOGE(TAG, "ucloud_ai_init failed, ret: %d\n", ret); return -1; } /*Config OSS Information*/ ucloud_ai_set_key_secret(OSS_ACCESS_KEY, OSS_ACCESS_SECRET); ucloud_ai_set_oss_endpoint(OSS_ENDPOINT); ucloud_ai_set_oss_bucket(OSS_BUCKET); switch (model_index) { #ifdef CONFIG_ALICLOUD_FACEBODY_ENABLE case UCLOUD_AI_MODEL_COMPARING_FACEBODY: LOG("Comparing facebody:\n"); ucloud_ai_facebody_comparing_face(FACE1_IMAGE, FACE2_IMAGE, NULL); break; case UCLOUD_AI_MODEL_GENERATE_HUMAN_ANIME_STYLE: LOG("Generate human anime style:\n"); ucloud_ai_facebody_generate_human_anime_style(ANIME_IMAGE, NULL); break; case UCLOUD_AI_MODEL_RECOGNIZE_EXPRESSION: LOG("Recognize expression:\n"); ucloud_ai_facebody_recognize_expression(EXPRESSION_IMAGE, NULL); break; #endif #ifdef CONFIG_ALICLOUD_OBJECTDET_ENABLE case UCLOUD_AI_MODEL_DETECT_OBJECT: LOG("Detect object:\n"); ucloud_ai_objectdet_detect_object(OBJECT_IMAGE, NULL); break; case UCLOUD_AI_MODEL_DETECT_MAIN_BODY: LOG("Detect main body:\n"); ucloud_ai_objectdet_detect_main_body(MAINBODY_IMAGE, NULL); break; #endif #ifdef CONFIG_ALICLOUD_IMAGESEG_ENABLE case UCLOUD_AI_MODEL_SEGMENT_COMMON_IMAGE: LOG("Segment common image:\n"); ucloud_ai_imageseg_segment_common_image(MAINBODY_IMAGE, NULL); break; case UCLOUD_AI_MODEL_SEGMENT_FACE: LOG("Segment face:\n"); ucloud_ai_imageseg_segment_face(FACE1_IMAGE, NULL); break; #endif #ifdef CONFIG_ALICLOUD_OCR_ENABLE case UCLOUD_AI_MODEL_RECOGNIZE_IDENTITY_CARD_FACE_SIDE: LOG("Recognize identity card face side:\n"); ucloud_ai_ocr_recognize_identity_card_face_side(CARD_FACE_IMAGE, NULL); break; case UCLOUD_AI_MODEL_RECOGNIZE_IDENTITY_CARD_BACK_SIDE: LOG("Recognize identity card back side:\n"); ucloud_ai_ocr_recognize_identity_card_back_side(CARD_BACK_IMAGE, NULL); break; case UCLOUD_AI_MODEL_RECOGNIZE_BANK_CARD: LOG("Recognize bank card:\n"); ucloud_ai_ocr_recognize_bank_card(BANK_CARD_IMAGE, NULL); break; case UCLOUD_AI_MODEL_RECOGNIZE_CHARACTER: LOG("Recognize character:\n"); ucloud_ai_ocr_recognize_character(CHARACTER_IMAGE, NULL); break; #endif #ifdef CONFIG_ALICLOUD_IMAGERECOG_ENABLE case UCLOUD_AI_MODEL_CLASSIFYING_RUBBISH: LOG("Classifying rubbish:\n"); ucloud_ai_imagerecog_classifying_rubbish(RUBBISH_IMAGE, NULL); break; case UCLOUD_AI_MODEL_DETECT_FRUITS: LOG("Detect fruits:\n"); ucloud_ai_imagerecog_detect_fruits(FRUITS_IMAGE, NULL); break; #endif #ifdef CONFIG_ALICLOUD_IMAGEENHAN_ENABLE case UCLOUD_AI_MODEL_ERASE_PERSON: LOG("Erase person:\n"); ucloud_ai_imageenhan_erase_person(PERSON_ORG_IMAGE, IMAGEENHAN_ERASE_PERSON_USERMASK_URL, NULL); break; case UCLOUD_AI_MODEL_EXTEND_IMAGE_STYLE: LOG("Extend image style:\n"); ucloud_ai_imageenhan_extend_image_style(STYLE_IMAGE, IMAGEENHAN_EXTEND_IMAGE_STYLE_URL, NULL); break; #endif default: break; } ret = ucloud_ai_uninit(); if (ret < 0) { LOGE(TAG, "ucloud_ai_uninit failed, ret: %d\n", ret); return -1; } return; } #if AOS_COMP_CLI /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(ucloud_ai_comp_example, ucloud_ai, ucloud_ai component base example) #endif
2,503
1,615
/** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.fun.ui; import android.content.Context; import android.graphics.Canvas; import com.immomo.mls.base.ud.lv.ILView; import com.immomo.mls.fun.ud.view.UDCanvasView; import com.immomo.mls.fun.weight.BorderRadiusView; /** * Created by Zhang.ke on 2019/7/26. */ public class LuaCanvasView<U extends UDCanvasView> extends BorderRadiusView implements ILView<U> { protected U userdata; private ViewLifeCycleCallback cycleCallback; public LuaCanvasView(Context context, U userdata) { super(context); this.userdata = userdata; setViewLifeCycleCallback(userdata); } //<editor-fold desc="ILViewGroup"> @Override public U getUserdata() { return userdata; } @Override public void setViewLifeCycleCallback(ViewLifeCycleCallback cycleCallback) { this.cycleCallback = cycleCallback; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (cycleCallback != null) { cycleCallback.onAttached(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (cycleCallback != null) { cycleCallback.onDetached(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); getUserdata().measureOverLayout(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); getUserdata().layoutOverLayout(left, top, right, bottom); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (getUserdata() != null) { ((ICanvasView) getUserdata()).onDrawCallback(canvas); getUserdata().drawOverLayout(canvas); } } }
854
1,346
<filename>dao-gen-core/src/main/java/com/ctrip/platform/dal/daogen/enums/DbModeTypeEnum.java package com.ctrip.platform.dal.daogen.enums; public enum DbModeTypeEnum { Cluster(0, "dalcluster"), Titan(1, "titankey"), No(2, "no"); DbModeTypeEnum(int code, String des) { this.code = code; this.des = des; } private int code; private String des; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } }
289
18,965
/* * 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 <jni.h> namespace facebook { /** * Instructs the JNI environment to throw an exception. * * @param pEnv JNI environment * @param szClassName class name to throw * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwException(JNIEnv* pEnv, const char* szClassName, const char* szFmt, va_list va_args); /** * Instructs the JNI environment to throw a NoClassDefFoundError. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwNoClassDefError(JNIEnv* pEnv, const char* szFmt, ...); /** * Instructs the JNI environment to throw a RuntimeException. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwRuntimeException(JNIEnv* pEnv, const char* szFmt, ...); /** * Instructs the JNI environment to throw a IllegalArgumentException. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwIllegalArgumentException(JNIEnv* pEnv, const char* szFmt, ...); /** * Instructs the JNI environment to throw a IllegalStateException. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwIllegalStateException(JNIEnv* pEnv, const char* szFmt, ...); /** * Instructs the JNI environment to throw an IOException. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwIOException(JNIEnv* pEnv, const char* szFmt, ...); /** * Instructs the JNI environment to throw an AssertionError. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwAssertionError(JNIEnv* pEnv, const char* szFmt, ...); /** * Instructs the JNI environment to throw an OutOfMemoryError. * * @param pEnv JNI environment * @param szFmt sprintf-style format string * @param ... sprintf-style args * @return 0 on success; a negative value on failure */ jint throwOutOfMemoryError(JNIEnv* pEnv, const char* szFmt, ...); /** * Finds the specified class. If it's not found, instructs the JNI environment to throw an * exception. * * @param pEnv JNI environment * @param szClassName the classname to find in JNI format (e.g. "java/lang/String") * @return the class or NULL if not found (in which case a pending exception will be queued). This * returns a global reference (JNIEnv::NewGlobalRef). */ jclass findClassOrThrow(JNIEnv *pEnv, const char* szClassName); /** * Finds the specified field of the specified class. If it's not found, instructs the JNI * environment to throw an exception. * * @param pEnv JNI environment * @param clazz the class to lookup the field in * @param szFieldName the name of the field to find * @param szSig the signature of the field * @return the field or NULL if not found (in which case a pending exception will be queued) */ jfieldID getFieldIdOrThrow(JNIEnv* pEnv, jclass clazz, const char* szFieldName, const char* szSig); /** * Finds the specified method of the specified class. If it's not found, instructs the JNI * environment to throw an exception. * * @param pEnv JNI environment * @param clazz the class to lookup the method in * @param szMethodName the name of the method to find * @param szSig the signature of the method * @return the method or NULL if not found (in which case a pending exception will be queued) */ jmethodID getMethodIdOrThrow( JNIEnv* pEnv, jclass clazz, const char* szMethodName, const char* szSig); } // namespace facebook
1,335
575
<reponame>zealoussnow/chromium<gh_stars>100-1000 // 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 CONTENT_BROWSER_ANDROID_SELECT_POPUP_H_ #define CONTENT_BROWSER_ANDROID_SELECT_POPUP_H_ #include <jni.h> #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "third_party/blink/public/mojom/choosers/popup_menu.mojom.h" #include "ui/android/view_android.h" namespace gfx { class Rect; } namespace content { class WebContentsImpl; class SelectPopup { public: explicit SelectPopup(WebContentsImpl* web_contents); ~SelectPopup(); // Creates a popup menu with |items|. // |multiple| defines if it should support multi-select. // If not |multiple|, |selected_item| sets the initially selected item. // Otherwise, item's "checked" flag selects it. void ShowMenu(mojo::PendingRemote<blink::mojom::PopupMenuClient> popup_client, const gfx::Rect& bounds, std::vector<blink::mojom::MenuItemPtr> items, int selected_item, bool multiple, bool right_aligned); // Hides a visible popup menu. void HideMenu(); // Notifies that items were selected in the currently showing select popup. void SelectMenuItems(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jlong selectPopupSourceFrame, const base::android::JavaParamRef<jintArray>& indices); private: WebContentsImpl* web_contents_; JavaObjectWeakGlobalRef java_obj_; // Select popup view ui::ViewAndroid::ScopedAnchorView popup_view_; mojo::Remote<blink::mojom::PopupMenuClient> popup_client_; }; } // namespace content #endif // CONTENT_BROWSER_ANDROID_SELECT_POPUP_H_
771
14,668
import os from wptserve.utils import isomorphic_encode filename = os.path.basename(isomorphic_encode(__file__)) def main(request, response): if request.method == u'POST': return 302, [(b'Location', b'./%s?redirect' % filename)], b'' return [(b'Content-Type', b'text/plain')], request.request_path
116
372
<gh_stars>100-1000 /* * * (c) Copyright 1991 OPEN SOFTWARE FOUNDATION, INC. * (c) Copyright 1991 HEWLETT-PACKARD COMPANY * (c) Copyright 1991 DIGITAL EQUIPMENT CORPORATION * To anyone who acknowledges that this file is provided "AS IS" * without any express or implied warranty: * permission to use, copy, modify, and distribute this * file for any purpose is hereby granted without fee, provided that * the above copyright notices and this notice appears in all source * code copies, and that none of the names of Open Software * Foundation, Inc., Hewlett-Packard Company, or Digital Equipment * Corporation be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. Neither Open Software Foundation, Inc., Hewlett- * Packard Company, nor Digital Equipment Corporation makes any * representations about the suitability of this software for any * purpose. * */ /* ** ** NAME: ** ** icharsup.h ** ** FACILITY: ** ** Interface Definition Language (IDL) Compiler ** ** ABSTRACT: ** ** Function prototypes and type definitions for international ** character support ** ** */ #ifndef ICHARSUP_H #define ICHARSUP_H /* Description of an operation's use of I-char machinery */ typedef struct BE_cs_info_t { boolean cs_machinery; /* TRUE if operation has I-char machinery */ boolean stag_by_ref; /* TRUE if passed by ref according to IDL */ NAMETABLE_id_t stag; boolean drtag_by_ref; /* TRUE if passed by ref according to IDL */ NAMETABLE_id_t drtag; boolean rtag_by_ref; /* TRUE if passed by ref according to IDL */ NAMETABLE_id_t rtag; } BE_cs_info_t; void BE_cs_analyze_and_spell_vars ( FILE *fid, /* [in] Handle for emitted C text */ AST_operation_n_t *p_operation, /* [in] Pointer to AST operation node */ BE_side_t side, /* [in] client or server */ BE_cs_info_t *p_cs_info /* [out] Description of I-char machinery */ ); void BE_spell_cs_state ( FILE *fid, /* [in] Handle for emitted C text */ char *state_access, /* [in] "IDL_ms." or "IDL_msp->" */ BE_side_t side, /* [in] client or server */ BE_cs_info_t *p_cs_info /* [in] Description of I-char machinery */ ); void BE_spell_cs_tag_rtn_call ( FILE *fid, /* [in] Handle for emitted C text */ char *state_access, /* [in] "IDL_ms." or "IDL_msp->" */ AST_operation_n_t *p_operation, /* [in] Pointer to AST operation node */ BE_side_t side, /* [in] client or server */ BE_handle_info_t *p_handle_info,/* [in] How to spell binding handle name */ BE_cs_info_t *p_cs_info, /* [in] Description of I-char machinery */ boolean pickling ); #endif
1,107
661
<gh_stars>100-1000 package com.desmond.squarecamera; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; /** * */ public class EditSavePhotoFragment extends Fragment { public static final String TAG = EditSavePhotoFragment.class.getSimpleName(); public static final String BITMAP_KEY = "bitmap_byte_array"; public static final String ROTATION_KEY = "rotation"; public static final String IMAGE_INFO = "image_info"; private static final int REQUEST_STORAGE = 1; public static Fragment newInstance(byte[] bitmapByteArray, int rotation, @NonNull ImageParameters parameters) { Fragment fragment = new EditSavePhotoFragment(); Bundle args = new Bundle(); args.putByteArray(BITMAP_KEY, bitmapByteArray); args.putInt(ROTATION_KEY, rotation); args.putParcelable(IMAGE_INFO, parameters); fragment.setArguments(args); return fragment; } public EditSavePhotoFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.squarecamera__fragment_edit_save_photo, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); int rotation = getArguments().getInt(ROTATION_KEY); byte[] data = getArguments().getByteArray(BITMAP_KEY); ImageParameters imageParameters = getArguments().getParcelable(IMAGE_INFO); if (imageParameters == null) { return; } final ImageView photoImageView = (ImageView) view.findViewById(R.id.photo); imageParameters.mIsPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; final View topView = view.findViewById(R.id.topView); if (imageParameters.mIsPortrait) { topView.getLayoutParams().height = imageParameters.mCoverHeight; } else { topView.getLayoutParams().width = imageParameters.mCoverWidth; } rotatePicture(rotation, data, photoImageView); view.findViewById(R.id.save_photo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { savePicture(); } }); } private void rotatePicture(int rotation, byte[] data, ImageView photoImageView) { Bitmap bitmap = ImageUtility.decodeSampledBitmapFromByte(getActivity(), data); // Log.d(TAG, "original bitmap width " + bitmap.getWidth() + " height " + bitmap.getHeight()); if (rotation != 0) { Bitmap oldBitmap = bitmap; Matrix matrix = new Matrix(); matrix.postRotate(rotation); bitmap = Bitmap.createBitmap( oldBitmap, 0, 0, oldBitmap.getWidth(), oldBitmap.getHeight(), matrix, false ); oldBitmap.recycle(); } photoImageView.setImageBitmap(bitmap); } private void savePicture() { requestForPermission(); } private void requestForPermission() { RuntimePermissionActivity.startActivity(EditSavePhotoFragment.this, REQUEST_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (Activity.RESULT_OK != resultCode) return; if (REQUEST_STORAGE == requestCode && data != null) { final boolean isGranted = data.getBooleanExtra(RuntimePermissionActivity.REQUESTED_PERMISSION, false); final View view = getView(); if (isGranted && view != null) { ImageView photoImageView = (ImageView) view.findViewById(R.id.photo); Bitmap bitmap = ((BitmapDrawable) photoImageView.getDrawable()).getBitmap(); Uri photoUri = ImageUtility.savePicture(getActivity(), bitmap); ((CameraActivity) getActivity()).returnPhotoUri(photoUri); } } else { super.onActivityResult(requestCode, resultCode, data); } } }
1,910
2,354
// This file is part of AsmJit project <https://asmjit.com> // // See asmjit.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #ifndef ASMJIT_X86_X86RAPASS_P_H_INCLUDED #define ASMJIT_X86_X86RAPASS_P_H_INCLUDED #include "../core/api-config.h" #ifndef ASMJIT_NO_COMPILER #include "../core/compiler.h" #include "../core/rabuilders_p.h" #include "../core/rapass_p.h" #include "../x86/x86assembler.h" #include "../x86/x86compiler.h" #include "../x86/x86emithelper_p.h" ASMJIT_BEGIN_SUB_NAMESPACE(x86) //! \cond INTERNAL //! \addtogroup asmjit_x86 //! \{ //! X86 register allocation pass. //! //! Takes care of generating function prologs and epilogs, and also performs register allocation. class X86RAPass : public BaseRAPass { public: ASMJIT_NONCOPYABLE(X86RAPass) typedef BaseRAPass Base; EmitHelper _emitHelper; //! \name Construction & Destruction //! \{ X86RAPass() noexcept; virtual ~X86RAPass() noexcept; //! \} //! \name Accessors //! \{ //! Returns the compiler casted to `x86::Compiler`. inline Compiler* cc() const noexcept { return static_cast<Compiler*>(_cb); } //! Returns emit helper. inline EmitHelper* emitHelper() noexcept { return &_emitHelper; } inline bool avxEnabled() const noexcept { return _emitHelper._avxEnabled; } inline bool avx512Enabled() const noexcept { return _emitHelper._avx512Enabled; } //! \} //! \name Utilities //! \{ inline uint32_t choose(uint32_t sseInstId, uint32_t avxInstId) noexcept { return avxEnabled() ? avxInstId : sseInstId; } //! \} //! \name Interface //! \{ void onInit() noexcept override; void onDone() noexcept override; Error buildCFG() noexcept override; Error _rewrite(BaseNode* first, BaseNode* stop) noexcept override; Error emitMove(uint32_t workId, uint32_t dstPhysId, uint32_t srcPhysId) noexcept override; Error emitSwap(uint32_t aWorkId, uint32_t aPhysId, uint32_t bWorkId, uint32_t bPhysId) noexcept override; Error emitLoad(uint32_t workId, uint32_t dstPhysId) noexcept override; Error emitSave(uint32_t workId, uint32_t srcPhysId) noexcept override; Error emitJump(const Label& label) noexcept override; Error emitPreCall(InvokeNode* invokeNode) noexcept override; //! \} }; //! \} //! \endcond ASMJIT_END_SUB_NAMESPACE #endif // !ASMJIT_NO_COMPILER #endif // ASMJIT_X86_X86RAPASS_P_H_INCLUDED
915
1,144
<reponame>gokhanForesight/metasfresh<filename>backend/de.metas.payment.esr/src/main/java-gen/de/metas/payment/esr/model/I_ESR_ImportFile.java package de.metas.payment.esr.model; import java.math.BigDecimal; import javax.annotation.Nullable; import org.adempiere.model.ModelColumn; /** Generated Interface for ESR_ImportFile * @author metasfresh (generated) */ @SuppressWarnings("unused") public interface I_ESR_ImportFile { String Table_Name = "ESR_ImportFile"; // /** AD_Table_ID=541753 */ // int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name); /** * Set Attachment. * * <br>Type: Search * <br>Mandatory: false * <br>Virtual Column: false */ void setAD_AttachmentEntry_ID (int AD_AttachmentEntry_ID); /** * Get Attachment. * * <br>Type: Search * <br>Mandatory: false * <br>Virtual Column: false */ int getAD_AttachmentEntry_ID(); @Nullable org.compiere.model.I_AD_AttachmentEntry getAD_AttachmentEntry(); void setAD_AttachmentEntry(@Nullable org.compiere.model.I_AD_AttachmentEntry AD_AttachmentEntry); ModelColumn<I_ESR_ImportFile, org.compiere.model.I_AD_AttachmentEntry> COLUMN_AD_AttachmentEntry_ID = new ModelColumn<>(I_ESR_ImportFile.class, "AD_AttachmentEntry_ID", org.compiere.model.I_AD_AttachmentEntry.class); String COLUMNNAME_AD_AttachmentEntry_ID = "AD_AttachmentEntry_ID"; /** * Get Client. * Client/Tenant for this installation. * * <br>Type: TableDir * <br>Mandatory: true * <br>Virtual Column: false */ int getAD_Client_ID(); String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** * Set Organisation. * Organisational entity within client * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ void setAD_Org_ID (int AD_Org_ID); /** * Get Organisation. * Organisational entity within client * * <br>Type: Search * <br>Mandatory: true * <br>Virtual Column: false */ int getAD_Org_ID(); String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** * Set Partner Bank Account. * Bank Account of the Business Partner * * <br>Type: Search * <br>Mandatory: false * <br>Virtual Column: false */ void setC_BP_BankAccount_ID (int C_BP_BankAccount_ID); /** * Get Partner Bank Account. * Bank Account of the Business Partner * * <br>Type: Search * <br>Mandatory: false * <br>Virtual Column: false */ int getC_BP_BankAccount_ID(); String COLUMNNAME_C_BP_BankAccount_ID = "C_BP_BankAccount_ID"; /** * Get Created. * Date this record was created * * <br>Type: DateTime * <br>Mandatory: true * <br>Virtual Column: false */ java.sql.Timestamp getCreated(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_Created = new ModelColumn<>(I_ESR_ImportFile.class, "Created", null); String COLUMNNAME_Created = "Created"; /** * Get Created By. * User who created this records * * <br>Type: Table * <br>Mandatory: true * <br>Virtual Column: false */ int getCreatedBy(); String COLUMNNAME_CreatedBy = "CreatedBy"; /** * Set Data Type. * Type of data * * <br>Type: List * <br>Mandatory: false * <br>Virtual Column: false */ void setDataType (@Nullable java.lang.String DataType); /** * Get Data Type. * Type of data * * <br>Type: List * <br>Mandatory: false * <br>Virtual Column: false */ @Nullable java.lang.String getDataType(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_DataType = new ModelColumn<>(I_ESR_ImportFile.class, "DataType", null); String COLUMNNAME_DataType = "DataType"; /** * Set Description. * * <br>Type: Text * <br>Mandatory: false * <br>Virtual Column: false */ void setDescription (@Nullable java.lang.String Description); /** * Get Description. * * <br>Type: Text * <br>Mandatory: false * <br>Virtual Column: false */ @Nullable java.lang.String getDescription(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_Description = new ModelColumn<>(I_ESR_ImportFile.class, "Description", null); String COLUMNNAME_Description = "Description"; /** * Set Sum Control Amount. * * <br>Type: Number * <br>Mandatory: true * <br>Virtual Column: false */ void setESR_Control_Amount (BigDecimal ESR_Control_Amount); /** * Get Sum Control Amount. * * <br>Type: Number * <br>Mandatory: true * <br>Virtual Column: false */ BigDecimal getESR_Control_Amount(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_ESR_Control_Amount = new ModelColumn<>(I_ESR_ImportFile.class, "ESR_Control_Amount", null); String COLUMNNAME_ESR_Control_Amount = "ESR_Control_Amount"; /** * Set Control Qty Transactions. * Der Wert wurde aus der Eingabedatei eingelesen (falls dort bereit gestellt) * * <br>Type: Quantity * <br>Mandatory: false * <br>Virtual Column: false */ void setESR_Control_Trx_Qty (@Nullable BigDecimal ESR_Control_Trx_Qty); /** * Get Control Qty Transactions. * Der Wert wurde aus der Eingabedatei eingelesen (falls dort bereit gestellt) * * <br>Type: Quantity * <br>Mandatory: false * <br>Virtual Column: false */ BigDecimal getESR_Control_Trx_Qty(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_ESR_Control_Trx_Qty = new ModelColumn<>(I_ESR_ImportFile.class, "ESR_Control_Trx_Qty", null); String COLUMNNAME_ESR_Control_Trx_Qty = "ESR_Control_Trx_Qty"; /** * Set ESR Import File. * * <br>Type: ID * <br>Mandatory: true * <br>Virtual Column: false */ void setESR_ImportFile_ID (int ESR_ImportFile_ID); /** * Get ESR Import File. * * <br>Type: ID * <br>Mandatory: true * <br>Virtual Column: false */ int getESR_ImportFile_ID(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_ESR_ImportFile_ID = new ModelColumn<>(I_ESR_ImportFile.class, "ESR_ImportFile_ID", null); String COLUMNNAME_ESR_ImportFile_ID = "ESR_ImportFile_ID"; /** * Set ESR Payment Import. * * <br>Type: Search * <br>Mandatory: false * <br>Virtual Column: false */ void setESR_Import_ID (int ESR_Import_ID); /** * Get ESR Payment Import. * * <br>Type: Search * <br>Mandatory: false * <br>Virtual Column: false */ int getESR_Import_ID(); @Nullable de.metas.payment.esr.model.I_ESR_Import getESR_Import(); void setESR_Import(@Nullable de.metas.payment.esr.model.I_ESR_Import ESR_Import); ModelColumn<I_ESR_ImportFile, de.metas.payment.esr.model.I_ESR_Import> COLUMN_ESR_Import_ID = new ModelColumn<>(I_ESR_ImportFile.class, "ESR_Import_ID", de.metas.payment.esr.model.I_ESR_Import.class); String COLUMNNAME_ESR_Import_ID = "ESR_Import_ID"; /** * Set File Name. * Name of the local file or URL * * <br>Type: String * <br>Mandatory: false * <br>Virtual Column: false */ void setFileName (@Nullable java.lang.String FileName); /** * Get File Name. * Name of the local file or URL * * <br>Type: String * <br>Mandatory: false * <br>Virtual Column: false */ @Nullable java.lang.String getFileName(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_FileName = new ModelColumn<>(I_ESR_ImportFile.class, "FileName", null); String COLUMNNAME_FileName = "FileName"; /** * Set Hash. * * <br>Type: String * <br>Mandatory: false * <br>Virtual Column: false */ void setHash (@Nullable java.lang.String Hash); /** * Get Hash. * * <br>Type: String * <br>Mandatory: false * <br>Virtual Column: false */ @Nullable java.lang.String getHash(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_Hash = new ModelColumn<>(I_ESR_ImportFile.class, "Hash", null); String COLUMNNAME_Hash = "Hash"; /** * Set Active. * The record is active in the system * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ void setIsActive (boolean IsActive); /** * Get Active. * The record is active in the system * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ boolean isActive(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_IsActive = new ModelColumn<>(I_ESR_ImportFile.class, "IsActive", null); String COLUMNNAME_IsActive = "IsActive"; /** * Set Receipt. * This is a sales transaction (receipt) * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ void setIsReceipt (boolean IsReceipt); /** * Get Receipt. * This is a sales transaction (receipt) * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ boolean isReceipt(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_IsReceipt = new ModelColumn<>(I_ESR_ImportFile.class, "IsReceipt", null); String COLUMNNAME_IsReceipt = "IsReceipt"; /** * Set Is Valid. * The element is valid * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ void setIsValid (boolean IsValid); /** * Get Is Valid. * The element is valid * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ boolean isValid(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_IsValid = new ModelColumn<>(I_ESR_ImportFile.class, "IsValid", null); String COLUMNNAME_IsValid = "IsValid"; /** * Set Processed. * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ void setProcessed (boolean Processed); /** * Get Processed. * * <br>Type: YesNo * <br>Mandatory: true * <br>Virtual Column: false */ boolean isProcessed(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_Processed = new ModelColumn<>(I_ESR_ImportFile.class, "Processed", null); String COLUMNNAME_Processed = "Processed"; /** * Get Updated. * Date this record was updated * * <br>Type: DateTime * <br>Mandatory: true * <br>Virtual Column: false */ java.sql.Timestamp getUpdated(); ModelColumn<I_ESR_ImportFile, Object> COLUMN_Updated = new ModelColumn<>(I_ESR_ImportFile.class, "Updated", null); String COLUMNNAME_Updated = "Updated"; /** * Get Updated By. * User who updated this records * * <br>Type: Table * <br>Mandatory: true * <br>Virtual Column: false */ int getUpdatedBy(); String COLUMNNAME_UpdatedBy = "UpdatedBy"; }
3,788
76,518
#include "pch.h" #include "CppUnitTest.h" #include <keyboardmanager/KeyboardManagerEditorLibrary/ShortcutErrorType.h> #include <keyboardmanager/common/Helpers.h> #include <common/interop/keyboard_layout.h> #include <keyboardmanager/KeyboardManagerEditorLibrary/EditorHelpers.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace EditorHelpersTests { TEST_CLASS (EditorHelpersTests) { public: // Test if the DoKeysOverlap method returns SameKeyPreviouslyMapped on passing the same key for both arguments TEST_METHOD (DoKeysOverlap_ShouldReturnSameKeyPreviouslyMapped_OnPassingSameKeyForBothArguments) { // Arrange DWORD key1 = 0x41; DWORD key2 = key1; // Act auto result = EditorHelpers::DoKeysOverlap(key1, key2); // Assert Assert::IsTrue(result == ShortcutErrorType::SameKeyPreviouslyMapped); } // Test if the DoKeysOverlap method returns ConflictingModifierKey on passing left modifier and common modifier TEST_METHOD (DoKeysOverlap_ShouldReturnConflictingModifierKey_OnPassingLeftModifierAndCommonModifierOfSameType) { // Arrange DWORD key1 = VK_LCONTROL; DWORD key2 = VK_CONTROL; // Act auto result = EditorHelpers::DoKeysOverlap(key1, key2); // Assert Assert::IsTrue(result == ShortcutErrorType::ConflictingModifierKey); } // Test if the DoKeysOverlap method returns ConflictingModifierKey on passing right modifier and common modifier TEST_METHOD (DoKeysOverlap_ShouldReturnConflictingModifierKey_OnPassingRightModifierAndCommonModifierOfSameType) { // Arrange DWORD key1 = VK_RCONTROL; DWORD key2 = VK_CONTROL; // Act auto result = EditorHelpers::DoKeysOverlap(key1, key2); // Assert Assert::IsTrue(result == ShortcutErrorType::ConflictingModifierKey); } // Test if the DoKeysOverlap method returns NoError on passing left modifier and right modifier TEST_METHOD (DoKeysOverlap_ShouldReturnNoError_OnPassingLeftModifierAndRightModifierOfSameType) { // Arrange DWORD key1 = VK_LCONTROL; DWORD key2 = VK_RCONTROL; // Act auto result = EditorHelpers::DoKeysOverlap(key1, key2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } // Test if the DoKeysOverlap method returns NoError on passing keys of different types TEST_METHOD (DoKeysOverlap_ShouldReturnNoError_OnPassingKeysOfDifferentTypes) { // Arrange DWORD key1 = VK_CONTROL; DWORD key2 = VK_SHIFT; // Act auto result = EditorHelpers::DoKeysOverlap(key1, key2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } // Test if the DoKeysOverlap method returns NoError on passing different action keys TEST_METHOD (DoKeysOverlap_ShouldReturnNoError_OnPassingDifferentActionKeys) { // Arrange DWORD key1 = 0x41; DWORD key2 = 0x42; // Act auto result = EditorHelpers::DoKeysOverlap(key1, key2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } // Test if the CheckRepeatedModifier method returns true on passing vector with same modifier repeated TEST_METHOD (CheckRepeatedModifier_ShouldReturnTrue_OnPassingSameModifierRepeated) { // Arrange std::vector<int32_t> keys = { VK_CONTROL, VK_CONTROL, 0x41 }; // Act bool result = EditorHelpers::CheckRepeatedModifier(keys, VK_CONTROL); // Assert Assert::IsTrue(result); } // Test if the CheckRepeatedModifier method returns true on passing vector with conflicting modifier repeated TEST_METHOD (CheckRepeatedModifier_ShouldReturnTrue_OnPassingConflictingModifierRepeated) { // Arrange std::vector<int32_t> keys = { VK_CONTROL, VK_LCONTROL, 0x41 }; // Act bool result = EditorHelpers::CheckRepeatedModifier(keys, VK_LCONTROL); // Assert Assert::IsTrue(result); } // Test if the CheckRepeatedModifier method returns false on passing vector with different modifiers TEST_METHOD (CheckRepeatedModifier_ShouldReturnFalse_OnPassingDifferentModifiers) { // Arrange std::vector<int32_t> keys = { VK_CONTROL, VK_SHIFT, 0x41 }; // Act bool result = EditorHelpers::CheckRepeatedModifier(keys, VK_SHIFT); // Assert Assert::IsFalse(result); } // Test if the IsValidShortcut method returns false on passing shortcut with null action key TEST_METHOD (IsValidShortcut_ShouldReturnFalse_OnPassingShortcutWithNullActionKey) { // Arrange Shortcut s; s.SetKey(NULL); // Act bool result = EditorHelpers::IsValidShortcut(s); // Assert Assert::IsFalse(result); } // Test if the IsValidShortcut method returns false on passing shortcut with only action key TEST_METHOD (IsValidShortcut_ShouldReturnFalse_OnPassingShortcutWithOnlyActionKey) { // Arrange Shortcut s; s.SetKey(0x41); // Act bool result = EditorHelpers::IsValidShortcut(s); // Assert Assert::IsFalse(result); } // Test if the IsValidShortcut method returns false on passing shortcut with only modifier keys TEST_METHOD (IsValidShortcut_ShouldReturnFalse_OnPassingShortcutWithOnlyModifierKeys) { // Arrange Shortcut s; s.SetKey(VK_CONTROL); s.SetKey(VK_SHIFT); // Act bool result = EditorHelpers::IsValidShortcut(s); // Assert Assert::IsFalse(result); } // Test if the IsValidShortcut method returns true on passing shortcut with modifier and action key TEST_METHOD (IsValidShortcut_ShouldReturnFalse_OnPassingShortcutWithModifierAndActionKey) { // Arrange Shortcut s; s.SetKey(VK_CONTROL); s.SetKey(0x41); // Act bool result = EditorHelpers::IsValidShortcut(s); // Assert Assert::IsTrue(result); } // Test if the DoKeysOverlap method returns NoError on passing invalid shortcut for one of the arguments TEST_METHOD (DoKeysOverlap_ShouldReturnNoError_OnPassingInvalidShortcutForOneOfTheArguments) { // Arrange Shortcut s1(std::vector<int32_t>{ NULL }); Shortcut s2(std::vector<int32_t>{ VK_CONTROL, 0x41 }); // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } // Test if the DoKeysOverlap method returns SameShortcutPreviouslyMapped on passing same shortcut for both arguments TEST_METHOD (DoKeysOverlap_ShouldReturnSameShortcutPreviouslyMapped_OnPassingSameShortcutForBothArguments) { // Arrange Shortcut s1(std::vector<int32_t>{ VK_CONTROL, 0x41 }); Shortcut s2 = s1; // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::SameShortcutPreviouslyMapped); } // Test if the DoKeysOverlap method returns NoError on passing shortcuts with different action keys TEST_METHOD (DoKeysOverlap_ShouldReturnNoError_OnPassingShortcutsWithDifferentActionKeys) { // Arrange Shortcut s1(std::vector<int32_t>{ VK_CONTROL, 0x42 }); Shortcut s2(std::vector<int32_t>{ VK_CONTROL, 0x41 }); // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } // Test if the DoKeysOverlap method returns NoError on passing shortcuts with different modifiers TEST_METHOD (DoKeysOverlap_ShouldReturnNoError_OnPassingShortcutsWithDifferentModifiers) { // Arrange Shortcut s1(std::vector<int32_t>{ VK_CONTROL, 0x42 }); Shortcut s2(std::vector<int32_t>{ VK_SHIFT, 0x42 }); // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } // Test if the DoKeysOverlap method returns ConflictingModifierShortcut on passing shortcuts with left modifier and common modifier TEST_METHOD (DoKeysOverlap_ShouldReturnConflictingModifierShortcut_OnPassingShortcutsWithLeftModifierAndCommonModifierOfSameType) { // Arrange Shortcut s1(std::vector<int32_t>{ VK_LCONTROL, 0x42 }); Shortcut s2(std::vector<int32_t>{ VK_CONTROL, 0x42 }); // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::ConflictingModifierShortcut); } // Test if the DoKeysOverlap method returns ConflictingModifierShortcut on passing shortcuts with right modifier and common modifier TEST_METHOD (DoKeysOverlap_ShouldReturnConflictingModifierShortcut_OnPassingShortcutsWithRightModifierAndCommonModifierOfSameType) { // Arrange Shortcut s1(std::vector<int32_t>{ VK_RCONTROL, 0x42 }); Shortcut s2(std::vector<int32_t>{ VK_CONTROL, 0x42 }); // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::ConflictingModifierShortcut); } // Test if the DoKeysOverlap method returns ConflictingModifierShortcut on passing shortcuts with left modifier and right modifier TEST_METHOD (DoKeysOverlap_ShouldReturnConflictingModifierShortcut_OnPassingShortcutsWithLeftModifierAndRightModifierOfSameType) { // Arrange Shortcut s1(std::vector<int32_t>{ VK_LCONTROL, 0x42 }); Shortcut s2(std::vector<int32_t>{ VK_RCONTROL, 0x42 }); // Act auto result = EditorHelpers::DoShortcutsOverlap(s1, s2); // Assert Assert::IsTrue(result == ShortcutErrorType::NoError); } }; }
4,877
356
<gh_stars>100-1000 package com.zjb.loader.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.LinearInterpolator; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher.ViewFactory; /** * time: 15/6/11 * description:封装了淡入淡出的ImageSwitcher * * @author sunjianfei */ public class AnimationImageView extends ImageSwitcher implements ViewFactory { private int qiniuWidth; private int qiniuHeight; public AnimationImageView(Context context) { super(context); initView(); } public int getQiniuWidth() { return qiniuWidth; } public void setQiniuWidth(int qiniuWidth) { this.qiniuWidth = qiniuWidth; } public int getQiniuHeight() { return qiniuHeight; } public void setQiniuHeight(int qiniuHeight) { this.qiniuHeight = qiniuHeight; } public AnimationImageView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { AlphaAnimation in = new AlphaAnimation(0.0f, 1.0f); in.setInterpolator(new LinearInterpolator()); in.setDuration(800); AlphaAnimation out = new AlphaAnimation(1.0f, 0.0f); in.setInterpolator(new LinearInterpolator()); out.setDuration(800); setInAnimation(in); setOutAnimation(out); setFactory(this); } @SuppressWarnings("deprecation") @Override public View makeView() { ImageView view = new ImageView(getContext()); view.setBackgroundColor(0x00000000); view.setScaleType(ImageView.ScaleType.CENTER_CROP); view.setLayoutParams(new LayoutParams( android.widget.Gallery.LayoutParams.MATCH_PARENT, android.widget.Gallery.LayoutParams.MATCH_PARENT)); return view; } }
810
2,151
<reponame>zipated/src // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_SCREEN_MANAGER_H_ #define CHROME_BROWSER_CHROMEOS_LOGIN_SCREEN_MANAGER_H_ #include <map> #include <memory> #include <string> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "chrome/browser/chromeos/login/screens/base_screen.h" namespace chromeos { class WizardController; // Class that manages creation and ownership of screens. class ScreenManager { public: // |wizard_controller| is not owned by this class. explicit ScreenManager(WizardController* wizard_controller); ~ScreenManager(); // Getter for screen with lazy initialization. BaseScreen* GetScreen(OobeScreen screen); bool HasScreen(OobeScreen screen); private: FRIEND_TEST_ALL_PREFIXES(EnrollmentScreenTest, TestCancel); FRIEND_TEST_ALL_PREFIXES(WizardControllerFlowTest, Accelerators); friend class WizardControllerFlowTest; friend class WizardControllerOobeResumeTest; friend class WizardInProcessBrowserTest; friend class WizardControllerBrokenLocalStateTest; // Created screens. std::map<OobeScreen, std::unique_ptr<BaseScreen>> screens_; // Used to allocate BaseScreen instances. Unowned. WizardController* wizard_controller_; DISALLOW_COPY_AND_ASSIGN(ScreenManager); }; } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_LOGIN_SCREEN_MANAGER_H_
487
1,338
<gh_stars>1000+ /* * Copyright 2003-2008, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ /* * inspired by the NewOS floppy driver * http://www.newos.org/cgi-bin/fileDownLoad.cgi?FSPC=//depot/newos/kernel/addons/dev/arch/i386/floppy/floppy.c&REV=6 * related docs: * - datasheets * http://floppyutil.sourceforge.net/floppy.html * http://www.openppc.org/datasheets/NatSemi_PC87308VUL_full.pdf * http://www.smsc.com/main/datasheets/37c665gt.pdf * http://www.smsc.com/main/datasheets/47b27x.pdf * - sources * http://www.freebsd.org/cgi/cvsweb.cgi/src/sys/isa/fd.c * http://fxr.watson.org/fxr/source/sys/fdcio.h?v=RELENG50 * http://fxr.watson.org/fxr/source/isa/fd.c?v=RELENG50 * http://lxr.linux.no/source/drivers/block/floppy.c */ /* * the stupid FDC engine is able to use several drives at a time, but *only* for some commands, * others need exclusive access, as they need the drive to be selected. * we just serialize the whole thing to simplify. */ #include <Drivers.h> #include <ISA.h> #include <PCI.h> #include <config_manager.h> #include <malloc.h> #include <stdio.h> #include <string.h> #include "floppy.h" /* compile time configuration */ /* enables support for more than one drive */ #define NEW_DEV_LAYOUT /* don't symlink raw -> 0/raw */ #define NO_SYMLINK_OLD /* publish the first drive as floppy/raw */ #define FIRST_ONE_NO_NUMBER /* default values... for 3"5 HD, but we support DD too now */ #define SECTORS_PER_TRACK 18 #define NUM_HEADS 2 #define SECTORS_PER_CYLINDER (SECTORS_PER_TRACK * NUM_HEADS) #define SECTOR_SIZE 512 #define TRACK_SIZE (SECTOR_SIZE * SECTORS_PER_CYLINDER) #define NUM_TRACKS 80 #define DISK_SIZE (TRACK_SIZE * NUM_TRACKS) extern const char floppy_icon[]; extern const char floppy_mini_icon[]; #define OLD_DEV_FORMAT "disk/floppy/raw" #ifndef NEW_DEV_LAYOUT # define MAX_FLOPPIES 1 # define DEV_FORMAT OLD_DEV_FORMAT #else # define MAX_FLOPPIES 4 # define DEV_FORMAT "disk/floppy/%d/raw" #endif static char floppy_dev_name[MAX_FLOPPIES][B_OS_NAME_LENGTH]; static const char *dev_names[MAX_FLOPPIES+1]; extern device_hooks floppy_hooks; int32 api_version = B_CUR_DRIVER_API_VERSION; isa_module_info *isa; config_manager_for_driver_module_info *config_man; struct floppy floppies[MAX_FLOPPIES]; /* by order of check */ /* from fd.c from fBSD */ const floppy_geometry supported_geometries[] = { /* { gap, nsecs, data_rate, fmtgap, sd2off, {secsz, s/trk, ntraks, nheads, type, rmable, ro, wonce}, flags, name }, */ { 0x1b, 2880, FDC_500KBPS, 0x6c, 0, { 512, 18, 80, 2, B_DISK, true, true, false}, FL_MFM, "1.44M" }, /* { 0x20, 5760, FDC_1MBPS, 0x4c, 1, { 512, 36, 80, 2, B_DISK, true, true, false}, FL_MFM|FL_PERP, "2.88M" }, */ { 0x20, 1440, FDC_250KBPS, 0x50, 0, { 512, 9, 80, 2, B_DISK, true, true, false}, FL_MFM, "720K" }, { 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, true, false, false}, 0, NULL } }; typedef struct floppy_cookie { struct floppy *flp; } floppy_cookie; static void motor_off_daemon(void *t, int tim); status_t init_hardware(void) { TRACE("init_hardware()\n"); /* assume there is always one */ return B_OK; } status_t init_driver(void) { status_t err; unsigned int i, j; int current; uint64 cmcookie = 0; struct device_info info; TRACE("init_driver()\n"); if ((err = get_module(B_ISA_MODULE_NAME, (module_info **)&isa)) < B_OK) { dprintf(FLO "no isa module!\n"); return err; } if ((err = get_module(B_CONFIG_MANAGER_FOR_DRIVER_MODULE_NAME, (module_info **)&config_man)) < B_OK) { dprintf(FLO "no config_manager module!\n"); put_module(B_ISA_MODULE_NAME); return err; } for (i = 0; i < MAX_FLOPPIES; i++) memset(&(floppies[i]), 0, sizeof(floppy_t)); current = 0; register_kernel_daemon(motor_off_daemon, floppies, 5); while (config_man->get_next_device_info(B_ISA_BUS, &cmcookie, &info, sizeof(struct device_info)) == B_OK) { struct device_configuration *conf; struct floppy *master; struct floppy *last = NULL; int flops; if ((info.config_status != B_OK) || ((info.flags & B_DEVICE_INFO_ENABLED) == 0) || ((info.flags & B_DEVICE_INFO_CONFIGURED) == 0) || (info.devtype.base != PCI_mass_storage) || (info.devtype.subtype != PCI_floppy) || (info.devtype.interface != 0) /* XXX: needed ?? */) continue; err = config_man->get_size_of_current_configuration_for(cmcookie); if (err < B_OK) continue; conf = (struct device_configuration *)malloc(err); if (conf == NULL) continue; if (config_man->get_current_configuration_for(cmcookie, conf, err) < B_OK) { free(conf); continue; } master = &(floppies[current]); for (i = 0; i < conf->num_resources; i++) { if (conf->resources[i].type == B_IO_PORT_RESOURCE) { int32 iobase = conf->resources[i].d.r.minbase; int32 len = conf->resources[i].d.r.len; /* WTF do I get * min 3f2 max 3f2 align 0 len 4 ? * on my K6-2, I even get 2 bytes at 3f2 + 2 bytes at 3f4 ! * looks like AT interface, suppose PS/2, which is 8 bytes wide. * answer: because the 8th byte is also for the IDE controller... * good old PC stuff... PPC here I come ! */ // XXX: maybe we shouldn't use DIGITAL_IN if register window // is only 6 bytes ? if (len != 8) { if ((master->iobase & 0xfffffff8) == 0x3f0) iobase = 0x3f0; else { dprintf(FLO "controller has weird register window len %ld !?\n", len); break; } } master->iobase = iobase; } if (conf->resources[i].type == B_IRQ_RESOURCE) { int val; for (val = 0; val < 32; val++) { if (conf->resources[i].d.m.mask & (1 << val)) { master->irq = val; break; } } } if (conf->resources[i].type == B_DMA_RESOURCE) { int val; for (val = 0; val < 32; val++) { if (conf->resources[i].d.m.mask & (1 << val)) { master->dma = val; break; } } } } if (master->iobase == 0) { dprintf(FLO "controller doesn't have any io ??\n"); goto config_error; } dprintf(FLO "controller at 0x%04lx, irq %ld, dma %ld\n", master->iobase, master->irq, master->dma); //master->dma = -1; // XXX: DEBUG: disable DMA /* allocate resources */ master->completion = create_sem(0, "floppy interrupt"); if (master->completion < 0) goto config_error; new_lock(&master->ben, "floppy driver access"); //if (new_lock(&master->ben, "floppy driver access") < B_OK) // goto config_error; /* 20K should hold a full cylinder XXX: B_LOMEM for DMA ! */ master->buffer_area = create_area("floppy cylinder buffer", (void **)&master->buffer, B_ANY_KERNEL_ADDRESS, CYL_BUFFER_SIZE, B_FULL_LOCK, B_READ_AREA|B_WRITE_AREA); if (master->buffer_area < B_OK) goto config_error2; B_INITIALIZE_SPINLOCK(&master->slock); master->isa = isa; if (install_io_interrupt_handler(master->irq, flo_intr, (void *)master, 0) < B_OK) goto config_error2; flops = count_floppies(master); /* actually a bitmap */ flops = MAX(flops, 1); /* XXX: assume at least one */ TRACE("drives found: 0x%01x\n", flops); for (i = 0; current < MAX_FLOPPIES && i < 4; i++) { if ((flops & (1 << i)) == 0) continue; floppies[current].next = NULL; if (last) last->next = &(floppies[current]); floppies[current].iobase = master->iobase; floppies[current].irq = master->irq; floppies[current].dma = master->dma; floppies[current].drive_num = i; floppies[current].master = master; floppies[current].isa = master->isa; floppies[current].completion = master->completion; floppies[current].track = -1; last = &(floppies[current]); current++; } /* XXX: TODO: remove "assume at least one" + cleanup if no drive on controller */ goto config_ok; config_error2: if (master->buffer_area) delete_area(master->buffer_area); free_lock(&master->ben); config_error: if (master->completion > 0) delete_sem(master->completion); master->iobase = 0; put_module(B_CONFIG_MANAGER_FOR_DRIVER_MODULE_NAME); put_module(B_ISA_MODULE_NAME); config_ok: free(conf); if (current >= MAX_FLOPPIES) break; } /* make device names */ for (i = 0, j = 0; i < MAX_FLOPPIES; i++) { if (floppies[i].iobase) { #ifdef FIRST_ONE_NO_NUMBER if (!i) strcpy(floppy_dev_name[i], OLD_DEV_FORMAT); else #endif sprintf(floppy_dev_name[i], DEV_FORMAT, i); dev_names[j++] = floppy_dev_name[i]; TRACE("names[%d] = %s\n", j-1, dev_names[j-1]); } else strcpy(floppy_dev_name[i], ""); } dev_names[j] = NULL; #ifdef NEW_DEV_LAYOUT #if !defined(NO_SYMLINK_OLD) && !defined(FIRST_ONE_NO_NUMBER) /* fake the good old single drive */ mkdir("/dev/disk/floppy", 0755); symlink("0/raw", "/dev/disk/floppy/raw"); #endif #endif return B_OK; } void uninit_driver(void) { int i; TRACE("uninit_driver()\n"); unregister_kernel_daemon(motor_off_daemon, floppies); for (i = 0; i < MAX_FLOPPIES; i++) { if (floppies[i].iobase) turn_off_motor(&floppies[i]); } TRACE("deallocating...\n"); for (i = 0; i < MAX_FLOPPIES; i++) { if (floppies[i].iobase) { if (floppies[i].master == &(floppies[i])) { remove_io_interrupt_handler(floppies[i].irq, flo_intr, (void *)&(floppies[i])); free_lock(&floppies[i].ben); delete_sem(floppies[i].completion); delete_area(floppies[i].buffer_area); } } } TRACE("uninit done\n"); put_module(B_CONFIG_MANAGER_FOR_DRIVER_MODULE_NAME); put_module(B_ISA_MODULE_NAME); } const char ** publish_devices(void) { if (dev_names[0] == NULL) return NULL; return dev_names; } device_hooks * find_device(const char *name) { (void)name; return &floppy_hooks; } static status_t flo_open(const char *name, uint32 flags, floppy_cookie **cookie) { int i; TRACE("open(%s)\n", name); if (flags & O_NONBLOCK) return EINVAL; for (i = 0; i < MAX_FLOPPIES; i++) { if (dev_names[i] && (strncmp(name, dev_names[i], strlen(dev_names[i])) == 0)) break; } if (i >= MAX_FLOPPIES) return ENODEV; *cookie = (floppy_cookie *)malloc(sizeof(floppy_cookie)); if (*cookie == NULL) return B_NO_MEMORY; (*cookie)->flp = &(floppies[i]); /* if we don't know yet if there's something in, check that */ if ((*cookie)->flp->status <= FLOP_MEDIA_CHANGED) query_media((*cookie)->flp, false); return B_OK; } static status_t flo_close(floppy_cookie *cookie) { TRACE("close()\n"); cookie->flp = NULL; return B_OK; } static status_t flo_free(floppy_cookie *cookie) { TRACE("free()\n"); free(cookie); return B_OK; } static status_t flo_read(floppy_cookie *cookie, off_t position, void *data, size_t *numbytes) { status_t err; size_t len = *numbytes; size_t bytes_read = 0; int sectsize = SECTOR_SIZE; int cylsize = TRACK_SIZE; /* hmm, badly named, it's actually track_size (a cylinder has 2 tracks, one per head) */ const device_geometry *geom = NULL; ssize_t disk_size = 0; if (cookie->flp->geometry) geom = &cookie->flp->geometry->g; if (geom) { sectsize = geom->bytes_per_sector; cylsize = sectsize * geom->sectors_per_track/* * geom->head_count*/; disk_size = (geom->bytes_per_sector) * (geom->sectors_per_track) * (geom->head_count) * (geom->cylinder_count); } if (disk_size <= 0) { *numbytes = 0; return B_DEV_NO_MEDIA; } if (position > disk_size) { dprintf(FLO "attempt to seek beyond device end!\n"); *numbytes = 0; return B_OK; } if (position + *numbytes > disk_size) { dprintf(FLO "attempt to read beyond device end!\n"); *numbytes = (size_t)((off_t)disk_size - position); if (*numbytes == 0) return B_OK; } // handle partial first block if ((position % SECTOR_SIZE) != 0) { size_t toread; TRACE("read: begin %Ld, %ld\n", position, bytes_read); err = read_sectors(cookie->flp, position / sectsize, 1); TRACE("PIO READ got %ld sect\n", err); if (err <= 0) { *numbytes = 0; return err; } toread = MIN(len, (size_t)sectsize); toread = MIN(toread, sectsize - (position % sectsize)); memcpy(data, cookie->flp->master->buffer + position % cylsize/*(sectsize * ) + (position % sectsize)*/, toread); len -= toread; bytes_read += toread; position += toread; } // read the middle blocks while (len >= (size_t)sectsize) { TRACE("read: middle %Ld, %ld, %ld\n", position, bytes_read, len); // try to read as many sectors as we can err = read_sectors(cookie->flp, position / sectsize, len / sectsize); TRACE("PIO READ got %ld sect\n", err); if (err <= 0) { *numbytes = 0; return err; } memcpy(((char *)data) + bytes_read, cookie->flp->master->buffer + position % cylsize, err*sectsize); len -= err * sectsize; bytes_read += err * sectsize; position += err * sectsize; } // handle partial last block if (len > 0 && (len % sectsize) != 0) { TRACE("read: end %Ld, %ld %ld\n", position, bytes_read, len); err = read_sectors(cookie->flp, position / sectsize, 1); TRACE("PIO READ got %ld sect\n", err); if (err <= 0) { *numbytes = 0; return err; } memcpy(((char *)data) + bytes_read, cookie->flp->master->buffer + position % cylsize, len); bytes_read += len; position += len; } *numbytes = bytes_read; return B_OK; } static status_t flo_write(floppy_cookie *cookie, off_t position, const void *data, size_t *numbytes) { *numbytes = 0; return B_ERROR; } static status_t flo_control(floppy_cookie *cookie, uint32 op, void *data, size_t len) { device_geometry *geom; status_t err; floppy_t *flp = cookie->flp; switch (op) { case B_GET_ICON: TRACE("control(B_GET_ICON, %ld)\n", ((device_icon *)data)->icon_size); if (((device_icon *)data)->icon_size == 16) { /* mini icon */ memcpy(((device_icon *)data)->icon_data, floppy_mini_icon, (16*16)); return B_OK; } if (((device_icon *)data)->icon_size == 32) { /* icon */ memcpy(((device_icon *)data)->icon_data, floppy_icon, (32*32)); return B_OK; } return EINVAL; case B_GET_BIOS_DRIVE_ID: TRACE("control(B_GET_BIOS_DRIVE_ID)\n"); *(uint8 *)data = 0; return B_OK; case B_GET_DEVICE_SIZE: TRACE("control(B_GET_DEVICE_SIZE)\n"); err = query_media(cookie->flp, true); *(size_t *)data = (flp->bgeom.bytes_per_sector) * (flp->bgeom.sectors_per_track) * (flp->bgeom.head_count) * (flp->bgeom.cylinder_count); return B_OK; case B_GET_GEOMETRY: case B_GET_BIOS_GEOMETRY: TRACE("control(B_GET_(BIOS)_GEOMETRY)\n"); err = query_media(cookie->flp, false); geom = (device_geometry *)data; geom->bytes_per_sector = flp->bgeom.bytes_per_sector; geom->sectors_per_track = flp->bgeom.sectors_per_track; geom->cylinder_count = flp->bgeom.cylinder_count; geom->head_count = flp->bgeom.head_count; geom->device_type = B_DISK; geom->removable = true; geom->read_only = flp->bgeom.read_only; geom->write_once = false; return B_OK; case B_GET_MEDIA_STATUS: TRACE("control(B_GET_MEDIA_STATUS)\n"); err = query_media(cookie->flp, false); *(status_t *)data = err; return B_OK; } TRACE("control(%ld)\n", op); return EINVAL; } static void motor_off_daemon(void *t, int tim) { int i; for (i = 0; i < MAX_FLOPPIES; i++) { if (floppies[i].iobase && !floppies[i].pending_cmd && floppies[i].motor_timeout > 0) { TRACE("floppies[%d].motor_timeout = %ld\n", i, floppies[i].motor_timeout); if (atomic_add((int32*)&floppies[i].motor_timeout, -500000) <= 500000) { dprintf("turning off motor for drive %d\n", floppies[i].drive_num); turn_off_motor(&floppies[i]); floppies[i].motor_timeout = 0; } } } } device_hooks floppy_hooks = { (device_open_hook)flo_open, (device_close_hook)flo_close, (device_free_hook)flo_free, (device_control_hook)flo_control, (device_read_hook)flo_read, (device_write_hook)flo_write, NULL, /* select */ NULL, /* deselect */ NULL, /* readv */ NULL /* writev */ };
6,998
353
<reponame>ptfrwrd/Apache_Flink_Lab_3 /* * Copyright 2017 data Artisans GmbH, 2019 Ververica GmbH * * 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.ververica.flinktraining.exercises.datastream_java.datatypes; public class EnrichedTrade { public EnrichedTrade() {} public EnrichedTrade(Trade trade, Customer customer) { this.trade = trade; this.customer = customer; } public Trade trade; public Customer customer; public String toString() { String customerInfo; if (customer == null) { customerInfo = "null"; } else { customerInfo = customer.customerInfo; } StringBuilder sb = new StringBuilder(); sb.append("EnrichedTrade(").append(trade.timestamp).append(") "); sb.append(customerInfo); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o != null && getClass() == o.getClass()) { EnrichedTrade that = (EnrichedTrade) o; return (this.trade.equals(that.trade) && (this.customer == null ? that.customer == null : this.customer.equals(that.customer))); } return false; } }
532
373
<reponame>linkingtd/UniAuth package com.dianrong.common.uniauth.common.server.cxf.propset; import com.dianrong.common.uniauth.common.server.cxf.client.ClientFilterSingleton; import com.dianrong.common.uniauth.common.server.cxf.client.HeaderProducer; import com.dianrong.common.uniauth.common.server.cxf.server.HeaderConsumer; import com.dianrong.common.uniauth.common.server.cxf.server.ServerFilterSingletion; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; /** * 在spring 初始化完成之后执行. * * @author wanglin */ @Component @Slf4j public class PropReadyListener implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware { // spring 容器对象引用 private ApplicationContext applicationContext; @Override public void onApplicationEvent(ContextRefreshedEvent event) { // root context try { ClientFilterSingleton.addNewHeaderProducers(findBeanList(HeaderProducer.class)); ServerFilterSingletion.addNewHeaderProducers(findBeanList(HeaderConsumer.class)); } catch (InterruptedException e) { log.error("failed to set prop to cxf filter", e); Thread.currentThread().interrupt(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * . 从applicationContext 中获取对应类型的bean * * @param requiredType can not be null */ private <T> List<T> findBeanList(Class<T> requiredType) throws InterruptedException { Assert.notNull(requiredType); List<T> beans = new ArrayList<T>(); String[] beanNames = this.applicationContext.getBeanNamesForType(requiredType, true, false); for (String tname : beanNames) { @SuppressWarnings("unchecked") T bean = (T) this.applicationContext.getBean(tname); beans.add(bean); } return beans; } }
794
1,078
fname='h:\\tmp.reg' import win32api, win32con, win32security, ntsecuritycon, pywintypes,os ## regsave will not overwrite a file if os.path.isfile(fname): os.remove(fname) new_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SECURITY_NAME),win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_TCB_NAME),win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_BACKUP_NAME),win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_RESTORE_NAME),win32con.SE_PRIVILEGE_ENABLED) ) ph = win32api.GetCurrentProcess() th = win32security.OpenProcessToken(ph,win32security.TOKEN_ALL_ACCESS|win32con.TOKEN_ADJUST_PRIVILEGES) win32security.AdjustTokenPrivileges(th,0,new_privs) my_sid = win32security.GetTokenInformation(th,ntsecuritycon.TokenUser)[0] hklm=win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,None,0,win32con.KEY_ALL_ACCESS) skey=win32api.RegOpenKey(hklm,'SYSTEM',0,win32con.KEY_ALL_ACCESS) sa=pywintypes.SECURITY_ATTRIBUTES() sd=pywintypes.SECURITY_DESCRIPTOR() sa.SECURITY_DESCRIPTOR=sd acl=pywintypes.ACL() pwr_sid = win32security.LookupAccountName('','Power Users')[0] acl.AddAccessAllowedAce(win32con.ACL_REVISION,win32con.GENERIC_READ|win32con.ACCESS_SYSTEM_SECURITY,my_sid) sd.SetSecurityDescriptorDacl(1,acl,0) sd.SetSecurityDescriptorOwner(pwr_sid,0) sa.bInheritHandle=1 assert sa.SECURITY_DESCRIPTOR is sd win32api.RegSaveKey(skey,fname,sa)
658
348
<gh_stars>100-1000 {"nom":"Terranjou","circ":"4ème circonscription","dpt":"Maine-et-Loire","inscrits":2741,"abs":1661,"votants":1080,"blancs":117,"nuls":28,"exp":935,"res":[{"nuance":"REM","nom":"<NAME>","voix":549},{"nuance":"UDI","nom":"<NAME>","voix":386}]}
107
778
<filename>applications/CompressiblePotentialFlowApplication/python_scripts/define_wake_process_2d.py import KratosMultiphysics import KratosMultiphysics.CompressiblePotentialFlowApplication as CPFApp import math def Factory(settings, Model): if(not isinstance(settings, KratosMultiphysics.Parameters)): raise Exception( "expected input shall be a Parameters object, encapsulating a json string") return DefineWakeProcess2D(Model, settings["Parameters"]) # TODO Implement this process in C++ and make it open mp parallel to save time selecting the wake elements class DefineWakeProcess2D(KratosMultiphysics.Process): def __init__(self, Model, settings): # Call the base Kratos process constructor KratosMultiphysics.Process.__init__(self) # Check default settings default_settings = KratosMultiphysics.Parameters(r'''{ "model_part_name": "", "epsilon": 1e-9, "compute_wake_at_each_step": false, "echo_level": 1 }''') settings.ValidateAndAssignDefaults(default_settings) body_model_part_name = settings["model_part_name"].GetString() if body_model_part_name == "": err_msg = "Empty model_part_name in DefineWakeProcess2D\n" err_msg += "Please specify the model part that contains the body surface nodes" raise Exception(err_msg) self.body_model_part = Model[body_model_part_name] self.epsilon = settings["epsilon"].GetDouble() self.echo_level = settings["echo_level"].GetInt() self.fluid_model_part = self.body_model_part.GetRootModelPart() self.compute_wake_at_each_step = settings["compute_wake_at_each_step"].GetBool() for cond in self.body_model_part.Conditions: for node in cond.GetNodes(): node.Set(KratosMultiphysics.SOLID) def ExecuteInitialize(self): CPFApp.Define2DWakeProcess(self.body_model_part, self.epsilon).ExecuteInitialize() #self.__FindWakeElements() def ExecuteInitializeSolutionStep(self): if self.compute_wake_at_each_step and self.fluid_model_part.ProcessInfo[KratosMultiphysics.STEP] > 1: CPFApp.Define2DWakeProcess(self.body_model_part, self.epsilon).ExecuteInitialize() def ExecuteFinalizeSolutionStep(self): if not self.fluid_model_part.HasSubModelPart("wake_sub_model_part"): raise Exception("Fluid model part does not have a wake_sub_model_part") else: self.wake_sub_model_part = self.fluid_model_part.GetSubModelPart("wake_sub_model_part") absolute_tolerance = 1e-9 CPFApp.PotentialFlowUtilities.CheckIfWakeConditionsAreFulfilled2D(self.wake_sub_model_part, absolute_tolerance, self.echo_level) CPFApp.PotentialFlowUtilities.ComputePotentialJump2D(self.wake_sub_model_part) def __FindWakeElements(self): if not self.fluid_model_part.HasSubModelPart("trailing_edge_model_part"): self.trailing_edge_model_part = self.fluid_model_part.CreateSubModelPart("trailing_edge_model_part") else: self.trailing_edge_model_part = self.fluid_model_part.GetSubModelPart("trailing_edge_model_part") if not self.fluid_model_part.HasSubModelPart("wake_sub_model_part"): self.wake_sub_model_part = self.fluid_model_part.CreateSubModelPart("wake_sub_model_part") else: self.wake_sub_model_part = self.fluid_model_part.GetSubModelPart("wake_sub_model_part") #List to store trailing edge elements id and wake elements id self.trailing_edge_element_id_list = [] self.wake_element_id_list = [] self.__SetWakeDirectionAndNormal() # Save the trailing edge for further computations self.__SaveTrailingEdgeNode() # Check which elements are cut and mark them as wake self.__MarkWakeElements() # Mark the elements touching the trailing edge from below as kutta self.__MarkKuttaElements() # Mark the trailing edge element that is further downstream as wake self.__MarkWakeTEElement() def __SetWakeDirectionAndNormal(self): free_stream_velocity = self.fluid_model_part.ProcessInfo.GetValue(CPFApp.FREE_STREAM_VELOCITY) if(free_stream_velocity.Size() != 3): raise Exception('The free stream velocity should be a vector with 3 components!') self.wake_direction = KratosMultiphysics.Vector(3) vnorm = math.sqrt( free_stream_velocity[0]**2 + free_stream_velocity[1]**2 + free_stream_velocity[2]**2) self.wake_direction[0] = free_stream_velocity[0]/vnorm self.wake_direction[1] = free_stream_velocity[1]/vnorm self.wake_direction[2] = free_stream_velocity[2]/vnorm self.wake_normal = KratosMultiphysics.Vector(3) self.wake_normal[0] = -self.wake_direction[1] self.wake_normal[1] = self.wake_direction[0] self.wake_normal[2] = 0.0 def __SaveTrailingEdgeNode(self): # This function finds and saves the trailing edge for further computations max_x_coordinate = -1e30 for node in self.body_model_part.Nodes: if(node.X > max_x_coordinate): max_x_coordinate = node.X self.trailing_edge_node = node self.trailing_edge_node.SetValue(CPFApp.TRAILING_EDGE, True) def __MarkWakeElements(self): # This function checks which elements are cut by the wake # and marks them as wake elements KratosMultiphysics.Logger.PrintInfo('...Selecting wake elements...') for elem in self.fluid_model_part.Elements: # Mark and save the elements touching the trailing edge self.__MarkTrailingEdgeElement(elem) # Elements downstream the trailing edge can be wake elements potentially_wake = self.__CheckIfPotentiallyWakeElement(elem) if(potentially_wake): # Compute the nodal distances of the element to the wake distances_to_wake = self.__ComputeDistancesToWake(elem) # Selecting the cut (wake) elements is_wake_element = self.__CheckIfWakeElement(distances_to_wake) if(is_wake_element): elem.SetValue(CPFApp.WAKE, True) elem.SetValue(CPFApp.WAKE_ELEMENTAL_DISTANCES, distances_to_wake) counter=0 self.wake_element_id_list.append(elem.Id) for node in elem.GetNodes(): node.SetValue(CPFApp.WAKE_DISTANCE,distances_to_wake[counter]) counter += 1 self.wake_sub_model_part.AddElements(self.wake_element_id_list) self.__SaveTrailingEdgeElements() KratosMultiphysics.Logger.PrintInfo('...Selecting wake elements finished...') def __MarkTrailingEdgeElement(self, elem): # This function marks the elements touching the trailing # edge and saves them in the trailing_edge_element_id_list # for further computations for elnode in elem.GetNodes(): if(elnode.GetValue(CPFApp.TRAILING_EDGE)): elem.SetValue(CPFApp.TRAILING_EDGE, True) self.trailing_edge_element_id_list.append(elem.Id) break def __SaveTrailingEdgeElements(self): # This function stores the trailing edge element # to its submodelpart. self.trailing_edge_model_part.AddElements(self.trailing_edge_element_id_list) def __CheckIfPotentiallyWakeElement(self, elem): # This function selects the elements downstream the # trailing edge as potentially wake elements # Compute the distance from the element's center to # the trailing edge x_distance_to_te = elem.GetGeometry().Center().X - self.trailing_edge_node.X y_distance_to_te = elem.GetGeometry().Center().Y - self.trailing_edge_node.Y # Compute the projection of the distance in the wake direction projection_on_wake = x_distance_to_te*self.wake_direction[0] + \ y_distance_to_te*self.wake_direction[1] # Elements downstream the trailing edge can be wake elements if(projection_on_wake > 0): return True else: return False def __ComputeDistancesToWake(self, elem): # This function computes the distance of the element nodes # to the wake nodal_distances_to_wake = KratosMultiphysics.Vector(3) counter = 0 for elnode in elem.GetNodes(): # Compute the distance from the node to the trailing edge x_distance_to_te = elnode.X - self.trailing_edge_node.X y_distance_to_te = elnode.Y - self.trailing_edge_node.Y # Compute the projection of the distance vector in the wake normal direction distance_to_wake = x_distance_to_te*self.wake_normal[0] + \ y_distance_to_te*self.wake_normal[1] # Nodes laying on the wake have a positive distance if(abs(distance_to_wake) < self.epsilon): distance_to_wake = self.epsilon nodal_distances_to_wake[counter] = distance_to_wake counter += 1 return nodal_distances_to_wake @staticmethod def __CheckIfWakeElement(distances_to_wake): # This function checks whether the element is cut by the wake # Initialize counters number_of_nodes_with_positive_distance = 0 number_of_nodes_with_negative_distance = 0 # Count how many element nodes are above and below the wake for nodal_distance_to_wake in distances_to_wake: if(nodal_distance_to_wake < 0.0): number_of_nodes_with_negative_distance += 1 else: number_of_nodes_with_positive_distance += 1 # Elements with nodes above and below the wake are wake elements return(number_of_nodes_with_negative_distance > 0 and number_of_nodes_with_positive_distance > 0) def __MarkKuttaElements(self): # This function selects the kutta elements. Kutta elements # are touching the trailing edge from below. for elem in self.trailing_edge_model_part.Elements: # Compute the distance from the element center to the trailing edge x_distance_to_te = elem.GetGeometry().Center().X - self.trailing_edge_node.X y_distance_to_te = elem.GetGeometry().Center().Y - self.trailing_edge_node.Y # Compute the projection of the distance vector in the wake normal direction distance_to_wake = x_distance_to_te*self.wake_normal[0] + \ y_distance_to_te*self.wake_normal[1] # Marking the elements under the trailing edge as kutta if(distance_to_wake < 0.0): elem.SetValue(CPFApp.KUTTA, True) @staticmethod def __CheckIfElemIsCutByWake(elem): nneg=0 # REMINDER: In 3D the elemental_distances may not be match with # the nodal distances if CalculateDistanceToSkinProcess is used distances = elem.GetValue(CPFApp.WAKE_ELEMENTAL_DISTANCES) for nodal_distance in distances: if nodal_distance<0: nneg += 1 return nneg==1 def __MarkWakeTEElement(self): # This function finds the trailing edge element that is further downstream # and marks it as wake trailing edge element. The rest of trailing edge elements are # unassigned from the wake. for elem in self.trailing_edge_model_part.Elements: if (elem.GetValue(CPFApp.WAKE)): if(self.__CheckIfElemIsCutByWake(elem)): #TE Element elem.Set(KratosMultiphysics.STRUCTURE) elem.SetValue(CPFApp.KUTTA, False) else: #Rest of elements touching the trailing edge but not part of the wake elem.SetValue(CPFApp.WAKE, False) self.wake_sub_model_part.RemoveElement(elem) def _CleanMarking(self): # This function removes all the markers set by _FindWakeElements() for elem in self.trailing_edge_model_part.Elements: elem.SetValue(CPFApp.TRAILING_EDGE, False) elem.Reset(KratosMultiphysics.STRUCTURE) elem.SetValue(CPFApp.KUTTA, False) for elem in self.wake_sub_model_part.Elements: elem.SetValue(CPFApp.WAKE, False) elem.Set(KratosMultiphysics.TO_ERASE, True) self.wake_sub_model_part.RemoveElements(KratosMultiphysics.TO_ERASE) self.trailing_edge_element_id_list = [] self.wake_element_id_list = []
5,449
1,477
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function, unicode_literals
72
2,338
<gh_stars>1000+ // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // REQUIRES: riscv-registered-target // RUN: %clang_cc1 -triple riscv64 -target-feature +experimental-v -disable-O0-optnone -emit-llvm %s -o - | opt -S -mem2reg | FileCheck --check-prefix=CHECK-RV64 %s #include <riscv_vector.h> // // CHECK-RV64-LABEL: @test_vmmv_m_b1( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 64 x i1> @llvm.riscv.vmand.nxv64i1.i64(<vscale x 64 x i1> [[OP1:%.*]], <vscale x 64 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 64 x i1> [[TMP0]] // vbool1_t test_vmmv_m_b1 (vbool1_t op1, size_t vl) { return vmmv(op1, vl); } // // CHECK-RV64-LABEL: @test_vmmv_m_b2( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 32 x i1> @llvm.riscv.vmand.nxv32i1.i64(<vscale x 32 x i1> [[OP1:%.*]], <vscale x 32 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 32 x i1> [[TMP0]] // vbool2_t test_vmmv_m_b2 (vbool2_t op1, size_t vl) { return vmmv(op1, vl); } // // CHECK-RV64-LABEL: @test_vmmv_m_b4( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i1> @llvm.riscv.vmand.nxv16i1.i64(<vscale x 16 x i1> [[OP1:%.*]], <vscale x 16 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 16 x i1> [[TMP0]] // vbool4_t test_vmmv_m_b4 (vbool4_t op1, size_t vl) { return vmmv(op1, vl); } // // CHECK-RV64-LABEL: @test_vmmv_m_b8( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i1> @llvm.riscv.vmand.nxv8i1.i64(<vscale x 8 x i1> [[OP1:%.*]], <vscale x 8 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 8 x i1> [[TMP0]] // vbool8_t test_vmmv_m_b8 (vbool8_t op1, size_t vl) { return vmmv(op1, vl); } // // CHECK-RV64-LABEL: @test_vmmv_m_b16( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i1> @llvm.riscv.vmand.nxv4i1.i64(<vscale x 4 x i1> [[OP1:%.*]], <vscale x 4 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 4 x i1> [[TMP0]] // vbool16_t test_vmmv_m_b16 (vbool16_t op1, size_t vl) { return vmmv(op1, vl); } // // CHECK-RV64-LABEL: @test_vmmv_m_b32( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i1> @llvm.riscv.vmand.nxv2i1.i64(<vscale x 2 x i1> [[OP1:%.*]], <vscale x 2 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 2 x i1> [[TMP0]] // vbool32_t test_vmmv_m_b32 (vbool32_t op1, size_t vl) { return vmmv(op1, vl); } // // CHECK-RV64-LABEL: @test_vmmv_m_b64( // CHECK-RV64-NEXT: entry: // CHECK-RV64-NEXT: [[TMP0:%.*]] = call <vscale x 1 x i1> @llvm.riscv.vmand.nxv1i1.i64(<vscale x 1 x i1> [[OP1:%.*]], <vscale x 1 x i1> [[OP1]], i64 [[VL:%.*]]) // CHECK-RV64-NEXT: ret <vscale x 1 x i1> [[TMP0]] // vbool64_t test_vmmv_m_b64 (vbool64_t op1, size_t vl) { return vmmv(op1, vl); }
1,641
311
package datadog.trace.bootstrap.instrumentation.java.concurrent; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.Executor; import java.util.concurrent.RunnableFuture; /** Advice placeholder representing a call to {@link AbstractExecutorService#newTaskFor}. */ public final class NewTaskForPlaceholder { // arguments chosen to match the real non-static call, except the first is the executor itself public static <T> RunnableFuture<T> newTaskFor( final Executor executor, final Runnable task, final T value) { throw new RuntimeException( "Calls to this method will be rewritten by NewTaskForRewritingVisitor"); } }
197
14,668
// Copyright 2016 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 "third_party/blink/renderer/platform/wtf/text/string_view.h" #include <unicode/utf16.h> #include "third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" #include "third_party/blink/renderer/platform/wtf/text/string_impl.h" #include "third_party/blink/renderer/platform/wtf/text/utf8.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace WTF { namespace { class StackStringViewAllocator { public: explicit StackStringViewAllocator( StringView::StackBackingStore& backing_store) : backing_store_(backing_store) {} using ResultStringType = StringView; template <typename CharType> StringView Alloc(wtf_size_t length, CharType*& buffer) { buffer = backing_store_.Realloc<CharType>(length); return StringView(buffer, length); } StringView CoerceOriginal(StringView string) { return string; } private: StringView::StackBackingStore& backing_store_; }; } // namespace StringView::StringView(const UChar* chars) : StringView(chars, chars ? LengthOfNullTerminatedString(chars) : 0) {} #if DCHECK_IS_ON() StringView::~StringView() { DCHECK(impl_); DCHECK(!impl_->HasOneRef() || impl_->IsStatic()) << "StringView does not own the StringImpl, it " "must not have the last ref."; } #endif // Helper to write a three-byte UTF-8 code point to the buffer, caller must // check room is available. static inline void PutUTF8Triple(char*& buffer, UChar ch) { DCHECK_GE(ch, 0x0800); *buffer++ = static_cast<char>(((ch >> 12) & 0x0F) | 0xE0); *buffer++ = static_cast<char>(((ch >> 6) & 0x3F) | 0x80); *buffer++ = static_cast<char>((ch & 0x3F) | 0x80); } std::string StringView::Utf8(UTF8ConversionMode mode) const { unsigned length = this->length(); if (!length) return std::string(); // Allocate a buffer big enough to hold all the characters // (an individual UTF-16 UChar can only expand to 3 UTF-8 bytes). // Optimization ideas, if we find this function is hot: // * We could speculatively create a std::string to contain 'length' // characters, and resize if necessary (i.e. if the buffer contains // non-ascii characters). (Alternatively, scan the buffer first for // ascii characters, so we know this will be sufficient). // * We could allocate a std::string with an appropriate size to // have a good chance of being able to write the string into the // buffer without reallocing (say, 1.5 x length). if (length > std::numeric_limits<unsigned>::max() / 3) return std::string(); Vector<char, 1024> buffer_vector(length * 3); char* buffer = buffer_vector.data(); if (Is8Bit()) { const LChar* characters = Characters8(); unicode::ConversionResult result = unicode::ConvertLatin1ToUTF8(&characters, characters + length, &buffer, buffer + buffer_vector.size()); // (length * 3) should be sufficient for any conversion DCHECK_NE(result, unicode::kTargetExhausted); } else { const UChar* characters = Characters16(); if (mode == kStrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD) { const UChar* characters_end = characters + length; char* buffer_end = buffer + buffer_vector.size(); while (characters < characters_end) { // Use strict conversion to detect unpaired surrogates. unicode::ConversionResult result = unicode::ConvertUTF16ToUTF8( &characters, characters_end, &buffer, buffer_end, true); DCHECK_NE(result, unicode::kTargetExhausted); // Conversion fails when there is an unpaired surrogate. Put // replacement character (U+FFFD) instead of the unpaired // surrogate. if (result != unicode::kConversionOK) { DCHECK_LE(0xD800, *characters); DCHECK_LE(*characters, 0xDFFF); // There should be room left, since one UChar hasn't been // converted. DCHECK_LE(buffer + 3, buffer_end); PutUTF8Triple(buffer, kReplacementCharacter); ++characters; } } } else { bool strict = mode == kStrictUTF8Conversion; unicode::ConversionResult result = unicode::ConvertUTF16ToUTF8(&characters, characters + length, &buffer, buffer + buffer_vector.size(), strict); // (length * 3) should be sufficient for any conversion DCHECK_NE(result, unicode::kTargetExhausted); // Only produced from strict conversion. if (result == unicode::kSourceIllegal) { DCHECK(strict); return std::string(); } // Check for an unconverted high surrogate. if (result == unicode::kSourceExhausted) { if (strict) return std::string(); // This should be one unpaired high surrogate. Treat it the same // was as an unpaired high surrogate would have been handled in // the middle of a string with non-strict conversion - which is // to say, simply encode it to UTF-8. DCHECK_EQ(characters + 1, Characters16() + length); DCHECK_GE(*characters, 0xD800); DCHECK_LE(*characters, 0xDBFF); // There should be room left, since one UChar hasn't been // converted. DCHECK_LE(buffer + 3, buffer + buffer_vector.size()); PutUTF8Triple(buffer, *characters); } } } return std::string(buffer_vector.data(), buffer - buffer_vector.data()); } bool StringView::ContainsOnlyASCIIOrEmpty() const { if (StringImpl* impl = SharedImpl()) return impl->ContainsOnlyASCIIOrEmpty(); if (IsEmpty()) return true; ASCIIStringAttributes attrs = Is8Bit() ? CharacterAttributes(Characters8(), length()) : CharacterAttributes(Characters16(), length()); return attrs.contains_only_ascii; } String StringView::ToString() const { if (IsNull()) return String(); if (IsEmpty()) return g_empty_string; if (StringImpl* impl = SharedImpl()) return impl; if (Is8Bit()) return String(Characters8(), length_); return StringImpl::Create8BitIfPossible(Characters16(), length_); } AtomicString StringView::ToAtomicString() const { if (IsNull()) return g_null_atom; if (IsEmpty()) return g_empty_atom; if (StringImpl* impl = SharedImpl()) return AtomicString(impl); if (Is8Bit()) return AtomicString(Characters8(), length_); return AtomicString(Characters16(), length_); } bool EqualStringView(const StringView& a, const StringView& b) { if (a.IsNull() || b.IsNull()) return a.IsNull() == b.IsNull(); if (a.length() != b.length()) return false; if (a.Bytes() == b.Bytes() && a.Is8Bit() == b.Is8Bit()) return true; if (a.Is8Bit()) { if (b.Is8Bit()) return Equal(a.Characters8(), b.Characters8(), a.length()); return Equal(a.Characters8(), b.Characters16(), a.length()); } if (b.Is8Bit()) return Equal(a.Characters16(), b.Characters8(), a.length()); return Equal(a.Characters16(), b.Characters16(), a.length()); } bool DeprecatedEqualIgnoringCaseAndNullity(const StringView& a, const StringView& b) { if (a.length() != b.length()) return false; if (a.Is8Bit()) { if (b.Is8Bit()) { return DeprecatedEqualIgnoringCase(a.Characters8(), b.Characters8(), a.length()); } return DeprecatedEqualIgnoringCase(a.Characters8(), b.Characters16(), a.length()); } if (b.Is8Bit()) { return DeprecatedEqualIgnoringCase(a.Characters16(), b.Characters8(), a.length()); } return DeprecatedEqualIgnoringCase(a.Characters16(), b.Characters16(), a.length()); } bool DeprecatedEqualIgnoringCase(const StringView& a, const StringView& b) { if (a.IsNull() || b.IsNull()) return a.IsNull() == b.IsNull(); return DeprecatedEqualIgnoringCaseAndNullity(a, b); } bool EqualIgnoringASCIICase(const StringView& a, const StringView& b) { if (a.IsNull() || b.IsNull()) return a.IsNull() == b.IsNull(); if (a.length() != b.length()) return false; if (a.Bytes() == b.Bytes() && a.Is8Bit() == b.Is8Bit()) return true; if (a.Is8Bit()) { if (b.Is8Bit()) return EqualIgnoringASCIICase(a.Characters8(), b.Characters8(), a.length()); return EqualIgnoringASCIICase(a.Characters8(), b.Characters16(), a.length()); } if (b.Is8Bit()) return EqualIgnoringASCIICase(a.Characters16(), b.Characters8(), a.length()); return EqualIgnoringASCIICase(a.Characters16(), b.Characters16(), a.length()); } StringView StringView::LowerASCIIMaybeUsingBuffer( StackBackingStore& buffer) const { return ConvertASCIICase(*this, LowerConverter(), StackStringViewAllocator(buffer)); } UChar32 StringView::CodepointAt(unsigned i) const { SECURITY_DCHECK(i < length()); if (Is8Bit()) return (*this)[i]; UChar32 codepoint; U16_GET(Characters16(), 0, i, length(), codepoint); return codepoint; } unsigned StringView::NextCodePointOffset(unsigned i) const { SECURITY_DCHECK(i < length()); if (Is8Bit()) return i + 1; const UChar* str = Characters16() + i; ++i; if (i < length() && U16_IS_LEAD(*str++) && U16_IS_TRAIL(*str)) ++i; return i; } } // namespace WTF
3,829
460
package com.tasly.product.core; import com.tasly.product.core.api.ProductService; import org.springframework.web.bind.annotation.RestController; /** * Created by dulei on 18/1/9. */ @RestController public class ProductServiceImpl implements ProductService { }
84
451
<reponame>kikislater/micmac<filename>applis/Traj_AJ/Traj_AJ_Match.cpp /*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : <NAME> Contributors : <NAME>, <NAME>. [1] <NAME>, <NAME>. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] <NAME>, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "general/all.h" #include "private/all.h" #include "Traj_Aj.h" using namespace NS_AJ; //================================= // LEARN OFFSET //================================= // Stat /* void cAppli_Traj_AJ::Avance(const std::vector<double> & aV,int aK0,double aVMax) { while( (aK0<int(aV.size()) ) && (aV[aK0]<aVMax)) { aK0++; } return aK0; } */ double cAppli_Traj_AJ::LearnOffsetByStatDiff(cTAj2_OneLayerIm* aLIm,cTAj2_LayerLogIm* aLLog,const cLearnByStatDiff & aLD) { std::vector<double> aVDif; for (int aKIm = 0 ; aKIm <aLIm->NbIm() ; aKIm++) { for (int aKLog = 0 ; aKLog <aLLog->NbLog() ; aKLog++) { double aTIm = aLIm->KthIm(aKIm)->T0(); double aTLog = aLLog->KthLog(aKLog)->T0(); aVDif.push_back(aTLog - aTIm); } } std::sort(aVDif.begin(),aVDif.end()); double a2E = 2 * aLD.MaxEcart().Val(); int aK0 = 0; int aK1 = 0; double aScoreMax = -1; double aOfsetMax=0; for (; aK0<int(aVDif.size()) ; aK0++) { while( (aK1<int(aVDif.size()) ) && (aVDif[aK1]<aVDif[aK0]+a2E)) { aK1++; } double aScore = aK1-aK0; if (aScore>aScoreMax) { aScoreMax = aScore; aOfsetMax = (aVDif[aK0] + aVDif[aK1-1]) /2.0; if (0) { std::cout << "OODffa " << aOfsetMax << " " << aVDif[aK0] << " " << aVDif[aK1-1] << " " << aScore << "\n"; } } } ELISE_ASSERT(aScoreMax > 0, "cAppli_Traj_AJ::LearnOffsetByStatDiff"); std::cout << "Learn Stat " << aScoreMax << " OFFSET =" << aOfsetMax << " dans interv avec " << aLIm->NbIm() << " images \n"; return aOfsetMax; } // Example double cAppli_Traj_AJ::LearnOffsetByExample(cTAj2_OneLayerIm* aLIm,cTAj2_LayerLogIm* aLLog,const cLearnByExample & aLbE) { cTAj2_OneImage * aIm0 = aLIm->ImOfName(aLbE.Im0()); int aK0Im = aIm0->Num(); int aK0Log = aLbE.Log0(); int aDeltaMin = ElMax3(aLbE.DeltaMinRech(),-aK0Im,-aK0Log); int aDeltaMax = ElMin3(aLbE.DeltaMaxRech(),aLIm->NbIm()-aK0Im,aLLog->NbLog()-aK0Log); // std::cout << aLIm->NbIm() << " " << aLLog->NbLog() << "\n"; // std::cout << aLbE.DeltaMaxRech() << " " << aK0Im << " " << aK0Log << "\n"; std::cout << aDeltaMin << " " << aDeltaMax << "\n"; std::vector<double> aVDif; for (int aDelta=aDeltaMin ; aDelta<aDeltaMax ; aDelta++) { int aKIm = aK0Im+aDelta; int aKLog = aK0Log+aDelta; double aTIm = aLIm->KthIm(aKIm)->T0(); double aTLog = aLLog->KthLog(aKLog)->T0(); aVDif.push_back(aTLog - aTIm); if (aLbE.Show().Val()) { std::cout << aLIm->KthIm(aKIm)-> Name() << " : " << aTLog - aTIm ; if (aKIm >= 1) { std::cout << " DTPrec " << aLIm->KthIm(aKIm)->T0() -aLIm->KthIm(aKIm-1)->T0() << " "; } std::cout << "\n"; } } std::sort(aVDif.begin(),aVDif.end()); double aVMed= (ValPercentile(aVDif,90.0)+ValPercentile(aVDif,10.0)) /2.0; if (aLbE.ShowPerc().Val()) { std::vector<double> aVPerc; aVPerc.push_back(0); aVPerc.push_back(5); aVPerc.push_back(10); aVPerc.push_back(25); aVPerc.push_back(50); aVPerc.push_back(75); aVPerc.push_back(90); aVPerc.push_back(95); aVPerc.push_back(100); for (int aK=0 ; aK<int(aVPerc.size()) ; aK++) { double aPerc = aVPerc[aK]; double aValP = ValPercentile(aVDif,aPerc); double aRk1 = aPerc; double aRk2 = (aValP-aVMed+0.5) * 100.0; std::cout << "Dif[" << aPerc << "%]=" << aValP << " Coh% " << (aRk1-aRk2) << "\n"; } std::cout << " -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n"; } return aVMed; } // Global double cAppli_Traj_AJ::LearnOffset(cTAj2_OneLayerIm* aLIm,cTAj2_LayerLogIm* aLLog,const cLearnOffset & aLOf) { if (aLOf.LearnByExample().IsInit()) { return LearnOffsetByExample(aLIm,aLLog,aLOf.LearnByExample().Val()); } if (aLOf.LearnByStatDiff().IsInit()) { return LearnOffsetByStatDiff(aLIm,aLLog,aLOf.LearnByStatDiff().Val()); } ELISE_ASSERT(false,"Internal Error cAppli_Traj_AJ::LearnOffset"); return 0; } //================================= // ALGO MATCH //================================= void cAppli_Traj_AJ::DoMatchNearest(cTAj2_OneLayerIm* aLIm,cTAj2_LayerLogIm* aLLog,const cMatchNearestIm & aMI) { for (int aKIm = 0 ; aKIm <aLIm->NbIm() ; aKIm++) { // bool DEBUG= (aKIm==100); cTAj2_OneImage * anIm= aLIm->KthIm(aKIm); for (int aKLog = 0 ; aKLog <aLLog->NbLog() ; aKLog++) { cTAj2_OneLogIm * aLog = aLLog->KthLog(aKLog); double aDif = ElAbs(aLog->T0() - anIm->T0() -mCurOffset); // if (aDif<0.52) std::cout << "DIF = " << aDif << "\n"; if (aDif < aMI.TolAmbig()) { anIm->UpdateMatch(aLog,aDif); aLog->UpdateMatch(anIm,aDif); } } // if (DEBUG) getchar(); } // std::cout << "uuuuuuuuuUUU \n"; getchar(); /* int aNbOk = 0; int aNbNoMatch = 0; int aNbAmbig = 0; for (int aKIm = 0 ; aKIm <aLIm->NbIm() ; aKIm++) { cTAj2_OneImage * anIm= aLIm->KthIm(aKIm); eTypeMatch aTM = anIm->QualityMatch(aMI.TolMatch()); anIm->SetDefQualityMatch(aTM); if (aTM==eMatchParfait) { aNbOk++; aLIm->AddMatchedIm(anIm); } else if ((aTM==eNoMatch) || (aTM==eMatchDifForte)) { aNbNoMatch++; std::cout << anIm->Name() << " UnMatched\n"; } else { aNbAmbig++; std::cout << anIm->Name() << " Ambigu\n"; } } std::cout << " -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n"; std::cout << "Un Matched Images " << aNbNoMatch << "\n"; std::cout << "Ambiguous Images " << aNbAmbig << "\n"; aNbOk = 0; aNbNoMatch = 0; aNbAmbig = 0; for (int aKLog = 0 ; aKLog <aLLog->NbLog() ; aKLog++) { cTAj2_OneLogIm * aLog = aLLog->KthLog(aKLog); eTypeMatch aTM = aLog->QualityMatch(aMI.TolMatch()); if (aTM==eMatchParfait) { aNbOk++; } else if ((aTM==eNoMatch) || (aTM==eMatchDifForte)) { aNbNoMatch++; } else { aNbAmbig++; } } std::cout << "Un Matched Log " << aNbNoMatch << "\n"; std::cout << "Ambiguous Log " << aNbAmbig << "\n"; std::cout << " -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n"; */ } void cAppli_Traj_AJ::DoAlgoMatchByName ( cTAj2_OneLayerIm* aLIm, cTAj2_LayerLogIm* aLLog, const cMatchByName & aMN ) { std::vector<cTAj2_OneLogIm *> & aVLs = aLLog->Logs(); std::vector<cTAj2_OneImage *> & aVIm = aLIm-> Ims(); for (int aKLog=0 ; aKLog<int(aVLs.size()); aKLog++) { const std::string & aKey = aVLs[aKLog]->KeyIm(); std::string aName = mICNM->Assoc1To1(aMN.KeyLog2Im(),aKey,true); for (int aKIm=0 ; aKIm<int(aVIm.size()); aKIm++) { if (aVIm[aKIm]->Name() == aName) { aVIm[aKIm]->UpdateMatch(aVLs[aKLog],0); aVLs[aKLog]->UpdateMatch(aVIm[aKIm],0); } } } } void cAppli_Traj_AJ::DoAlgoMatch(cTAj2_OneLayerIm* aLIm,cTAj2_LayerLogIm* aLLog,const cAlgoMatch & anAlgo) { aLIm->ResetMatch(); aLLog->ResetMatch(); double aTol = 1e20; if (anAlgo.MatchNearestIm().IsInit()) { DoMatchNearest(aLIm,aLLog,anAlgo.MatchNearestIm().Val()); aTol = anAlgo.MatchNearestIm().Val().TolMatch(); } else if (anAlgo.MatchByName().IsInit()) { DoAlgoMatchByName(aLIm,aLLog,anAlgo.MatchByName().Val()); } else { ELISE_ASSERT(false,"Internal Error cAppli_Traj_AJ::LearnOffset"); } int aNbOk = 0; int aNbNoMatch = 0; int aNbAmbig = 0; for (int aKIm = 0 ; aKIm <aLIm->NbIm() ; aKIm++) { cTAj2_OneImage * anIm= aLIm->KthIm(aKIm); eTypeMatch aTM = anIm->QualityMatch(aTol); anIm->SetDefQualityMatch(aTM); if (aTM==eMatchParfait) { aNbOk++; aLIm->AddMatchedIm(anIm); } else if ((aTM==eNoMatch) || (aTM==eMatchDifForte)) { aNbNoMatch++; std::cout << anIm->Name() << " UnMatched\n"; } else { aNbAmbig++; std::cout << anIm->Name() << " Ambigu\n"; } } std::cout << " -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n"; std::cout << "Un Matched Images " << aNbNoMatch << "\n"; std::cout << "Ambiguous Images " << aNbAmbig << "\n"; aNbOk = 0; aNbNoMatch = 0; aNbAmbig = 0; for (int aKLog = 0 ; aKLog <aLLog->NbLog() ; aKLog++) { cTAj2_OneLogIm * aLog = aLLog->KthLog(aKLog); eTypeMatch aTM = aLog->QualityMatch(aTol); if (aTM==eMatchParfait) { aNbOk++; } else if ((aTM==eNoMatch) || (aTM==eMatchDifForte)) { aNbNoMatch++; } else { aNbAmbig++; } } std::cout << "Un Matched Log " << aNbNoMatch << "\n"; std::cout << "Ambiguous Log " << aNbAmbig << "\n"; std::cout << " -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n"; } //================================= // GENERE ORIENT //================================= void cAppli_Traj_AJ::GenerateOrient ( cTAj2_OneLayerIm* aLIm, const cTrAJ2_SectionMatch & aSM, const cTrAJ2_GenerateOrient & aGO ) { bool aTFC = aGO.Teta1FromCap().Val(); bool aDelayGps = aGO.CorrecDelayGps().IsInit(); bool isVReq = aTFC || aDelayGps; if (isVReq) { ELISE_ASSERT ( aSM.ModeliseVitesse().IsInit(), "Vitesses required in cAppli_Traj_AJ::GenerateOrient" ); } cSysCoord * aCS = cSysCoord::FromXML(aGO.SysCible(),mDC.c_str()); CamStenope * aCam = Std_Cal_From_File(DC()+aGO.NameCalib()); for (int aKIm = 0 ; aKIm <aLIm->NbIm() ; aKIm++) { cTAj2_OneImage * anIm= aLIm->KthIm(aKIm); ///std::cout << "AAAAA " << (anIm->DefQualityMatch()==eMatchParfait) << " " << ((!isVReq ) || (anIm->VitOK())) << "\n"; if ( (anIm->DefQualityMatch()==eMatchParfait) && ((!isVReq ) || (anIm->VitOK())) ) { ///std::cout << "BBBBB\n"; cTAj2_OneLogIm * aLog = anIm->BestMatch(); if (0) { std::cout << anIm->Name() << " " << aLog->KLine() << "\n"; } std::string aNameOr = DC() + mICNM->Assoc1To1(aGO.KeyName(),anIm->Name(),true); ElMatrix<double> aRVectCam2Av = Std_RAff_C2M(aLIm->SIm().OrientationCamera(),aLIm->SIm().ConvOrCam().Val()); double aCap = aLog->Teta(0); Pt3dr aCentre = aCS->FromGeoC(aLog->PGeoC()); if (isVReq) { Pt3dr aP0 = aCS->FromGeoC(aLog->PGeoC()); Pt3dr aP1 = aCS->FromGeoC(aLog->PGeoC()+anIm->Vitesse()); Pt3dr aV = aP1 - aP0; double aCapV = atan2(aV.y,aV.x); if (aTFC) { aCap = aCapV; } if (aDelayGps) { aCentre = aCentre + aV * aGO.CorrecDelayGps().Val(); } } ElMatrix<double> aRVectCap = ElMatrix<double>::Rotation(aCap,0,0); // oZ ElMatrix<double> aRouli = ElMatrix<double>::Rotation(0,aLog->Teta(1),0); // oY ElMatrix<double> aTangage = ElMatrix<double>::Rotation(0,0,aLog->Teta(2)); // oX ElMatrix<double> aRVectAv2Ter = aRVectCap * aRouli * aTangage; if (aKIm==0) { std::cout << "ROLTANG " << aLog->Teta(0) << " " << aLog->Teta(1) << " " << aLog->Teta(2) << "\n"; ElRotation3D aR (Pt3dr(0,0,0),aRVectAv2Ter); std::cout << "MAT " << aR.teta01() << " " << aR.teta02() << " " << aR.teta12() << "\n"; } /* */ ElMatrix<double> aRVectCam2Ter = aLog->MatI2C() * aRVectAv2Ter * aRVectCam2Av; ///ShowMatr("JJJkkk",aLog->MatI2C()); // ElMatrix<double> aRR = aLog->MatI2C() ; std::cout << aRR.Teta12() << "\n"; ElRotation3D aRAv2Ter (aCentre,aRVectCam2Ter); // ElRotation3D aRAv2Ter (aCS->FromGeoC(aLog->PGeoC()),aRVectCam2Ter); // cOrientationExterneRigide anOER = From_Std_RAff_C2M(aRAv2Ter,true); aCam->SetOrientation(aRAv2Ter.inv()); aCam->SetAltiSol(aGO.AltiSol()); aCam->SetTime(aLog->T0()); cOrientationConique anOC = aCam->StdExportCalibGlob(aGO.ModeMatrix().Val()); MakeFileXML(anOC,aNameOr); if (aKIm==0) { ElCamera * aCS = Cam_Gen_From_XML(anOC,mICNM); ElRotation3D aR = aCS->Orient().inv(); std::cout << "RELEC " << aR.teta01() << " " << aR.teta02() << " " << aR.teta12() << "\n"; } if (TraceImage(*anIm)) { std::cout << "Name " << anIm->Name() << " LINE " << aLog->KLine() << " GC " << aLog->PGeoC() << " Loc " << aCS->FromGeoC(aLog->PGeoC()) << "\n"; } if (0) { std::cout << "Name " << anIm->Name() << " Loc " << aCS->FromGeoC(aLog->PGeoC()) << " CapINS " << aLog->Teta(0) << " R " << aLog->Teta(1) << " T " << aLog->Teta(2); if ((aKIm>0) && (aKIm<aLIm->NbIm()-1)) { cTAj2_OneImage * aIPrec= aLIm->KthIm(aKIm-1); cTAj2_OneImage * aINext= aLIm->KthIm(aKIm+1); if ( (aIPrec->DefQualityMatch()==eMatchParfait) && (aINext->DefQualityMatch()==eMatchParfait) ) { cTAj2_OneLogIm * aLPrec = aIPrec->BestMatch(); cTAj2_OneLogIm * aLNext = aINext->BestMatch(); Pt3dr aVec = aCS->FromGeoC(aLNext->PGeoC()) -aCS->FromGeoC(aLPrec->PGeoC()); Pt2dr aV2(aVec.x,aVec.y); // std::cout << aV2 ; // aV2 = aV2 / Pt2dr(0,1); // double aDTeta = atan2(aV2.y,aV2.x)+ aLog->Teta(0); // if (aDTeta < -PI) aDTeta += 2* PI; // if (aDTeta > PI) aDTeta -= 2* PI; std::cout << " Delta TRAJ " << aLog->Teta(0)-atan2(aV2.y,aV2.x) ; } } std::cout << "\n"; } // getchar(); } } } //================================= // VITESSES //================================= void cAppli_Traj_AJ::DoEstimeVitesse(cTAj2_OneLayerIm * aLIm,const cTrAJ2_ModeliseVitesse & aMV) { const std::vector<cTAj2_OneImage *> & aVI = aLIm->MatchedIms() ; for (int aK=1 ; aK<int(aVI.size()) ; aK++) { cTAj2_OneImage * aPrec = aVI[aK-1]; cTAj2_OneImage * aNext = aVI[aK]; double aDT = aPrec->BestMatch()->T0()-aNext->BestMatch()->T0(); bool aOK = ElAbs(aDT) < aMV.DeltaTimeMax(); if (aOK) aNext->SetLinks(aPrec); } for (int aK=0 ; aK<int(aVI.size()) ; aK++) { aVI[aK]->EstimVitesse(); if (! aVI[aK]->VitOK()) std::cout << "For " << aVI[aK]->Name() << " No vitesse estimed\n"; } } //================================= // GLOBAL //================================= void cAppli_Traj_AJ::DoOneMatch(const cTrAJ2_SectionMatch & aSM) { cTAj2_OneLayerIm * aLIm = ImLayerOfId(aSM.IdIm()); cTAj2_LayerLogIm * aLLog = LogLayerOfId(aSM.IdLog()); mIsInitCurOffset = false; if (aSM.LearnOffset().IsInit()) { mIsInitCurOffset = true; mCurOffset = LearnOffset(aLIm,aLLog,aSM.LearnOffset().Val()); } ELISE_ASSERT ( mIsInitCurOffset == (! aSM.AlgoMatch().MatchByName().IsInit()), "Incohe CurOffset / MatchByName" ); DoAlgoMatch(aLIm,aLLog,aSM.AlgoMatch()); if (mIsInitCurOffset) std::cout << "OFFS = " << mCurOffset << "\n"; if (aSM.ModeliseVitesse().IsInit()) { DoEstimeVitesse(aLIm,aSM.ModeliseVitesse().Val()); } if (aSM.GenerateOrient().IsInit()) { GenerateOrient(aLIm,aSM,aSM.GenerateOrient().Val()); } } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
10,635
4,002
<gh_stars>1000+ package me.zeroX150.cornos.gui.screen; import com.lukflug.panelstudio.CollapsibleContainer; import com.lukflug.panelstudio.DraggableContainer; import com.lukflug.panelstudio.FixedComponent; import com.lukflug.panelstudio.SettingsAnimation; import com.lukflug.panelstudio.mc16.MinecraftGUI; import com.lukflug.panelstudio.settings.*; import com.lukflug.panelstudio.theme.ColorScheme; import com.lukflug.panelstudio.theme.Theme; import me.zeroX150.cornos.Cornos; import me.zeroX150.cornos.etc.config.*; import me.zeroX150.cornos.etc.manager.KeybindManager; import me.zeroX150.cornos.etc.render.particles.ConnectingParticles; import me.zeroX150.cornos.features.module.Module; import me.zeroX150.cornos.features.module.ModuleRegistry; import me.zeroX150.cornos.features.module.ModuleType; import me.zeroX150.cornos.features.module.impl.external.Hud; import net.minecraft.client.gui.DrawableHelper; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.Text; import org.lwjgl.glfw.GLFW; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ClickGUI extends MinecraftGUI { private final GUIInterface guiInterface; private final com.lukflug.panelstudio.ClickGUI gui; ConnectingParticles p; public ClickGUI() { p = new ConnectingParticles(100); guiInterface = new GUIInterface(true) { @Override protected String getResourcePrefix() { return "ccl:gui/"; } @Override public void drawString(Point pos, String s, Color c) { end(); Cornos.minecraft.textRenderer.draw(new MatrixStack(), " " + s, pos.x, pos.y, c.getRGB()); begin(); } @Override public int getFontWidth(String s) { return Cornos.minecraft.textRenderer.getWidth(s); } @Override public int getFontHeight() { return Cornos.minecraft.textRenderer.fontHeight; } }; Theme theme = new com.lukflug.panelstudio.theme.GameSenseTheme(new ColorScheme() { @Override public Color getActiveColor() { return me.zeroX150.cornos.features.module.impl.external.ClickGUI.activeColor.getColor(); } @Override public Color getInactiveColor() { return me.zeroX150.cornos.features.module.impl.external.ClickGUI.inactiveColor.getColor(); } @Override public Color getBackgroundColor() { return me.zeroX150.cornos.features.module.impl.external.ClickGUI.backgroundColor.getColor(); } @Override public Color getOutlineColor() { return Hud.themeColor.getColor(); } @Override public Color getFontColor() { return Colors.TEXT.get(); } @Override public int getOpacity() { return 255; } }, 8, 4, 0); gui = new com.lukflug.panelstudio.ClickGUI(guiInterface, context -> { int h = Cornos.minecraft.getWindow().getScaledHeight(); int x = Cornos.minecraft.getWindow().getScaledWidth() / 2; DrawableHelper.drawCenteredString(new MatrixStack(), Cornos.minecraft.textRenderer, context.getDescription(), x, h - 15, 0xFFFFFFFF); }); int offset = 10 - 114; int offsetY = 10; for (ModuleType type : ModuleType.values()) { if (type == ModuleType.HIDDEN) continue; int maxW = 96; for (Module m : ModuleRegistry.getAll()) { if (m.type != type) continue; maxW = Math.max(maxW, Cornos.minecraft.textRenderer.getWidth(m.type.getN())); } offset += 114; if (offset > Cornos.minecraft.getWindow().getScaledWidth()) { offset = 10; offsetY += 114; } com.lukflug.panelstudio.DraggableContainer container = new DraggableContainer(type.getN(), null, theme.getContainerRenderer(), new SimpleToggleable(false), new SettingsAnimation(me.zeroX150.cornos.features.module.impl.external.ClickGUI.getNumSet()), null, new Point(offset, offsetY), maxW + 8) { @Override protected int getScrollHeight(int childHeight) { int h = Cornos.minecraft.getWindow().getScaledHeight(); return Math.min(Math.min(h - 20, 400), childHeight); } }; gui.addComponent(container); for (Module m : ModuleRegistry.getAll()) { if (m.type != type) continue; maxW = Math.max(maxW, Cornos.minecraft.textRenderer.getWidth(m.name)); CollapsibleContainer mc = new CollapsibleContainer(m.name, m.description, theme.getContainerRenderer(), new SimpleToggleable(false), new SettingsAnimation(me.zeroX150.cornos.features.module.impl.external.ClickGUI.getNumSet()), new SimpleToggleable(m.isEnabled()) { @Override public boolean isOn() { return m.isEnabled(); } @Override public void toggle() { m.setEnabled(!m.isEnabled()); } }); container.addComponent(mc); for (MConf.ConfigKey kc : m.mconf.config) { maxW = Math.max(maxW, Cornos.minecraft.textRenderer.getWidth(kc.key + ": " + kc.value)); // it works. // don't question it. if (kc instanceof MConfToggleable) { BooleanComponent bc = new BooleanComponent(kc.key, kc.description, theme.getComponentRenderer(), new com.lukflug.panelstudio.settings.Toggleable() { @Override public void toggle() { ((MConfToggleable) kc).toggle(); } @Override public boolean isOn() { return ((MConfToggleable) kc).isEnabled(); } }); mc.addComponent(bc); } else if (kc instanceof MConfMultiOption) { List<String> l = new ArrayList<>(Arrays.asList(((MConfMultiOption) kc).possibleValues)); EnumSetting es = new EnumSetting() { int current = l.indexOf(kc.value); @Override public void increment() { current++; if (current > (((MConfMultiOption) kc).possibleValues.length - 1)) current = 0; kc.setValue(((MConfMultiOption) kc).possibleValues[current]); } @Override public String getValueName() { return ((MConfMultiOption) kc).possibleValues[current]; } }; EnumComponent ec = new EnumComponent(kc.key, kc.description, theme.getComponentRenderer(), es); mc.addComponent(ec); } else if (kc instanceof MConfKeyBind) { KeybindSetting ks = new KeybindSetting() { @Override public int getKey() { return (int) ((MConfKeyBind) kc).getValue(); } @Override public void setKey(int key) { if (key == 47 || key == 0) kc.setValue(-1 + ""); else kc.setValue(key + ""); KeybindManager.reload(); } @Override public String getKeyName() { String ret; if (this.getKey() < 0) { ret = "None"; } else { ret = GLFW.glfwGetKeyName(this.getKey(), this.getKey()); } if (ret == null) ret = this.getKey() + ""; return ret; } }; KeybindComponent kc1 = new KeybindComponent(theme.getComponentRenderer(), ks); mc.addComponent(kc1); } else if (kc instanceof MConfNum) { NumberSetting ns = new NumberSetting() { @Override public double getNumber() { return ((MConfNum) kc).getValue(); } @Override public void setNumber(double value) { kc.setValue(value + ""); } @Override public double getMaximumValue() { return ((MConfNum) kc).max; } @Override public double getMinimumValue() { return ((MConfNum) kc).min; } @Override public int getPrecision() { return 1; } }; NumberComponent nc = new NumberComponent(kc.key, kc.description, theme.getComponentRenderer(), ns, ((MConfNum) kc).min, ((MConfNum) kc).max); mc.addComponent(nc); } else if (kc instanceof MConfColor) { MConfColor rgbaColor = (MConfColor) kc; ColorSetting c = new ColorSetting() { @Override public Color getValue() { return rgbaColor.getColor(); } @Override public void setValue(Color value) { rgbaColor.setColor(value); } @Override public Color getColor() { return rgbaColor.getColor(); } @Override public boolean getRainbow() { return rgbaColor.isRainbow(); } @Override public void setRainbow(boolean rainbow) { rgbaColor.setRainbow(rainbow); } }; ColorComponent cc = new ColorComponent(kc.key, kc.description, theme.getComponentRenderer(), new SettingsAnimation(me.zeroX150.cornos.features.module.impl.external.ClickGUI.getNumSet()), theme.getComponentRenderer(), c, false, true, new com.lukflug.panelstudio.settings.Toggleable() { boolean state = false; @Override public void toggle() { state = !state; } @Override public boolean isOn() { return state; } }); mc.addComponent(cc); } } } } } @Override protected void init() { super.init(); int w = Cornos.minecraft.getWindow().getScaledWidth(); int h = Cornos.minecraft.getWindow().getScaledHeight(); ButtonWidget expand = new ButtonWidget(w - 21, h - 21, 20, 20, Text.of("▼"), button -> { for (FixedComponent component : gui.getComponents()) { if (component instanceof CollapsibleContainer) { CollapsibleContainer collapsibleContainer = (CollapsibleContainer) component; if (!collapsibleContainer.isOn()) collapsibleContainer.toggle(); } } }); ButtonWidget no = new ButtonWidget(w - 21, h - 42, 20, 20, Text.of("▲"), button -> { for (FixedComponent component : gui.getComponents()) { if (component instanceof CollapsibleContainer) { CollapsibleContainer collapsibleContainer = (CollapsibleContainer) component; if (collapsibleContainer.isOn()) collapsibleContainer.toggle(); } } }); addButton(expand); addButton(no); } @Override protected com.lukflug.panelstudio.ClickGUI getGUI() { return gui; } @Override protected GUIInterface getInterface() { return guiInterface; } @Override protected int getScrollSpeed() { return 10; } @Override public void render(MatrixStack matrices, int mouseX, int mouseY, float partialTicks) { int h = Cornos.minecraft.getWindow().getScaledHeight(); int w = Cornos.minecraft.getWindow().getScaledWidth(); DrawableHelper.fill(matrices, 0, 0, w, h, Colors.GUIBACKGROUND.get().getRGB()); p.render(); super.render(matrices, mouseX, mouseY, partialTicks); } @Override public void tick() { p.tick(); super.tick(); } }
8,434
3,390
<reponame>Noahhoetger2001/test-infra # Copyright 2016 The Kubernetes 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. import cPickle as pickle import functools import logging import os import re import cloudstorage as gcs import jinja2 import webapp2 from google.appengine.api import urlfetch from google.appengine.api import memcache from webapp2_extras import sessions from webapp2_extras import security import secrets import filters as jinja_filters JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/templates'), extensions=['jinja2.ext.autoescape', 'jinja2.ext.loopcontrols'], trim_blocks=True, autoescape=True) JINJA_ENVIRONMENT.line_statement_prefix = '%' jinja_filters.register(JINJA_ENVIRONMENT.filters) def get_session_secret(): try: return str(secrets.get('session')) except KeyError: # Make a new session key -- only happens once per hostname! logging.warning('creating new session key!') session_key = security.generate_random_string(entropy=256) secrets.put('session', session_key) return session_key class BaseHandler(webapp2.RequestHandler): """Base class for Handlers that render Jinja templates.""" def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) # The default deadline of 5 seconds is too aggressive of a target for GCS # directory listing operations. urlfetch.set_default_fetch_deadline(60) def check_csrf(self): # https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet # #Checking_The_Referer_Header origin = self.request.headers.get('origin') + '/' expected = self.request.host_url + '/' if not (origin and origin == expected): logging.error('csrf check failed for %s, origin: %r', self.request.url, origin) self.abort(403) # This example code is from: # http://webapp2.readthedocs.io/en/latest/api/webapp2_extras/sessions.html def dispatch(self): # pylint: disable=attribute-defined-outside-init # maybe initialize secrets (first request) sessions_config = self.app.config['webapp2_extras.sessions'] if not sessions_config['secret_key']: sessions_config['secret_key'] = get_session_secret() # Get a session store for this request. self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response) @webapp2.cached_property def session(self): # Returns a session using the default cookie key. return self.session_store.get_session() def render(self, template, context): """Render a context dictionary using a given template.""" template = JINJA_ENVIRONMENT.get_template(template) self.response.write(template.render(context)) class IndexHandler(BaseHandler): """Render the index.""" def get(self): self.render("index.html", {'jobs': self.app.config['jobs']}) def memcache_memoize(prefix, expires=60 * 60, neg_expires=60): """Decorate a function to memoize its results using memcache. The function must take a single string as input, and return a pickleable type. Args: prefix: A prefix for memcache keys to use for memoization. expires: How long to memoized values, in seconds. neg_expires: How long to memoize falsey values, in seconds Returns: A decorator closure to wrap the function. """ # setting the namespace based on the current version prevents different # versions from sharing cache values -- meaning there's no need to worry # about incompatible old key/value pairs namespace = os.environ['CURRENT_VERSION_ID'] def wrapper(func): @functools.wraps(func) def wrapped(*args): key = '%s%s' % (prefix, args) data = memcache.get(key, namespace=namespace) if data is not None: return data else: data = func(*args) serialized_length = len(pickle.dumps(data, pickle.HIGHEST_PROTOCOL)) if serialized_length > 1000000: logging.warning('data too large to fit in memcache: %s > 1MB', serialized_length) return data try: if data: memcache.add(key, data, expires, namespace=namespace) else: memcache.add(key, data, neg_expires, namespace=namespace) except ValueError: logging.exception('unable to write to memcache') return data return wrapped return wrapper @memcache_memoize('gs-ls://', expires=60) def gcs_ls(path): """Enumerate files in a GCS directory. Returns a list of FileStats.""" if path[-1] != '/': path += '/' return list(gcs.listbucket(path, delimiter='/')) @memcache_memoize('gs-ls-recursive://', expires=60) def gcs_ls_recursive(path): """Enumerate files in a GCS directory recursively. Returns a list of FileStats.""" if path[-1] != '/': path += '/' return list(gcs.listbucket(path)) def pad_numbers(s): """Modify a string to make its numbers suitable for natural sorting.""" return re.sub(r'\d+', lambda m: m.group(0).rjust(16, '0'), s)
2,449
4,054
<reponame>Anlon-Burke/vespa<gh_stars>1000+ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "symbol_table.h" #include <vespa/vespalib/stllike/hash_map.hpp> namespace vespalib::slime { SymbolTable::SymbolTable(size_t expectedNumSymbols) : _symbols(3*expectedNumSymbols), _names(expectedNumSymbols, expectedNumSymbols*16) { } SymbolTable::~SymbolTable() = default; void SymbolTable::clear() { _names.clear(); _symbols.clear(); } Symbol SymbolTable::insert(const Memory &name) { SymbolMap::const_iterator pos = _symbols.find(name); if (pos == _symbols.end()) { Symbol symbol(_names.size()); SymbolVector::Reference r(_names.push_back(name.data, name.size)); _symbols.insert(std::make_pair(Memory(r.c_str(), r.size()), symbol)); return symbol; } return pos->second; } Symbol SymbolTable::lookup(const Memory &name) const { SymbolMap::const_iterator pos = _symbols.find(name); if (pos == _symbols.end()) { return Symbol(); } return pos->second; } }
445
575
<reponame>Ron423c/chromium<filename>chrome/browser/extensions/api/terminal/crostini_startup_status_unittest.cc<gh_stars>100-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 "chrome/browser/extensions/api/terminal/crostini_startup_status.h" #include <memory> #include <vector> #include "base/bind.h" #include "chrome/browser/chromeos/crostini/crostini_simple_types.h" #include "testing/gtest/include/gtest/gtest.h" using crostini::mojom::InstallerState; namespace extensions { class CrostiniStartupStatusTest : public testing::Test { protected: void Print(const std::string& output) { output_.emplace_back(std::move(output)); } void Done() { done_ = true; } CrostiniStartupStatus* NewStartupStatus(bool verbose) { return new CrostiniStartupStatus( base::BindRepeating(&CrostiniStartupStatusTest::Print, base::Unretained(this)), verbose); } void SetUp() override {} std::vector<std::string> output_; bool done_ = false; }; TEST_F(CrostiniStartupStatusTest, TestNotVerbose) { auto* startup_status = NewStartupStatus(false); startup_status->OnStageStarted(InstallerState::kStart); startup_status->OnStageStarted(InstallerState::kInstallImageLoader); startup_status->OnCrostiniRestarted(crostini::CrostiniResult::SUCCESS); EXPECT_EQ(output_.size(), 1u); // CR, delete line, default color, show cursor. EXPECT_EQ(output_[0], "\r\x1b[K\x1b[0m\x1b[?25h"); } TEST_F(CrostiniStartupStatusTest, TestVerbose) { auto* startup_status = NewStartupStatus(true); startup_status->OnStageStarted(InstallerState::kStart); startup_status->OnStageStarted(InstallerState::kInstallImageLoader); startup_status->OnCrostiniRestarted(crostini::CrostiniResult::SUCCESS); ASSERT_EQ(output_.size(), 5u); // Hide cursor, init progress. EXPECT_EQ(output_[0], "\x1b[?25l\x1b[35m[ ] "); // CR, purple, forward 12, yellow, stage. EXPECT_EQ(output_[1], "\r\x1b[35m[\x1b[12C\x1b[K\x1b[33mInitializing "); // CR, purple, progress, forward 11, erase, yellow, stage. EXPECT_EQ(output_[2], "\r\x1b[35m[=\x1b[11C\x1b[K\x1b[33mChecking the virtual machine "); // CR, purple, progress, forward 2, erase, green, done, symbol, CRLF. EXPECT_EQ(output_[3], "\r\x1b[35m[==========\x1b[2C\x1b[K\x1b[1;32mReady\r\n "); // CR, delete line, default color, show cursor; EXPECT_EQ(output_[4], "\r\x1b[K\x1b[0m\x1b[?25h"); } } // namespace extensions
1,034
920
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; import com.vecsight.dragonite.sdk.exception.ConnectionNotAliveException; import com.vecsight.dragonite.sdk.exception.IncorrectSizeException; import com.vecsight.dragonite.sdk.exception.SenderClosedException; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import com.vecsight.dragonite.sdk.msg.Message; import java.io.IOException; import java.net.SocketAddress; public class DragoniteServerSocket extends DragoniteSocket { private final ReceiveHandler receiver; private final ResendHandler resender; //THREAD private final SendHandler sender; private final BucketPacketSender bucketPacketSender; private final ACKSender ackSender; //THREAD private final SocketAddress remoteAddress; private final DragoniteServer dragoniteServer; private volatile boolean alive = true; private volatile long lastReceiveTime, lastSendTime; private final ConnectionState state = new ConnectionState(); private final Object closeLock = new Object(); private volatile String description; public DragoniteServerSocket(final SocketAddress remoteAddress, final long sendSpeed, final DragoniteServer dragoniteServer) { this.remoteAddress = remoteAddress; this.dragoniteServer = dragoniteServer; updateLastReceiveTime(); bucketPacketSender = new BucketPacketSender(bytes -> { dragoniteServer.sendPacket(bytes, remoteAddress); updateLastSendTime(); }, sendSpeed); ackSender = new ACKSender(this, bucketPacketSender, DragoniteGlobalConstants.ACK_INTERVAL_MS, dragoniteServer.getPacketSize()); resender = new ResendHandler(this, bucketPacketSender, state, dragoniteServer.getResendMinDelayMS(), DragoniteGlobalConstants.ACK_INTERVAL_MS); receiver = new ReceiveHandler(this, ackSender, state, dragoniteServer.getWindowMultiplier(), resender, dragoniteServer.getPacketSize()); sender = new SendHandler(this, bucketPacketSender, receiver, state, resender, dragoniteServer.getPacketSize()); description = "DSSocket"; } protected void onHandleMessage(final Message message, final int pktLength) { receiver.onHandleMessage(message, pktLength); } @Override protected void updateLastReceiveTime() { lastReceiveTime = System.currentTimeMillis(); } @Override public long getLastReceiveTime() { return lastReceiveTime; } @Override protected void updateLastSendTime() { lastSendTime = System.currentTimeMillis(); } @Override public long getLastSendTime() { return lastSendTime; } protected void sendHeartbeat() throws InterruptedException, IOException, SenderClosedException { sender.sendHeartbeatMessage(); } @Override public byte[] read() throws InterruptedException, ConnectionNotAliveException { return receiver.read(); } @Override public void send(final byte[] bytes) throws InterruptedException, IncorrectSizeException, IOException, SenderClosedException { if (dragoniteServer.isAutoSplit()) { sender.sendDataMessage_autoSplit(bytes); } else { sender.sendDataMessage_noSplit(bytes); } } @Override public DragoniteSocketStatistics getStatistics() { return new DragoniteSocketStatistics(remoteAddress, description, sender.getSendLength(), bucketPacketSender.getSendRawLength(), receiver.getReadLength(), receiver.getReceivedRawLength(), state.getEstimatedRTT(), state.getDevRTT(), resender.getTotalMessageCount(), resender.getResendCount(), receiver.getReceivedPktCount(), receiver.getDupPktCount()); } @Override public String getDescription() { return description; } @Override public void setDescription(final String description) { this.description = description; } @Override public boolean isAlive() { return alive; } @Override public SocketAddress getRemoteSocketAddress() { return remoteAddress; } @Override public long getSendSpeed() { return bucketPacketSender.getSpeed(); } @Override public void setSendSpeed(final long sendSpeed) { bucketPacketSender.setSpeed(sendSpeed); } @Override protected void closeSender() { sender.stopSend(); } @Override public void closeGracefully() throws InterruptedException, IOException, SenderClosedException { //send close msg //tick send //still receive //wait for close ack //close all synchronized (closeLock) { if (alive) { sender.sendCloseMessage((short) 0, true, true); destroy(); } } } @Override public void destroy() { destroy_impl(true); } protected void destroy_NoRemove() { destroy_impl(false); } private void destroy_impl(final boolean remove) { synchronized (closeLock) { if (alive) { alive = false; sender.stopSend(); receiver.close(); resender.close(); ackSender.close(); if (remove) dragoniteServer.removeConnectionFromMap(remoteAddress); } } } }
2,082
1,483
/* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package org.lealone.db.async; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class AsyncTaskHandlerFactory { private static AsyncTaskHandler DEFAULT_HANDLER = new AsyncTaskHandler() { @Override public void handle(AsyncTask task) { task.run(); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(AsyncTask task, long initialDelay, long delay, TimeUnit unit) { task.run(); return null; } }; private static final AtomicInteger index = new AtomicInteger(0); private static AsyncTaskHandler[] handlers = { DEFAULT_HANDLER }; public static void setAsyncTaskHandlers(AsyncTaskHandler[] handlers) { AsyncTaskHandlerFactory.handlers = handlers; } public static AsyncTaskHandler getAsyncTaskHandler() { return handlers[index.getAndIncrement() % handlers.length]; } }
392
1,989
<reponame>baoqt2/practical-machine-learning-with-python # coding: utf-8 """ Created on Mon May 17 00:00:00 2017 @author: DIP """ # # Import necessary dependencies and settings # In[1]: import pandas as pd import numpy as np import re import nltk # # Sample corpus of text documents # In[2]: corpus = ['The sky is blue and beautiful.', 'Love this blue and beautiful sky!', 'The quick brown fox jumps over the lazy dog.', 'The brown fox is quick and the blue dog is lazy!', 'The sky is very blue and the sky is very beautiful today', 'The dog is lazy but the brown fox is quick!' ] labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals'] corpus = np.array(corpus) corpus_df = pd.DataFrame({'Document': corpus, 'Category': labels}) corpus_df = corpus_df[['Document', 'Category']] corpus_df # # Simple text pre-processing # In[3]: wpt = nltk.WordPunctTokenizer() stop_words = nltk.corpus.stopwords.words('english') def normalize_document(doc): # lower case and remove special characters\whitespaces doc = re.sub(r'[^a-zA-Z0-9\s]', '', doc, re.I) doc = doc.lower() doc = doc.strip() # tokenize document tokens = wpt.tokenize(doc) # filter stopwords out of document filtered_tokens = [token for token in tokens if token not in stop_words] # re-create document from filtered tokens doc = ' '.join(filtered_tokens) return doc normalize_corpus = np.vectorize(normalize_document) # In[4]: norm_corpus = normalize_corpus(corpus) norm_corpus # # Bag of Words Model # In[5]: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(min_df=0., max_df=1.) cv_matrix = cv.fit_transform(norm_corpus) cv_matrix = cv_matrix.toarray() cv_matrix # In[6]: vocab = cv.get_feature_names() pd.DataFrame(cv_matrix, columns=vocab) # # Bag of N-Grams Model # In[7]: bv = CountVectorizer(ngram_range=(2,2)) bv_matrix = bv.fit_transform(norm_corpus) bv_matrix = bv_matrix.toarray() vocab = bv.get_feature_names() pd.DataFrame(bv_matrix, columns=vocab) # # TF-IDF Model # In[8]: from sklearn.feature_extraction.text import TfidfVectorizer tv = TfidfVectorizer(min_df=0., max_df=1., use_idf=True) tv_matrix = tv.fit_transform(norm_corpus) tv_matrix = tv_matrix.toarray() vocab = tv.get_feature_names() pd.DataFrame(np.round(tv_matrix, 2), columns=vocab) # # Document Similarity # In[9]: from sklearn.metrics.pairwise import cosine_similarity similarity_matrix = cosine_similarity(tv_matrix) similarity_df = pd.DataFrame(similarity_matrix) similarity_df # ## Clustering documents using similarity features # In[10]: from sklearn.cluster import KMeans km = KMeans(n_clusters=2) km.fit_transform(similarity_df) cluster_labels = km.labels_ cluster_labels = pd.DataFrame(cluster_labels, columns=['ClusterLabel']) pd.concat([corpus_df, cluster_labels], axis=1) # # Topic models # In[11]: from sklearn.decomposition import LatentDirichletAllocation lda = LatentDirichletAllocation(n_topics=2, max_iter=100, random_state=42) dt_matrix = lda.fit_transform(tv_matrix) features = pd.DataFrame(dt_matrix, columns=['T1', 'T2']) features # ## Show topics and their weights # In[12]: tt_matrix = lda.components_ for topic_weights in tt_matrix: topic = [(token, weight) for token, weight in zip(vocab, topic_weights)] topic = sorted(topic, key=lambda x: -x[1]) topic = [item for item in topic if item[1] > 0.6] print(topic) print() # ## Clustering documents using topic model features # In[13]: km = KMeans(n_clusters=2) km.fit_transform(features) cluster_labels = km.labels_ cluster_labels = pd.DataFrame(cluster_labels, columns=['ClusterLabel']) pd.concat([corpus_df, cluster_labels], axis=1) # # Word Embeddings # In[14]: from gensim.models import word2vec wpt = nltk.WordPunctTokenizer() tokenized_corpus = [wpt.tokenize(document) for document in norm_corpus] # Set values for various parameters feature_size = 10 # Word vector dimensionality window_context = 10 # Context window size min_word_count = 1 # Minimum word count sample = 1e-3 # Downsample setting for frequent words w2v_model = word2vec.Word2Vec(tokenized_corpus, size=feature_size, window=window_context, min_count = min_word_count, sample=sample) # In[15]: w2v_model.wv['sky'] # In[16]: def average_word_vectors(words, model, vocabulary, num_features): feature_vector = np.zeros((num_features,),dtype="float64") nwords = 0. for word in words: if word in vocabulary: nwords = nwords + 1. feature_vector = np.add(feature_vector, model[word]) if nwords: feature_vector = np.divide(feature_vector, nwords) return feature_vector def averaged_word_vectorizer(corpus, model, num_features): vocabulary = set(model.wv.index2word) features = [average_word_vectors(tokenized_sentence, model, vocabulary, num_features) for tokenized_sentence in corpus] return np.array(features) # In[17]: w2v_feature_array = averaged_word_vectorizer(corpus=tokenized_corpus, model=w2v_model, num_features=feature_size) pd.DataFrame(w2v_feature_array) # In[18]: from sklearn.cluster import AffinityPropagation ap = AffinityPropagation() ap.fit(w2v_feature_array) cluster_labels = ap.labels_ cluster_labels = pd.DataFrame(cluster_labels, columns=['ClusterLabel']) pd.concat([corpus_df, cluster_labels], axis=1)
2,401
370
<filename>src/main/java/com/vitco/app/importer/CCVxlImporter.java package com.vitco.app.importer; import com.vitco.app.importer.dataStatic.CCVxlStatic; import com.vitco.app.util.file.FileIn; import com.vitco.app.util.file.RandomAccessFileIn; import java.io.File; import java.io.IOException; /** * Voxel Importer for "Command & Conquer: Red Alert 2" voxel objects * * Taken from VxlReader * https://github.com/OpenRA/OpenRA/blob/bleed/OpenRA.Game/FileFormats/VxlReader.cs */ public class CCVxlImporter extends AbstractImporter { // constructor public CCVxlImporter(File file, String name) throws IOException { super(file, name); } // type of game (they use different color palettes) public enum NormalType { TiberianSun(2), RedAlert2(4); public final int id; NormalType(int id) { this.id = id; } } // voxel layer private final static class VxlLimb { public String name; public float scale; public float[] bounds; public int[] size; public NormalType type; public int voxelCount; } // read the voxel information for a specific layer private void readVoxelData(RandomAccessFileIn s, VxlLimb l) throws IOException { int baseSize = l.size[0] * l.size[1]; int[] colStart = new int[baseSize]; for (int i = 0; i < baseSize; i++) { colStart[i] = s.readInt32(); } s.seek(4 * baseSize, RandomAccessFileIn.CURRENT); int dataStart = (int) s.getFilePointer(); // Count the voxels in this limb l.voxelCount = 0; for (int i = 0; i < baseSize; i++) { // Empty column if (colStart[i] == -1) { continue; } s.seek(dataStart + colStart[i], RandomAccessFileIn.BEGINNING); int z = 0; do { z += s.readUInt8(); int count = s.readUInt8(); z += count; l.voxelCount += count; s.seek(2 * count + 1, RandomAccessFileIn.CURRENT); } while (z < l.size[2]); } // Read the data for (int i = 0; i < baseSize; i++) { // Empty column if (colStart[i] == -1) continue; s.seek(dataStart + colStart[i], RandomAccessFileIn.BEGINNING); int x = i % l.size[0]; int y = i / l.size[0]; int z = 0; do { z += s.readUInt8(); int count = s.readUInt8(); for (int j = 0; j < count; j++) { int color = s.readUInt8(); s.readUInt8(); //int normal = s.readUInt8(); // add a voxel with correct color addVoxel( x, -z, y, l.type == NormalType.TiberianSun ? CCVxlStatic.COLORS_TIBERIAN_DAWN[color] : CCVxlStatic.COLORS_RED_ALERT[color] ); z++; } // Skip duplicate count s.readUInt8(); } while (z < l.size[2]); } } // read file - returns true if file has loaded correctly @Override protected boolean read(FileIn fileIn, RandomAccessFileIn s) throws IOException { // identifier if (!s.readASCII(16).startsWith("Voxel Animation")) { return false; } // read basic information s.readUInt32(); int limbCount = s.readUInt32(); s.readUInt32(); int bodySize = s.readUInt32(); s.seek(770, RandomAccessFileIn.CURRENT); // Read Limb (layer) headers VxlLimb[] limbs = new VxlLimb[limbCount]; for (int i = 0; i < limbCount; i++) { limbs[i] = new VxlLimb(); limbs[i].name = s.readASCII(16).trim(); s.seek(12, RandomAccessFileIn.CURRENT); } // skip to the limb (layer) footers s.seek(802 + 28 * limbCount + bodySize, RandomAccessFileIn.BEGINNING); int[] limbDataOffset = new int[limbCount]; for (int i = 0; i < limbCount; i++) { limbDataOffset[i] = s.readUInt32(); s.seek(8, RandomAccessFileIn.CURRENT); limbs[i].scale = s.readFloat(); s.seek(48, RandomAccessFileIn.CURRENT); limbs[i].bounds = new float[6]; for (int j = 0; j < 6; j++) { limbs[i].bounds[j] = s.readFloat(); } limbs[i].size = new int[] {s.readByte() & 0xFF, s.readByte() & 0xFF, s.readByte() & 0xFF }; limbs[i].type = s.readByte() == 2 ? NormalType.TiberianSun : NormalType.RedAlert2; } // read the voxel data for all layers for (int i = 0; i < limbCount; i++) { // add a new layer addLayer(limbs[i].name); s.seek(802 + 28*limbCount + limbDataOffset[i], RandomAccessFileIn.BEGINNING); readVoxelData(s, limbs[i]); } // success (i.e. no error) return true; } }
2,665
6,478
<filename>spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/balancer/NacosBalancer.java /* * Copyright 2013-2018 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 com.alibaba.cloud.nacos.balancer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.client.naming.core.Balancer; import org.springframework.cloud.client.ServiceInstance; /** * @author itmuch.com XuDaojie * @since 2021.1 */ public class NacosBalancer extends Balancer { /** * Choose instance by weight. * @param instances Instance List * @return the chosen instance */ public static Instance getHostByRandomWeight2(List<Instance> instances) { return getHostByRandomWeight(instances); } /** * Spring Cloud LoadBalancer Choose instance by weight. * @param serviceInstances Instance List * @return the chosen instance */ public static ServiceInstance getHostByRandomWeight3( List<ServiceInstance> serviceInstances) { Map<Instance, ServiceInstance> instanceMap = new HashMap<>(); List<Instance> nacosInstance = serviceInstances.stream().map(serviceInstance -> { Map<String, String> metadata = serviceInstance.getMetadata(); // see // com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery.hostToServiceInstance() Instance instance = new Instance(); instance.setIp(serviceInstance.getHost()); instance.setPort(serviceInstance.getPort()); instance.setWeight(Double.parseDouble(metadata.get("nacos.weight"))); instance.setHealthy(Boolean.parseBoolean(metadata.get("nacos.healthy"))); instanceMap.put(instance, serviceInstance); return instance; }).collect(Collectors.toList()); Instance instance = getHostByRandomWeight2(nacosInstance); return instanceMap.get(instance); } }
760
1,639
#include<bits/stdc++.h> using namespace std; const int N = 3e5 + 9, mod = 998244353; struct base { double x, y; base() { x = y = 0; } base(double x, double y): x(x), y(y) { } }; inline base operator + (base a, base b) { return base(a.x + b.x, a.y + b.y); } inline base operator - (base a, base b) { return base(a.x - b.x, a.y - b.y); } inline base operator * (base a, base b) { return base(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); } inline base conj(base a) { return base(a.x, -a.y); } int lim = 1; vector<base> roots = {{0, 0}, {1, 0}}; vector<int> rev = {0, 1}; const double PI = acosl(- 1.0); void ensure_base(int p) { if(p <= lim) return; rev.resize(1 << p); for(int i = 0; i < (1 << p); i++) rev[i] = (rev[i >> 1] >> 1) + ((i & 1) << (p - 1)); roots.resize(1 << p); while(lim < p) { double angle = 2 * PI / (1 << (lim + 1)); for(int i = 1 << (lim - 1); i < (1 << lim); i++) { roots[i << 1] = roots[i]; double angle_i = angle * (2 * i + 1 - (1 << lim)); roots[(i << 1) + 1] = base(cos(angle_i), sin(angle_i)); } lim++; } } void fft(vector<base> &a, int n = -1) { if(n == -1) n = a.size(); assert((n & (n - 1)) == 0); int zeros = __builtin_ctz(n); ensure_base(zeros); int shift = lim - zeros; for(int i = 0; i < n; i++) if(i < (rev[i] >> shift)) swap(a[i], a[rev[i] >> shift]); for(int k = 1; k < n; k <<= 1) { for(int i = 0; i < n; i += 2 * k) { for(int j = 0; j < k; j++) { base z = a[i + j + k] * roots[j + k]; a[i + j + k] = a[i + j] - z; a[i + j] = a[i + j] + z; } } } } //eq = 0: 4 FFTs in total //eq = 1: 3 FFTs in total vector<int> multiply(vector<int> &a, vector<int> &b, int eq = 0) { int need = a.size() + b.size() - 1; int p = 0; while((1 << p) < need) p++; ensure_base(p); int sz = 1 << p; vector<base> A, B; if(sz > (int)A.size()) A.resize(sz); for(int i = 0; i < (int)a.size(); i++) { int x = (a[i] % mod + mod) % mod; A[i] = base(x & ((1 << 15) - 1), x >> 15); } fill(A.begin() + a.size(), A.begin() + sz, base{0, 0}); fft(A, sz); if(sz > (int)B.size()) B.resize(sz); if(eq) copy(A.begin(), A.begin() + sz, B.begin()); else { for(int i = 0; i < (int)b.size(); i++) { int x = (b[i] % mod + mod) % mod; B[i] = base(x & ((1 << 15) - 1), x >> 15); } fill(B.begin() + b.size(), B.begin() + sz, base{0, 0}); fft(B, sz); } double ratio = 0.25 / sz; base r2(0, - 1), r3(ratio, 0), r4(0, - ratio), r5(0, 1); for(int i = 0; i <= (sz >> 1); i++) { int j = (sz - i) & (sz - 1); base a1 = (A[i] + conj(A[j])), a2 = (A[i] - conj(A[j])) * r2; base b1 = (B[i] + conj(B[j])) * r3, b2 = (B[i] - conj(B[j])) * r4; if(i != j) { base c1 = (A[j] + conj(A[i])), c2 = (A[j] - conj(A[i])) * r2; base d1 = (B[j] + conj(B[i])) * r3, d2 = (B[j] - conj(B[i])) * r4; A[i] = c1 * d1 + c2 * d2 * r5; B[i] = c1 * d2 + c2 * d1; } A[j] = a1 * b1 + a2 * b2 * r5; B[j] = a1 * b2 + a2 * b1; } fft(A, sz); fft(B, sz); vector<int> res(need); for(int i = 0; i < need; i++) { long long aa = A[i].x + 0.5; long long bb = B[i].x + 0.5; long long cc = A[i].y + 0.5; res[i] = (aa + ((bb % mod) << 15) + ((cc % mod) << 30))%mod; } return res; } template <int32_t MOD> struct modint { int32_t value; modint() = default; modint(int32_t value_) : value(value_) {} inline modint<MOD> operator + (modint<MOD> other) const { int32_t c = this->value + other.value; return modint<MOD>(c >= MOD ? c - MOD : c); } inline modint<MOD> operator - (modint<MOD> other) const { int32_t c = this->value - other.value; return modint<MOD>(c < 0 ? c + MOD : c); } inline modint<MOD> operator * (modint<MOD> other) const { int32_t c = (int64_t)this->value * other.value % MOD; return modint<MOD>(c < 0 ? c + MOD : c); } inline modint<MOD> & operator += (modint<MOD> other) { this->value += other.value; if (this->value >= MOD) this->value -= MOD; return *this; } inline modint<MOD> & operator -= (modint<MOD> other) { this->value -= other.value; if (this->value < 0) this->value += MOD; return *this; } inline modint<MOD> & operator *= (modint<MOD> other) { this->value = (int64_t)this->value * other.value % MOD; if (this->value < 0) this->value += MOD; return *this; } inline modint<MOD> operator - () const { return modint<MOD>(this->value ? MOD - this->value : 0); } modint<MOD> pow(uint64_t k) const { modint<MOD> x = *this, y = 1; for (; k; k >>= 1) { if (k & 1) y *= x; x *= x; } return y; } modint<MOD> inv() const { return pow(MOD - 2); } // MOD must be a prime inline modint<MOD> operator / (modint<MOD> other) const { return *this * other.inv(); } inline modint<MOD> operator /= (modint<MOD> other) { return *this *= other.inv(); } inline bool operator == (modint<MOD> other) const { return value == other.value; } inline bool operator != (modint<MOD> other) const { return value != other.value; } inline bool operator < (modint<MOD> other) const { return value < other.value; } inline bool operator > (modint<MOD> other) const { return value > other.value; } }; template <int32_t MOD> modint<MOD> operator * (int64_t value, modint<MOD> n) { return modint<MOD>(value) * n; } template <int32_t MOD> modint<MOD> operator * (int32_t value, modint<MOD> n) { return modint<MOD>(value % MOD) * n; } template <int32_t MOD> ostream & operator << (ostream & out, modint<MOD> n) { return out << n.value; } using mint = modint<mod>; struct poly { vector<mint> a; inline void normalize() { while((int)a.size() && a.back() == 0) a.pop_back(); } template<class...Args> poly(Args...args): a(args...) { } poly(const initializer_list<mint> &x): a(x.begin(), x.end()) { } int size() const { return (int)a.size(); } inline mint coef(const int i) const { return (i < a.size() && i >= 0) ? a[i]: mint(0); } mint operator[](const int i) const { return (i < a.size() && i >= 0) ? a[i]: mint(0); } //Beware!! p[i] = k won't change the value of p.a[i] bool is_zero() const { for (int i = 0; i < size(); i++) if (a[i] != 0) return 0; return 1; } poly operator + (const poly &x) const { int n = max(size(), x.size()); vector<mint> ans(n); for(int i = 0; i < n; i++) ans[i] = coef(i) + x.coef(i); while ((int)ans.size() && ans.back() == 0) ans.pop_back(); return ans; } poly operator - (const poly &x) const { int n = max(size(), x.size()); vector<mint> ans(n); for(int i = 0; i < n; i++) ans[i] = coef(i) - x.coef(i); while ((int)ans.size() && ans.back() == 0) ans.pop_back(); return ans; } poly operator * (const poly& b) const { if(is_zero() || b.is_zero()) return {}; vector<int> A, B; for(auto x: a) A.push_back(x.value); for(auto x: b.a) B.push_back(x.value); auto res = multiply(A, B, (A == B)); vector<mint> ans; for(auto x: res) ans.push_back(mint(x)); while ((int)ans.size() && ans.back() == 0) ans.pop_back(); return ans; } poly operator * (const mint& x) const { int n = size(); vector<mint> ans(n); for(int i = 0; i < n; i++) ans[i] = a[i] * x; return ans; } poly operator / (const mint &x) const{ return (*this) * x.inv(); } poly& operator += (const poly &x) { return *this = (*this) + x; } poly& operator -= (const poly &x) { return *this = (*this) - x; } poly& operator *= (const poly &x) { return *this = (*this) * x; } poly& operator *= (const mint &x) { return *this = (*this) * x; } poly& operator /= (const mint &x) { return *this = (*this) / x; } poly mod_xk(int k) const { return {a.begin(), a.begin() + min(k, size())}; } //modulo by x^k poly mul_xk(int k) const { // multiply by x^k poly ans(*this); ans.a.insert(ans.a.begin(), k, 0); return ans; } poly div_xk(int k) const { // divide by x^k return vector<mint>(a.begin() + min(k, (int)a.size()), a.end()); } poly substr(int l, int r) const { // return mod_xk(r).div_xk(l) l = min(l, size()); r = min(r, size()); return vector<mint>(a.begin() + l, a.begin() + r); } poly differentiate() const { int n = size(); vector<mint> ans(n); for(int i = 1; i < size(); i++) ans[i - 1] = coef(i) * i; return ans; } poly integrate() const { int n = size(); vector<mint> ans(n + 1); for(int i = 0; i < size(); i++) ans[i + 1] = coef(i) / (i + 1); return ans; } poly inverse(int n) const { // 1 / p(x) % x^n, O(nlogn) assert(!is_zero()); assert(a[0] != 0); poly ans{mint(1) / a[0]}; for(int i = 1; i < n; i *= 2) { ans = (ans * mint(2) - ans * ans * mod_xk(2 * i)).mod_xk(2 * i); } return ans.mod_xk(n); } poly log(int n) const { //ln p(x) mod x^n assert(a[0] == 1); return (differentiate().mod_xk(n) * inverse(n)).integrate().mod_xk(n); } poly exp(int n) const { //e ^ p(x) mod x^n if(is_zero()) return {1}; assert(a[0] == 0); poly ans({1}); int i = 1; while(i < n) { poly C = ans.log(2 * i).div_xk(i) - substr(i, 2 * i); ans -= (ans * C).mod_xk(i).mul_xk(i); i *= 2; } return ans.mod_xk(n); } }; // number of subsets of an array of n elements having sum equal to k for each k from 1 to m int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; vector<int> a(m + 1, 0); for (int i = 0; i < n; i++) { int k; cin >> k; // k >= 1, handle [k = 0] separately if (k <= m) a[k]++; } poly p(m + 1, 0); for (int i = 1; i <= m; i++) { for (int j = 1; i * j <= m; j++) { if (j & 1) p.a[i * j] += mint(a[i]) / j; else p.a[i * j] -= mint(a[i]) / j; } } p = p.exp(m + 1); for (int i = 1; i <= m; i++) cout << p[i] << ' '; cout << '\n'; // check for m = 0 return 0; } // https://judge.yosupo.jp/problem/sharp_p_subset_sum
4,744
443
<filename>include/nty_buffer.h /* * MIT License * * Copyright (c) [2018] [WangBoJing] * 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. * * * **** ***** ************ *** * ** ** * *** * * * ** ** * ** * * * ** * * ** * * * ** * * ** * ** ** * ** * *** ** * ** * *********** ***** ***** ** ***** * **** * ** * ** ** ** ** *** * **** * ** * ** * ** ** * ** ** ** *** ** * ** * ** * * ** ** ** ** * * ** * ** ** * ** ** ** ** ** * ** * ** * * ** ** ** ** * ** * ** ** * ** ** ** ** * ** * ** ** * ** ** ** ** * ** * ** * * ** ** ** ** * ** * ** ** * ** ** ** ** * *** ** * * ** ** * ** ** * *** ** * ** ** ** * ** ** * ** ** * ** ** ** * *** ** * ** ** * * ** ** * **** ** ***** * **** * ****** ***** ** **** * ** * ** ***** ** **** ****** * */ #ifndef __NTY_BUFFER_H__ #define __NTY_BUFFER_H__ #include <stdint.h> #include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <errno.h> #include "nty_queue.h" #include "nty_tree.h" #include "nty_mempool.h" enum rb_caller { AT_APP, AT_MTCP }; #define MAX(a, b) ((a)>(b)?(a):(b)) #define MIN(a, b) ((a)<(b)?(a):(b)) /*----------------------------------------------------------------------------*/ typedef struct _nty_sb_manager { size_t chunk_size; uint32_t cur_num; uint32_t cnum; struct _nty_mempool *mp; struct _nty_sb_queue *freeq; } nty_sb_manager; typedef struct _nty_send_buffer { unsigned char *data; unsigned char *head; uint32_t head_off; uint32_t tail_off; uint32_t len; uint64_t cum_len; uint32_t size; uint32_t head_seq; uint32_t init_seq; } nty_send_buffer; #ifndef _INDEX_TYPE_ #define _INDEX_TYPE_ typedef uint32_t index_type; typedef int32_t signed_index_type; #endif typedef struct _nty_sb_queue { index_type _capacity; volatile index_type _head; volatile index_type _tail; nty_send_buffer * volatile * _q; } nty_sb_queue; #define NextIndex(sq, i) (i != sq->_capacity ? i + 1: 0) #define PrevIndex(sq, i) (i != 0 ? i - 1: sq->_capacity) #define MemoryBarrier(buf, idx) __asm__ volatile("" : : "m" (buf), "m" (idx)) /** rb frag queue **/ typedef struct _nty_rb_frag_queue { index_type _capacity; volatile index_type _head; volatile index_type _tail; struct _nty_fragment_ctx * volatile * _q; } nty_rb_frag_queue; /** ring buffer **/ typedef struct _nty_fragment_ctx { uint32_t seq; uint32_t len:31, is_calloc:1; struct _nty_fragment_ctx *next; } nty_fragment_ctx; typedef struct _nty_ring_buffer { u_char *data; u_char *head; uint32_t head_offset; uint32_t tail_offset; int merged_len; uint64_t cum_len; int last_len; int size; uint32_t head_seq; uint32_t init_seq; nty_fragment_ctx *fctx; } nty_ring_buffer; typedef struct _nty_rb_manager { size_t chunk_size; uint32_t cur_num; uint32_t cnum; nty_mempool *mp; nty_mempool *frag_mp; nty_rb_frag_queue *free_fragq; nty_rb_frag_queue *free_fragq_int; } nty_rb_manager; typedef struct _nty_stream_queue { index_type _capacity; volatile index_type _head; volatile index_type _tail; struct _nty_tcp_stream * volatile * _q; } nty_stream_queue; typedef struct _nty_stream_queue_int { struct _nty_tcp_stream **array; int size; int first; int last; int count; } nty_stream_queue_int; nty_sb_manager *nty_sbmanager_create(size_t chunk_size, uint32_t cnum); nty_rb_manager *RBManagerCreate(size_t chunk_size, uint32_t cnum); nty_stream_queue *CreateStreamQueue(int capacity); nty_stream_queue_int *CreateInternalStreamQueue(int size); void DestroyInternalStreamQueue(nty_stream_queue_int *sq); nty_send_buffer *SBInit(nty_sb_manager *sbm, uint32_t init_seq); void SBFree(nty_sb_manager *sbm, nty_send_buffer *buf); size_t SBPut(nty_sb_manager *sbm, nty_send_buffer *buf, const void *data, size_t len); int SBEnqueue(nty_sb_queue *sq, nty_send_buffer *buf); size_t SBRemove(nty_sb_manager *sbm, nty_send_buffer *buf, size_t len); size_t RBRemove(nty_rb_manager *rbm, nty_ring_buffer* buff, size_t len, int option); int RBPut(nty_rb_manager *rbm, nty_ring_buffer* buff, void* data, uint32_t len, uint32_t cur_seq); void RBFree(nty_rb_manager *rbm, nty_ring_buffer* buff); int StreamInternalEnqueue(nty_stream_queue_int *sq, struct _nty_tcp_stream *stream); struct _nty_tcp_stream *StreamInternalDequeue(nty_stream_queue_int *sq); /*** ******************************** sb queue ******************************** ***/ nty_sb_queue *CreateSBQueue(int capacity); int StreamQueueIsEmpty(nty_stream_queue *sq); nty_send_buffer *SBDequeue(nty_sb_queue *sq); nty_ring_buffer *RBInit(nty_rb_manager *rbm, uint32_t init_seq); struct _nty_tcp_stream *StreamDequeue(nty_stream_queue *sq); int StreamEnqueue(nty_stream_queue *sq, struct _nty_tcp_stream *stream); void DestroyStreamQueue(nty_stream_queue *sq); #endif
3,822
1,041
<gh_stars>1000+ package io.ebean.config; /** * Configuration for transaction profiling. */ public class ProfilingConfig { /** * When true transaction profiling is enabled. */ private boolean enabled; /** * Set true for verbose mode. */ private boolean verbose; /** * The minimum transaction execution time to be included in profiling. */ private long minimumMicros; /** * A specific set of profileIds to include in profiling. */ private int[] includeProfileIds = {}; /** * The number of profiles to write per file. */ private long profilesPerFile = 1000; private String directory = "profiling"; /** * Return true if transaction profiling is enabled. */ public boolean isEnabled() { return enabled; } /** * Set to true to enable transaction profiling. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Return true if verbose mode is used. */ public boolean isVerbose() { return verbose; } /** * Set to true to use verbose mode. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Return the minimum transaction execution to be included in profiling. */ public long getMinimumMicros() { return minimumMicros; } /** * Set the minimum transaction execution to be included in profiling. */ public void setMinimumMicros(long minimumMicros) { this.minimumMicros = minimumMicros; } /** * Return the specific set of profileIds to include in profiling. * When not set all transactions with profileIds are included. */ public int[] getIncludeProfileIds() { return includeProfileIds; } /** * Set a specific set of profileIds to include in profiling. * When not set all transactions with profileIds are included. */ public void setIncludeProfileIds(int[] includeProfileIds) { this.includeProfileIds = includeProfileIds; } /** * Return the number of profiles to write to a single file. */ public long getProfilesPerFile() { return profilesPerFile; } /** * Set the number of profiles to write to a single file. */ public void setProfilesPerFile(long profilesPerFile) { this.profilesPerFile = profilesPerFile; } /** * Return the directory profiling files are put into. */ public String getDirectory() { return directory; } /** * Set the directory profiling files are put into. */ public void setDirectory(String directory) { this.directory = directory; } /** * Load setting from properties. */ public void loadSettings(PropertiesWrapper p, String name) { enabled = p.getBoolean("profiling", enabled); verbose = p.getBoolean("profiling.verbose", verbose); directory = p.get("profiling.directory", directory); profilesPerFile = p.getLong("profiling.profilesPerFile", profilesPerFile); minimumMicros = p.getLong("profiling.minimumMicros", minimumMicros); String includeIds = p.get("profiling.includeProfileIds"); if (includeIds != null) { includeProfileIds = parseIds(includeIds); } } private int[] parseIds(String includeIds) { String[] ids = includeIds.split(","); int[] vals = new int[ids.length]; for (int i = 0; i < ids.length; i++) { vals[i] = Integer.parseInt(ids[i]); } return vals; } }
1,095
387
#include "pch.h" #include "resource.h" #include "InstallServiceDlg.h" #include "DialogHelper.h" const WinSys::ServiceInstallParams& CInstallServiceDlg::GetInstallParams() const { return m_InstallParams; } LRESULT CInstallServiceDlg::OnInitDialog(UINT, WPARAM, LPARAM, BOOL&) { DialogHelper::AdjustOKCancelButtons(this); DialogHelper::SetDialogIcon(this, IDI_SERVICE); ::SHAutoComplete(GetDlgItem(IDC_PATH), SHACF_FILESYSTEM); ::SHAutoComplete(GetDlgItem(IDC_TARGET_PATH), SHACF_FILESYS_DIRS); { ComboData data[] = { { L"Kernel Driver", 1 }, { L"File System Driver/Filter", 2 }, { L"Service Own Process", 0x10 }, { L"Service Shared Process", 0x20 }, { L"Service User Own Process", 0x50 }, { L"Service User Shared Process", 0x60 }, }; FillComboBox(IDC_TYPE, data, _countof(data), 2); } { ComboData data[] = { { L"Boot Start (Drivers only)", 0 }, { L"System Start (Drivers only)", 1 }, { L"Auto Start", 2 }, { L"Delayed Auto Start", 2 | 0x80 }, { L"Manual Start", 3 }, { L"Disabled", 4 }, }; FillComboBox(IDC_STARTUP, data, _countof(data), 4); } { ComboData data[] = { { L"Ignore", 0 }, { L"Normal", 1 }, { L"Severe", 2 }, { L"Critical", 3 } }; FillComboBox(IDC_ERROR_CONTROL, data, _countof(data), 1); } { ComboData data[] = { { L"Local System", 1 }, { L"Network Service", 2 }, { L"Local Service", 3 }, }; FillComboBox(IDC_ACCOUNT, data, _countof(data)); } return 0; } LRESULT CInstallServiceDlg::OnCloseCmd(WORD, WORD wID, HWND, BOOL&) { if (wID == IDOK) { m_InstallParams.ServiceName = GetDlgItemText(IDC_NAME); m_InstallParams.DisplayName = GetDlgItemText(IDC_DISPLAYNAME); CComboBox cb(GetDlgItem(IDC_STARTUP)); auto type = cb.GetItemData(cb.GetCurSel()); m_InstallParams.DelayedAutoStart = (type & 0x80) == 0x80; type &= 0xf; m_InstallParams.StartupType = static_cast<WinSys::ServiceStartType>(type); cb.Detach(); cb.Attach(GetDlgItem(IDC_TYPE)); m_InstallParams.ServiceType = static_cast<WinSys::ServiceType>(cb.GetItemData(cb.GetCurSel())); cb.Detach(); cb.Attach(GetDlgItem(IDC_ERROR_CONTROL)); m_InstallParams.ErrorControl = static_cast<WinSys::ServiceErrorControl>(cb.GetItemData(cb.GetCurSel())); m_InstallParams.AccountName = GetDlgItemText(IDC_ACCOUNT); m_InstallParams.Password = GetDlgItemText(IDC_PASSWORD); m_InstallParams.ImagePath = GetDlgItemText(IDC_PATH); if (m_InstallParams.ImagePath.empty()) { AtlMessageBox(*this, L"Image path cannot be empty", IDS_TITLE, MB_ICONERROR); return 0; } m_InstallParams.TargetPath = GetDlgItemText(IDC_TARGET_PATH); m_InstallParams.Dependencies = GetDlgItemText(IDC_DEP); m_InstallParams.LoadOrderGroup = GetDlgItemText(IDC_GROUP); } EndDialog(wID); return 0; } LRESULT CInstallServiceDlg::OnNameChanged(WORD, WORD wID, HWND, BOOL&) { GetDlgItem(IDOK).EnableWindow(GetDlgItem(IDC_NAME).GetWindowTextLength() > 0); return 0; } LRESULT CInstallServiceDlg::OnBrowseFile(WORD, WORD wID, HWND, BOOL&) { CSimpleFileDialog dlg(TRUE, nullptr, nullptr, OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST, L"Executables (*.exe)\0*.exe\0Drivers (*.sys)\0*.sys\0All Files\0*.*\0", *this); if (dlg.DoModal() == IDOK) SetDlgItemText(IDC_PATH, dlg.m_szFileName); return 0; } std::wstring CInstallServiceDlg::GetDlgItemText(UINT id) { CWindow win(GetDlgItem(id)); auto len = win.GetWindowTextLength(); std::wstring text; if (len) { text.resize(len + 1); win.GetWindowText(text.data(), len + 1); } return text; } void CInstallServiceDlg::FillComboBox(UINT id, ComboData* data, int count, int selected) { CComboBox cb(GetDlgItem(id)); for (int i = 0; i < count; i++) { auto& item = data[i]; cb.SetItemData(cb.AddString(item.text), item.data); } cb.SetCurSel(selected); cb.Detach(); }
1,650
10,225
package io.quarkus.vertx.graphql.it; import io.quarkus.test.junit.NativeImageTest; @NativeImageTest class VertxGraphqlIT extends VertxGraphqlTest { }
57
1,089
package org.zalando.logbook; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.function.Function; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.apache.commons.lang3.StringUtils.reverse; import static org.assertj.core.api.Assertions.assertThat; import static org.zalando.logbook.HeaderFilters.replaceCookies; final class CookieHeaderFilterTest { @Test void parsesSetCookieHeader() { final HeaderFilter unit = replaceCookies("sessionToken"::equals, "XXX"); final HttpHeaders before = HttpHeaders.of( "Set-Cookie", "theme=light", "sessionToken=abc<PASSWORD>; Path=/; Expires=Wed, 09 Jun 2021 10:18:14 GMT"); final HttpHeaders after = unit.filter(before); assertThat(after) .containsEntry("Set-Cookie", asList( "theme=light", "sessionToken=XXX; Path=/; Expires=Wed, 09 Jun 2021 10:18:14 GMT")); } @Test void ignoresEmptySetCookieHeader() { final HeaderFilter unit = replaceCookies("sessionToken"::equals, "XXX"); final HttpHeaders before = HttpHeaders.of("Set-Cookie", ""); final HttpHeaders after = unit.filter(before); assertThat(after).containsEntry("Set-Cookie", singletonList("")); } @ParameterizedTest @CsvSource({ "'',''", "sessionToken=,sessionToken=XXX", "sessionToken=abc123,sessionToken=XXX", "theme=light; sessionToken=abc123,theme=light; sessionToken=XXX", "sessionToken=abc123; userId=me,sessionToken=XXX; userId=me", "theme=light; sessionToken=abc123; userId=me,theme=light; sessionToken=XXX; userId=me" }) void parsesCookieHeader(final String input, final String expected) { final HeaderFilter unit = replaceCookies("sessionToken"::equals, "XXX"); final HttpHeaders before = HttpHeaders.of("Cookie", input); final HttpHeaders after = unit.filter(before); assertThat(after).containsEntry("Cookie", singletonList(expected)); } @ParameterizedTest @CsvSource({ "'',''", "sessionToken=,sessionToken=", "sessionToken=abc123,sessionToken=<PASSWORD>cba", "theme=light; sessionToken=<PASSWORD>,theme=light; sessionToken=<PASSWORD>", "sessionToken=<PASSWORD>; userId=me,sessionToken=<PASSWORD>; userId=em", "theme=light; sessionToken=<PASSWORD>; userId=me,theme=light; sessionToken=<PASSWORD>; userId=em" }) void replacesCookieHeader(final String input, final String expected) { final Function<String, String> replacer = StringUtils::reverse; final List<String> bannedCookieNames = Arrays.asList("sessionToken", "userId"); final HeaderFilter unit = replaceCookies(bannedCookieNames::contains, replacer); final HttpHeaders before = HttpHeaders.of("Cookie", input); final HttpHeaders after = unit.filter(before); assertThat(after).containsEntry("Cookie", singletonList(expected)); } @Test void ignoresNoCookieHeaders() { final HeaderFilter unit = replaceCookies("sessionToken"::equals, "XXX"); final HttpHeaders after = unit.filter(HttpHeaders.empty()); assertThat(after).isEmpty(); } }
1,450
1,109
# -*- coding: utf-8 -*- from datetime import datetime, timedelta import subprocess from cdecimal import Decimal from sqlalchemy import and_, func, select from twisted.internet import defer from twisted.internet.defer import inlineCallbacks from twisted.internet.task import LoopingCall from twisted.python import log from gryphon.data_service.auditors.auditor import Auditor import gryphon.data_service.util as util from gryphon.lib.models.emeraldhavoc.base import EmeraldHavocBase from gryphon.lib.models.emeraldhavoc.exchange_volume import ExchangeVolume from gryphon.lib.models.emeraldhavoc.trade import Trade from gryphon.lib.slacker import Slacker metadata = EmeraldHavocBase.metadata trades = metadata.tables['trade'] exchange_volumes = metadata.tables['exchange_volume'] class TradesAuditor(Auditor): def __init__(self, exchanges=[]): self.exchanges = exchanges def heartbeat(self, response=None): subprocess.call(["touch", "monit/heartbeat/trades_auditor_heartbeat.txt"]) @defer.inlineCallbacks def start(self): self.redis = yield util.setup_redis() self.setup_mysql() self.heartbeat_key = 'trades_auditor_heartbeat' self.looping_call = LoopingCall(self.audit).start(1800) self.accuracy_bottom = Decimal('0.99') self.accuracy_top = Decimal('1.01') self.slacker = Slacker('#notifications', 'Auditor') @inlineCallbacks def audit(self): successes = [] for exchange in self.exchanges: now = datetime.utcnow() twenty_four_hours_ago = now - timedelta(hours=24) ten_minutes_ago = now - timedelta(minutes=10) trades_sum_result = yield self.engine.execute( select([func.sum(trades.c.volume)]) .where(and_( trades.c.exchange.__eq__(exchange), trades.c.timestamp.between(twenty_four_hours_ago, now), )) ) trades_sum_result = yield trades_sum_result.fetchone() trades_volume = trades_sum_result[0] or 0 exchange_volume_result = yield self.engine.execute( select([exchange_volumes.c.exchange_volume]) .where(and_( exchange_volumes.c.exchange.__eq__(exchange), exchange_volumes.c.timestamp.between(ten_minutes_ago, now), )) .order_by(exchange_volumes.c.timestamp.desc()) ) exchange_volume_result = yield exchange_volume_result.fetchone() if exchange_volume_result: most_recent_exchange_volume = exchange_volume_result[0] accuracy = trades_volume / most_recent_exchange_volume log.msg('Trade Volume Accuracy on %s: %s' % (exchange, accuracy)) if accuracy < self.accuracy_bottom or accuracy > self.accuracy_top: successes.append(False) self.slacker.notify( '%s Trades Poller at %s accuracy. Outside %s-%s' % ( exchange, accuracy, self.accuracy_bottom, self.accuracy_top, )) else: successes.append(True) # If all exchanges passed their audit then we heartbeat. if all(successes): self.heartbeat()
1,593
1,353
<gh_stars>1000+ /* * Copyright (c) 2008, <NAME> * 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 "TwelveMonkeys" nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.util; import com.twelvemonkeys.lang.StringUtil; import com.twelvemonkeys.xml.XMLSerializer; import org.w3c.dom.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Properties subclass, that reads and writes files in a simple XML format. * Can be used in-place where ever {@link java.util.Properties} * is used. The major differences are that it reads * and writes XML files, instead of ".properties" format files, and has * support for typed values (where normal Properties only supports Strings). * <P/> * The greatest advantage of the XML format, is that it * supports hierarchial structures or grouping of properties, in addtition to * be a more standard way of storing data. The XML format also opens up for * allowing for more metadata on * the properties, such as type and the format information, specifying how to * read and write them. * <P/> * This class relies on SAX for reading and parsing XML, in * addition, it requires DOM for outputting XML. It is possible * to configure what (SAX implementing) parser to use, by setting the system * property {@code org.xml.sax.driver} to your favourite SAX parser. The * default is the {@code org.apache.xerces.parsers.SAXParser}. * <P/> * <STRONG><A name="DTD"></A>XML Format (DTD):</STRONG><BR/> * <PRE> * &lt;!ELEMENT properties (property)*&gt; * &lt;!ELEMENT property (value?, property*)&gt; * &lt;!ATTLIST property * name CDATA #REQUIRED * value CDATA #IMPLIED * type CDATA "String" * format CDATA #IMPLIED * &gt; * &lt;!ELEMENT value (PCDATA)&gt; * &lt;!ATTLIST value * type CDATA "String" * format CDATA #IMPLIED * &gt; * </PRE> * See {@link #SYSTEM_DTD_URI}, {@link #DTD}. * <BR/><BR/> * <STRONG>XML Format eample:</STRONG><BR/> * <PRE> * &lt;?xml version="1.0" encoding="UTF-8"?&gt; * &lt;!DOCTYPE properties SYSTEM "http://www.twelvemonkeys.com/xml/XMLProperties.dtd"&gt; * &lt;!-- A simple XMLProperties example --&gt; * &lt;!-- Sat Jan 05 00:16:55 CET 2002 --&gt; * &lt;properties&gt; * &lt;property name="one" value="1" type="Integer" /&gt; * &lt;property name="two"&gt; * &lt;property name="a" value="A" /&gt; * &lt;property name="b"&gt; * &lt;value&gt;B is a very long value, that can span several * lines * &lt;![CDATA[&lt;this&gt;&lt;doesn't ---&gt; really * matter&lt; * ]]&gt; * as it is escaped using CDATA.&lt;/value&gt; * &lt/property&gt; * &lt;property name="c" value="C"&gt; * &lt;property name="i" value="I"/&gt; * &lt;/property&gt; * &lt;/property&gt; * &lt;property name="date" value="16. Mar 2002" * type="java.util.Date" format="dd. MMM yyyy"/&gt; * &lt;property name="none" value="" /&gt; * &lt;/properties&gt; * </PRE> * Results in the properties {@code one=1, two.a=A, two.b=B is a very long..., * two.c=C, two.c.i=I, date=Sat Mar 16 00:00:00 CET 2002 * } and {@code none=}. Note that there is no property named * {@code two}. * * @see java.util.Properties * @see #setPropertyValue(String,Object) * @see #getPropertyValue(String) * @see #load(InputStream) * @see #store(OutputStream,String) * * @author <A href="<EMAIL>"><NAME></A> * @author last modified by $Author: haku $ * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/util/XMLProperties.java#1 $ * */ // TODO: Consider deleting this code.. Look at Properties XML format. public class XMLProperties extends Properties { /** {@code "UTF-8"} */ public final static String UTF_8_ENCODING = "UTF-8"; /** {@code "xmlns"} */ public final static String XMLNS = "xmlns"; /** {@code "properties"} */ public final static String PROPERTIES = "properties"; /** {@code "property"} */ public final static String PROPERTY = "property"; /** {@code "name"} */ public final static String PROPERTY_NAME = "name"; /** {@code "value"} */ public final static String PROPERTY_VALUE = "value"; /** {@code "type"} */ public final static String PROPERTY_TYPE = "type"; /** {@code "format"} */ public final static String PROPERTY_FORMAT = "format"; /** {@code "String"} ({@link java.lang.String}) */ public final static String DEFAULT_TYPE = "String"; /** {@code "yyyy-MM-dd hh:mm:ss.SSS"} * ({@link java.sql.Timestamp} format, excpet nanos) */ public final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd hh:mm:ss.SSS"; /** This is the DTD */ public final static String DTD = "<!ELEMENT properties (property*)>\n<!ELEMENT property (value?, property*)>\n<!ATTLIST property\n\tname CDATA #REQUIRED\n\tvalue CDATA #IMPLIED\n\ttype CDATA \"String\"\n>\n<!ELEMENT value (#PCDATA)>\n<!ATTLIST value\n\ttype CDATA \"String\"\n>"; /** {@code "http://www.twelvemonkeys.com/xml/XMLProperties.dtd"} */ public final static String SYSTEM_DTD_URI = "http://www.twelvemonkeys.com/xml/XMLProperties.dtd"; /** {@code "http://www.twelvemonkeys.com/xml/XMLProperties"} */ public final static String NAMESPACE_URI = "http://www.twelvemonkeys.com/xml/XMLProperties"; /** {@code "http://xml.org/sax/features/validation"} */ public final static String SAX_VALIDATION_URI = "http://xml.org/sax/features/validation"; /** debug */ private boolean mValidation = true; protected Vector mErrors = null; protected Vector mWarnings = null; // protected Hashtable mTypes = new Hashtable(); protected Hashtable mFormats = new Hashtable(); protected static DateFormat sDefaultFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT); /** * Creates an empty property list with no default values. */ public XMLProperties() {} /** * Creates an empty property list with the specified defaults. * * @param pDefaults the defaults. */ public XMLProperties(Properties pDefaults) { // Sets the protected defaults variable super(pDefaults); } void addXMLError(SAXParseException pException) { if (mErrors == null) { mErrors = new Vector(); } mErrors.add(pException); } /** * Gets the non-fatal XML errors (SAXParseExceptions) resulting from a * load. * * @return An array of SAXParseExceptions, or null if none occured. * * @see XMLProperties.PropertiesHandler * @see #load(InputStream) */ public SAXParseException[] getXMLErrors() { if (mErrors == null) { return null; } return (SAXParseException[]) mErrors.toArray(new SAXParseException[mErrors.size()]); } void addXMLWarning(SAXParseException pException) { if (mWarnings == null) { mWarnings = new Vector(); } mWarnings.add(pException); } /** * Gets the XML warnings (SAXParseExceptions) resulting from a load. * * @return An array of SAXParseExceptions, or null if none occured. * * @see XMLProperties.PropertiesHandler * @see #load(InputStream) */ public SAXParseException[] getXMLWarnings() { if (mWarnings == null) { return null; } return (SAXParseException[]) mWarnings.toArray(new SAXParseException[mWarnings.size()]); } /** * Reads a property list (key and element pairs) from the input stream. The * stream is assumed to be using the UFT-8 character encoding, and be in * valid, well-formed XML format. * <P/> * After loading, any errors or warnings from the SAX parser, are available * as array of SAXParseExceptions from the getXMLErrors and getXMLWarnings * methods. * * @param pInput the input stream to load from. * * @exception IOException if an error occurred when reading from the input * stream. Any SAXExceptions are also wrapped in IOExceptions. * * @see Properties#load(InputStream) * @see #DTD * @see #SYSTEM_DTD_URI * @see XMLProperties.PropertiesHandler * @see #getXMLErrors * @see #getXMLWarnings */ public synchronized void load(InputStream pInput) throws IOException { // Get parser instance XMLReader parser; // Try to instantiate System default parser String driver = System.getProperty("org.xml.sax.driver"); if (driver == null) { // Instantiate the org.apache.xerces.parsers.SAXParser as default driver = "org.apache.xerces.parsers.SAXParser"; } try { parser = XMLReaderFactory.createXMLReader(driver); parser.setFeature(SAX_VALIDATION_URI, mValidation); } catch (SAXNotRecognizedException saxnre) { // It should be okay to throw RuntimeExptions, as you will need an // XML parser throw new RuntimeException("Error configuring XML parser \"" + driver + "\": " + saxnre.getClass().getName() + ": " + saxnre.getMessage()); } catch (SAXException saxe) { throw new RuntimeException("Error creating XML parser \"" + driver + "\": " + saxe.getClass().getName() + ": " + saxe.getMessage()); } // Register handler PropertiesHandler handler = new PropertiesHandler(this); parser.setContentHandler(handler); parser.setErrorHandler(handler); parser.setDTDHandler(handler); parser.setEntityResolver(handler); // Read and parse XML try { parser.parse(new InputSource(pInput)); } catch (SAXParseException saxpe) { // Wrap SAXException in IOException to be consistent throw new IOException("Error parsing XML: " + saxpe.getClass().getName() + ": " + saxpe.getMessage() + " Line: " + saxpe.getLineNumber() + " Column: " + saxpe.getColumnNumber()); } catch (SAXException saxe) { // Wrap SAXException in IOException to be consistent // Doesn't realy matter, as the SAXExceptions seems to be pretty // meaningless themselves... throw new IOException("Error parsing XML: " + saxe.getClass().getName() + ": " + saxe.getMessage()); } } /** * Initializes the value of a property. * * @todo move init code to the parser? * * @throws ClassNotFoundException if there is no class found for the given * type * @throws IllegalArgumentException if the value given, is not parseable * as the given type */ protected Object initPropertyValue(String pValue, String pType, String pFormat) throws ClassNotFoundException { // System.out.println("pValue=" + pValue + " pType=" + pType // + " pFormat=" + pFormat); // No value to convert if (pValue == null) { return null; } // No conversion needed for Strings if ((pType == null) || pType.equals("String") || pType.equals("java.lang.String")) { return pValue; } Object value; if (pType.equals("Date") || pType.equals("java.util.Date")) { // Special parser needed try { // Parse date through StringUtil if (pFormat == null) { value = StringUtil.toDate(pValue, sDefaultFormat); } else { value = StringUtil.toDate(pValue, new SimpleDateFormat(pFormat)); } } catch (IllegalArgumentException e) { // Not parseable... throw e; } // Return return value; } else if (pType.equals("java.sql.Timestamp")) { // Special parser needed try { // Parse timestamp through StringUtil value = StringUtil.toTimestamp(pValue); } catch (IllegalArgumentException e) { // Not parseable... throw new RuntimeException(e.getMessage()); } // Return return value; } else { int dot = pType.indexOf("."); if (dot < 0) { pType = "java.lang." + pType; } // Get class Class cl = Class.forName(pType); // Try to create instance from <Constructor>(String) value = createInstance(cl, pValue); if (value == null) { // createInstance failed for some reason // Try to invoke the static method valueof(String) value = invokeStaticMethod(cl, "valueOf", pValue); // If the value is still null, well, then I cannot help... } } // Return return value; } /** * Creates an object from the given class' single argument constructor. * * @return The object created from the constructor. * If the constructor could not be invoked for any reason, null is * returned. */ private Object createInstance(Class pClass, Object pParam) { Object value; try { // Create param and argument arrays Class[] param = { pParam.getClass() }; Object[] arg = { pParam }; // Get constructor Constructor constructor = pClass.getDeclaredConstructor(param); // Invoke and create instance value = constructor.newInstance(arg); } catch (Exception e) { return null; } return value; } /** * Creates an object from any given static method, given the parameter * * @return The object returned by the static method. * If the return type of the method is a primitive type, it is wrapped in * the corresponding wrapper object (int is wrapped in an Integer). * If the return type of the method is void, null is returned. * If the method could not be invoked for any reason, null is returned. */ private Object invokeStaticMethod(Class pClass, String pMethod, Object pParam) { Object value = null; try { // Create param and argument arrays Class[] param = { pParam.getClass() }; Object[] arg = { pParam }; // Get method // *** If more than one such method is found in the class, and one // of these methods has a RETURN TYPE that is more specific than // any of the others, that method is reflected; otherwise one of // the methods is chosen ARBITRARILY. // java/lang/Class.html#getMethod(java.lang.String, java.lang.Class[]) java.lang.reflect.Method method = pClass.getMethod(pMethod, param); // Invoke public static method if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) { value = method.invoke(null, arg); } } catch (Exception e) { return null; } return value; } /** * Gets the format of a property. This value is used for formatting the * value before it is stored as xml. * * @param pKey a key in this hashtable. * * @return the format for the specified key or null if it does not * have one. */ public String getPropertyFormat(String pKey) { // Get format return StringUtil.valueOf(mFormats.get(pKey)); } /** * Sets the format of a property. This value is used for formatting the * value before it is stored as xml. * * @param pKey a key in this hashtable. * @param pFormat a string representation of the format. * * @return the previous format for the specified key or null if it did not * have one. */ public synchronized String setPropertyFormat(String pKey, String pFormat) { // Insert format return StringUtil.valueOf(mFormats.put(pKey, pFormat)); } /** * Calls the Hashtable method put. Provided for parallelism with the * getPropertyValue method. Enforces use of strings for property keys. * The value returned is the result of the Hashtable call to put. * * @param pKey the key to be placed into this property list. * @param pValue the value corresponding to key. * * @return the previous value of the specified key in this property list, * or null if it did not have one. * * @see #getPropertyValue(String) */ public synchronized Object setPropertyValue(String pKey, Object pValue) { // Insert value return put(pKey, pValue); } /** * Searches for the property with the specified key in this property list. * If the key is not found in this property list, the default property * list, and its defaults, recursively, are then checked. The method * returns null if the property is not found. * * @param pKey the property key. * * @return the value in this property list with the specified key value. * * @see #setPropertyValue(String, Object) * @see #getPropertyValue(String, Object) * @see Properties#defaults */ public synchronized Object getPropertyValue(String pKey) { return getPropertyValue(pKey, null); } /** * Searches for the property with the specified key in this property list. * If the key is not found in this property list, the default property * list, and its defaults, recursively, are then checked. The method * returns the default value argument if the property is not found. * * @param pKey the property key. * @param pDefaultValue the default value. * * @return the value in this property list with the specified key value. * * @see #getPropertyValue(String) * @see Properties#defaults */ public Object getPropertyValue(String pKey, Object pDefaultValue) { Object value = super.get(pKey); // super.get() is EXTREMELEY IMPORTANT if (value != null) { return value; } if (defaults instanceof XMLProperties) { return (((XMLProperties) defaults).getPropertyValue(pKey)); } return ((defaults != null) ? defaults.getProperty(pKey) : pDefaultValue); } /** * Overloaded get method, that <EM>always returns Strings</EM>. * Due to the way the store and list methods of * java.util.Properties works (it calls get and casts to String, instead * of calling getProperty), this methods returns * StringUtil.valueOf(super.get), to avoid ClassCastExcpetions. * <P/> * <SMALL>If you need the old functionality back, * getPropertyValue returns super.get directly. * A cleaner approach would be to override the list and store * methods, but it's too much work for nothing...</SMALL> * * @param pKey a key in this hashtable * * @return the value to which the key is mapped in this hashtable, * converted to a string; null if the key is not mapped to any value in * this hashtable. * * @see #getPropertyValue(String) * @see Properties#getProperty(String) * @see Hashtable#get(Object) * @see StringUtil#valueOf(Object) */ public Object get(Object pKey) { //System.out.println("get(" + pKey + "): " + super.get(pKey)); Object value = super.get(pKey); // --- if ((value != null) && (value instanceof Date)) { // Hmm.. This is true for subclasses too... // Special threatment of Date String format = getPropertyFormat(StringUtil.valueOf(pKey)); if (format != null) { value = new SimpleDateFormat(format).format(value); } else { value = sDefaultFormat.format(value); } return value; } // --- // Simply return value return StringUtil.valueOf(value); } /** * Searches for the property with the specified key in this property list. * If the key is not found in this property list, the default property list, * and its defaults, recursively, are then checked. The method returns the * default value argument if the property is not found. * * @param pKey the hashtable key. * @param pDefaultValue a default value. * * @return the value in this property list with the specified key value. * @see #setProperty * @see #defaults */ public String getProperty(String pKey, String pDefaultValue) { // Had to override this because Properties uses super.get()... String value = (String) get(pKey); // Safe cast, see get(Object) if (value != null) { return value; } return ((defaults != null) ? defaults.getProperty(pKey) : pDefaultValue); } /** * Searches for the property with the specified key in this property list. * If the key is not found in this property list, the default property list, * and its defaults, recursively, are then checked. The method returns * {@code null} if the property is not found. * * @param pKey the property key. * @return the value in this property list with the specified key value. * @see #setProperty * @see #defaults */ public String getProperty(String pKey) { // Had to override this because Properties uses super.get()... return getProperty(pKey, null); } /** * Writes this property list (key and element pairs) in this * {@code Properties} * table to the output stream in a format suitable for loading into a * Properties table using the load method. This implementation writes * the list in XML format. The stream is written using the UTF-8 character * encoding. * * @param pOutput the output stream to write to. * @param pHeader a description of the property list. * * @exception IOException if writing this property list to the specified * output stream throws an IOException. * * @see java.util.Properties#store(OutputStream,String) */ public synchronized void store(OutputStream pOutput, String pHeader) throws IOException { storeXML(this, pOutput, pHeader); } /** * Utility method that stores the property list in normal properties * format. This method writes the list of Properties (key and element * pairs) in the given {@code Properties} * table to the output stream in a format suitable for loading into a * Properties table using the load method. The stream is written using the * ISO 8859-1 character encoding. * * @param pProperties the Properties table to store * @param pOutput the output stream to write to. * @param pHeader a description of the property list. * * @exception IOException if writing this property list to the specified * output stream throws an IOException. * * @see java.util.Properties#store(OutputStream,String) */ public static void storeProperties(Map pProperties, OutputStream pOutput, String pHeader) throws IOException { // Create new properties Properties props = new Properties(); // Copy all elements from the pProperties (shallow) Iterator iterator = pProperties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); props.setProperty((String) entry.getKey(), StringUtil.valueOf(entry.getValue())); } // Store normal properties props.store(pOutput, pHeader); } /** * Utility method that stores the property list in XML format. This method * writes the list of Properties (key and element pairs) in the given * {@code Properties} * table to the output stream in a format suitable for loading into a * XMLProperties table using the load method. Useful for converting * Properties into XMLProperties. * The stream is written using the UTF-8 character * encoding. * * @param pProperties the Properties table to store. * @param pOutput the output stream to write to. * @param pHeader a description of the property list. * * @exception IOException if writing this property list to the specified * output stream throws an IOException. * * @see #store(OutputStream,String) * @see java.util.Properties#store(OutputStream,String) * * @todo Find correct way of setting namespace URI's * @todo Store type and format information */ public static void storeXML(Map pProperties, OutputStream pOutput, String pHeader) throws IOException { // Build XML tree (Document) and write // Find the implementation DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw (IOException) new IOException(e.getMessage()).initCause(e); } DOMImplementation dom = builder.getDOMImplementation(); Document document = dom.createDocument(null, PROPERTIES, dom.createDocumentType(PROPERTIES, null, SYSTEM_DTD_URI)); Element root = document.getDocumentElement(); // This is probably not the correct way of setting a default namespace root.setAttribute(XMLNS, NAMESPACE_URI); // Create and insert the normal Properties headers as XML comments if (pHeader != null) { document.insertBefore(document.createComment(" " + pHeader + " "), root); } document.insertBefore(document.createComment(" " + new Date() + " "), root); // Insert elements from the Properties Iterator iterator = pProperties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); String format = null; if (pProperties instanceof XMLProperties) { format = ((XMLProperties) pProperties).getPropertyFormat(key); } insertElement(document, key, value, format); } // Create serializer and output document //XMLSerializer serializer = new XMLSerializer(pOutput, new OutputFormat(document, UTF_8_ENCODING, true)); XMLSerializer serializer = new XMLSerializer(pOutput, UTF_8_ENCODING); serializer.serialize(document); } /** * Inserts elements to the given document one by one, and creates all its * parents if needed. * * @param pDocument the document to insert to. * @param pName the name of the property element. * @param pValue the value of the property element. * @param pFormat * * @todo I guess this implementation could use some optimisaztion, as * we do a lot of unneccessary looping. */ private static void insertElement(Document pDocument, String pName, Object pValue, String pFormat) { // Get names of all elements we need String[] names = StringUtil.toStringArray(pName, "."); // Get value formatted as string String value = null; if (pValue != null) { // --- if (pValue instanceof Date) { // Special threatment of Date if (pFormat != null) { value = new SimpleDateFormat(pFormat).format(pValue); } else { value = sDefaultFormat.format(pValue); } } else { value = String.valueOf(pValue); } // --- } // Loop through document from root, and insert parents as needed Element element = pDocument.getDocumentElement(); for (int i = 0; i < names.length; i++) { boolean found = false; // Get children NodeList children = element.getElementsByTagName(PROPERTY); Element child = null; // Search for correct name for (int j = 0; j < children.getLength(); j++) { child = (Element) children.item(j); if (names[i].equals(child.getAttribute(PROPERTY_NAME))) { // Found found = true; element = child; break; // Next name } } // Test if the node was not found, otherwise we need to insert if (!found) { // Not found child = pDocument.createElement(PROPERTY); child.setAttribute(PROPERTY_NAME, names[i]); // Insert it element.appendChild(child); element = child; } // If it's the destination node, set the value if ((i + 1) == names.length) { // If the value string contains special data, // use a CDATA block instead of the "value" attribute if (StringUtil.contains(value, "\n") || StringUtil.contains(value, "\t") || StringUtil.contains(value, "\"") || StringUtil.contains(value, "&") || StringUtil.contains(value, "<") || StringUtil.contains(value, ">")) { // Create value element Element valueElement = pDocument.createElement(PROPERTY_VALUE); // Set type attribute String className = pValue.getClass().getName(); className = StringUtil.replace(className, "java.lang.", ""); if (!DEFAULT_TYPE.equals(className)) { valueElement.setAttribute(PROPERTY_TYPE, className); } // Set format attribute if (pFormat != null) { valueElement.setAttribute(PROPERTY_FORMAT, pFormat); } // Crate cdata section CDATASection cdata = pDocument.createCDATASection(value); // Append to document tree valueElement.appendChild(cdata); child.appendChild(valueElement); } else { // Just set normal attribute value child.setAttribute(PROPERTY_VALUE, value); // Set type attribute String className = pValue.getClass().getName(); className = StringUtil.replace(className, "java.lang.", ""); if (!DEFAULT_TYPE.equals(className)) { child.setAttribute(PROPERTY_TYPE, className); } // If format is set, store in attribute if (pFormat != null) { child.setAttribute(PROPERTY_FORMAT, pFormat); } } } } } /** * Gets all properties in a properties group. * If no properties exists in the specified group, {@code null} is * returned. * * @param pGroupKey the group key * * @return a new Properties continaing all properties in the group. Keys in * the new Properties wil not contain the group key. * If no properties exists in the specified group, {@code null} is * returned. */ public Properties getProperties(String pGroupKey) { // Stupid impl... XMLProperties props = new XMLProperties(); String groupKey = pGroupKey; if (groupKey.charAt(groupKey.length()) != '.') { groupKey += "."; } Iterator iterator = entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String key = (String) entry.getKey(); if (key.startsWith(groupKey)) { String subKey = key.substring(key.indexOf(groupKey)); props.setPropertyValue(subKey, entry.getValue()); } } return ((props.size() > 0) ? props : null); } /** * Sets the properties in the given properties group. * Existing properties in the same group, will not be removed, unless they * are replaced by new values. * Any existing properties in the same group that was replaced, are * returned. If no properties are replaced, <CODE>null<CODE> is * returned. * * @param pGroupKey the group key * @param pProperties the properties to set into this group * * @return Any existing properties in the same group that was replaced. * If no properties are replaced, <CODE>null<CODE> is * returned. */ public Properties setProperties(String pGroupKey, Properties pProperties) { XMLProperties old = new XMLProperties(); String groupKey = pGroupKey; if (groupKey.charAt(groupKey.length()) != '.') { groupKey += "."; } Iterator iterator = pProperties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String key = (String) entry.getKey(); Object obj = setPropertyValue(groupKey + key, entry.getValue()); // Return removed entries if (obj != null) { old.setPropertyValue(groupKey + key, entry.getValue()); } } return ((old.size() > 0) ? old : null); } /** * For testing only. */ public static void main(String[] pArgs) throws Exception { // -- Print DTD System.out.println("DTD: \n" + DTD); System.out.println("--"); // -- Test load System.out.println("Reading properties from \"" + pArgs[0] + "\"..."); XMLProperties props = new XMLProperties(); props.load(new FileInputStream(new File(pArgs[0]))); props.list(System.out); System.out.println("--"); // -- Test recursion String key = "key"; Object old = props.setProperty(key, "AAA"); Properties p1 = new XMLProperties(new XMLProperties(props)); Properties p2 = new Properties(new Properties(props)); System.out.println("XMLProperties: " + p1.getProperty(key) + " ==" + " Properties: " + p2.getProperty(key)); if (old == null) { props.remove("key"); } else { props.put("key", old); // Put old value back, to avoid confusion... } System.out.println("--"); // -- Test store //props.store(System.out, "XML Properties file written by XMLProperties."); File out = new File("copy_of_" + pArgs[0]); System.out.println("Writing properties to \"" + out.getName() + "\""); if (!out.exists()) { props.store(new FileOutputStream(out), "XML Properties file written by XMLProperties."); } else { System.err.println("File \"" + out.getName() + "\" allready exists, cannot write!"); } // -- Test utility methods // Write normal properties from XMLProperties out = new File("copy_of_" + pArgs[0].substring(0, pArgs[0].lastIndexOf(".")) + ".properties"); System.out.println("Writing properties to \"" + out.getName() + "\""); if (!out.exists()) { storeProperties(props, new FileOutputStream(out), "Properties file written by XMLProperties."); } else { System.err.println("File \"" + out.getName() + "\" allready exists, cannot write!"); } System.out.println("--"); // -- Test type attribute System.out.println("getPropertyValue(\"one\"): " + props.getPropertyValue("one") + " class: " + props.getPropertyValue("one").getClass()); System.out.println("setPropertyValue(\"now\", " + new Date() + "): " + props.setPropertyValue("now", new Date()) + " class: " + props.getPropertyValue("now").getClass()); System.out.println("getPropertyValue(\"date\"): " + props.getPropertyValue("date") + " class: " + props.getPropertyValue("date").getClass()); System.out.println("getPropertyValue(\"time\"): " + props.getPropertyValue("time") + " class: " + props.getPropertyValue("time").getClass()); } /** * ContentHandler, ErrorHandler and EntityResolver implementation for the * SAX Parser. */ protected class PropertiesHandler extends DefaultHandler { protected Stack mStack = null; /** Stores the characters read so far, from the characters callback */ protected char[] mReadSoFar = null; protected boolean mIsValue = false; protected String mType = null; protected String mFormat = null; protected XMLProperties mProperties = null; protected Locator mLocator = null; /** * Creates a PropertiesHandler for the given XMLProperties. */ PropertiesHandler(XMLProperties pProperties) { mProperties = pProperties; mStack = new Stack(); } /** * setDocumentLocator implementation. */ public void setDocumentLocator(Locator pLocator) { // System.out.println("Setting locator: " + pLocator); mLocator = pLocator; } /** * Calls XMLProperties.addXMLError with the given SAXParseException * as the argument. */ public void error(SAXParseException pException) throws SAXParseException { //throw pException; mProperties.addXMLError(pException); /* System.err.println("error: " + pException.getMessage()); System.err.println("line: " + mLocator.getLineNumber()); System.err.println("column: " + mLocator.getColumnNumber()); */ } /** * Throws the given SAXParseException (and stops the parsing). */ public void fatalError(SAXParseException pException) throws SAXParseException { throw pException; /* System.err.println("fatal error: " + pException.getMessage()); System.err.println("line: " + mLocator.getLineNumber()); System.err.println("column: " + mLocator.getColumnNumber()); */ } /** * Calls XMLProperties.addXMLWarning with the given SAXParseException * as the argument. */ public void warning(SAXParseException pException) throws SAXParseException { // throw pException; mProperties.addXMLWarning(pException); /* System.err.println("warning: " + pException.getMessage()); System.err.println("line: " + mLocator.getLineNumber()); System.err.println("column: " + mLocator.getColumnNumber()); */ } /** * startElement implementation. */ public void startElement(String pNamespaceURI, String pLocalName, String pQualifiedName, Attributes pAttributes) throws SAXException { /* String attributes = ""; for (int i = 0; i < pAttributes.getLength(); i++) { attributes += pAttributes.getQName(i) + "=" + pAttributes.getValue(i) + (i < pAttributes.getLength() ? ", " : ""); } System.out.println("startElement: " + pNamespaceURI + "." + pLocalName + " (" + pQualifiedName + ") " + attributes); */ if (XMLProperties.PROPERTY.equals(pLocalName)) { // Get attibute values String name = pAttributes.getValue(XMLProperties.PROPERTY_NAME); String value = pAttributes.getValue(XMLProperties.PROPERTY_VALUE); String type = pAttributes.getValue(XMLProperties.PROPERTY_TYPE); String format = pAttributes.getValue(XMLProperties.PROPERTY_FORMAT); // Get the full name of the property if (!mStack.isEmpty()) { name = (String) mStack.peek() + "." + name; } // Set the property if (value != null) { mProperties.setProperty(name, value); // Store type & format if (!XMLProperties.DEFAULT_TYPE.equals(type)) { mType = type; mFormat = format; // Might be null (no format) } } // Push the last name on the stack mStack.push(name); } // /PROPERTY else if (XMLProperties.PROPERTY_VALUE.equals(pLocalName)) { // Get attibute values String name = (String) mStack.peek(); String type = pAttributes.getValue(XMLProperties.PROPERTY_TYPE); String format = pAttributes.getValue(XMLProperties.PROPERTY_FORMAT); // Store type & format if (!XMLProperties.DEFAULT_TYPE.equals(type)) { mType = type; mFormat = format; } mIsValue = true; } } /** * endElement implementation. */ public void endElement(String pNamespaceURI, String pLocalName, String pQualifiedName) throws SAXException { /* System.out.println("endElement: " + pNamespaceURI + "." + pLocalName + " (" + pQualifiedName + ")"); */ if (XMLProperties.PROPERTY.equals(pLocalName)) { // Just remove the last name String name = (String) mStack.pop(); // Init typed values try { String prop = mProperties.getProperty(name); // Value may be null, if so just skip if (prop != null) { Object value = mProperties.initPropertyValue(prop, mType, mFormat); // Store format if ((mFormat != null) &&!XMLProperties.DEFAULT_DATE_FORMAT.equals(mFormat)) { mProperties.setPropertyFormat(name, mFormat); } //System.out.println("-->" + prop + "-->" + value); mProperties.setPropertyValue(name, value); } // Clear type & format mType = null; mFormat = null; } catch (Exception e) { e.printStackTrace(System.err); throw new SAXException(e); } } else if (XMLProperties.PROPERTY_VALUE.equals(pLocalName)) { if (mStack.isEmpty()) { // There can't be any characters here, really return; } // Get the full name of the property String name = (String) mStack.peek(); // Set the property String value = new String(mReadSoFar); //System.err.println("characters: >" + value+ "<"); if (!StringUtil.isEmpty(value)) { // If there is allready a value, both the value attribute // and element have been specified, this is an error if (mProperties.containsKey(name)) { throw new SAXParseException( "Value can only be specified either using the \"value\" attribute, OR the \"value\" element, not both.", mLocator); } // Finally, set the property mProperties.setProperty(name, value); } // Done value processing mIsValue = false; } } /** * characters implementation */ public void characters(char[] pChars, int pStart, int pLength) throws SAXException { // TODO: Use StringBuilder instead? if (mIsValue) { // If nothing read so far if (mReadSoFar == null) { // Create new array and copy into mReadSoFar = new char[pLength]; System.arraycopy(pChars, pStart, mReadSoFar, 0, pLength); } else { // Merge arrays mReadSoFar = (char[]) CollectionUtil.mergeArrays(mReadSoFar, 0, mReadSoFar.length, pChars, pStart, pLength); } } } /** * Intercepts the entity * "http://www.twelvemonkeys.com/xml/XMLProperties.dtd", and return * an InputSource based on the internal DTD of XMLProperties instead. * * @todo Maybe intercept a PUBLIC DTD and be able to have SYSTEM DTD * override? */ public InputSource resolveEntity(String pPublicId, String pSystemId) { // If we are looking for the standard SYSTEM DTD, then // Return an InputSource based on the internal DTD. if (XMLProperties.SYSTEM_DTD_URI.equals(pSystemId)) { return new InputSource(new StringReader(XMLProperties.DTD)); } // use the default behaviour return null; } } }
17,616
1,556
<filename>python-stdlib/json/test_json.py<gh_stars>1000+ import json inp = ["foo", {"bar": ("baz", None, 1, 2)}] print(inp) s = json.dumps(inp) print(s) outp = json.loads(s) print(outp) # Doesn't work because JSON doesn't have tuples # assert inp == outp
108
945
/* ---------------------------------------------------------------------------- @COPYRIGHT : Copyright 1993,1994,1995 <NAME>, McConnell Brain Imaging Centre, Montreal Neurological Institute, McGill University. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies. The author and McGill University make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. ---------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /*HAVE_CONFIG_H*/ #include <internal_volume_io.h> VIOAPI void convert_voxels_to_values( VIO_Volume volume, int n_voxels, VIO_Real voxels[], VIO_Real values[] ) { int v; VIO_Real scale, trans; if( !volume->real_range_set ) { if( voxels != values ) { for_less( v, 0, n_voxels ) values[v] = voxels[v]; } return; } scale = volume->real_value_scale; trans = volume->real_value_translation; for_less( v, 0, n_voxels ) values[v] = scale * voxels[v] + trans; } VIOAPI void get_volume_value_hyperslab( VIO_Volume volume, int v0, int v1, int v2, int v3, int v4, int n0, int n1, int n2, int n3, int n4, VIO_Real values[] ) { switch( get_volume_n_dimensions(volume) ) { case 1: get_volume_value_hyperslab_1d( volume, v0, n0, values ); break; case 2: get_volume_value_hyperslab_2d( volume, v0, v1, n0, n1, values ); break; case 3: get_volume_value_hyperslab_3d( volume, v0, v1, v2, n0, n1, n2, values ); break; case 4: get_volume_value_hyperslab_4d( volume, v0, v1, v2, v3, n0, n1, n2, n3, values ); break; case 5: get_volume_value_hyperslab_5d( volume, v0, v1, v2, v3, v4, n0, n1, n2, n3, n4, values ); break; } } VIOAPI void get_volume_value_hyperslab_5d( VIO_Volume volume, int v0, int v1, int v2, int v3, int v4, int n0, int n1, int n2, int n3, int n4, VIO_Real values[] ) { get_volume_voxel_hyperslab_5d( volume, v0, v1, v2, v3, v4, n0, n1, n2, n3, n4, values ); convert_voxels_to_values( volume, n0 * n1 * n2 * n3 * n4, values, values ); } VIOAPI void get_volume_value_hyperslab_4d( VIO_Volume volume, int v0, int v1, int v2, int v3, int n0, int n1, int n2, int n3, VIO_Real values[] ) { get_volume_voxel_hyperslab_4d( volume, v0, v1, v2, v3, n0, n1, n2, n3, values ); convert_voxels_to_values( volume, n0 * n1 * n2 * n3, values, values ); } VIOAPI void get_volume_value_hyperslab_3d( VIO_Volume volume, int v0, int v1, int v2, int n0, int n1, int n2, VIO_Real values[] ) { get_volume_voxel_hyperslab_3d( volume, v0, v1, v2, n0, n1, n2, values ); convert_voxels_to_values( volume, n0 * n1 * n2, values, values ); } VIOAPI void get_volume_value_hyperslab_2d( VIO_Volume volume, int v0, int v1, int n0, int n1, VIO_Real values[] ) { get_volume_voxel_hyperslab_2d( volume, v0, v1, n0, n1, values ); convert_voxels_to_values( volume, n0 * n1, values, values ); } VIOAPI void get_volume_value_hyperslab_1d( VIO_Volume volume, int v0, int n0, VIO_Real values[] ) { get_volume_voxel_hyperslab_1d( volume, v0, n0, values ); convert_voxels_to_values( volume, n0, values, values ); } static void slow_get_volume_voxel_hyperslab( VIO_Volume volume, int v0, int v1, int v2, int v3, int v4, int n0, int n1, int n2, int n3, int n4, VIO_Real values[] ) { int i0, i1, i2, i3, i4, n_dims; n_dims = get_volume_n_dimensions( volume ); if( n_dims < 5 ) n4 = 1; if( n_dims < 4 ) n3 = 1; if( n_dims < 3 ) n2 = 1; if( n_dims < 2 ) n1 = 1; if( n_dims < 1 ) n0 = 1; for_less( i0, 0, n0 ) for_less( i1, 0, n1 ) for_less( i2, 0, n2 ) for_less( i3, 0, n3 ) for_less( i4, 0, n4 ) { *values = get_volume_voxel_value( volume, v0 + i0, v1 + i1, v2 + i2, v3 + i3, v4 + i4 ); ++values; } } static VIO_Real *int_to_real_conversion = NULL; static void check_real_conversion_lookup( void ) { VIO_Real min_value1, max_value1, min_value2, max_value2; long i, long_min, long_max; if( int_to_real_conversion != NULL ) return; get_type_range( VIO_UNSIGNED_SHORT, &min_value1, &max_value1 ); get_type_range( VIO_SIGNED_SHORT, &min_value2, &max_value2 ); long_min = (long) MIN( min_value1, min_value2 ); long_max = (long) MAX( max_value1, max_value2 ); ALLOC( int_to_real_conversion, long_max - long_min + 1 ); #if 0 #ifndef NO_DEBUG_ALLOC (void) unrecord_ptr_alloc_check( int_to_real_conversion, __FILE__, __LINE__ ); #endif #endif int_to_real_conversion -= long_min; for_inclusive( i, long_min, long_max ) int_to_real_conversion[i] = (VIO_Real) i; } VIOAPI void get_voxel_values_5d( VIO_Data_types data_type, void *void_ptr, int steps[], int counts[], VIO_Real values[] ) { int step0, step1, step2, step3, step4; int i0, i1, i2, i3, i4; int n0, n1, n2, n3, n4; unsigned char *VIO_UCHAR_ptr; signed char *signed_byte_ptr; unsigned short *unsigned_short_ptr; signed short *signed_short_ptr; unsigned int *unsigned_int_ptr; signed int *signed_int_ptr; float *float_ptr; double *double_ptr; n0 = counts[0]; n1 = counts[1]; n2 = counts[2]; n3 = counts[3]; n4 = counts[4]; step0 = steps[0]; step1 = steps[1]; step2 = steps[2]; step3 = steps[3]; step4 = steps[4]; step0 -= n1 * step1; step1 -= n2 * step2; step2 -= n3 * step3; step3 -= n4 * step4; check_real_conversion_lookup(); switch( data_type ) { case VIO_UNSIGNED_BYTE: ASSIGN_PTR(VIO_UCHAR_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = int_to_real_conversion[ (long) *VIO_UCHAR_ptr]; ++values; VIO_UCHAR_ptr += step4; } VIO_UCHAR_ptr += step3; } VIO_UCHAR_ptr += step2; } VIO_UCHAR_ptr += step1; } VIO_UCHAR_ptr += step0; } break; case VIO_SIGNED_BYTE: ASSIGN_PTR(signed_byte_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = int_to_real_conversion[ (long) *signed_byte_ptr]; ++values; signed_byte_ptr += step4; } signed_byte_ptr += step3; } signed_byte_ptr += step2; } signed_byte_ptr += step1; } signed_byte_ptr += step0; } break; case VIO_UNSIGNED_SHORT: ASSIGN_PTR(unsigned_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = int_to_real_conversion[ (long) *unsigned_short_ptr]; ++values; unsigned_short_ptr += step4; } unsigned_short_ptr += step3; } unsigned_short_ptr += step2; } unsigned_short_ptr += step1; } unsigned_short_ptr += step0; } break; case VIO_SIGNED_SHORT: ASSIGN_PTR(signed_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = int_to_real_conversion[ (long) *signed_short_ptr]; ++values; signed_short_ptr += step4; } signed_short_ptr += step3; } signed_short_ptr += step2; } signed_short_ptr += step1; } signed_short_ptr += step0; } break; case VIO_UNSIGNED_INT: ASSIGN_PTR(unsigned_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = (VIO_Real) *unsigned_int_ptr; ++values; unsigned_int_ptr += step4; } unsigned_int_ptr += step3; } unsigned_int_ptr += step2; } unsigned_int_ptr += step1; } unsigned_int_ptr += step0; } break; case VIO_SIGNED_INT: ASSIGN_PTR(signed_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = (VIO_Real) *signed_int_ptr; ++values; signed_int_ptr += step4; } signed_int_ptr += step3; } signed_int_ptr += step2; } signed_int_ptr += step1; } signed_int_ptr += step0; } break; case VIO_FLOAT: ASSIGN_PTR(float_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = (VIO_Real) *float_ptr; ++values; float_ptr += step4; } float_ptr += step3; } float_ptr += step2; } float_ptr += step1; } float_ptr += step0; } break; default: case VIO_DOUBLE: ASSIGN_PTR(double_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { for_less( i4, 0, n4 ) { *values = (VIO_Real) *double_ptr; ++values; double_ptr += step4; } double_ptr += step3; } double_ptr += step2; } double_ptr += step1; } double_ptr += step0; } break; } } VIOAPI void get_voxel_values_4d( VIO_Data_types data_type, void *void_ptr, int steps[], int counts[], VIO_Real values[] ) { int step0, step1, step2, step3; int i0, i1, i2, i3; int n0, n1, n2, n3; unsigned char *VIO_UCHAR_ptr; signed char *signed_byte_ptr; unsigned short *unsigned_short_ptr; signed short *signed_short_ptr; unsigned int *unsigned_int_ptr; signed int *signed_int_ptr; float *float_ptr; double *double_ptr; n0 = counts[0]; n1 = counts[1]; n2 = counts[2]; n3 = counts[3]; step0 = steps[0]; step1 = steps[1]; step2 = steps[2]; step3 = steps[3]; step0 -= n1 * step1; step1 -= n2 * step2; step2 -= n3 * step3; check_real_conversion_lookup(); switch( data_type ) { case VIO_UNSIGNED_BYTE: ASSIGN_PTR(VIO_UCHAR_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = int_to_real_conversion[ (long) *VIO_UCHAR_ptr]; ++values; VIO_UCHAR_ptr += step3; } VIO_UCHAR_ptr += step2; } VIO_UCHAR_ptr += step1; } VIO_UCHAR_ptr += step0; } break; case VIO_SIGNED_BYTE: ASSIGN_PTR(signed_byte_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = int_to_real_conversion[(long) *signed_byte_ptr]; ++values; signed_byte_ptr += step3; } signed_byte_ptr += step2; } signed_byte_ptr += step1; } signed_byte_ptr += step0; } break; case VIO_UNSIGNED_SHORT: ASSIGN_PTR(unsigned_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = int_to_real_conversion[ (long) *unsigned_short_ptr]; ++values; unsigned_short_ptr += step3; } unsigned_short_ptr += step2; } unsigned_short_ptr += step1; } unsigned_short_ptr += step0; } break; case VIO_SIGNED_SHORT: ASSIGN_PTR(signed_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = int_to_real_conversion[ (long) *signed_short_ptr]; ++values; signed_short_ptr += step3; } signed_short_ptr += step2; } signed_short_ptr += step1; } signed_short_ptr += step0; } break; case VIO_UNSIGNED_INT: ASSIGN_PTR(unsigned_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = (VIO_Real) *unsigned_int_ptr; ++values; unsigned_int_ptr += step3; } unsigned_int_ptr += step2; } unsigned_int_ptr += step1; } unsigned_int_ptr += step0; } break; case VIO_SIGNED_INT: ASSIGN_PTR(signed_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = (VIO_Real) *signed_int_ptr; ++values; signed_int_ptr += step3; } signed_int_ptr += step2; } signed_int_ptr += step1; } signed_int_ptr += step0; } break; case VIO_FLOAT: ASSIGN_PTR(float_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = (VIO_Real) *float_ptr; ++values; float_ptr += step3; } float_ptr += step2; } float_ptr += step1; } float_ptr += step0; } break; default: case VIO_DOUBLE: ASSIGN_PTR(double_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { for_less( i3, 0, n3 ) { *values = (VIO_Real) *double_ptr; ++values; double_ptr += step3; } double_ptr += step2; } double_ptr += step1; } double_ptr += step0; } break; } } VIOAPI void get_voxel_values_3d( VIO_Data_types data_type, void *void_ptr, int steps[], int counts[], VIO_Real values[] ) { int step0, step1, step2; int i0, i1, i2; int n0, n1, n2; unsigned char *VIO_UCHAR_ptr; signed char *signed_byte_ptr; unsigned short *unsigned_short_ptr; signed short *signed_short_ptr; unsigned int *unsigned_int_ptr; signed int *signed_int_ptr; float *float_ptr; double *double_ptr; check_real_conversion_lookup(); n0 = counts[0]; n1 = counts[1]; n2 = counts[2]; step0 = steps[0]; step1 = steps[1]; step2 = steps[2]; /*--- special case, for speed */ if( data_type == VIO_UNSIGNED_BYTE && n0 == 2 && n1 == 2 && n2 == 2 && step2 == 1 ) { step0 -= step1 + 1; step1 -= 1; ASSIGN_PTR(VIO_UCHAR_ptr) = void_ptr; values[0] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; ++VIO_UCHAR_ptr; values[1] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; VIO_UCHAR_ptr += step1; values[2] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; ++VIO_UCHAR_ptr; values[3] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; VIO_UCHAR_ptr += step0; values[4] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; ++VIO_UCHAR_ptr; values[5] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; VIO_UCHAR_ptr += step1; values[6] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; ++VIO_UCHAR_ptr; values[7] = int_to_real_conversion[(unsigned long) *VIO_UCHAR_ptr]; return; } step0 -= n1 * step1; step1 -= n2 * step2; switch( data_type ) { case VIO_UNSIGNED_BYTE: ASSIGN_PTR(VIO_UCHAR_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = int_to_real_conversion[(long) *VIO_UCHAR_ptr]; ++values; VIO_UCHAR_ptr += step2; } VIO_UCHAR_ptr += step1; } VIO_UCHAR_ptr += step0; } break; case VIO_SIGNED_BYTE: ASSIGN_PTR(signed_byte_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = int_to_real_conversion[(long) *signed_byte_ptr]; ++values; signed_byte_ptr += step2; } signed_byte_ptr += step1; } signed_byte_ptr += step0; } break; case VIO_UNSIGNED_SHORT: ASSIGN_PTR(unsigned_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = int_to_real_conversion[(long) *unsigned_short_ptr]; ++values; unsigned_short_ptr += step2; } unsigned_short_ptr += step1; } unsigned_short_ptr += step0; } break; case VIO_SIGNED_SHORT: ASSIGN_PTR(signed_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = int_to_real_conversion[(long) *signed_short_ptr]; ++values; signed_short_ptr += step2; } signed_short_ptr += step1; } signed_short_ptr += step0; } break; case VIO_UNSIGNED_INT: ASSIGN_PTR(unsigned_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = (VIO_Real) *unsigned_int_ptr; ++values; unsigned_int_ptr += step2; } unsigned_int_ptr += step1; } unsigned_int_ptr += step0; } break; case VIO_SIGNED_INT: ASSIGN_PTR(signed_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = (VIO_Real) *signed_int_ptr; ++values; signed_int_ptr += step2; } signed_int_ptr += step1; } signed_int_ptr += step0; } break; case VIO_FLOAT: ASSIGN_PTR(float_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = (VIO_Real) *float_ptr; ++values; float_ptr += step2; } float_ptr += step1; } float_ptr += step0; } break; default: case VIO_DOUBLE: ASSIGN_PTR(double_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { for_less( i2, 0, n2 ) { *values = (VIO_Real) *double_ptr; ++values; double_ptr += step2; } double_ptr += step1; } double_ptr += step0; } break; } } VIOAPI void get_voxel_values_2d( VIO_Data_types data_type, void *void_ptr, int steps[], int counts[], VIO_Real values[] ) { int step0, step1; int i0, i1; int n0, n1; unsigned char *VIO_UCHAR_ptr; signed char *signed_byte_ptr; unsigned short *unsigned_short_ptr; signed short *signed_short_ptr; unsigned int *unsigned_int_ptr; signed int *signed_int_ptr; float *float_ptr; double *double_ptr; n0 = counts[0]; n1 = counts[1]; step0 = steps[0]; step1 = steps[1]; step0 -= n1 * step1; check_real_conversion_lookup(); switch( data_type ) { case VIO_UNSIGNED_BYTE: ASSIGN_PTR(VIO_UCHAR_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = int_to_real_conversion[(long) *VIO_UCHAR_ptr]; ++values; VIO_UCHAR_ptr += step1; } VIO_UCHAR_ptr += step0; } break; case VIO_SIGNED_BYTE: ASSIGN_PTR(signed_byte_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = int_to_real_conversion[(long) *signed_byte_ptr]; ++values; signed_byte_ptr += step1; } signed_byte_ptr += step0; } break; case VIO_UNSIGNED_SHORT: ASSIGN_PTR(unsigned_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = int_to_real_conversion[(long) *unsigned_short_ptr]; ++values; unsigned_short_ptr += step1; } unsigned_short_ptr += step0; } break; case VIO_SIGNED_SHORT: ASSIGN_PTR(signed_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = int_to_real_conversion[(long) *signed_short_ptr]; ++values; signed_short_ptr += step1; } signed_short_ptr += step0; } break; case VIO_UNSIGNED_INT: ASSIGN_PTR(unsigned_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = (VIO_Real) *unsigned_int_ptr; ++values; unsigned_int_ptr += step1; } unsigned_int_ptr += step0; } break; case VIO_SIGNED_INT: ASSIGN_PTR(signed_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = (VIO_Real) *signed_int_ptr; ++values; signed_int_ptr += step1; } signed_int_ptr += step0; } break; case VIO_FLOAT: ASSIGN_PTR(float_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = (VIO_Real) *float_ptr; ++values; float_ptr += step1; } float_ptr += step0; } break; default: case VIO_DOUBLE: ASSIGN_PTR(double_ptr) = void_ptr; for_less( i0, 0, n0 ) { for_less( i1, 0, n1 ) { *values = (VIO_Real) *double_ptr; ++values; double_ptr += step1; } double_ptr += step0; } break; } } VIOAPI void get_voxel_values_1d( VIO_Data_types data_type, void *void_ptr, int step0, int n0, VIO_Real values[] ) { int i0; unsigned char *VIO_UCHAR_ptr; signed char *signed_byte_ptr; unsigned short *unsigned_short_ptr; signed short *signed_short_ptr; unsigned int *unsigned_int_ptr; signed int *signed_int_ptr; float *float_ptr; double *double_ptr; check_real_conversion_lookup(); switch( data_type ) { case VIO_UNSIGNED_BYTE: ASSIGN_PTR(VIO_UCHAR_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = int_to_real_conversion[(long) *VIO_UCHAR_ptr]; ++values; VIO_UCHAR_ptr += step0; } break; case VIO_SIGNED_BYTE: ASSIGN_PTR(signed_byte_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = int_to_real_conversion[(long) *signed_byte_ptr]; ++values; signed_byte_ptr += step0; } break; case VIO_UNSIGNED_SHORT: ASSIGN_PTR(unsigned_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = int_to_real_conversion[(long) *unsigned_short_ptr]; ++values; unsigned_short_ptr += step0; } break; case VIO_SIGNED_SHORT: ASSIGN_PTR(signed_short_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = int_to_real_conversion[(long) *signed_short_ptr]; ++values; signed_short_ptr += step0; } break; case VIO_UNSIGNED_INT: ASSIGN_PTR(unsigned_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = (VIO_Real) *unsigned_int_ptr; ++values; unsigned_int_ptr += step0; } break; case VIO_SIGNED_INT: ASSIGN_PTR(signed_int_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = (VIO_Real) *signed_int_ptr; ++values; signed_int_ptr += step0; } break; case VIO_FLOAT: ASSIGN_PTR(float_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = (VIO_Real) *float_ptr; ++values; float_ptr += step0; } break; default: case VIO_DOUBLE: ASSIGN_PTR(double_ptr) = void_ptr; for_less( i0, 0, n0 ) { *values = (VIO_Real) *double_ptr; ++values; double_ptr += step0; } break; } } static void get_voxel_values( VIO_Volume volume, void *void_ptr, int n_dims, int steps[], int counts[], VIO_Real values[] ) { VIO_Data_types data_type; data_type = get_volume_data_type( volume ); switch( n_dims ) { case 0: get_voxel_values_1d( data_type, void_ptr, 1, 1, values ); break; case 1: get_voxel_values_1d( data_type, void_ptr, steps[0], counts[0], values ); break; case 2: get_voxel_values_2d( data_type, void_ptr, steps, counts, values ); break; case 3: get_voxel_values_3d( data_type, void_ptr, steps, counts, values ); break; case 4: get_voxel_values_4d( data_type, void_ptr, steps, counts, values ); break; case 5: get_voxel_values_5d( data_type, void_ptr, steps, counts, values ); break; } } VIOAPI void get_volume_voxel_hyperslab_5d( VIO_Volume volume, int v0, int v1, int v2, int v3, int v4, int n0, int n1, int n2, int n3, int n4, VIO_Real values[] ) { int steps[VIO_MAX_DIMENSIONS]; int counts[VIO_MAX_DIMENSIONS]; int sizes[VIO_MAX_DIMENSIONS]; int dim, stride; void *void_ptr; if( volume->is_cached_volume ) { slow_get_volume_voxel_hyperslab( volume, v0, v1, v2, v3, v4, n0, n1, n2, n3, n4, values ); return; } get_volume_sizes( volume, sizes ); GET_MULTIDIM_PTR_5D( void_ptr, volume->array, v0, v1, v2, v3, v4 ) stride = 1; dim = 5; if( n4 > 1 ) { --dim; counts[dim] = n4; steps[dim] = stride; } stride *= sizes[4]; if( n3 > 1 ) { --dim; counts[dim] = n3; steps[dim] = stride; } stride *= sizes[3]; if( n2 > 1 ) { --dim; counts[dim] = n2; steps[dim] = stride; } stride *= sizes[2]; if( n1 > 1 ) { --dim; counts[dim] = n1; steps[dim] = stride; } stride *= sizes[1]; if( n0 > 1 ) { --dim; counts[dim] = n0; steps[dim] = stride; } get_voxel_values( volume, void_ptr, 5 - dim, &steps[dim], &counts[dim], values ); } VIOAPI void get_volume_voxel_hyperslab_4d( VIO_Volume volume, int v0, int v1, int v2, int v3, int n0, int n1, int n2, int n3, VIO_Real values[] ) { int steps[VIO_MAX_DIMENSIONS]; int counts[VIO_MAX_DIMENSIONS]; int sizes[VIO_MAX_DIMENSIONS]; int dim, stride; void *void_ptr; if( volume->is_cached_volume ) { slow_get_volume_voxel_hyperslab( volume, v0, v1, v2, v3, 0, n0, n1, n2, n3, 0, values ); return; } get_volume_sizes( volume, sizes ); GET_MULTIDIM_PTR_4D( void_ptr, volume->array, v0, v1, v2, v3 ) stride = 1; dim = 4; if( n3 > 1 ) { --dim; counts[dim] = n3; steps[dim] = stride; } stride *= sizes[3]; if( n2 > 1 ) { --dim; counts[dim] = n2; steps[dim] = stride; } stride *= sizes[2]; if( n1 > 1 ) { --dim; counts[dim] = n1; steps[dim] = stride; } stride *= sizes[1]; if( n0 > 1 ) { --dim; counts[dim] = n0; steps[dim] = stride; } get_voxel_values( volume, void_ptr, 4 - dim, &steps[dim], &counts[dim], values ); } VIOAPI void get_volume_voxel_hyperslab_3d( VIO_Volume volume, int v0, int v1, int v2, int n0, int n1, int n2, VIO_Real values[] ) { int steps[VIO_MAX_DIMENSIONS]; int counts[VIO_MAX_DIMENSIONS]; int sizes[VIO_MAX_DIMENSIONS]; int dim, stride; void *void_ptr; if( volume->is_cached_volume ) { slow_get_volume_voxel_hyperslab( volume, v0, v1, v2, 0, 0, n0, n1, n2, 0, 0, values ); return; } get_volume_sizes( volume, sizes ); GET_MULTIDIM_PTR_3D( void_ptr, volume->array, v0, v1, v2 ) stride = 1; dim = 3; if( n2 > 1 ) { --dim; counts[dim] = n2; steps[dim] = stride; } stride *= sizes[2]; if( n1 > 1 ) { --dim; counts[dim] = n1; steps[dim] = stride; } stride *= sizes[1]; if( n0 > 1 ) { --dim; counts[dim] = n0; steps[dim] = stride; } get_voxel_values( volume, void_ptr, 3 - dim, &steps[dim], &counts[dim], values ); } VIOAPI void get_volume_voxel_hyperslab_2d( VIO_Volume volume, int v0, int v1, int n0, int n1, VIO_Real values[] ) { int steps[VIO_MAX_DIMENSIONS]; int counts[VIO_MAX_DIMENSIONS]; int sizes[VIO_MAX_DIMENSIONS]; int dim, stride; void *void_ptr; if( volume->is_cached_volume ) { slow_get_volume_voxel_hyperslab( volume, v0, v1, 0, 0, 0, n0, n1, 0, 0, 0, values ); return; } get_volume_sizes( volume, sizes ); GET_MULTIDIM_PTR_2D( void_ptr, volume->array, v0, v1 ) stride = 1; dim = 2; if( n1 > 1 ) { --dim; counts[dim] = n1; steps[dim] = stride; } stride *= sizes[1]; if( n0 > 1 ) { --dim; counts[dim] = n0; steps[dim] = stride; } get_voxel_values( volume, void_ptr, 2 - dim, &steps[dim], &counts[dim], values ); } VIOAPI void get_volume_voxel_hyperslab_1d( VIO_Volume volume, int v0, int n0, VIO_Real values[] ) { int steps[VIO_MAX_DIMENSIONS]; int counts[VIO_MAX_DIMENSIONS]; int sizes[VIO_MAX_DIMENSIONS]; int dim; void *void_ptr; if( volume->is_cached_volume ) { slow_get_volume_voxel_hyperslab( volume, v0, 0, 0, 0, 0, n0, 0, 0, 0, 0, values ); return; } get_volume_sizes( volume, sizes ); GET_MULTIDIM_PTR_1D( void_ptr, volume->array, v0 ) dim = 1; if( n0 > 1 ) { --dim; counts[dim] = n0; steps[dim] = 1; } get_voxel_values( volume, void_ptr, 1 - dim, &steps[dim], &counts[dim], values ); } VIOAPI void get_volume_voxel_hyperslab( VIO_Volume volume, int v0, int v1, int v2, int v3, int v4, int n0, int n1, int n2, int n3, int n4, VIO_Real voxels[] ) { switch( get_volume_n_dimensions(volume) ) { case 1: get_volume_voxel_hyperslab_1d( volume, v0, n0, voxels ); break; case 2: get_volume_voxel_hyperslab_2d( volume, v0, v1, n0, n1, voxels ); break; case 3: get_volume_voxel_hyperslab_3d( volume, v0, v1, v2, n0, n1, n2, voxels ); break; case 4: get_volume_voxel_hyperslab_4d( volume, v0, v1, v2, v3, n0, n1, n2, n3, voxels ); break; case 5: get_volume_voxel_hyperslab_5d( volume, v0, v1, v2, v3, v4, n0, n1, n2, n3, n4, voxels ); break; } }
24,947
835
<gh_stars>100-1000 # THIS FILE IS AUTO-GENERATED. DO NOT EDIT from verta._swagger.base_type import BaseType class VersioningBlobExpanded(BaseType): def __init__(self, path=None, blob=None): required = { "path": False, "blob": False, } self.path = path self.blob = blob for k, v in required.items(): if self[k] is None and v: raise ValueError('attribute {} is required'.format(k)) @staticmethod def from_json(d): from .VersioningBlob import VersioningBlob tmp = d.get('path', None) if tmp is not None: d['path'] = tmp tmp = d.get('blob', None) if tmp is not None: d['blob'] = VersioningBlob.from_json(tmp) return VersioningBlobExpanded(**d)
305
4,994
<reponame>GitHubRepoDescription/tiny-dnn /* Copyright (c) 2013, <NAME> and the respective contributors All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "tiny_dnn/tiny_dnn.h" using namespace tiny_dnn; int main(int argc, char *argv[]) { #if defined(USE_OPENCL) || defined(USE_CUDA) if (argc < 3) { nn_warn("Need two parameters: platform_id and device_id."); return 0; } const int platform_id = atoi(argv[1]); const int device_id = atoi(argv[2]); printAvailableDevice(platform_id, device_id); #else CNN_UNREFERENCED_PARAMETER(argc); CNN_UNREFERENCED_PARAMETER(argv); nn_warn("TinyDNN was not compiled with OpenCL or CUDA support."); #endif return 0; }
301
368
// // DDSeqNoManager.h // Duoduo // // Created by 独嘉 on 14-5-7. // Copyright (c) 2014年 zuoye. All rights reserved. // #import <Foundation/Foundation.h> @interface DDSeqNoManager : NSObject + (instancetype)instance; - (uint32_t)seqNo; @end
108
1,144
<reponame>shivammmmm/querybook<filename>querybook/server/lib/data_doc/data_cell.py from lib.config import get_config_value cell_types = get_config_value("datadoc.cell_types") def get_valid_meta(input_vals, valid_vals, default_vals=None): if input_vals is None: return default_vals if not check_type_match(input_vals, valid_vals): raise ValueError( f"Invalid meta type, expected {type(valid_vals)} actual {type(input_vals)}" ) if isinstance(valid_vals, dict): return_obj = {} for valid_key, valid_val in valid_vals.items(): if valid_key in input_vals: # only for series object for chart y_axis if valid_key == "series" and type(valid_val) is dict and 0 in valid_val: if _validate_series(valid_val, input_vals["series"]): return_obj[valid_key] = input_vals["series"] else: raise ValueError("Invalid meta type for axis series") else: # Normal case, iterate all keys return_obj[valid_key] = get_valid_meta( input_vals=input_vals[valid_key], valid_vals=valid_val, default_vals=( default_vals.get(valid_key) if default_vals else None ), ) return return_obj elif isinstance(valid_vals, list): return [ get_valid_meta( input_vals=input_val, valid_vals=valid_vals[0], default_vals=(default_vals or [None])[0], ) for input_val in input_vals ] else: return input_vals def _validate_series(valid_val, input_val): valid_series_keys = valid_val[0].keys() # Do a shallow key validation return all( all([item_key in valid_series_keys for item_key in series_item]) for series_item in input_val.values() ) def sanitize_data_cell_meta(cell_type: str, meta): cell_type_info = cell_types[cell_type] valid_dict = cell_type_info["meta"] default_dict = cell_type_info["meta_default"] if meta is None: return default_dict return get_valid_meta( input_vals=meta, valid_vals=valid_dict, default_vals=default_dict ) def check_type_match(actual_val, expected_val) -> bool: """Check actual_val matches type of expected_val The exception here is that expected_val can be float, and in that case actual_val can be either int or float Args: actual_val (Any): Actual type expected_val (Any): Expected type Returns: bool: Whether the type matches """ if type(actual_val) == type(expected_val): return True # Make an exception here since int can be represented as float # But not vice versa (for example, index) if type(expected_val) == float and type(actual_val) == int: return True return False
1,405
4,224
/**************************************************************************** * * Copyright (C) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /* * @file drv_input_capture.c * * Servo driver supporting input capture connected to imxrt timer blocks. * * Works with any FLEXPWN that have input pins. * * Require an interrupt. * * */ #include <px4_platform_common/px4_config.h> #include <nuttx/arch.h> #include <nuttx/irq.h> #include <sys/types.h> #include <stdbool.h> #include <assert.h> #include <debug.h> #include <time.h> #include <queue.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <arch/board/board.h> #include <drivers/drv_input_capture.h> #include <px4_arch/io_timer.h> #include <chip.h> #include "hardware/imxrt_flexpwm.h" #define MAX_CHANNELS_PER_TIMER 2 #define SM_SPACING (IMXRT_FLEXPWM_SM1CNT_OFFSET-IMXRT_FLEXPWM_SM0CNT_OFFSET) #define _REG(_addr) (*(volatile uint16_t *)(_addr)) #define _REG16(_base, _reg) (*(volatile uint16_t *)(_base + _reg)) #define REG(_tmr, _sm, _reg) _REG16(io_timers[(_tmr)].base + ((_sm) * SM_SPACING), (_reg)) static input_capture_stats_t channel_stats[MAX_TIMER_IO_CHANNELS]; static struct channel_handler_entry { capture_callback_t callback; void *context; } channel_handlers[MAX_TIMER_IO_CHANNELS]; static void input_capture_chan_handler(void *context, const io_timers_t *timer, uint32_t chan_index, const timer_io_channels_t *chan, hrt_abstime isrs_time, uint16_t isrs_rcnt, uint16_t capture) { channel_stats[chan_index].last_edge = px4_arch_gpioread(chan->gpio_in); if ((isrs_rcnt - capture) > channel_stats[chan_index].latency) { channel_stats[chan_index].latency = (isrs_rcnt - capture); } channel_stats[chan_index].edges++; channel_stats[chan_index].last_time = isrs_time - (isrs_rcnt - capture); uint32_t overflow = 0;//_REG32(timer, KINETIS_FTM_CSC_OFFSET(chan->timer_channel - 1)) & FTM_CSC_CHF; if (overflow) { /* Error we has a second edge before we cleared CCxR */ channel_stats[chan_index].overflows++; } if (channel_handlers[chan_index].callback) { channel_handlers[chan_index].callback(channel_handlers[chan_index].context, chan_index, channel_stats[chan_index].last_time, channel_stats[chan_index].last_edge, overflow); } } static void input_capture_bind(unsigned channel, capture_callback_t callback, void *context) { irqstate_t flags = px4_enter_critical_section(); channel_handlers[channel].callback = callback; channel_handlers[channel].context = context; px4_leave_critical_section(flags); } static void input_capture_unbind(unsigned channel) { input_capture_bind(channel, NULL, NULL); } int up_input_capture_set(unsigned channel, input_capture_edge edge, capture_filter_t filter, capture_callback_t callback, void *context) { if (edge > Both) { return -EINVAL; } int rv = io_timer_validate_channel_index(channel); if (rv == 0) { if (edge == Disabled) { io_timer_set_enable(false, IOTimerChanMode_Capture, 1 << channel); input_capture_unbind(channel); } else { input_capture_bind(channel, callback, context); rv = io_timer_channel_init(channel, IOTimerChanMode_Capture, input_capture_chan_handler, context); if (rv != 0) { return rv; } rv = up_input_capture_set_filter(channel, filter); if (rv == 0) { rv = up_input_capture_set_trigger(channel, edge); if (rv == 0) { rv = io_timer_set_enable(true, IOTimerChanMode_Capture, 1 << channel); } } } } return rv; } int up_input_capture_get_filter(unsigned channel, capture_filter_t *filter) { return 0; } int up_input_capture_set_filter(unsigned channel, capture_filter_t filter) { return 0; } int up_input_capture_get_trigger(unsigned channel, input_capture_edge *edge) { int rv = io_timer_validate_channel_index(channel); if (rv == 0) { rv = -ENXIO; /* Any pins in capture mode */ if (io_timer_get_channel_mode(channel) == IOTimerChanMode_Capture) { rv = OK; uint32_t timer = timer_io_channels[channel].timer_index; uint32_t offset = timer_io_channels[channel].val_offset == PWMA_VAL ? IMXRT_FLEXPWM_SM0CAPTCTRLA_OFFSET : IMXRT_FLEXPWM_SM0CAPTCTRLB_OFFSET; uint32_t rvalue = REG(timer, timer_io_channels[channel].sub_module, offset); rvalue &= SMC_EDGA0_BOTH; switch (rvalue) { case (SMC_EDGA0_RISING): *edge = Rising; break; case (SMC_EDGA0_FALLING): *edge = Falling; break; case (SMC_EDGA0_BOTH): *edge = Both; break; default: rv = -EIO; } } } return rv; } int up_input_capture_set_trigger(unsigned channel, input_capture_edge edge) { int rv = io_timer_validate_channel_index(channel); if (rv == 0) { rv = -ENXIO; /* Any pins in capture mode */ if (io_timer_get_channel_mode(channel) == IOTimerChanMode_Capture) { uint16_t edge_bits = 0; switch (edge) { case Disabled: break; case Rising: edge_bits = SMC_EDGA0_RISING; break; case Falling: edge_bits = SMC_EDGA0_FALLING; break; case Both: edge_bits = SMC_EDGA0_BOTH; break; default: return -EINVAL;; } uint32_t timer = timer_io_channels[channel].timer_index; uint32_t offset = timer_io_channels[channel].val_offset == PWMA_VAL ? IMXRT_FLEXPWM_SM0CAPTCTRLA_OFFSET : IMXRT_FLEXPWM_SM0CAPTCTRLB_OFFSET; irqstate_t flags = px4_enter_critical_section(); uint32_t rvalue = REG(timer, timer_io_channels[channel].sub_module, offset); rvalue &= ~SMC_EDGA0_BOTH; rvalue |= edge_bits; REG(timer, timer_io_channels[channel].sub_module, offset) = rvalue; px4_leave_critical_section(flags); rv = OK; } } return rv; } int up_input_capture_get_callback(unsigned channel, capture_callback_t *callback, void **context) { int rv = io_timer_validate_channel_index(channel); if (rv == 0) { rv = -ENXIO; /* Any pins in capture mode */ if (io_timer_get_channel_mode(channel) == IOTimerChanMode_Capture) { irqstate_t flags = px4_enter_critical_section(); *callback = channel_handlers[channel].callback; *context = channel_handlers[channel].context; px4_leave_critical_section(flags); rv = OK; } } return rv; } int up_input_capture_set_callback(unsigned channel, capture_callback_t callback, void *context) { int rv = io_timer_validate_channel_index(channel); if (rv == 0) { rv = -ENXIO; /* Any pins in capture mode */ if (io_timer_get_channel_mode(channel) == IOTimerChanMode_Capture) { input_capture_bind(channel, callback, context); rv = 0; } } return rv; } int up_input_capture_get_stats(unsigned channel, input_capture_stats_t *stats, bool clear) { int rv = io_timer_validate_channel_index(channel); if (rv == 0) { irqstate_t flags = px4_enter_critical_section(); *stats = channel_stats[channel]; if (clear) { memset(&channel_stats[channel], 0, sizeof(*stats)); } px4_leave_critical_section(flags); } return rv; }
3,343
1,537
# Copyright (c) 2016, Xilinx, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from random import randint from copy import deepcopy import pytest from pynq import Overlay from pynq.tests.util import user_answer_yes from pynq.lib.logictools import PatternGenerator from pynq.lib.logictools.waveform import wave_to_bitstring from pynq.lib.logictools import ARDUINO from pynq.lib.logictools import PYNQZ1_LOGICTOOLS_SPECIFICATION from pynq.lib.logictools import MAX_NUM_PATTERN_SAMPLES __author__ = "<NAME>" __copyright__ = "Copyright 2016, Xilinx" __email__ = "<EMAIL>" try: ol = Overlay('logictools.bit', download=False) flag0 = True except IOError: flag0 = False flag1 = user_answer_yes("\nTest pattern generator?") if flag1: mb_info = ARDUINO flag = flag0 and flag1 def build_loopback_pattern(num_samples): """Method to construct loopback signal patterns. Each loopback signal channel is simulating a clock signal with a specific frequency. And the number of samples can be specified. Parameters ---------- num_samples : int The number of samples can be looped. Returns ------- dict A waveform dictionary that can be recognized by WaveDrom. """ loopback_pattern = {'signal': [ ['stimulus'], {}, ['analysis']], 'foot': {'tock': 1}, 'head': {'text': 'Loopback Test'}} pin_dict = PYNQZ1_LOGICTOOLS_SPECIFICATION['traceable_outputs'] interface_width = PYNQZ1_LOGICTOOLS_SPECIFICATION['interface_width'] all_pins = [k for k in list(pin_dict.keys())[:interface_width]] for i in range(interface_width): wavelane1 = dict() wavelane2 = dict() wavelane1['name'] = 'clk{}'.format(i) wavelane2['name'] = 'clk{}'.format(i) wavelane1['pin'] = all_pins[i] wavelane2['pin'] = all_pins[i] loopback_pattern['signal'][-1].append(wavelane2) if i % 4 == 0: wavelane1['wave'] = 'lh' * int(num_samples / 2) elif i % 4 == 1: wavelane1['wave'] = 'l.h.' * int(num_samples / 4) elif i % 4 == 2: wavelane1['wave'] = 'l...h...' * int(num_samples / 8) else: wavelane1['wave'] = 'l.......h.......' * int(num_samples / 16) loopback_pattern['signal'][0].append(wavelane1) return loopback_pattern def build_random_pattern(num_samples): """Method to construct random signal patterns. Each random signal channel is a collection of random bits. And the number of samples can be specified. Parameters ---------- num_samples : int The number of samples can be looped. Returns ------- dict A waveform dictionary that can be recognized by WaveDrom. """ random_pattern = {'signal': [ ['stimulus'], {}, ['analysis']], 'foot': {'tock': 1}, 'head': {'text': 'Random Test'}} pin_dict = PYNQZ1_LOGICTOOLS_SPECIFICATION['traceable_outputs'] interface_width = PYNQZ1_LOGICTOOLS_SPECIFICATION['interface_width'] all_pins = [k for k in list(pin_dict.keys())[:interface_width]] for i in range(interface_width): wavelane1 = dict() wavelane2 = dict() wavelane1['name'] = 'signal{}'.format(i) wavelane2['name'] = 'signal{}'.format(i) wavelane1['pin'] = all_pins[i] wavelane2['pin'] = all_pins[i] random_pattern['signal'][-1].append(wavelane2) rand_list = [str(randint(0, 1)) for _ in range(num_samples)] rand_str = ''.join(rand_list) wavelane1['wave'] = rand_str.replace('0', 'l').replace('1', 'h') random_pattern['signal'][0].append(wavelane1) return random_pattern @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_state(): """Test for the PatternGenerator class. This test will test a set of loopback signals. Each lane is simulating a clock of a specific frequency. """ ol.download() print("\nDisconnect all the pins.") input("Hit enter after done ...") num_samples = 128 loopback_sent = build_loopback_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) assert pattern_generator.status == 'RESET' pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis') assert pattern_generator.status == 'READY' pattern_generator.run() assert pattern_generator.status == 'RUNNING' loopback_recv = pattern_generator.waveform.waveform_dict list1 = list2 = list3 = list() for wavelane_group in loopback_sent['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': list1 = wavelane_group[1:] for wavelane_group in loopback_recv['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': list2 = wavelane_group[1:] elif wavelane_group and wavelane_group[0] == 'analysis': list3 = wavelane_group[1:] assert list1 == list2, \ 'Stimulus not equal in generated and captured patterns.' assert list2 == list3, \ 'Stimulus not equal to analysis in captured patterns.' pattern_generator.stop() assert pattern_generator.status == 'READY' pattern_generator.reset() assert pattern_generator.status == 'RESET' del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_no_trace(): """Test for the PatternGenerator class. This test will test the case when no analyzer is used. Exception should be raised when users want to show the waveform. """ ol.download() num_samples = 128 loopback_sent = build_loopback_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) pattern_generator.trace(use_analyzer=False, num_analyzer_samples=num_samples) exception_raised = False try: pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis') pattern_generator.run() pattern_generator.show_waveform() except ValueError: exception_raised = True assert exception_raised, 'Should raise exception for show_waveform().' pattern_generator.reset() del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_num_samples(): """Test for the PatternGenerator class. This test will examine 0 sample and more than the maximum number of samples. In these cases, exception should be raised. Here the `MAX_NUM_PATTERN_SAMPLE` is used for display purpose. The maximum number of samples that can be captured by the trace analyzer is defined as `MAX_NUM_TRACE_SAMPLES`. """ ol.download() for num_samples in [0, MAX_NUM_PATTERN_SAMPLES+1]: loopback_sent = build_loopback_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) exception_raised = False try: pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis') except ValueError: exception_raised = True assert exception_raised, 'Should raise exception if number of ' \ 'samples is out of range.' pattern_generator.reset() del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_random(): """Test for the PatternGenerator class. This test will examine 1 sample, and a maximum number of samples. For theses cases, random signals will be used, and all the pins will be used to build the pattern. """ ol.download() for num_samples in [1, MAX_NUM_PATTERN_SAMPLES]: loopback_sent = build_random_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis', frequency_mhz=100) pattern_generator.run() loopback_recv = pattern_generator.waveform.waveform_dict list1 = list2 = list3 = list() for wavelane_group in loopback_sent['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list1.append(temp) for wavelane_group in loopback_recv['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list2.append(temp) elif wavelane_group and wavelane_group[0] == 'analysis': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list3.append(temp) assert list1 == list2, \ 'Stimulus not equal in generated and captured patterns.' assert list2 == list3, \ 'Stimulus not equal to analysis in captured patterns.' pattern_generator.stop() pattern_generator.reset() del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_step(): """Test for the PatternGenerator class. This test will examine a moderate number of 128 samples (in order to shorten testing time). For theses cases, random signals will be used, and all the pins will be used to build the pattern. Each sample is captured after advancing the `step()`. """ ol.download() num_samples = 128 loopback_sent = build_random_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis', frequency_mhz=100) for _ in range(num_samples): pattern_generator.step() loopback_recv = pattern_generator.waveform.waveform_dict list1 = list2 = list3 = list() for wavelane_group in loopback_sent['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list1.append(temp) for wavelane_group in loopback_recv['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list2.append(temp) elif wavelane_group and wavelane_group[0] == 'analysis': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list3.append(temp) assert list1 == list2, \ 'Stimulus not equal in generated and captured patterns.' assert list2 == list3, \ 'Stimulus not equal to analysis in captured patterns.' pattern_generator.stop() pattern_generator.reset() del pattern_generator
5,767
14,668
// 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 "chrome/browser/download/download_offline_content_provider_factory.h" #include <string> #include "base/memory/singleton.h" #include "build/build_config.h" #include "chrome/browser/download/download_offline_content_provider.h" #include "chrome/browser/download/offline_item_utils.h" #include "chrome/browser/offline_items_collection/offline_content_aggregator_factory.h" #include "chrome/browser/profiles/profile_key.h" #include "chrome/browser/transition_manager/full_browser_transition_manager.h" #include "components/keyed_service/core/simple_dependency_manager.h" #include "components/offline_items_collection/core/offline_content_aggregator.h" namespace { void OnProfileCreated(DownloadOfflineContentProvider* provider, Profile* profile) { provider->OnProfileCreated(profile); } } // namespace // static DownloadOfflineContentProviderFactory* DownloadOfflineContentProviderFactory::GetInstance() { return base::Singleton<DownloadOfflineContentProviderFactory>::get(); } // static DownloadOfflineContentProvider* DownloadOfflineContentProviderFactory::GetForKey(SimpleFactoryKey* key) { return static_cast<DownloadOfflineContentProvider*>( GetInstance()->GetServiceForKey(key, true)); } DownloadOfflineContentProviderFactory::DownloadOfflineContentProviderFactory() : SimpleKeyedServiceFactory("DownloadOfflineContentProvider", SimpleDependencyManager::GetInstance()) {} DownloadOfflineContentProviderFactory:: ~DownloadOfflineContentProviderFactory() = default; std::unique_ptr<KeyedService> DownloadOfflineContentProviderFactory::BuildServiceInstanceFor( SimpleFactoryKey* key) const { OfflineContentAggregator* aggregator = OfflineContentAggregatorFactory::GetForKey(key); std::string name_space = OfflineContentAggregator::CreateUniqueNameSpace( OfflineItemUtils::GetDownloadNamespacePrefix(key->IsOffTheRecord()), key->IsOffTheRecord()); auto provider = std::make_unique<DownloadOfflineContentProvider>(aggregator, name_space); auto callback = base::BindOnce(&OnProfileCreated, provider.get()); FullBrowserTransitionManager::Get()->RegisterCallbackOnProfileCreation( key, std::move(callback)); return provider; } SimpleFactoryKey* DownloadOfflineContentProviderFactory::GetKeyToUse( SimpleFactoryKey* key) const { return key; }
768
3,269
<gh_stars>1000+ #include "common/Levenstein.h" #include "common/common.h" #include <vector> using namespace std; int sorbet::Levenstein::distance(string_view s1, string_view s2, int bound) noexcept { if (s1.data() == s2.data() && s1.size() == s2.size()) { return 0; } // A mildly tweaked version from // https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#C++ int s1len = s1.size(); int s2len = s2.size(); if (s2len < s1len) { swap(s1, s2); swap(s1len, s2len); } if (s2len - s1len > bound) { return INT_MAX; } vector<int> column(s1len + 1); absl::c_iota(column, 0); for (int x = 1; x <= s2len; x++) { column[0] = x; int lastDiagonal = x - 1; for (auto y = 1; y <= s1len; y++) { int oldDiagonal = column[y]; auto possibilities = {column[y] + 1, column[y - 1] + 1, lastDiagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)}; column[y] = min(possibilities); lastDiagonal = oldDiagonal; } } int result = column[s1len]; return result; }
546
5,169
{ "name": "AFNetworkings", "version": "0.0.7", "summary": "It is a transition animation asset.", "description": "AFNetworkings is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.", "homepage": "https://github.com/Snackstops/AFNetworkings", "license": { "type": "MIT" }, "authors": { "Snackstops": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/Snackstops/AFNetworkings.git", "tag": "0.0.7" }, "source_files": "AFNetworkings/AFNetworkings.framework/Headers/*.{h}", "vendored_frameworks": "AFNetworkings/AFNetworkings.framework", "public_header_files": "AFNetworkings/AFNetworkings.framework/Headers/AFNetworkings.h", "frameworks": [ "UIKit", "Foundation", "SafariServices" ], "dependencies": { "JPush": [ ] } }
382
868
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 FLARE_BASE_INTERNAL_BIASED_MUTEX_H_ #define FLARE_BASE_INTERNAL_BIASED_MUTEX_H_ #include <atomic> #include <mutex> #include "flare/base/internal/annotation.h" #include "flare/base/internal/memory_barrier.h" #include "flare/base/likely.h" namespace flare::internal { namespace detail::biased_mutex { // Helper class for implementing fast-path of `BiasedMutex.` template <class Owner> class BlessedSide { public: void lock(); void unlock(); private: void LockSlow(); Owner* GetOwner() noexcept { return static_cast<Owner*>(this); } }; // Helper class for implementing slow-path of `BiasedMutex.` template <class Owner> class ReallySlowSide { public: void lock(); void unlock(); private: Owner* GetOwner() noexcept { return static_cast<Owner*>(this); } }; } // namespace detail::biased_mutex // TL;DR: DO NOT USE IT. IT'S TERRIBLY SLOW. // // This mutex is "biased" in that it boosts one ("blessed") side's perf. in // grabbing lock, by sacrificing other contenders. This mutex can boost overall // perf. if you're using it in scenarios where you have separate fast-path and // slow-path (which should be executed rare). Note that there can only be one // "blessed" side. THE SLOW SIDE IS **REALLY REALLY** SLOW AND MAY HAVE A // NEGATIVE IMPACT ON OTHER THREADS (esp. considering that the heavy side of our // asymmetric memory barrier performs really bad). Incorrect use of this mutex // can hurt performane badly. YOU HAVE BEEN WARNED. // // Note that it's a SPINLOCK. In case your critical section is long, do not use // it. // // Internally it's a "Dekker's lock". By using asymmetric memory barrier (@sa: // `memory_barrier.h`), we can eliminate both RMW atomic & "actual" memory // barrier in fast path. // // @sa: https://en.wikipedia.org/wiki/Dekker%27s_algorithm // // Usage: // // // Fast path. // std::scoped_lock _(*biased_mutex.blessed_side()); // // // Slow path. // std::scoped_lock _(*biased_mutex.really_slow_side()); class BiasedMutex : private detail::biased_mutex::BlessedSide<BiasedMutex>, private detail::biased_mutex::ReallySlowSide<BiasedMutex> { using BlessedSide = detail::biased_mutex::BlessedSide<BiasedMutex>; using ReallySlowSide = detail::biased_mutex::ReallySlowSide<BiasedMutex>; friend class detail::biased_mutex::BlessedSide<BiasedMutex>; friend class detail::biased_mutex::ReallySlowSide<BiasedMutex>; public: #ifdef FLARE_INTERNAL_USE_TSAN BiasedMutex() { FLARE_INTERNAL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static); } ~BiasedMutex() { FLARE_INTERNAL_TSAN_MUTEX_DESTROY(this, 0); } #endif BlessedSide* blessed_side() { return this; } ReallySlowSide* really_slow_side() { return this; } private: std::atomic<bool> wants_to_enter_[2] = {}; std::atomic<std::uint8_t> turn_ = 0; // (Our implementation of) Dekker's lock only allows two participants, so we // use this lock to serialize contenders in slow path. std::mutex slow_lock_lock_; }; ////////////////////////////////////// // Implementation goes below. // ////////////////////////////////////// namespace detail::biased_mutex { template <class Owner> inline void BlessedSide<Owner>::lock() { FLARE_INTERNAL_TSAN_MUTEX_PRE_LOCK(this, 0); GetOwner()->wants_to_enter_[0].store(true, std::memory_order_relaxed); AsymmetricBarrierLight(); // There's no need to synchronizes with "other" bless-side -- There won't be // one. This lock permits only one bless-side, i.e., us. // // Therefore we only have to synchronize with the slow side. This is achieved // by acquiring on `wants_to_enter_[1]`. if (FLARE_UNLIKELY( GetOwner()->wants_to_enter_[1].load(std::memory_order_acquire))) { LockSlow(); } FLARE_INTERNAL_TSAN_MUTEX_POST_LOCK(this, 0, 0); } template <class Owner> [[gnu::noinline]] void BlessedSide<Owner>::LockSlow() { AsymmetricBarrierLight(); // Not necessary, TBH. while (FLARE_UNLIKELY( // Synchronizes with the slow side. GetOwner()->wants_to_enter_[1].load(std::memory_order_acquire))) { if (GetOwner()->turn_.load(std::memory_order_relaxed) != 0) { GetOwner()->wants_to_enter_[0].store(false, std::memory_order_relaxed); while (GetOwner()->turn_.load(std::memory_order_relaxed) != 0) { // Spin. } GetOwner()->wants_to_enter_[0].store(true, std::memory_order_relaxed); AsymmetricBarrierLight(); } } } template <class Owner> inline void BlessedSide<Owner>::unlock() { FLARE_INTERNAL_TSAN_MUTEX_PRE_UNLOCK(this, 0); GetOwner()->turn_.store(1, std::memory_order_relaxed); // Synchronizes with the slow side. GetOwner()->wants_to_enter_[0].store(false, std::memory_order_release); FLARE_INTERNAL_TSAN_MUTEX_POST_UNLOCK(this, 0); } template <class Owner> void ReallySlowSide<Owner>::lock() { FLARE_INTERNAL_TSAN_MUTEX_PRE_LOCK(this, 0); GetOwner()->slow_lock_lock_.lock(); GetOwner()->wants_to_enter_[1].store(true, std::memory_order_relaxed); AsymmetricBarrierHeavy(); while (FLARE_UNLIKELY( // Synchronizes with the fast side. GetOwner()->wants_to_enter_[0].load(std::memory_order_acquire))) { if (GetOwner()->turn_.load(std::memory_order_relaxed) != 1) { GetOwner()->wants_to_enter_[1].store(false, std::memory_order_relaxed); while (GetOwner()->turn_.load(std::memory_order_relaxed) != 1) { // Spin. } GetOwner()->wants_to_enter_[1].store(true, std::memory_order_relaxed); AsymmetricBarrierHeavy(); } } FLARE_INTERNAL_TSAN_MUTEX_POST_LOCK(this, 0, 0); } template <class Owner> void ReallySlowSide<Owner>::unlock() { FLARE_INTERNAL_TSAN_MUTEX_PRE_UNLOCK(this, 0); GetOwner()->turn_.store(0, std::memory_order_relaxed); // Synchronizes with the fast side. GetOwner()->wants_to_enter_[1].store(false, std::memory_order_release); GetOwner()->slow_lock_lock_.unlock(); FLARE_INTERNAL_TSAN_MUTEX_POST_UNLOCK(this, 0); } }; // namespace detail::biased_mutex } // namespace flare::internal #endif // FLARE_BASE_INTERNAL_BIASED_MUTEX_H_
2,395
713
<gh_stars>100-1000 package org.infinispan.server.hotrod.test; import java.util.Collection; import org.infinispan.server.hotrod.ServerAddress; /** * @author wburns * @since 9.0 */ public abstract class AbstractTestTopologyAwareResponse { public final int topologyId; public final Collection<ServerAddress> members; protected AbstractTestTopologyAwareResponse(int topologyId, Collection<ServerAddress> members) { this.topologyId = topologyId; this.members = members; } }
163
2,706
<gh_stars>1000+ /* Copyright (c) 2013-2015 <NAME> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GUI_MENU_H #define GUI_MENU_H #include <mgba-util/common.h> CXX_GUARD_START #include <mgba-util/vector.h> struct GUIMenu; struct GUIMenuItem { const char* title; void* data; unsigned state; const char* const* validStates; unsigned nStates; struct GUIMenu* submenu; }; DECLARE_VECTOR(GUIMenuItemList, struct GUIMenuItem); struct GUIBackground; struct GUIMenu { const char* title; const char* subtitle; struct GUIMenuItemList items; size_t index; struct GUIBackground* background; }; enum GUIMenuExitReason { GUI_MENU_EXIT_ACCEPT, GUI_MENU_EXIT_BACK, GUI_MENU_EXIT_CANCEL, }; enum GUIMessageBoxButtons { GUI_MESSAGE_BOX_OK = 1, GUI_MESSAGE_BOX_CANCEL = 2 }; struct GUIParams; enum GUIMenuExitReason GUIShowMenu(struct GUIParams* params, struct GUIMenu* menu, struct GUIMenuItem** item); ATTRIBUTE_FORMAT(printf, 4, 5) enum GUIMenuExitReason GUIShowMessageBox(struct GUIParams* params, int buttons, int frames, const char* format, ...); void GUIDrawBattery(struct GUIParams* params); void GUIDrawClock(struct GUIParams* params); CXX_GUARD_END #endif
518
580
// DynaMix // Copyright (c) 2013-2019 <NAME>, <NAME> // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #include <iostream> #include <dynamix/dynamix.hpp> using namespace std; //[allocators_global /*` DynaMix allows you to set custom allocators for the persistent pieces of memory the library may require. The library allocates some memory on initialization, which happens at a global scope -- before the entry point of a program. It also has some allocations which are for instances with a very short lifetime. Currently those are not covered by the allocators. What you can control with the custom allocators is the new memory allocated for `dynamix::object` instances - their internal mixin data. You can assign a global allocator to the library and you can also set individual allocators per mixin type. First let's see how you can create a global allocator. Let's assume you have a couple of functions of your own that allocate and deallocate memory in some way specific to your needs: */ char* allocate(size_t size); void deallocate(char* buffer); /*` To create a global allocator, you need to create a class derived from `domain_allocator` and override its virtual methods. */ class custom_allocator : public dynamix::domain_allocator { /*` The first two methods allocate a buffer for the mixin data pointers. Every object has pointers to its mixins within it. This is the array of such pointers. The class `domain_allocator` has a static constant member -- `mixin_data_size` -- which you should use to see the size of a single element in that array. The methods also have arguments referring to the object for which the mixin data is being allocated. We won't be using it in this simple example. */ virtual char* alloc_mixin_data(size_t count, const dynamix::object*) override { return allocate(count * mixin_data_size); } virtual void dealloc_mixin_data(char* ptr, size_t, const dynamix::object*) override { deallocate(ptr); } /*` The other two methods you need to overload allocate and deallocate the memory for an actual mixin class instance. As you may have already read, the buffer allocated for a mixin instance is bigger than needed because the library stores a pointer to the owning object immediately before the memory used by the mixin instance. That's why this function is not as simple as the one for the mixin data array. It has to conform to the mixin (and also `object` pointer) alignment. */ virtual std::pair<char*, size_t> alloc_mixin(const dynamix::mixin_type_info& info, const dynamix::object*) override { /*` The users are strongly advised to use the static method `domain_allocator::mem_size_for_mixin`. It will appropriately calculate how much memory is needed for the mixin instance such that there is enough room at the beginning for the pointer to the owning object and the memory alignment is respected. */ size_t size = mem_size_for_mixin(info.size, info.alignment); char* buffer = allocate(size); /*` After you allocate the buffer you should take care of the other return value - the mixin offset. It calculates the offset of the actual mixin instance memory within the buffer, such that there is room for the owning object pointer in before it and all alignments are respected. You are encouraged to use the static method `domain_allocator::mixin_offset` for this purpose. */ size_t offset = mixin_offset(buffer, info.alignment); return std::make_pair(buffer, offset); } /*` The mixin instance deallocation method can be trivial */ virtual void dealloc_mixin(char* ptr, size_t, const dynamix::mixin_type_info&, const dynamix::object*) override { deallocate(ptr); } //] }; //[allocators_mixin /*` As we mentioned before, you can have an allocator specific for a mixin type. A common case for such use is to have a per-frame allocator -- one that has a preallocated buffer which is used much like a stack, with its pointer reset at the end of each simulation frame (or at the beginning each new one). Let's create such an allocator. First, a mixin instance allocator is not necessarily bound to a concrete mixin type. You can have the same instance of such an allocator set for many mixins (which would be a common use of a per-frame allocator), but for our example let's create one that *is* bound to an instance. We will make it a template class because the code for each mixin type will be the same. A mixin instance allocator needs to be derived from the class `mixin_allocator`. You then need to overload its two virtual methods which are exactly the same as the mixin instance allocation/deallocation methods in `domain_allocator`. */ template <typename Mixin> class per_frame_allocator : public dynamix::mixin_allocator { private: static const size_t NUM_IN_PAGE = 1000; size_t _num_allocations; // number of "living" instances allocated const size_t mixin_buf_size; // the size of a single mixin instance buffer vector<char*> _pages; // use pages of data where each page can store NUM_IN_PAGE instances size_t _page_byte_index; // index within a memory "page" const size_t page_size; // size in bytes of a page public: // some way to obtain the instance static per_frame_allocator& instance() { static per_frame_allocator i; return i; } per_frame_allocator() : _num_allocations(0) , mixin_buf_size( mem_size_for_mixin( sizeof(Mixin), std::alignment_of<Mixin>::value)) , page_size(mixin_buf_size * NUM_IN_PAGE) { new_memory_page(); } void new_memory_page() { char* page = new char[page_size]; _pages.push_back(page); _page_byte_index = 0; } virtual std::pair<char*, size_t> alloc_mixin(const dynamix::mixin_type_info& info, const dynamix::object*) override { if(_page_byte_index == NUM_IN_PAGE) { // if we don't have space in our current page, create a new one new_memory_page(); } char* buffer = _pages.back() + _page_byte_index * mixin_buf_size; // again calculate the offset using this static member function size_t offset = mixin_offset(buffer, info.alignment); ++_page_byte_index; ++_num_allocations; return std::make_pair(buffer, offset); } virtual void dealloc_mixin(char* buf, size_t, const dynamix::mixin_type_info&, const dynamix::object*) override { #if !defined(NDEBUG) // in debug mode check if the mixin is within any of our pages bool found = false; for (size_t i = 0; i < _pages.size(); ++i) { const char* page_begin = _pages[i]; const char* page_end = page_begin + page_size; if (buf >= page_begin && buf < page_end) { found = true; break; } } // deallocating memory, which hasn't been allocated from that allocator I_DYNAMIX_ASSERT(found); #else I_DYNAMIX_MAYBE_UNUSED(buf); #endif // no actual deallocation to be done // just decrement our living instances counter --_num_allocations; } // function to be called once each frame that resets the allocator void reset() { I_DYNAMIX_ASSERT(_num_allocations == 0); // premature reset for(size_t i=1; i<_pages.size(); ++i) { delete[] _pages[i]; } _pages.resize(1); _page_byte_index = 0; } }; /*` Now this class can be set as a mixin allocator for a given mixin type. A side effect of the fact that it's bound to the type is that it keeps mixin instances in a continuous buffer. With some changes (to take care of potential holes in the buffer) such an allocator can be used by a subsystem that works through mixins relying on them being in a continuous buffer to avoid cache misses. To illustrate a usage for our mixin allocator, let's imagine we have a game. If a character in our game dies, it will be destroyed at the end of the current frame and should stop responding to any messages. We can create a mixin called `dead_character` which implements all those the messages with a higher priority than the rest of the mixins. Since every object that has a `dead_character` mixin will be destroyed by the end of the frame, it will be safe to use the per-frame allocator for it. First let's create the mixin class and sample messages: */ class dead_character { public: void die() {} // ... }; DYNAMIX_MESSAGE_0(void, die); DYNAMIX_DEFINE_MESSAGE(die); //... /*` Now we define the mixin so that it uses the allocator, we just need to add it with "`&`" to the mixin feature list, just like we add messages. There are two ways to do so. The first one would be to do it like this: DYNAMIX_DEFINE_MIXIN(dead_character, ... & dynamix::priority(1, die_msg) & dynamix::allocator<per_frame_allocator<dead_character>>()); This will create the instance of the allocator internally and we won't be able to get it. Since in our case we do care about the instance because we want to call its `reset` method, we could use an alternative way, by just adding an actual instance of the allocator to the feature list: */ DYNAMIX_DEFINE_MIXIN(dead_character, /*...*/ dynamix::priority(1, die_msg) & per_frame_allocator<dead_character>::instance()); /*` If we share a mixin instance allocator between multiple mixins, the second way is also the way to go. */ //] int main() { //[allocators_global_use /*` To use the custom global allocator you need to instantiate it and then set it with `set_global_allocator`. Unlike the mutation rules, the responsibility for the allocator instance is yours. You need to make sure that the lifetime of the instance is at least as long as the lifetime of all objects in the system. Unfortunately this means that if you have global or static objects, you need to create a new pointer that is, in a way, a memory leak. If you do not have global or static objects, it should be safe for it to just be a local variable in your program's entry point function. */ custom_allocator alloc; dynamix::set_global_allocator(&alloc); //] //[allocators_mixin_use /*` Now all mixin allocations and deallocations will pass through our mixin allocator: */ dynamix::object o; dynamix::mutate(o) .add<dead_character>(); dynamix::mutate(o) .remove<dead_character>(); // safe because we've destroyed all instances of dead_character per_frame_allocator<dead_character>::instance().reset(); //] return 0; } char* allocate(size_t size) { return new char[size]; } void deallocate(char* buffer) { delete[] buffer; } //[tutorial_allocators //` %{allocators_global} //` %{allocators_global_use} //` %{allocators_mixin} //` %{allocators_mixin_use} //]
3,658
1,605
/***************************************************************************** * * 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.xmpbox.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayOutputStream; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.type.OECFType; import org.apache.xmpbox.type.TextType; import org.apache.xmpbox.type.TypeMapping; import org.apache.xmpbox.xml.DomXmpParser; import org.apache.xmpbox.xml.XmpSerializer; import org.junit.jupiter.api.Test; import java.io.InputStream; class TestExifXmp { @Test void testNonStrict() throws Exception { InputStream is = this.getClass().getResourceAsStream("/validxmp/exif.xmp"); DomXmpParser builder = new DomXmpParser(); builder.setStrictParsing(false); XMPMetadata rxmp = builder.parse(is); ExifSchema schema = (ExifSchema)rxmp.getSchema(ExifSchema.class); TextType ss = (TextType)schema.getProperty(ExifSchema.SPECTRAL_SENSITIVITY); assertNotNull(ss); assertEquals("spectral sens value",ss.getValue()); } @Test void testGenerate() throws Exception { XMPMetadata metadata = XMPMetadata.createXMPMetadata(); TypeMapping tmapping = metadata.getTypeMapping(); ExifSchema exif = new ExifSchema(metadata); metadata.addSchema(exif); OECFType oecf = new OECFType(metadata); oecf.addProperty(tmapping.createInteger(oecf.getNamespace(), oecf.getPrefix(), OECFType.COLUMNS, 14)); oecf.setPropertyName(ExifSchema.OECF); exif.addProperty(oecf); XmpSerializer serializer = new XmpSerializer(); serializer.serialize(metadata, new ByteArrayOutputStream(), false); } }
917
335
"""Tests for the path filter.""" import unittest import mock from grow.routing import path_filter class PathFilterTestCase(unittest.TestCase): """Test the routes.""" def setUp(self): self.filter = path_filter.PathFilter() def test_filter_defaults(self): """Default filters work.""" # Normal files work. self.assertTrue(self.filter.is_valid('/sitemap.xml')) self.assertTrue(self.filter.is_valid('/index.html')) self.assertTrue(self.filter.is_valid('/static/images/logo.png')) self.assertTrue(self.filter.is_valid('/.grow/index.html')) # Dot files should be ignored. self.assertFalse(self.filter.is_valid('/.DS_STORE')) self.assertFalse(self.filter.is_valid('/.htaccess')) @mock.patch('grow.routing.path_filter.DEFAULT_INCLUDED', [1, 2]) @mock.patch('grow.routing.path_filter.DEFAULT_IGNORED', [3, 4]) def test_filter_default_filters(self): """Default filters work.""" self.assertEqual([1, 2], list(self.filter.included)) self.assertEqual([3, 4], list(self.filter.ignored)) def test_filter_ignores(self): """Simple ignore filters work.""" self.filter.add_ignored('foo.bar') # Normal files work. self.assertTrue(self.filter.is_valid('/sitemap.xml')) self.assertTrue(self.filter.is_valid('/index.html')) self.assertTrue(self.filter.is_valid('/static/images/logo.png')) self.assertTrue(self.filter.is_valid('/.grow/index.html')) # Defaults are not kept. self.assertTrue(self.filter.is_valid('/.DS_STORE')) self.assertTrue(self.filter.is_valid('/.htaccess')) # Custom filters work. self.assertFalse(self.filter.is_valid('/foo.bar')) self.assertFalse(self.filter.is_valid('/foo/bar/foo.bar')) def test_filter_included(self): """Simple included filters work.""" self.filter.add_ignored('foo.bar') self.filter.add_included('/bar/foo.bar') # Normal files work. self.assertTrue(self.filter.is_valid('/sitemap.xml')) self.assertTrue(self.filter.is_valid('/index.html')) self.assertTrue(self.filter.is_valid('/static/images/logo.png')) self.assertTrue(self.filter.is_valid('/.grow/index.html')) # Defaults are not kept. self.assertTrue(self.filter.is_valid('/.DS_STORE')) self.assertTrue(self.filter.is_valid('/.htaccess')) # Custom filters work. self.assertFalse(self.filter.is_valid('/foo.bar')) # Included filter overrides the ignores. self.assertTrue(self.filter.is_valid('/foo/bar/foo.bar')) def test_filter_constructor(self): """Simple ignore filters work.""" self.filter = path_filter.PathFilter( ['foo.bar'], ['/bar/foo.bar']) # Normal files work. self.assertTrue(self.filter.is_valid('/sitemap.xml')) self.assertTrue(self.filter.is_valid('/index.html')) self.assertTrue(self.filter.is_valid('/static/images/logo.png')) self.assertTrue(self.filter.is_valid('/.grow/index.html')) # Defaults are not kept. self.assertTrue(self.filter.is_valid('/.DS_STORE')) self.assertTrue(self.filter.is_valid('/.htaccess')) # Custom filters work. self.assertFalse(self.filter.is_valid('/foo.bar')) # Included filter overrides the ignores. self.assertTrue(self.filter.is_valid('/foo/bar/foo.bar'))
1,496
2,829
/* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef EULER_CORE_INDEX_RANGE_SAMPLE_INDEX_H_ #define EULER_CORE_INDEX_RANGE_SAMPLE_INDEX_H_ #include <vector> #include <algorithm> #include <memory> #include <utility> #include <string> #include "euler/common/logging.h" #include "euler/core/index/sample_index.h" #include "euler/core/index/index_util.h" #include "euler/core/index/range_index_result.h" #include "euler/common/file_io.h" #include "euler/common/bytes_io.h" #include "euler/common/bytes_compute.h" namespace euler { template<typename T1, typename T2> class RangeSampleIndex : public SampleIndex { public: typedef T1 IdType; typedef T2 ValueType; typedef typename std::vector<T1>::const_iterator ResultPos; typedef std::pair<ResultPos, ResultPos> ResultRange; public: explicit RangeSampleIndex(const std::string& name) : SampleIndex(name) {} uint32_t SerializeSize() const; bool Serialize(FileIO* file_io) const override; bool Deserialize(FileIO* file_io) override; bool Deserialize_ori(FileIO* file_io); // values must sorted bool Init(const std::vector<IdType>& ids, const std::vector<ValueType>& values, const std::vector<float>& weights); ~RangeSampleIndex() {} std::shared_ptr<IndexResult> SearchAll() const override { std::vector<ResultRange> r = {std::make_pair(ids_.begin(), ids_.end())}; RangeIndexResult<T1, T2>* h = new RangeIndexResult<T1, T2>(this->GetName()); h->Init(ids_.begin(), ids_.end(), values_.begin(), sum_weights_.begin(), r); return std::shared_ptr<IndexResult> (h); } std::shared_ptr<IndexResult> Search(IndexSearchType op, const std::string& value) const override { std::vector<ResultRange> r; if (op == IN) { return SearchIN(value); } else if (op == NOT_IN) { return SearchNOTIN(value); } else { ValueType v = euler::StringTo<ValueType>(value); if (op == LESS) { r = SearchLess(v); } else if (op == LESS_EQ) { r = SearchLessEqual(v); } else if (op == GREATER) { r = SearchMore(v); } else if (op == GREATER_EQ) { r = SearchMoreEqual(v); } else if (op == EQ) { r = SearchEqual(v); } else if (op == NOT_EQ) { r = SearchNotEqual(v); } else { return std::shared_ptr<IndexResult>(); } RangeIndexResult<T1, T2>* h = new RangeIndexResult<T1, T2>(this->GetName()); h->Init(ids_.begin(), ids_.end(), values_.begin(), sum_weights_.begin(), r); return std::shared_ptr<IndexResult> (h); } return std::shared_ptr<IndexResult>(); } private: std::vector<ResultRange> SearchLess(const ValueType& value) const { auto p = std::lower_bound(values_.begin(), values_.end(), value); auto diff = p - values_.begin(); if (diff > 0) { std::vector<ResultRange> v = {std::make_pair(ids_.begin(), ids_.begin() + diff)}; return v; } return std::vector<ResultRange>(); } std::vector<ResultRange> SearchLessEqual(const ValueType& value) const { auto p = std::upper_bound(values_.begin(), values_.end(), value); auto diff = p - values_.begin(); if (diff > 0) { std::vector<ResultRange> v = {std::make_pair(ids_.begin(), ids_.begin() + diff)}; return v; } return std::vector<ResultRange>(); } std::vector<ResultRange> SearchMore(const ValueType& value) const { auto p = std::upper_bound(values_.begin(), values_.end(), value); if (p != values_.end()) { auto diff = p - values_.begin(); std::vector<ResultRange> v = {std::make_pair(ids_.begin() + diff, ids_.end())}; return v; } return std::vector<ResultRange>(); } std::vector<ResultRange> SearchMoreEqual(const ValueType& value) const { auto p = std::lower_bound(values_.begin(), values_.end(), value); if (p != values_.end()) { auto diff = p - values_.begin(); std::vector<ResultRange> v = {std::make_pair(ids_.begin() + diff, ids_.end())}; return v; } return std::vector<ResultRange>(); } std::vector<ResultRange> SearchEqual(const ValueType& value) const { auto p = std::equal_range(values_.begin(), values_.end(), value); if (p.first != p.second) { auto begin = p.first - values_.begin(); auto end = p.second - values_.begin(); std::vector<ResultRange> v = {std::make_pair(ids_.begin() + begin, ids_.begin() + end)}; return v; } return std::vector<ResultRange>(); } std::vector<ResultRange> SearchNotEqual(const ValueType& value) const { auto p = std::equal_range(values_.begin(), values_.end(), value); if (p.first + values_.size() != p.second) { auto begin = p.first - values_.begin(); auto end = p.second - values_.begin(); std::vector<ResultRange> result; result.push_back(std::make_pair(ids_.begin(), ids_.begin() + begin)); result.push_back(std::make_pair(ids_.begin() + end, ids_.end())); return result; } return std::vector<ResultRange>(); } std::shared_ptr<IndexResult> SearchIN(const std::string& value) const { const std::string DELIM = "::"; auto vec = euler::Split(value, DELIM); if (vec.size() >= 1) { auto result = Search(EQ, vec[0]); for (size_t i = 1; i < vec.size(); ++i) { result = result->Union(Search(EQ, vec[i])); } return result; } return std::shared_ptr<IndexResult>(); } std::shared_ptr<IndexResult> SearchNOTIN(const std::string& value) const { const std::string DELIM = "::"; auto vec = euler::Split(value, DELIM); if (vec.size() >= 1) { auto result = Search(NOT_EQ, vec[0]); for (size_t i = 1; i < vec.size(); ++i) { result = result->Intersection(Search(NOT_EQ, vec[i])); } return result; } return std::shared_ptr<IndexResult>(); } public: bool Merge(std::shared_ptr<SampleIndex> hIndex) override { auto index = dynamic_cast<RangeSampleIndex*>(hIndex.get()); if (index == nullptr) { EULER_LOG(FATAL) << "convert to HashSampleIndex ptr error "; return false; } return Merge(*index); } bool Merge(const RangeSampleIndex& r) { std::vector<Pair> p; VecToPairVec(ids_, values_, sum_weights_, &p); VecToPairVec(r.ids_, r.values_, r.sum_weights_, &p); std::sort(p.begin(), p.end()); ids_.resize(p.size()); values_.resize(p.size()); sum_weights_.resize(p.size()); float total_weight = 0; for (size_t i = 0; i < p.size(); ++i) { ids_[i] = p[i].id_; values_[i] = p[i].value_; total_weight += p[i].weight_; sum_weights_[i] = total_weight; } return true; } bool Merge(const std::vector<std::shared_ptr<SampleIndex>>& r) override { std::vector<Pair> p; VecToPairVec(ids_, values_, sum_weights_, &p); for (auto it : r) { auto iit = dynamic_cast<RangeSampleIndex*>(it.get()); VecToPairVec(iit->ids_, iit->values_, iit->sum_weights_, &p); } std::sort(p.begin(), p.end()); ids_.resize(p.size()); values_.resize(p.size()); sum_weights_.resize(p.size()); float total_weight = 0; for (size_t i = 0; i < p.size(); ++i) { ids_[i] = p[i].id_; values_[i] = p[i].value_; total_weight += p[i].weight_; sum_weights_[i] = total_weight; } return true; } private: struct Pair { Pair(IdType id, ValueType value, float weight): id_(id), value_(value), weight_(weight) {} IdType id_; ValueType value_; float weight_; bool operator<(const Pair& r) { return value_ < r.value_; } }; void VecToPairVec(const std::vector<IdType>& ids, const std::vector<ValueType>& values, const std::vector<float>& sum_weights, std::vector<Pair>* pair) const { for (size_t i = 0; i < ids.size(); ++i) { float weight = 0; if (i == 0) { weight = sum_weights[0]; } else { weight = sum_weights[i] - sum_weights[i-1]; } Pair p(ids[i], values[i], weight); pair->push_back(p); } } private: std::vector<IdType> ids_; std::vector<ValueType> values_; std::vector<float> sum_weights_; }; template<typename T1, typename T2> uint32_t RangeSampleIndex<T1, T2>::SerializeSize() const { uint32_t total = BytesSize(ids_); total += BytesSize(values_); total += BytesSize(sum_weights_); return total; } template<typename T1, typename T2> bool RangeSampleIndex<T1, T2>::Serialize(FileIO* file_io) const { if (!file_io->Append(ids_)) { EULER_LOG(ERROR) << "write ids error"; return false; } if (!file_io->Append(values_)) { EULER_LOG(ERROR) << "write values error"; return false; } std::vector<float> weights; weights.reserve(sum_weights_.size()); std::adjacent_difference(sum_weights_.begin(), sum_weights_.end(), back_inserter(weights)); if (!file_io->Append(weights)) { EULER_LOG(ERROR) << "write sum weights error"; return false; } return true; } template<typename T1, typename T2> bool RangeSampleIndex<T1, T2>::Deserialize(FileIO* file_io) { ids_.clear(); values_.clear(); sum_weights_.clear(); std::vector<Pair> pair; while (!file_io->FileEnd()) { std::vector<IdType> id; std::vector<ValueType> value; std::vector<float> weight; if (!file_io->Read(&id)) { EULER_LOG(ERROR) << "read ids error"; return false; } if (!file_io->Read(&value)) { EULER_LOG(ERROR) << "read values error"; return false; } if (!file_io->Read(&weight)) { EULER_LOG(ERROR) << "read sum weights error"; return false; } if (id.size() != value.size() || id.size() != weight.size()) { EULER_LOG(ERROR) << "id, value, weight size not equal"; return false; } for (size_t i = 0; i < id.size(); ++i) { Pair p(id[i], value[i], weight[i]); pair.push_back(p); } } std::sort(pair.begin(), pair.end()); float cum_weight = 0; ids_.resize(pair.size()); values_.resize(pair.size()); sum_weights_.resize(pair.size()); for (size_t i = 0; i < pair.size(); ++i) { ids_[i] = pair[i].id_; values_[i] = pair[i].value_; cum_weight += pair[i].weight_; sum_weights_[i] = cum_weight; } return true; } template<typename T1, typename T2> bool RangeSampleIndex<T1, T2>::Deserialize_ori(FileIO* file_io) { ids_.clear(); values_.clear(); sum_weights_.clear(); if (!file_io->Read(&ids_)) { EULER_LOG(ERROR) << "read ids error"; return false; } if (!file_io->Read(&values_)) { EULER_LOG(ERROR) << "read values error"; return false; } if (!file_io->Read(&sum_weights_)) { EULER_LOG(ERROR) << "read weights error"; return false; } if (ids_.size() != values_.size() || ids_.size() != sum_weights_.size()) { EULER_LOG(ERROR) << "id, value, weight size not equal"; return false; } float cum_weight = 0; for (size_t i = 0; i < sum_weights_.size(); ++i) { cum_weight += sum_weights_[i]; sum_weights_[i] = cum_weight; } return true; } // values must sorted template<typename T1, typename T2> bool RangeSampleIndex<T1, T2>::Init(const std::vector<IdType>& ids, const std::vector<ValueType>& values, const std::vector<float>& weights) { if (ids.size() == values.size() && values.size() == weights.size()) { float sum_weight = 0.0; ids_.resize(ids.size()); values_.resize(values.size()); sum_weights_.resize(weights.size()); std::copy(ids.begin(), ids.end(), ids_.begin()); std::copy(values.begin(), values.end(), values_.begin()); auto f = [&sum_weight](float w){sum_weight += w; return sum_weight; }; std::transform(weights.begin(), weights.end(), sum_weights_.begin(), f); return true; } else { EULER_LOG(ERROR) << "ids values weights size not equal, init error "; return false; } } } // namespace euler #endif // EULER_CORE_INDEX_RANGE_SAMPLE_INDEX_H_
5,243
357
/* PsychToolbox3/Source/Common/PsychCellGlue.h AUTHORS: <EMAIL> awi <EMAIL> mk PLATFORMS: All PROJECTS: All HISTORY: 12/17/03 awi wrote it. DESCRIPTION: PsychStructGlue defines abstracted functions to create cell arrays passed between the calling environment and the PsychToolbox. */ //begin include once #ifndef PSYCH_IS_INCLUDED_CellGlue #define PSYCH_IS_INCLUDED_CellGlue #include "Psych.h" psych_bool PsychAllocOutCellVector(int position, PsychArgRequirementType isRequired, int numElements, PsychGenericScriptType **pCell); void PsychSetCellVectorStringElement(int index, const char *text, PsychGenericScriptType *cellVector); //void PsychSetCellVectorDoubleElement(int index, double value, PsychGenericScriptType *cellVector); //void PsychSetCellVectorNativeElement(int index, PsychGenericScriptType *pNativeElement, PsychGenericScriptType *cellVector); //psych_bool PsychAllocInNativeCellVector(int position, PsychArgRequirementType isRequired, const PsychGenericScriptType **cellVector); //psych_bool PsychAllocInNativeString(int position, PsychArgRequirementType isRequired, const PsychGenericScriptType **nativeString); //end include once #endif
379
1,261
<reponame>luizoti/toga import sys import os import subprocess import platform from pathlib import Path import toga from toga.style import Pack from toga.constants import COLUMN examples_dir = Path(__file__).parents[3] class ExampleExamplesOverviewApp(toga.App): # Button callback functions def run(self, widget, **kwargs): row = self.table.selection env = os.environ.copy() env["PYTHONPATH"] = row.path subprocess.run([sys.executable, "-m", row.name], env=env) def open(self, widget, **kwargs): row = self.table.selection if platform.system() == "Windows": os.startfile(row.path) elif platform.system() == "Darwin": subprocess.run(["open", row.path]) else: subprocess.run(["xdg-open", row.path]) def on_example_selected(self, widget, row): readme_path = row.path / "README.rst" try: with open(readme_path) as f: readme_text = f.read() except OSError: readme_text = "README could not be loaded" self.info_view.value = readme_text def startup(self): # ==== Set up main window ====================================================== self.main_window = toga.MainWindow(title=self.name) # Label for user instructions label = toga.Label( "Please select an example to run", style=Pack(padding_bottom=10), ) # ==== Table with examples ===================================================== self.examples = [] # search for all folders that contain modules for root, dirs, files in os.walk(examples_dir): # skip hidden folders dirs[:] = [d for d in dirs if not d.startswith(".")] if any(name == "__main__.py" for name in files): path = Path(root) self.examples.append(dict(name=path.name, path=path.parent)) self.examples.sort(key=lambda e: e["path"]) self.table = toga.Table( headings=["Name", "Path"], data=self.examples, on_double_click=self.run, on_select=self.on_example_selected, style=Pack(padding_bottom=10, flex=1), ) # Buttons self.btn_run = toga.Button( "Run Example", on_press=self.run, style=Pack(flex=1, padding_right=5) ) self.btn_open = toga.Button( "Open folder", on_press=self.open, style=Pack(flex=1, padding_left=5) ) button_box = toga.Box(children=[self.btn_run, self.btn_open]) # ==== View of example README ================================================== self.info_view = toga.MultilineTextInput( placeholder="Please select example", readonly=True, style=Pack(padding=1) ) # ==== Assemble layout ========================================================= left_box = toga.Box( children=[self.table, button_box], style=Pack( direction=COLUMN, padding=1, flex=1, ), ) split_container = toga.SplitContainer(content=[left_box, self.info_view]) outer_box = toga.Box( children=[label, split_container], style=Pack(padding=10, direction=COLUMN), ) # Add the content on the main window self.main_window.content = outer_box # Show the main window self.main_window.show() def main(): return ExampleExamplesOverviewApp( "Examples Overview", "org.beeware.widgets.examples_overview" ) if __name__ == "__main__": app = main() app.main_loop()
1,655
4,392
<gh_stars>1000+ #include <stdio.h> #include <string.h> #include "cblas.h" #include "cblas_test.h" int cblas_ok, cblas_lerr, cblas_info; int link_xerbla=TRUE; char *cblas_rout; #ifdef F77_Char void F77_xerbla(F77_Char F77_srname, void *vinfo); #else void F77_xerbla(char *srname, void *vinfo); #endif void chkxer(void) { extern int cblas_ok, cblas_lerr, cblas_info; extern int link_xerbla; extern char *cblas_rout; if (cblas_lerr == 1 ) { printf("***** ILLEGAL VALUE OF PARAMETER NUMBER %d NOT DETECTED BY %s *****\n", cblas_info, cblas_rout); cblas_ok = 0 ; } cblas_lerr = 1 ; } void F77_d2chke(char *rout) { char *sf = ( rout ) ; double A[2] = {0.0,0.0}, X[2] = {0.0,0.0}, Y[2] = {0.0,0.0}, ALPHA=0.0, BETA=0.0; extern int cblas_info, cblas_lerr, cblas_ok; extern int RowMajorStrg; extern char *cblas_rout; if (link_xerbla) /* call these first to link */ { cblas_xerbla(cblas_info,cblas_rout,""); F77_xerbla(cblas_rout,&cblas_info); } cblas_ok = TRUE ; cblas_lerr = PASSED ; if (strncmp( sf,"cblas_dgemv",11)==0) { cblas_rout = "cblas_dgemv"; cblas_info = 1; cblas_dgemv(INVALID, CblasNoTrans, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dgemv(CblasColMajor, INVALID, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dgemv(CblasColMajor, CblasNoTrans, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dgemv(CblasColMajor, CblasNoTrans, 0, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = FALSE; cblas_dgemv(CblasColMajor, CblasNoTrans, 2, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = FALSE; cblas_dgemv(CblasColMajor, CblasNoTrans, 0, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 12; RowMajorStrg = FALSE; cblas_dgemv(CblasColMajor, CblasNoTrans, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; RowMajorStrg = TRUE; cblas_dgemv(CblasRowMajor, INVALID, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dgemv(CblasRowMajor, CblasNoTrans, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dgemv(CblasRowMajor, CblasNoTrans, 0, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = TRUE; cblas_dgemv(CblasRowMajor, CblasNoTrans, 0, 2, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = TRUE; cblas_dgemv(CblasRowMajor, CblasNoTrans, 0, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 12; RowMajorStrg = TRUE; cblas_dgemv(CblasRowMajor, CblasNoTrans, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dgbmv",11)==0) { cblas_rout = "cblas_dgbmv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dgbmv(INVALID, CblasNoTrans, 0, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, INVALID, 0, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, INVALID, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, 0, INVALID, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, 0, 0, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, 2, 0, 0, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, 0, 0, 1, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 11; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, 0, 0, 0, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 14; RowMajorStrg = FALSE; cblas_dgbmv(CblasColMajor, CblasNoTrans, 0, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, INVALID, 0, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, INVALID, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, 0, INVALID, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, 0, 0, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, 2, 0, 0, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, 0, 0, 1, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 11; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, 0, 0, 0, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 14; RowMajorStrg = TRUE; cblas_dgbmv(CblasRowMajor, CblasNoTrans, 0, 0, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dsymv",11)==0) { cblas_rout = "cblas_dsymv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dsymv(INVALID, CblasUpper, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dsymv(CblasColMajor, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dsymv(CblasColMajor, CblasUpper, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dsymv(CblasColMajor, CblasUpper, 2, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dsymv(CblasColMajor, CblasUpper, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 11; RowMajorStrg = FALSE; cblas_dsymv(CblasColMajor, CblasUpper, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dsymv(CblasRowMajor, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dsymv(CblasRowMajor, CblasUpper, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dsymv(CblasRowMajor, CblasUpper, 2, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dsymv(CblasRowMajor, CblasUpper, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 11; RowMajorStrg = TRUE; cblas_dsymv(CblasRowMajor, CblasUpper, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dsbmv",11)==0) { cblas_rout = "cblas_dsbmv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dsbmv(INVALID, CblasUpper, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dsbmv(CblasColMajor, INVALID, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dsbmv(CblasColMajor, CblasUpper, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dsbmv(CblasColMajor, CblasUpper, 0, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = FALSE; cblas_dsbmv(CblasColMajor, CblasUpper, 0, 1, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = FALSE; cblas_dsbmv(CblasColMajor, CblasUpper, 0, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 12; RowMajorStrg = FALSE; cblas_dsbmv(CblasColMajor, CblasUpper, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dsbmv(CblasRowMajor, INVALID, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dsbmv(CblasRowMajor, CblasUpper, INVALID, 0, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dsbmv(CblasRowMajor, CblasUpper, 0, INVALID, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = TRUE; cblas_dsbmv(CblasRowMajor, CblasUpper, 0, 1, ALPHA, A, 1, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = TRUE; cblas_dsbmv(CblasRowMajor, CblasUpper, 0, 0, ALPHA, A, 1, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 12; RowMajorStrg = TRUE; cblas_dsbmv(CblasRowMajor, CblasUpper, 0, 0, ALPHA, A, 1, X, 1, BETA, Y, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dspmv",11)==0) { cblas_rout = "cblas_dspmv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dspmv(INVALID, CblasUpper, 0, ALPHA, A, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dspmv(CblasColMajor, INVALID, 0, ALPHA, A, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dspmv(CblasColMajor, CblasUpper, INVALID, ALPHA, A, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = FALSE; cblas_dspmv(CblasColMajor, CblasUpper, 0, ALPHA, A, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = FALSE; cblas_dspmv(CblasColMajor, CblasUpper, 0, ALPHA, A, X, 1, BETA, Y, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dspmv(CblasRowMajor, INVALID, 0, ALPHA, A, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dspmv(CblasRowMajor, CblasUpper, INVALID, ALPHA, A, X, 1, BETA, Y, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = TRUE; cblas_dspmv(CblasRowMajor, CblasUpper, 0, ALPHA, A, X, 0, BETA, Y, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = TRUE; cblas_dspmv(CblasRowMajor, CblasUpper, 0, ALPHA, A, X, 1, BETA, Y, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dtrmv",11)==0) { cblas_rout = "cblas_dtrmv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dtrmv(INVALID, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dtrmv(CblasColMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dtrmv(CblasColMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dtrmv(CblasColMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dtrmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = FALSE; cblas_dtrmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 2, A, 1, X, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = FALSE; cblas_dtrmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dtrmv(CblasRowMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dtrmv(CblasRowMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dtrmv(CblasRowMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dtrmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = TRUE; cblas_dtrmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 2, A, 1, X, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = TRUE; cblas_dtrmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dtbmv",11)==0) { cblas_rout = "cblas_dtbmv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dtbmv(INVALID, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, CblasUpper, INVALID, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, CblasUpper, CblasNoTrans, INVALID, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 1, A, 1, X, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = FALSE; cblas_dtbmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, CblasUpper, INVALID, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, CblasUpper, CblasNoTrans, INVALID, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 1, A, 1, X, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = TRUE; cblas_dtbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dtpmv",11)==0) { cblas_rout = "cblas_dtpmv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dtpmv(INVALID, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dtpmv(CblasColMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dtpmv(CblasColMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dtpmv(CblasColMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dtpmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dtpmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, X, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dtpmv(CblasRowMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dtpmv(CblasRowMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dtpmv(CblasRowMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dtpmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dtpmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, X, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dtrsv",11)==0) { cblas_rout = "cblas_dtrsv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dtrsv(INVALID, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dtrsv(CblasColMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dtrsv(CblasColMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dtrsv(CblasColMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dtrsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = FALSE; cblas_dtrsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 2, A, 1, X, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = FALSE; cblas_dtrsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dtrsv(CblasRowMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dtrsv(CblasRowMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dtrsv(CblasRowMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dtrsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 7; RowMajorStrg = TRUE; cblas_dtrsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 2, A, 1, X, 1 ); chkxer(); cblas_info = 9; RowMajorStrg = TRUE; cblas_dtrsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, 1, X, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dtbsv",11)==0) { cblas_rout = "cblas_dtbsv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dtbsv(INVALID, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, CblasUpper, INVALID, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, INVALID, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 1, A, 1, X, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = FALSE; cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, CblasUpper, INVALID, CblasNonUnit, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, CblasUpper, CblasNoTrans, INVALID, 0, 0, A, 1, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, 0, A, 1, X, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, INVALID, A, 1, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 1, A, 1, X, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = TRUE; cblas_dtbsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, 0, A, 1, X, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dtpsv",11)==0) { cblas_rout = "cblas_dtpsv"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dtpsv(INVALID, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dtpsv(CblasColMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dtpsv(CblasColMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = FALSE; cblas_dtpsv(CblasColMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = FALSE; cblas_dtpsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dtpsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, X, 0 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dtpsv(CblasRowMajor, INVALID, CblasNoTrans, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dtpsv(CblasRowMajor, CblasUpper, INVALID, CblasNonUnit, 0, A, X, 1 ); chkxer(); cblas_info = 4; RowMajorStrg = TRUE; cblas_dtpsv(CblasRowMajor, CblasUpper, CblasNoTrans, INVALID, 0, A, X, 1 ); chkxer(); cblas_info = 5; RowMajorStrg = TRUE; cblas_dtpsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, INVALID, A, X, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dtpsv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, 0, A, X, 0 ); chkxer(); } else if (strncmp( sf,"cblas_dger",10)==0) { cblas_rout = "cblas_dger"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dger(INVALID, 0, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dger(CblasColMajor, INVALID, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dger(CblasColMajor, 0, INVALID, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dger(CblasColMajor, 0, 0, ALPHA, X, 0, Y, 1, A, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dger(CblasColMajor, 0, 0, ALPHA, X, 1, Y, 0, A, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = FALSE; cblas_dger(CblasColMajor, 2, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dger(CblasRowMajor, INVALID, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dger(CblasRowMajor, 0, INVALID, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dger(CblasRowMajor, 0, 0, ALPHA, X, 0, Y, 1, A, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dger(CblasRowMajor, 0, 0, ALPHA, X, 1, Y, 0, A, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = TRUE; cblas_dger(CblasRowMajor, 0, 2, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); } else if (strncmp( sf,"cblas_dsyr2",11)==0) { cblas_rout = "cblas_dsyr2"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dsyr2(INVALID, CblasUpper, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dsyr2(CblasColMajor, INVALID, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dsyr2(CblasColMajor, CblasUpper, INVALID, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dsyr2(CblasColMajor, CblasUpper, 0, ALPHA, X, 0, Y, 1, A, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dsyr2(CblasColMajor, CblasUpper, 0, ALPHA, X, 1, Y, 0, A, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = FALSE; cblas_dsyr2(CblasColMajor, CblasUpper, 2, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dsyr2(CblasRowMajor, INVALID, 0, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dsyr2(CblasRowMajor, CblasUpper, INVALID, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dsyr2(CblasRowMajor, CblasUpper, 0, ALPHA, X, 0, Y, 1, A, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dsyr2(CblasRowMajor, CblasUpper, 0, ALPHA, X, 1, Y, 0, A, 1 ); chkxer(); cblas_info = 10; RowMajorStrg = TRUE; cblas_dsyr2(CblasRowMajor, CblasUpper, 2, ALPHA, X, 1, Y, 1, A, 1 ); chkxer(); } else if (strncmp( sf,"cblas_dspr2",11)==0) { cblas_rout = "cblas_dspr2"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dspr2(INVALID, CblasUpper, 0, ALPHA, X, 1, Y, 1, A ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dspr2(CblasColMajor, INVALID, 0, ALPHA, X, 1, Y, 1, A ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dspr2(CblasColMajor, CblasUpper, INVALID, ALPHA, X, 1, Y, 1, A ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dspr2(CblasColMajor, CblasUpper, 0, ALPHA, X, 0, Y, 1, A ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dspr2(CblasColMajor, CblasUpper, 0, ALPHA, X, 1, Y, 0, A ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dspr2(CblasRowMajor, INVALID, 0, ALPHA, X, 1, Y, 1, A ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dspr2(CblasRowMajor, CblasUpper, INVALID, ALPHA, X, 1, Y, 1, A ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dspr2(CblasRowMajor, CblasUpper, 0, ALPHA, X, 0, Y, 1, A ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dspr2(CblasRowMajor, CblasUpper, 0, ALPHA, X, 1, Y, 0, A ); chkxer(); } else if (strncmp( sf,"cblas_dsyr",10)==0) { cblas_rout = "cblas_dsyr"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dsyr(INVALID, CblasUpper, 0, ALPHA, X, 1, A, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dsyr(CblasColMajor, INVALID, 0, ALPHA, X, 1, A, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dsyr(CblasColMajor, CblasUpper, INVALID, ALPHA, X, 1, A, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dsyr(CblasColMajor, CblasUpper, 0, ALPHA, X, 0, A, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = FALSE; cblas_dsyr(CblasColMajor, CblasUpper, 2, ALPHA, X, 1, A, 1 ); chkxer(); cblas_info = 2; RowMajorStrg = TRUE; cblas_dsyr(CblasRowMajor, INVALID, 0, ALPHA, X, 1, A, 1 ); chkxer(); cblas_info = 3; RowMajorStrg = TRUE; cblas_dsyr(CblasRowMajor, CblasUpper, INVALID, ALPHA, X, 1, A, 1 ); chkxer(); cblas_info = 6; RowMajorStrg = TRUE; cblas_dsyr(CblasRowMajor, CblasUpper, 0, ALPHA, X, 0, A, 1 ); chkxer(); cblas_info = 8; RowMajorStrg = TRUE; cblas_dsyr(CblasRowMajor, CblasUpper, 2, ALPHA, X, 1, A, 1 ); chkxer(); } else if (strncmp( sf,"cblas_dspr",10)==0) { cblas_rout = "cblas_dspr"; cblas_info = 1; RowMajorStrg = FALSE; cblas_dspr(INVALID, CblasUpper, 0, ALPHA, X, 1, A ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dspr(CblasColMajor, INVALID, 0, ALPHA, X, 1, A ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dspr(CblasColMajor, CblasUpper, INVALID, ALPHA, X, 1, A ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dspr(CblasColMajor, CblasUpper, 0, ALPHA, X, 0, A ); chkxer(); cblas_info = 2; RowMajorStrg = FALSE; cblas_dspr(CblasColMajor, INVALID, 0, ALPHA, X, 1, A ); chkxer(); cblas_info = 3; RowMajorStrg = FALSE; cblas_dspr(CblasColMajor, CblasUpper, INVALID, ALPHA, X, 1, A ); chkxer(); cblas_info = 6; RowMajorStrg = FALSE; cblas_dspr(CblasColMajor, CblasUpper, 0, ALPHA, X, 0, A ); chkxer(); } if (cblas_ok == TRUE) printf(" %-12s PASSED THE TESTS OF ERROR-EXITS\n", cblas_rout); else printf("******* %s FAILED THE TESTS OF ERROR-EXITS *******\n",cblas_rout); }
18,699
511
<filename>node_modules/grpc/deps/grpc/src/core/ext/filters/client_channel/subchannel_index.h /* * * Copyright 2016 gRPC 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. * */ #ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INDEX_H #define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INDEX_H #include "src/core/ext/filters/client_channel/subchannel.h" /** \file Provides an index of active subchannels so that they can be shared amongst channels */ /** Create a key that can be used to uniquely identify a subchannel */ grpc_subchannel_key* grpc_subchannel_key_create( const grpc_subchannel_args* args); /** Destroy a subchannel key */ void grpc_subchannel_key_destroy(grpc_subchannel_key* key); /** Given a subchannel key, find the subchannel registered for it. Returns NULL if no such channel exists. Thread-safe. */ grpc_subchannel* grpc_subchannel_index_find(grpc_subchannel_key* key); /** Register a subchannel against a key. Takes ownership of \a constructed. Returns the registered subchannel. This may be different from \a constructed in the case of a registration race. */ grpc_subchannel* grpc_subchannel_index_register(grpc_subchannel_key* key, grpc_subchannel* constructed); /** Remove \a constructed as the registered subchannel for \a key. */ void grpc_subchannel_index_unregister(grpc_subchannel_key* key, grpc_subchannel* constructed); int grpc_subchannel_key_compare(const grpc_subchannel_key* a, const grpc_subchannel_key* b); /** Initialize the subchannel index (global) */ void grpc_subchannel_index_init(void); /** Shutdown the subchannel index (global) */ void grpc_subchannel_index_shutdown(void); /** Increment the refcount (non-zero) of subchannel index (global). */ void grpc_subchannel_index_ref(void); /** Decrement the refcount of subchannel index (global). If the refcount drops to zero, unref the subchannel index and destroy its mutex. */ void grpc_subchannel_index_unref(void); /** \em TEST ONLY. * If \a force_creation is true, all key comparisons will be false, resulting in * new subchannels always being created. Otherwise, the keys will be compared as * usual. * * This function is *not* threadsafe on purpose: it should *only* be used in * test code. * * Tests using this function \em MUST run tests with and without \a * force_creation set. */ void grpc_subchannel_index_test_only_set_force_creation(bool force_creation); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INDEX_H */
1,056
679
<filename>main/bridges/test/java_uno/equals/testequals.cxx /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #include "com/sun/star/bridge/XBridge.hpp" #include "com/sun/star/bridge/XBridgeFactory.hpp" #include "com/sun/star/connection/Connector.hpp" #include "com/sun/star/connection/XConnection.hpp" #include "com/sun/star/connection/XConnector.hpp" #include "com/sun/star/lang/XMultiComponentFactory.hpp" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/lang/XSingleComponentFactory.hpp" #include "com/sun/star/registry/InvalidRegistryException.hpp" #include "com/sun/star/registry/XRegistryKey.hpp" #include "com/sun/star/uno/Exception.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/uno/XInterface.hpp" #include "cppuhelper/factory.hxx" #include "cppuhelper/implbase2.hxx" #include "cppuhelper/weak.hxx" #include "rtl/string.h" #include "rtl/ustring.hxx" #include "sal/types.h" #include "test/java_uno/equals/XBase.hpp" #include "test/java_uno/equals/XDerived.hpp" #include "test/java_uno/equals/XTestInterface.hpp" #include "uno/environment.h" #include "uno/lbnames.h" namespace css = com::sun::star; namespace { class Service: public cppu::WeakImplHelper2< css::lang::XServiceInfo, test::java_uno::equals::XTestInterface > { public: virtual inline rtl::OUString SAL_CALL getImplementationName() throw (css::uno::RuntimeException) { return rtl::OUString::createFromAscii(getImplementationName_static()); } virtual sal_Bool SAL_CALL supportsService( rtl::OUString const & rServiceName) throw (css::uno::RuntimeException); virtual inline css::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (css::uno::RuntimeException) { return getSupportedServiceNames_static(); } virtual void SAL_CALL connect(rtl::OUString const & rConnection, rtl::OUString const & rProtocol) throw (css::uno::Exception); virtual css::uno::Reference< css::uno::XInterface > SAL_CALL get( rtl::OUString const & rName) throw (css::uno::RuntimeException); static inline sal_Char const * getImplementationName_static() { return "com.sun.star.test.bridges.testequals.impl"; } static css::uno::Sequence< rtl::OUString > getSupportedServiceNames_static(); static css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance( css::uno::Reference< css::uno::XComponentContext > const & rContext) throw (css::uno::Exception); private: explicit inline Service( css::uno::Reference< css::uno::XComponentContext > const & rContext): m_xContext(rContext) {} css::uno::Reference< css::uno::XComponentContext > m_xContext; css::uno::Reference< css::bridge::XBridge > m_xBridge; }; } sal_Bool Service::supportsService(rtl::OUString const & rServiceName) throw (css::uno::RuntimeException) { css::uno::Sequence< rtl::OUString > aNames( getSupportedServiceNames_static()); for (sal_Int32 i = 0; i< aNames.getLength(); ++i) if (aNames[i] == rServiceName) return true; return false; } void Service::connect(rtl::OUString const & rConnection, rtl::OUString const & rProtocol) throw (css::uno::Exception) { css::uno::Reference< css::connection::XConnection > xConnection( css::connection::Connector::create(m_xContext)->connect(rConnection)); css::uno::Reference< css::bridge::XBridgeFactory > xBridgeFactory( m_xContext->getServiceManager()->createInstanceWithContext( rtl::OUString::createFromAscii("com.sun.star.bridge.BridgeFactory"), m_xContext), css::uno::UNO_QUERY); m_xBridge = xBridgeFactory->createBridge(rtl::OUString(), rProtocol, xConnection, 0); } css::uno::Reference< css::uno::XInterface > Service::get(rtl::OUString const & rName) throw (css::uno::RuntimeException) { return m_xBridge->getInstance(rName); } css::uno::Sequence< rtl::OUString > Service::getSupportedServiceNames_static() { css::uno::Sequence< rtl::OUString > aNames(1); aNames[0] = rtl::OUString::createFromAscii( "com.sun.star.test.bridges.testequals"); return aNames; } css::uno::Reference< css::uno::XInterface > Service::createInstance( css::uno::Reference< css::uno::XComponentContext > const & rContext) throw (css::uno::Exception) { // Make types known: getCppuType( static_cast< css::uno::Reference< test::java_uno::equals::XBase > const * >(0)); getCppuType( static_cast< css::uno::Reference< test::java_uno::equals::XDerived > const * >(0)); getCppuType( static_cast< css::uno::Reference< test::java_uno::equals::XTestInterface > const * >( 0)); return static_cast< cppu::OWeakObject * >(new Service(rContext)); } extern "C" void SAL_CALL component_getImplementationEnvironment( sal_Char const ** pEnvTypeName, uno_Environment **) { *pEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } extern "C" void * SAL_CALL component_getFactory(sal_Char const * pImplName, void * pServiceManager, void *) { void * pFactory = 0; if (pServiceManager) if (rtl_str_compare(pImplName, Service::getImplementationName_static()) == 0) { css::uno::Reference< css::lang::XSingleComponentFactory > xFactory(cppu::createSingleComponentFactory( &Service::createInstance, rtl::OUString::createFromAscii( Service::getImplementationName_static()), Service::getSupportedServiceNames_static())); if (xFactory.is()) { xFactory->acquire(); pFactory = xFactory.get(); } } return pFactory; } namespace { bool writeInfo(void * pRegistryKey, sal_Char const * pImplementationName, css::uno::Sequence< rtl::OUString > const & rServiceNames) { rtl::OUString aKeyName(rtl::OUString::createFromAscii("/")); aKeyName += rtl::OUString::createFromAscii(pImplementationName); aKeyName += rtl::OUString::createFromAscii("/UNO/SERVICES"); css::uno::Reference< css::registry::XRegistryKey > xKey; try { xKey = static_cast< css::registry::XRegistryKey * >(pRegistryKey)-> createKey(aKeyName); } catch (css::registry::InvalidRegistryException &) {} if (!xKey.is()) return false; bool bSuccess = true; for (sal_Int32 i = 0; i < rServiceNames.getLength(); ++i) try { xKey->createKey(rServiceNames[i]); } catch (css::registry::InvalidRegistryException &) { bSuccess = false; break; } return bSuccess; } } extern "C" sal_Bool SAL_CALL component_writeInfo(void *, void * pRegistryKey) { return pRegistryKey && writeInfo(pRegistryKey, Service::getImplementationName_static(), Service::getSupportedServiceNames_static()); }
3,349
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Combres-sous-les-Côtes","circ":"2ème circonscription","dpt":"Meuse","inscrits":95,"abs":42,"votants":53,"blancs":6,"nuls":1,"exp":46,"res":[{"nuance":"REM","nom":"<NAME>","voix":36},{"nuance":"FN","nom":"<NAME>","voix":10}]}
115
4,646
<reponame>Recaust/Launcher3<filename>src/com/android/launcher3/compat/ShortcutConfigActivityInfo.java<gh_stars>1000+ /* * 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. */ package com.android.launcher3.compat; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.content.IntentSender; import android.content.pm.ActivityInfo; import android.content.pm.LauncherActivityInfo; import android.content.pm.LauncherApps; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Process; import android.os.UserHandle; import android.util.Log; import android.widget.Toast; import com.android.launcher3.IconCache; import com.android.launcher3.LauncherSettings; import com.android.launcher3.R; import com.android.launcher3.ShortcutInfo; /** * Wrapper class for representing a shortcut configure activity. */ public abstract class ShortcutConfigActivityInfo { private static final String TAG = "SCActivityInfo"; private final ComponentName mCn; private final UserHandle mUser; protected ShortcutConfigActivityInfo(ComponentName cn, UserHandle user) { mCn = cn; mUser = user; } public ComponentName getComponent() { return mCn; } public UserHandle getUser() { return mUser; } public int getItemType() { return LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; } public abstract CharSequence getLabel(); public abstract Drawable getFullResIcon(IconCache cache); /** * Return a shortcut info, if it can be created directly on drop, without requiring any * {@link #startConfigActivity(Activity, int)}. */ public ShortcutInfo createShortcutInfo() { return null; } public boolean startConfigActivity(Activity activity, int requestCode) { Intent intent = new Intent(Intent.ACTION_CREATE_SHORTCUT) .setComponent(getComponent()); try { activity.startActivityForResult(intent, requestCode); return true; } catch (ActivityNotFoundException e) { Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity.", e); } return false; } /** * Returns true if various properties ({@link #getLabel()}, {@link #getFullResIcon}) can * be safely persisted. */ public boolean isPersistable() { return true; } static class ShortcutConfigActivityInfoVL extends ShortcutConfigActivityInfo { private final ActivityInfo mInfo; private final PackageManager mPm; public ShortcutConfigActivityInfoVL(ActivityInfo info, PackageManager pm) { super(new ComponentName(info.packageName, info.name), Process.myUserHandle()); mInfo = info; mPm = pm; } @Override public CharSequence getLabel() { return mInfo.loadLabel(mPm); } @Override public Drawable getFullResIcon(IconCache cache) { return cache.getFullResIcon(mInfo); } } @TargetApi(26) public static class ShortcutConfigActivityInfoVO extends ShortcutConfigActivityInfo { private final LauncherActivityInfo mInfo; public ShortcutConfigActivityInfoVO(LauncherActivityInfo info) { super(info.getComponentName(), info.getUser()); mInfo = info; } @Override public CharSequence getLabel() { return mInfo.getLabel(); } @Override public Drawable getFullResIcon(IconCache cache) { return cache.getFullResIcon(mInfo); } @Override public boolean startConfigActivity(Activity activity, int requestCode) { if (getUser().equals(Process.myUserHandle())) { return super.startConfigActivity(activity, requestCode); } IntentSender is = activity.getSystemService(LauncherApps.class) .getShortcutConfigActivityIntent(mInfo); try { activity.startIntentSenderForResult(is, requestCode, null, 0, 0, 0); return true; } catch (IntentSender.SendIntentException e) { Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); return false; } } } }
2,056
435
<reponame>Montana/datawave<gh_stars>100-1000 package datawave.edge.util; import com.google.protobuf.InvalidProtocolBufferException; import datawave.edge.protobuf.EdgeData; import datawave.edge.protobuf.EdgeData.EdgeValue.Builder; import org.apache.accumulo.core.data.Value; import org.apache.commons.lang.StringUtils; import java.util.List; import java.util.UUID; /** * Utility class for serializing edge table protocol buffer. Previously, the EdgeValueHelper class was sufficient for handling the edge values, but with the * addition of fields beyond the counts, a more generic solution is required. * */ public class EdgeValue { private final Long count; private final Integer bitmask; private final String sourceValue; private final String sinkValue; private final List<Long> hours; private final List<Long> duration; private String loadDate; private UUID uuidObj; // see EdgeData.proto. hasOnlyUuidString is true if uuid_string is/should be set in the protobuf message, meaning that uuid is not set because a UUID object // couldn't be created from the original uuid private boolean hasOnlyUuidString; // see hasOnlyUuidString. This is either the uuid_string value or if uuid_string is not set it contains a human readable version of uuidObj private String uuidString; private Boolean badActivityDate; private EdgeValue(Long count, Integer bitmask, String sourceValue, String sinkValue) { this(count, bitmask, sourceValue, sinkValue, null, null, null, null, false, null, null); } private EdgeValue(Long count, Integer bitmask, String sourceValue, String sinkValue, List<Long> hours, List<Long> duration, String loadDate, String uuidString, boolean hasOnlyUuidString, UUID uuidObj, Boolean badActivityDate) { if (count == 0) { this.count = null; } else { this.count = count; } if (bitmask == 0) { this.bitmask = null; } else { this.bitmask = bitmask; } this.sourceValue = sourceValue; this.sinkValue = sinkValue; this.hours = hours; this.duration = duration; this.loadDate = loadDate; this.uuidString = uuidString; this.hasOnlyUuidString = hasOnlyUuidString; this.uuidObj = uuidObj; this.badActivityDate = badActivityDate; } private static final int[] HOUR_MASKS = {0x000001, 0x000002, 0x000004, 0x000008, 0x000010, 0x000020, 0x000040, 0x000080, 0x000100, 0x000200, 0x000400, 0x000800, 0x001000, 0x002000, 0x004000, 0x008000, 0x010000, 0x020000, 0x040000, 0x080000, 0x100000, 0x200000, 0x400000, 0x800000}; public static class EdgeValueBuilder { private Long count; private Integer bitmask; private String sourceValue = null; private String sinkValue = null; private List<Long> hours = null; private List<Long> duration = null; private String loadDate = null; private UUID uuidObj = null; private boolean hasOnlyUuidString = false; private String uuidString = null; private Boolean badActivityDate = null; private EdgeValueBuilder() { this.count = 0l; this.bitmask = 0; } private EdgeValueBuilder(EdgeValue edgeValue) { this.count = edgeValue.getCount(); this.bitmask = edgeValue.getBitmask(); this.sourceValue = edgeValue.getSourceValue(); this.sinkValue = edgeValue.getSinkValue(); this.hours = edgeValue.getHours(); this.duration = edgeValue.getDuration(); this.loadDate = edgeValue.getLoadDate(); this.hasOnlyUuidString = edgeValue.hasOnlyUuidString; this.uuidObj = edgeValue.getUuidObject(); this.uuidString = edgeValue.getUuid(); } public EdgeValue build() { return new EdgeValue(this.count, this.bitmask, this.sourceValue, this.sinkValue, this.hours, this.duration, this.loadDate, this.uuidString, this.hasOnlyUuidString, this.uuidObj, this.badActivityDate); } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public Integer getBitmask() { return bitmask; } public void setBitmask(Integer bitmask) { this.bitmask = bitmask; } public void setHour(Integer hour) { if (hour > 23 || hour < 0) { throw new IllegalArgumentException("Supplied Integer for hour bitmask is out of range: " + hour); } if (bitmask == null) { bitmask = 0; } bitmask |= HOUR_MASKS[hour]; } public void combineBitmask(int otherMask) { this.bitmask |= otherMask; } public String getSourceValue() { return sourceValue; } public String getSinkValue() { return sinkValue; } public void setSourceValue(String sourceValue) { this.sourceValue = sourceValue; } public void setSinkValue(String sinkValue) { this.sinkValue = sinkValue; } public List<Long> getHours() { return hours; } public void setHours(List<Long> hours) { this.hours = hours; } public List<Long> getDuration() { return duration; } public void setDuration(List<Long> duration) { this.duration = duration; } public String getLoadDate() { return loadDate; } public void setLoadDate(String loadDate) { this.loadDate = loadDate; } public UUID getUuidObj() { if (this.hasOnlyUuidString) { return null; } if (null == uuidObj && StringUtils.isNotBlank(this.uuidString)) { try { // try to parse the uuid string to a UUID object this.uuidObj = convertUuidStringToUuidObj(this.uuidString); } catch (Exception e) { // if it failed to parse, settle for the uuid_string this.hasOnlyUuidString = true; } } return uuidObj; } public void setUuidObj(UUID uuidObj) { this.uuidObj = uuidObj; } public String getUuid() { // if missing, attempt to initialize uuid from uuidObj if (StringUtils.isBlank(this.uuidString) && null != this.uuidObj) { this.uuidString = convertUuidObjectToString(this.uuidObj); } return this.uuidString; } public void setUuid(String uuid) { this.uuidString = uuid; } public Boolean isBadActivityDate() { return badActivityDate; } public void setBadActivityDate(Boolean badActivityDate) { this.badActivityDate = badActivityDate; } public boolean badActivityDateSet() { if (this.badActivityDate == null) { return false; } else { return true; } } public void setOnlyUuidString(boolean hasOnlyUuidString) { this.hasOnlyUuidString = hasOnlyUuidString; } } // ////// END BUILDER //////// public static EdgeValueBuilder newBuilder() { return new EdgeValueBuilder(); } public static EdgeValueBuilder newBuilder(EdgeValue edgeValue) { return new EdgeValueBuilder(edgeValue); } public static EdgeValue decode(Value value) throws InvalidProtocolBufferException { EdgeData.EdgeValue proto = EdgeData.EdgeValue.parseFrom(value.get()); EdgeValueBuilder builder = new EdgeValueBuilder(); if (proto.hasCount()) { builder.setCount(proto.getCount()); } else { builder.setCount(0l); } if (proto.hasHourBitmask()) { builder.setBitmask(proto.getHourBitmask()); } if (proto.hasSourceValue()) { builder.setSourceValue(proto.getSourceValue()); } if (proto.hasSinkValue()) { builder.setSinkValue(proto.getSinkValue()); } List<Long> hoursList = proto.getHoursList(); if (hoursList != null && hoursList.isEmpty() == false) { builder.setHours(hoursList); } List<Long> durationList = proto.getDurationList(); if (durationList != null && durationList.isEmpty() == false) { builder.setDuration(durationList); } if (proto.hasLoadDate()) { builder.setLoadDate(proto.getLoadDate()); } if (proto.hasUuid()) { builder.setOnlyUuidString(false); builder.setUuidObj(convertUuidObject(proto.getUuid())); } else if (proto.hasUuidString()) { // if there is a uuid string in the protobuf data, it means that we shouldn't have a uuid object at all builder.setOnlyUuidString(true); builder.setUuid(proto.getUuidString()); } if (proto.hasBadActivity()) { builder.setBadActivityDate(proto.getBadActivity()); } return builder.build(); } public Value encode() { Builder builder = EdgeData.EdgeValue.newBuilder(); if (this.hasCount()) { builder.setCount(this.getCount()); } else { builder.setCount(0l); } if (this.hasBitmask()) { builder.setHourBitmask(this.getBitmask()); } if (this.sourceValue != null) { builder.setSourceValue(this.sourceValue); } if (this.sinkValue != null) { builder.setSinkValue(this.sinkValue); } if (this.hours != null) { builder.addAllHours(this.hours); } if (this.duration != null) { builder.addAllDuration(this.duration); } if (this.loadDate != null) { builder.setLoadDate(loadDate); } // iff the string uuid couldn't parse into a uuid object, the protobuf edge will contain uuid_string and not the uuid object if (this.hasOnlyUuidString) { // we know in advance that this has only the uuid_string (parsing must have already failed) if (StringUtils.isNotBlank(this.uuidString)) { // as long as the uuid isn't empty, set it builder.setUuidString(this.uuidString); } } else if (this.uuidObj != null) { // already have the uuid object, so there's no reason to reparse the string builder.setUuid(convertUuidObject(this.uuidObj)); } else if (StringUtils.isNotBlank(this.uuidString)) { try { // try to parse the uuid string to a UUID object this.uuidObj = convertUuidStringToUuidObj(this.uuidString); builder.setUuid(convertUuidObject(this.uuidObj)); } catch (Exception e) { // if it failed to parse, settle for the uuid_string this.hasOnlyUuidString = true; builder.setUuidString(this.uuidString); } } if (this.badActivityDate != null) { builder.setBadActivity(badActivityDate); } return new Value(builder.build().toByteArray()); } public static UUID convertUuidStringToUuidObj(String uuidString) { return UUID.fromString(uuidString); } public Long getCount() { return count; } public boolean hasCount() { return this.count != null; } public Integer getBitmask() { if (null == bitmask) return 0; return bitmask; } public boolean hasBitmask() { return this.bitmask != null; } public boolean hasLoadDate() { return this.loadDate != null; } public boolean isHourSet(int hour) { if (hour > 23 || hour < 0) { throw new IllegalArgumentException("Supplied Integer for hour bitmask lookup is out of range: " + hour); } if (!this.hasBitmask()) { throw new IllegalStateException("No bitmask is defined."); } return ((this.bitmask & HOUR_MASKS[hour]) > 0); } public String getSourceValue() { return sourceValue; } public String getSinkValue() { return sinkValue; } public List<Long> getHours() { return hours; } public List<Long> getDuration() { return duration; } public String getLoadDate() { return loadDate; } public UUID getUuidObject() { if (this.hasOnlyUuidString) { return null; } if (null == uuidObj && StringUtils.isNotBlank(this.uuidString)) { try { // try to parse the uuid string to a UUID object this.uuidObj = convertUuidStringToUuidObj(this.uuidString); } catch (Exception e) { // if it failed to parse, settle for the uuid_string this.hasOnlyUuidString = true; } } return uuidObj; } public String getUuid() { // if human readable string is missing, attempt to create one from the uuidObj if ((null == this.uuidString || this.uuidString.isEmpty()) && null != this.uuidObj) { this.uuidString = convertUuidObjectToString(this.uuidObj); } return this.uuidString; } public static String convertUuidObjectToString(UUID rawUuid) { return rawUuid.toString(); } public static UUID convertUuidObject(EdgeData.EdgeValue.UUID rawUuid) { return new UUID(rawUuid.getMostSignificantBits(), rawUuid.getLeastSignificantBits()); } public static EdgeData.EdgeValue.UUID convertUuidObject(UUID rawUuid) { EdgeData.EdgeValue.UUID.Builder builder = EdgeData.EdgeValue.UUID.newBuilder(); builder.setLeastSignificantBits(rawUuid.getLeastSignificantBits()); builder.setMostSignificantBits(rawUuid.getMostSignificantBits()); return builder.build(); } public Boolean isBadActivityDate() { return badActivityDate; } public void setBadActivityDate(Boolean badActivityDate) { this.badActivityDate = badActivityDate; } public boolean badActivityDateSet() { if (this.badActivityDate == null) { return false; } else { return true; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EdgeValue edgeValue = (EdgeValue) o; if (count != null ? !count.equals(edgeValue.count) : edgeValue.count != null) return false; if (bitmask != null ? !bitmask.equals(edgeValue.bitmask) : edgeValue.bitmask != null) return false; if (sourceValue != null ? !sourceValue.equals(edgeValue.sourceValue) : edgeValue.sourceValue != null) return false; if (sinkValue != null ? !sinkValue.equals(edgeValue.sinkValue) : edgeValue.sinkValue != null) return false; if (hours != null ? !hours.equals(edgeValue.hours) : edgeValue.hours != null) return false; if (duration != null ? !duration.equals(edgeValue.duration) : edgeValue.duration != null) return false; if (loadDate != null ? !loadDate.equals(edgeValue.loadDate) : edgeValue.loadDate != null) return false; if (badActivityDate != null ? !badActivityDate.equals(edgeValue.badActivityDate) : edgeValue.badActivityDate != null) return false; // a protobuf Edge will have either a UUID object, preferrably, or a uuidString - but not both // the uuidObj and uuidString are both lazily initialized if (StringUtils.isNotBlank(uuidString) && StringUtils.isNotBlank(edgeValue.uuidString)) { return uuidString.equals(edgeValue.uuidString); } else if (null != uuidObj && null != edgeValue.uuidObj) { return uuidObj.equals(edgeValue.uuidObj); } else if (null != uuidObj && edgeValue.hasOnlyUuidString) { return false; } else if (null != edgeValue.uuidObj && edgeValue.hasOnlyUuidString) { return false; } else { // getUuid will force uuidString to get initialized if it isn't already return (getUuid() == null ? edgeValue.getUuid() == null : getUuid().equals(edgeValue.getUuid())); } } @Override public int hashCode() { int result = count != null ? count.hashCode() : 0; result = 31 * result + (bitmask != null ? bitmask.hashCode() : 0); result = 31 * result + (sourceValue != null ? sourceValue.hashCode() : 0); result = 31 * result + (sinkValue != null ? sinkValue.hashCode() : 0); result = 31 * result + (hours != null ? hours.hashCode() : 0); result = 31 * result + (duration != null ? duration.hashCode() : 0); result = 31 * result + (loadDate != null ? loadDate.hashCode() : 0); if (uuidObj == null && !hasOnlyUuidString) { // force initialization of uuidObj, if possible (will short circuit if already failed to parse) getUuidObject(); } if (uuidObj != null) { // if it's impossible to use uuidObj, then use uuidString result = 31 * result + uuidObj.hashCode(); } else { result = 31 * result + (uuidString != null ? uuidString.hashCode() : 0); } return 31 * result + (badActivityDate != null ? badActivityDate.hashCode() : 0); } @Override public String toString() { return "count: " + (count != null ? count.toString() : "") + ", bitmask: " + (bitmask != null ? bitmask.toString() : "") + ", sourceValue: " + (sourceValue != null ? sourceValue.toString() : "") + ", sinkValue: " + (sinkValue != null ? sinkValue.toString() : "") + ", hours: " + (hours != null ? hours.toString() : "") + ", duration: " + (duration != null ? duration.toString() : "") + ", loadDate: " + (loadDate != null ? loadDate.toString() : "") + ", uuidString: " + (hasOnlyUuidString && uuidString != null ? uuidString.toString() : "") + ", uuidObj: " + (uuidObj != null ? uuidObj.toString() : "") + ", badActivityDate: " + (badActivityDate != null ? badActivityDate.toString() : ""); } }
8,702
1,449
<reponame>westgoten/anvil package trikita.anvil.gridlayout.v7; import android.support.v7.widget.GridLayout; import android.util.Printer; import android.view.View; import java.lang.Boolean; import java.lang.Integer; import java.lang.Object; import java.lang.String; import java.lang.Void; import trikita.anvil.Anvil; import trikita.anvil.BaseDSL; /** * DSL for creating views and settings their attributes. * This file has been generated by {@code gradle generateGridLayoutv7DSL}. * It contains views and their setters from the library gridlayout-v7. * Please, don't edit it manually unless for debugging. */ public final class GridLayoutv7DSL implements Anvil.AttributeSetter { static { Anvil.registerAttributeSetter(new GridLayoutv7DSL()); } public static BaseDSL.ViewClassResult gridLayout() { return BaseDSL.v(GridLayout.class); } public static Void gridLayout(Anvil.Renderable r) { return BaseDSL.v(GridLayout.class, r); } public static Void alignmentMode(int arg) { return BaseDSL.attr("alignmentMode", arg); } public static Void columnCount(int arg) { return BaseDSL.attr("columnCount", arg); } public static Void columnOrderPreserved(boolean arg) { return BaseDSL.attr("columnOrderPreserved", arg); } public static Void orientation(int arg) { return BaseDSL.attr("orientation", arg); } public static Void printer(Printer arg) { return BaseDSL.attr("printer", arg); } public static Void rowCount(int arg) { return BaseDSL.attr("rowCount", arg); } public static Void rowOrderPreserved(boolean arg) { return BaseDSL.attr("rowOrderPreserved", arg); } public static Void useDefaultMargins(boolean arg) { return BaseDSL.attr("useDefaultMargins", arg); } public boolean set(View v, String name, final Object arg, final Object old) { switch (name) { case "alignmentMode": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setAlignmentMode((int) arg); return true; } break; case "columnCount": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setColumnCount((int) arg); return true; } break; case "columnOrderPreserved": if (v instanceof GridLayout && arg instanceof Boolean) { ((GridLayout) v).setColumnOrderPreserved((boolean) arg); return true; } break; case "orientation": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setOrientation((int) arg); return true; } break; case "printer": if (v instanceof GridLayout && arg instanceof Printer) { ((GridLayout) v).setPrinter((Printer) arg); return true; } break; case "rowCount": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setRowCount((int) arg); return true; } break; case "rowOrderPreserved": if (v instanceof GridLayout && arg instanceof Boolean) { ((GridLayout) v).setRowOrderPreserved((boolean) arg); return true; } break; case "useDefaultMargins": if (v instanceof GridLayout && arg instanceof Boolean) { ((GridLayout) v).setUseDefaultMargins((boolean) arg); return true; } break; } return false; } }
1,352
348
{"nom":"Orban","circ":"1ère circonscription","dpt":"Tarn","inscrits":273,"abs":117,"votants":156,"blancs":16,"nuls":3,"exp":137,"res":[{"nuance":"DVD","nom":"<NAME>","voix":101},{"nuance":"FN","nom":"M. <NAME>","voix":36}]}
88
1,742
<reponame>sim-wangyan/x7<filename>demo/src/main/java/x7/codetemplate/ScheduleTemplate.java package x7.codetemplate; import java.util.concurrent.Callable; public interface ScheduleTemplate { boolean schedule(Class scheduleClazz, Callable<Boolean> callable); }
100
9,734
/* * 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.arrow.flight.auth2; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.function.Consumer; import org.apache.arrow.flight.CallHeaders; /** * Client credentials that use a username and password. */ public final class BasicAuthCredentialWriter implements Consumer<CallHeaders> { private final String name; private final String password; public BasicAuthCredentialWriter(String name, String password) { this.name = name; this.password = password; } @Override public void accept(CallHeaders outputHeaders) { outputHeaders.insert(Auth2Constants.AUTHORIZATION_HEADER, Auth2Constants.BASIC_PREFIX + Base64.getEncoder().encodeToString(String.format("%s:%s", name, password).getBytes(StandardCharsets.UTF_8))); } }
451
335
<filename>B/Biogeography_noun.json { "word": "Biogeography", "definitions": [ "The branch of biology that deals with the geographical distribution of plants and animals." ], "parts-of-speech": "Noun" }
82
4,857
/* * 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.hadoop.hbase.io.compress; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.io.compress.CodecPool; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionInputStream; import org.apache.hadoop.io.compress.CompressionOutputStream; import org.apache.hadoop.io.compress.Compressor; import org.apache.hadoop.io.compress.Decompressor; import org.apache.hadoop.io.compress.DoNotPool; import org.apache.hadoop.util.ReflectionUtils; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Compression related stuff. * Copied from hadoop-3315 tfile. */ @InterfaceAudience.Private public final class Compression { private static final Logger LOG = LoggerFactory.getLogger(Compression.class); // LZO public static final String LZO_CODEC_CLASS_KEY = "hbase.io.compress.lzo.codec"; public static final String LZO_CODEC_CLASS_DEFAULT = "com.hadoop.compression.lzo.LzoCodec"; // GZ public static final String GZ_CODEC_CLASS_KEY = "hbase.io.compress.gz.codec"; // Our ReusableStreamGzipCodec fixes an inefficiency in Hadoop's Gzip codec, allowing us to // reuse compression streams, but still requires the Hadoop native codec. public static final String GZ_CODEC_CLASS_DEFAULT = "org.apache.hadoop.hbase.io.compress.ReusableStreamGzipCodec"; // SNAPPY public static final String SNAPPY_CODEC_CLASS_KEY = "hbase.io.compress.snappy.codec"; public static final String SNAPPY_CODEC_CLASS_DEFAULT = "org.apache.hadoop.io.compress.SnappyCodec"; // LZ4 public static final String LZ4_CODEC_CLASS_KEY = "hbase.io.compress.lz4.codec"; public static final String LZ4_CODEC_CLASS_DEFAULT = "org.apache.hadoop.io.compress.Lz4Codec"; // ZSTD public static final String ZSTD_CODEC_CLASS_KEY = "hbase.io.compress.zstd.codec"; public static final String ZSTD_CODEC_CLASS_DEFAULT = "org.apache.hadoop.io.compress.ZStandardCodec"; // BZIP2 public static final String BZIP2_CODEC_CLASS_KEY = "hbase.io.compress.bzip2.codec"; public static final String BZIP2_CODEC_CLASS_DEFAULT = "org.apache.hadoop.io.compress.BZip2Codec"; // LZMA public static final String LZMA_CODEC_CLASS_KEY = "hbase.io.compress.lzma.codec"; public static final String LZMA_CODEC_CLASS_DEFAULT = "org.apache.hadoop.hbase.io.compress.xz.LzmaCodec"; /** * Prevent the instantiation of class. */ private Compression() { super(); } static class FinishOnFlushCompressionStream extends FilterOutputStream { public FinishOnFlushCompressionStream(CompressionOutputStream cout) { super(cout); } @Override public void write(byte b[], int off, int len) throws IOException { out.write(b, off, len); } @Override public void flush() throws IOException { CompressionOutputStream cout = (CompressionOutputStream) out; cout.finish(); cout.flush(); cout.resetState(); } } /** * Returns the classloader to load the Codec class from. */ private static ClassLoader getClassLoaderForCodec() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = Compression.class.getClassLoader(); } if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } if (cl == null) { throw new RuntimeException("A ClassLoader to load the Codec could not be determined"); } return cl; } /** * Compression algorithms. The ordinal of these cannot change or else you * risk breaking all existing HFiles out there. Even the ones that are * not compressed! (They use the NONE algorithm) */ @edu.umd.cs.findbugs.annotations.SuppressWarnings( value="SE_TRANSIENT_FIELD_NOT_RESTORED", justification="We are not serializing so doesn't apply (not sure why transient though)") @InterfaceAudience.Public public static enum Algorithm { // LZO is GPL and requires extra install to setup. See // https://stackoverflow.com/questions/23441142/class-com-hadoop-compression-lzo-lzocodec-not-found-for-spark-on-cdh-5 LZO("lzo", LZO_CODEC_CLASS_KEY, LZO_CODEC_CLASS_DEFAULT) { // Use base type to avoid compile-time dependencies. private volatile transient CompressionCodec lzoCodec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (lzoCodec == null) { synchronized (lock) { if (lzoCodec == null) { lzoCodec = buildCodec(conf, this); } } } return lzoCodec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { lzoCodec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return lzoCodec; } } }, GZ("gz", GZ_CODEC_CLASS_KEY, GZ_CODEC_CLASS_DEFAULT) { private volatile transient CompressionCodec gzCodec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (gzCodec == null) { synchronized (lock) { if (gzCodec == null) { gzCodec = buildCodec(conf, this); } } } return gzCodec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { gzCodec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return gzCodec; } } }, NONE("none", "", "") { @Override CompressionCodec getCodec(Configuration conf) { return null; } @Override public CompressionCodec reload(Configuration conf) { return null; } @Override public synchronized InputStream createDecompressionStream( InputStream downStream, Decompressor decompressor, int downStreamBufferSize) throws IOException { if (downStreamBufferSize > 0) { return new BufferedInputStream(downStream, downStreamBufferSize); } return downStream; } @Override public synchronized OutputStream createCompressionStream( OutputStream downStream, Compressor compressor, int downStreamBufferSize) throws IOException { if (downStreamBufferSize > 0) { return new BufferedOutputStream(downStream, downStreamBufferSize); } return downStream; } }, SNAPPY("snappy", SNAPPY_CODEC_CLASS_KEY, SNAPPY_CODEC_CLASS_DEFAULT) { // Use base type to avoid compile-time dependencies. private volatile transient CompressionCodec snappyCodec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (snappyCodec == null) { synchronized (lock) { if (snappyCodec == null) { snappyCodec = buildCodec(conf, this); } } } return snappyCodec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { snappyCodec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return snappyCodec; } } }, LZ4("lz4", LZ4_CODEC_CLASS_KEY, LZ4_CODEC_CLASS_DEFAULT) { // Use base type to avoid compile-time dependencies. private volatile transient CompressionCodec lz4Codec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (lz4Codec == null) { synchronized (lock) { if (lz4Codec == null) { lz4Codec = buildCodec(conf, this); } } } return lz4Codec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { lz4Codec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return lz4Codec; } } }, BZIP2("bzip2", BZIP2_CODEC_CLASS_KEY, BZIP2_CODEC_CLASS_DEFAULT) { // Use base type to avoid compile-time dependencies. private volatile transient CompressionCodec bzipCodec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (bzipCodec == null) { synchronized (lock) { if (bzipCodec == null) { bzipCodec = buildCodec(conf, this); } } } return bzipCodec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { bzipCodec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return bzipCodec; } } }, ZSTD("zstd", ZSTD_CODEC_CLASS_KEY, ZSTD_CODEC_CLASS_DEFAULT) { // Use base type to avoid compile-time dependencies. private volatile transient CompressionCodec zStandardCodec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (zStandardCodec == null) { synchronized (lock) { if (zStandardCodec == null) { zStandardCodec = buildCodec(conf, this); } } } return zStandardCodec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { zStandardCodec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return zStandardCodec; } } }, LZMA("lzma", LZMA_CODEC_CLASS_KEY, LZMA_CODEC_CLASS_DEFAULT) { // Use base type to avoid compile-time dependencies. private volatile transient CompressionCodec lzmaCodec; private final transient Object lock = new Object(); @Override CompressionCodec getCodec(Configuration conf) { if (lzmaCodec == null) { synchronized (lock) { if (lzmaCodec == null) { lzmaCodec = buildCodec(conf, this); } } } return lzmaCodec; } @Override public CompressionCodec reload(Configuration conf) { synchronized (lock) { lzmaCodec = buildCodec(conf, this); LOG.warn("Reloaded configuration for {}", name()); return lzmaCodec; } } }; private final Configuration conf; private final String compressName; private final String confKey; private final String confDefault; /** data input buffer size to absorb small reads from application. */ private static final int DATA_IBUF_SIZE = 1 * 1024; /** data output buffer size to absorb small writes from application. */ private static final int DATA_OBUF_SIZE = 4 * 1024; Algorithm(String name, String confKey, String confDefault) { this.conf = HBaseConfiguration.create(); this.conf.setBoolean("io.native.lib.available", true); this.compressName = name; this.confKey = confKey; this.confDefault = confDefault; } abstract CompressionCodec getCodec(Configuration conf); /** * Reload configuration for the given algorithm. * <p> * NOTE: Experts only. This can only be done safely during process startup, before * the algorithm's codecs are in use. If the codec implementation is changed, the * new implementation may not be fully compatible with what was loaded at static * initialization time, leading to potential data corruption. * Mostly used by unit tests. * @param conf configuration */ public abstract CompressionCodec reload(Configuration conf); public InputStream createDecompressionStream( InputStream downStream, Decompressor decompressor, int downStreamBufferSize) throws IOException { CompressionCodec codec = getCodec(conf); // Set the internal buffer size to read from down stream. if (downStreamBufferSize > 0) { ((Configurable)codec).getConf().setInt("io.file.buffer.size", downStreamBufferSize); } CompressionInputStream cis = codec.createInputStream(downStream, decompressor); BufferedInputStream bis2 = new BufferedInputStream(cis, DATA_IBUF_SIZE); return bis2; } public OutputStream createCompressionStream( OutputStream downStream, Compressor compressor, int downStreamBufferSize) throws IOException { OutputStream bos1 = null; if (downStreamBufferSize > 0) { bos1 = new BufferedOutputStream(downStream, downStreamBufferSize); } else { bos1 = downStream; } CompressionOutputStream cos = createPlainCompressionStream(bos1, compressor); BufferedOutputStream bos2 = new BufferedOutputStream(new FinishOnFlushCompressionStream(cos), DATA_OBUF_SIZE); return bos2; } /** * Creates a compression stream without any additional wrapping into * buffering streams. */ public CompressionOutputStream createPlainCompressionStream( OutputStream downStream, Compressor compressor) throws IOException { CompressionCodec codec = getCodec(conf); ((Configurable)codec).getConf().setInt("io.file.buffer.size", 32 * 1024); return codec.createOutputStream(downStream, compressor); } public Compressor getCompressor() { CompressionCodec codec = getCodec(conf); if (codec != null) { Compressor compressor = CodecPool.getCompressor(codec); if (LOG.isTraceEnabled()) LOG.trace("Retrieved compressor " + compressor + " from pool."); if (compressor != null) { if (compressor.finished()) { // Somebody returns the compressor to CodecPool but is still using it. LOG.warn("Compressor obtained from CodecPool is already finished()"); } compressor.reset(); } return compressor; } return null; } public void returnCompressor(Compressor compressor) { if (compressor != null) { if (LOG.isTraceEnabled()) LOG.trace("Returning compressor " + compressor + " to pool."); CodecPool.returnCompressor(compressor); } } public Decompressor getDecompressor() { CompressionCodec codec = getCodec(conf); if (codec != null) { Decompressor decompressor = CodecPool.getDecompressor(codec); if (LOG.isTraceEnabled()) LOG.trace("Retrieved decompressor " + decompressor + " from pool."); if (decompressor != null) { if (decompressor.finished()) { // Somebody returns the decompressor to CodecPool but is still using it. LOG.warn("Decompressor {} obtained from CodecPool is already finished", decompressor); } decompressor.reset(); } return decompressor; } return null; } public void returnDecompressor(Decompressor decompressor) { if (decompressor != null) { if (LOG.isTraceEnabled()) LOG.trace("Returning decompressor " + decompressor + " to pool."); CodecPool.returnDecompressor(decompressor); if (decompressor.getClass().isAnnotationPresent(DoNotPool.class)) { if (LOG.isTraceEnabled()) LOG.trace("Ending decompressor " + decompressor); decompressor.end(); } } } public String getName() { return compressName; } } public static Algorithm getCompressionAlgorithmByName(String compressName) { Algorithm[] algos = Algorithm.class.getEnumConstants(); for (Algorithm a : algos) { if (a.getName().equals(compressName)) { return a; } } throw new IllegalArgumentException("Unsupported compression algorithm name: " + compressName); } /** * Get names of supported compression algorithms. * * @return Array of strings, each represents a supported compression * algorithm. Currently, the following compression algorithms are supported. */ public static String[] getSupportedAlgorithms() { Algorithm[] algos = Algorithm.class.getEnumConstants(); String[] ret = new String[algos.length]; int i = 0; for (Algorithm a : algos) { ret[i++] = a.getName(); } return ret; } /** * Load a codec implementation for an algorithm using the supplied configuration. * @param conf the configuration to use * @param algo the algorithm to implement */ private static CompressionCodec buildCodec(final Configuration conf, final Algorithm algo) { try { String codecClassName = conf.get(algo.confKey, algo.confDefault); if (codecClassName == null) { throw new RuntimeException("No codec configured for " + algo.confKey); } Class<?> codecClass = getClassLoaderForCodec().loadClass(codecClassName); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, new Configuration(conf)); LOG.info("Loaded codec {} for compression algorithm {}", codec.getClass().getCanonicalName(), algo.name()); return codec; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); java.util.Map<String, CompressionCodec> implMap = new java.util.HashMap<>(); for (Algorithm algo: Algorithm.class.getEnumConstants()) { try { implMap.put(algo.name(), algo.getCodec(conf)); } catch (Exception e) { // Ignore failures to load codec native implementations while building the report. // We are to report what is configured. } } for (Algorithm algo: Algorithm.class.getEnumConstants()) { System.out.println(algo.name() + ":"); System.out.println(" name: " + algo.getName()); System.out.println(" confKey: " + algo.confKey); System.out.println(" confDefault: " + algo.confDefault); CompressionCodec codec = implMap.get(algo.name()); System.out.println(" implClass: " + (codec != null ? codec.getClass().getCanonicalName() : "<none>")); } } }
7,599
344
<filename>src/utils/TimeUtils.hpp #ifndef CHATOPERA_UTILS_TIME_FUNCTS_H #define CHATOPERA_UTILS_TIME_FUNCTS_H #include <cstdio> #include <ctime> #include <string> /** * 获得当前时间 * 符合MySQL Timestamp */ inline std::string GetCurrentTimestampFormatted() { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo); std::puts(buffer); std::string now(buffer); return now; } #endif
225
1,602
/* * Copyright © 2009 CNRS * Copyright © 2009-2017 Inria. All rights reserved. * Copyright © 2009, 2011 <NAME> * Copyright © 2011 Cisco Systems, Inc. All rights reserved. * See COPYING in top-level directory. */ /* The configuration file */ #ifndef HWLOC_DEBUG_H #define HWLOC_DEBUG_H #include <private/autogen/config.h> #ifdef HWLOC_DEBUG #include <stdarg.h> #include <stdio.h> #endif #ifdef HWLOC_DEBUG static __hwloc_inline int hwloc_debug_enabled(void) { static int checked = 0; static int enabled = 1; if (!checked) { const char *env = getenv("HWLOC_DEBUG_VERBOSE"); if (env) enabled = atoi(env); if (enabled) fprintf(stderr, "hwloc verbose debug enabled, may be disabled with HWLOC_DEBUG_VERBOSE=0 in the environment.\n"); checked = 1; } return enabled; } #endif #if HWLOC_HAVE_ATTRIBUTE_FORMAT /* FIXME: use __hwloc_attribute_format from private/private.h but that header cannot be used in plugins */ static __hwloc_inline void hwloc_debug(const char *s __hwloc_attribute_unused, ...) __attribute__ ((__format__ (__printf__, 1, 2))); #endif static __hwloc_inline void hwloc_debug(const char *s __hwloc_attribute_unused, ...) { #ifdef HWLOC_DEBUG if (hwloc_debug_enabled()) { va_list ap; va_start(ap, s); vfprintf(stderr, s, ap); va_end(ap); } #endif } #ifdef HWLOC_DEBUG #define hwloc_debug_bitmap(fmt, bitmap) do { \ if (hwloc_debug_enabled()) { \ char *s; \ hwloc_bitmap_asprintf(&s, bitmap); \ fprintf(stderr, fmt, s); \ free(s); \ } } while (0) #define hwloc_debug_1arg_bitmap(fmt, arg1, bitmap) do { \ if (hwloc_debug_enabled()) { \ char *s; \ hwloc_bitmap_asprintf(&s, bitmap); \ fprintf(stderr, fmt, arg1, s); \ free(s); \ } } while (0) #define hwloc_debug_2args_bitmap(fmt, arg1, arg2, bitmap) do { \ if (hwloc_debug_enabled()) { \ char *s; \ hwloc_bitmap_asprintf(&s, bitmap); \ fprintf(stderr, fmt, arg1, arg2, s); \ free(s); \ } } while (0) #else #define hwloc_debug_bitmap(s, bitmap) do { } while(0) #define hwloc_debug_1arg_bitmap(s, arg1, bitmap) do { } while(0) #define hwloc_debug_2args_bitmap(s, arg1, arg2, bitmap) do { } while(0) #endif #endif /* HWLOC_DEBUG_H */
897
327
package de.fhpotsdam.unfolding.examples.marker.cluster; import processing.core.PApplet; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.marker.Marker; import de.fhpotsdam.unfolding.marker.MarkerManager; import de.fhpotsdam.unfolding.marker.SimplePointMarker; import de.fhpotsdam.unfolding.utils.MapUtils; /** * Shows different set of markers depending on the zoom level. * * <p> * Zoom in twice to see the detail markers. * </p> * * This is one way of handling this, via different MarkerManager. You could also simply switch visibility of the markers * and use only the default MarkerManager. Which to prefer depends on your use case, and your markers. */ public class ZoomDependentMarkerClusterApp extends PApplet { UnfoldingMap map; MarkerManager<Marker> markerManager; MarkerManager<Marker> detailsMarkerManager; float oldZoomLevel = 0; public void settings() { size(800, 600, P2D); } public void setup() { map = new UnfoldingMap(this); map.zoomAndPanTo(5, new Location(41.50, -72.38)); MapUtils.createDefaultEventDispatcher(this, map); markerManager = populateMarkerManager(); detailsMarkerManager = populateDetailsMarkerManager(); map.addMarkerManager(markerManager); map.addMarkerManager(detailsMarkerManager); } public void draw() { background(0); float zoomLevel = map.getZoomLevel(); if (oldZoomLevel != zoomLevel) { if (zoomLevel >= 7) { markerManager.disableDrawing(); detailsMarkerManager.enableDrawing(); } else { markerManager.enableDrawing(); detailsMarkerManager.disableDrawing(); } oldZoomLevel = zoomLevel; } map.draw(); } private MarkerManager<Marker> populateMarkerManager() { MarkerManager<Marker> markerManager = new MarkerManager<Marker>(); SimplePointMarker nycMarker = new SimplePointMarker(new Location(40.71, -73.99)); nycMarker.setDiameter(20); markerManager.addMarker(nycMarker); SimplePointMarker bostonMarker = new SimplePointMarker(new Location(42.35, -71.04)); bostonMarker.setDiameter(20); markerManager.addMarker(bostonMarker); return markerManager; } private MarkerManager<Marker> populateDetailsMarkerManager() { MarkerManager<Marker> markerManager = new MarkerManager<Marker>(); Marker nycMarker1 = new SimplePointMarker(new Location(40.763, -73.979)); markerManager.addMarker(nycMarker1); Marker nycMarker2 = new SimplePointMarker(new Location(40.852, -73.882)); markerManager.addMarker(nycMarker2); Marker nycMarker3 = new SimplePointMarker(new Location(40.656, -73.944)); markerManager.addMarker(nycMarker3); Marker nycMarker4 = new SimplePointMarker(new Location(40.739, -73.802)); markerManager.addMarker(nycMarker4); Marker bostonMarker1 = new SimplePointMarker(new Location(42.3603, -71.060)); markerManager.addMarker(bostonMarker1); Marker bostonMarker2 = new SimplePointMarker(new Location(42.3689, -71.097)); markerManager.addMarker(bostonMarker2); return markerManager; } public static void main(String args[]) { PApplet.main(new String[] { ZoomDependentMarkerClusterApp.class.getName() }); } }
1,144
778
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Importing the Kratos Library import KratosMultiphysics # Importing the base class from KratosMultiphysics.ParticleMechanicsApplication.mpm_implicit_dynamic_solver import MPMImplicitDynamicSolver def CreateSolver(model, custom_settings): return MPMQuasiStaticSolver(model, custom_settings) class MPMQuasiStaticSolver(MPMImplicitDynamicSolver): def __init__(self, model, custom_settings): # Set defaults and validate custom settings in the base class. # Construct the base solver. super(MPMQuasiStaticSolver, self).__init__(model, custom_settings) KratosMultiphysics.Logger.PrintInfo("::[MPMQuasiStaticSolver]:: ", "Construction is finished.") ### Protected functions ### def _IsDynamic(self): return False
297
3,393
<filename>deps/str-starts-with/package.json<gh_stars>1000+ { "name": "str-starts-with", "version": "0.0.3", "repo": "stephenmathieson/str-starts-with.c", "description": "Check if a string starts with another string", "keywords": [ "string" ], "license": "MIT", "src": [ "src/str-starts-with.c", "src/str-starts-with.h" ] }
150
642
<gh_stars>100-1000 package com.jeesuite.zuul.model; import java.util.List; public class GrantPermParam { private Integer roleId; private List<PermissionItem> items; public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public List<PermissionItem> getItems() { return items; } public void setItems(List<PermissionItem> items) { this.items = items; } }
163
348
{"nom":"Massals","circ":"1ère circonscription","dpt":"Tarn","inscrits":121,"abs":42,"votants":79,"blancs":8,"nuls":9,"exp":62,"res":[{"nuance":"DVD","nom":"M. <NAME>","voix":49},{"nuance":"FN","nom":"M. <NAME>","voix":13}]}
90
310
{ "name": "Comics (iOS)", "description": "A comic viewer and store app.", "url": "https://itunes.apple.com/us/app/comics/id303491945" }
54
777
<filename>third_party/WebKit/Source/platform/network/NetworkUtils.cpp // Copyright 2016 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 "platform/network/NetworkUtils.h" #include "components/mime_util/mime_util.h" #include "net/base/data_url.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/base/url_util.h" #include "net/http/http_response_headers.h" #include "platform/SharedBuffer.h" #include "platform/weborigin/KURL.h" #include "public/platform/URLConversion.h" #include "public/platform/WebString.h" #include "url/gurl.h" #include "wtf/text/StringUTF8Adaptor.h" #include "wtf/text/WTFString.h" namespace { net::registry_controlled_domains::PrivateRegistryFilter getNetPrivateRegistryFilter(blink::NetworkUtils::PrivateRegistryFilter filter) { switch (filter) { case blink::NetworkUtils::IncludePrivateRegistries: return net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES; case blink::NetworkUtils::ExcludePrivateRegistries: return net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES; } // There are only two NetworkUtils::PrivateRegistryFilter enum entries, so // we should never reach this point. However, we must have a default return // value to avoid a compiler error. NOTREACHED(); return net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES; } } // namespace namespace blink { namespace NetworkUtils { bool isReservedIPAddress(const String& host) { net::IPAddress address; StringUTF8Adaptor utf8(host); if (!net::ParseURLHostnameToAddress(utf8.asStringPiece(), &address)) return false; return address.IsReserved(); } bool isLocalHostname(const String& host, bool* isLocal6) { StringUTF8Adaptor utf8(host); return net::IsLocalHostname(utf8.asStringPiece(), isLocal6); } String getDomainAndRegistry(const String& host, PrivateRegistryFilter filter) { StringUTF8Adaptor hostUtf8(host); std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( hostUtf8.asStringPiece(), getNetPrivateRegistryFilter(filter)); return String(domain.data(), domain.length()); } PassRefPtr<SharedBuffer> parseDataURL(const KURL& url, AtomicString& mimetype, AtomicString& charset) { std::string utf8MimeType; std::string utf8Charset; std::string data; if (net::DataURL::Parse(WebStringToGURL(url.getString()), &utf8MimeType, &utf8Charset, &data) && mime_util::IsSupportedMimeType(utf8MimeType)) { mimetype = WebString::fromUTF8(utf8MimeType); charset = WebString::fromUTF8(utf8Charset); return SharedBuffer::create(data.data(), data.size()); } return nullptr; } bool isRedirectResponseCode(int responseCode) { return net::HttpResponseHeaders::IsRedirectResponseCode(responseCode); } } // NetworkUtils } // namespace blink
1,132
2,270
/* ============================================================================== This file is part of the JUCE examples. Copyright (c) 2020 - Raw Material Software Limited The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ /******************************************************************************* The block below describes the properties of this PIP. A PIP is a short snippet of code that can be read by the Projucer and used to generate a JUCE project. BEGIN_JUCE_PIP_METADATA name: WindowsDemo version: 1.0.0 vendor: JUCE website: http://juce.com description: Displays various types of windows. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics, juce_gui_basics, juce_gui_extra exporters: xcode_mac, vs2019, linux_make, androidstudio, xcode_iphone moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1 type: Component mainClass: WindowsDemo useLocalCopy: 1 END_JUCE_PIP_METADATA *******************************************************************************/ #pragma once #include "../Assets/DemoUtilities.h" //============================================================================== /** Just a simple window that deletes itself when closed. */ class BasicWindow : public DocumentWindow { public: BasicWindow (const String& name, Colour backgroundColour, int buttonsNeeded) : DocumentWindow (name, backgroundColour, buttonsNeeded) {} void closeButtonPressed() { delete this; } private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BasicWindow) }; //============================================================================== /** This window contains a ColourSelector which can be used to change the window's colour. */ class ColourSelectorWindow : public DocumentWindow, private ChangeListener { public: ColourSelectorWindow (const String& name, Colour backgroundColour, int buttonsNeeded) : DocumentWindow (name, backgroundColour, buttonsNeeded) { selector.setCurrentColour (backgroundColour); selector.setColour (ColourSelector::backgroundColourId, Colours::transparentWhite); selector.addChangeListener (this); setContentOwned (&selector, false); } ~ColourSelectorWindow() { selector.removeChangeListener (this); } void closeButtonPressed() { delete this; } private: ColourSelector selector { ColourSelector::showColourAtTop | ColourSelector::showSliders | ColourSelector::showColourspace }; void changeListenerCallback (ChangeBroadcaster* source) { if (source == &selector) setBackgroundColour (selector.getCurrentColour()); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelectorWindow) }; //============================================================================== class BouncingBallComponent : public Component, public Timer { public: BouncingBallComponent() { setInterceptsMouseClicks (false, false); Random random; auto size = 10.0f + (float) random.nextInt (30); ballBounds.setBounds (random.nextFloat() * 100.0f, random.nextFloat() * 100.0f, size, size); direction.x = random.nextFloat() * 8.0f - 4.0f; direction.y = random.nextFloat() * 8.0f - 4.0f; colour = Colour ((juce::uint32) random.nextInt()) .withAlpha (0.5f) .withBrightness (0.7f); startTimer (60); } void paint (Graphics& g) override { g.setColour (colour); g.fillEllipse (ballBounds - getPosition().toFloat()); } void timerCallback() override { ballBounds += direction; if (ballBounds.getX() < 0) direction.x = std::abs (direction.x); if (ballBounds.getY() < 0) direction.y = std::abs (direction.y); if (ballBounds.getRight() > (float) getParentWidth()) direction.x = -std::abs (direction.x); if (ballBounds.getBottom() > (float) getParentHeight()) direction.y = -std::abs (direction.y); setBounds (ballBounds.getSmallestIntegerContainer()); } private: Colour colour; Rectangle<float> ballBounds; Point<float> direction; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BouncingBallComponent) }; //============================================================================== class BouncingBallsContainer : public Component { public: BouncingBallsContainer (int numBalls) { for (int i = 0; i < numBalls; ++i) { auto* newBall = new BouncingBallComponent(); balls.add (newBall); addAndMakeVisible (newBall); } } void mouseDown (const MouseEvent& e) override { dragger.startDraggingComponent (this, e); } void mouseDrag (const MouseEvent& e) override { // as there's no titlebar we have to manage the dragging ourselves dragger.dragComponent (this, e, nullptr); } void paint (Graphics& g) override { if (isOpaque()) g.fillAll (Colours::white); else g.fillAll (Colours::blue.withAlpha (0.2f)); g.setFont (16.0f); g.setColour (Colours::black); g.drawFittedText ("This window has no titlebar and a transparent background.", getLocalBounds().reduced (8, 0), Justification::centred, 5); g.drawRect (getLocalBounds()); } private: ComponentDragger dragger; OwnedArray<BouncingBallComponent> balls; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BouncingBallsContainer) }; //============================================================================== class WindowsDemo : public Component { public: enum Windows { dialog, document, alert, numWindows }; WindowsDemo() { setOpaque (true); addAndMakeVisible (showWindowsButton); showWindowsButton.onClick = [this] { showAllWindows(); }; addAndMakeVisible (closeWindowsButton); closeWindowsButton.onClick = [this] { closeAllWindows(); }; setSize (250, 250); } ~WindowsDemo() override { if (dialogWindow != nullptr) { dialogWindow->exitModalState (0); // we are shutting down: can't wait for the message manager // to eventually delete this delete dialogWindow; } closeAllWindows(); } void paint (Graphics& g) override { g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground, Colours::grey)); } void resized() override { Rectangle<int> buttonSize (0, 0, 108, 28); Rectangle<int> area ((getWidth() / 2) - (buttonSize.getWidth() / 2), (getHeight() / 2) - buttonSize.getHeight(), buttonSize.getWidth(), buttonSize.getHeight()); showWindowsButton .setBounds (area.reduced (2)); closeWindowsButton.setBounds (area.translated (0, buttonSize.getHeight()).reduced (2)); } private: // Because in this demo the windows delete themselves, we'll use the // Component::SafePointer class to point to them, which automatically becomes // null when the component that it points to is deleted. Array<Component::SafePointer<Component>> windows; SafePointer<DialogWindow> dialogWindow; TextButton showWindowsButton { "Show Windows" }, closeWindowsButton { "Close Windows" }; void showAllWindows() { closeAllWindows(); showDocumentWindow (false); showDocumentWindow (true); showTransparentWindow(); showDialogWindow(); } void closeAllWindows() { for (auto& window : windows) window.deleteAndZero(); windows.clear(); } void showDialogWindow() { String m; m << "Dialog Windows can be used to quickly show a component, usually blocking mouse input to other windows." << newLine << newLine << "They can also be quickly closed with the escape key, try it now."; DialogWindow::LaunchOptions options; auto* label = new Label(); label->setText (m, dontSendNotification); label->setColour (Label::textColourId, Colours::whitesmoke); options.content.setOwned (label); Rectangle<int> area (0, 0, 300, 200); options.content->setSize (area.getWidth(), area.getHeight()); options.dialogTitle = "Dialog Window"; options.dialogBackgroundColour = Colour (0xff0e345a); options.escapeKeyTriggersCloseButton = true; options.useNativeTitleBar = false; options.resizable = true; dialogWindow = options.launchAsync(); if (dialogWindow != nullptr) dialogWindow->centreWithSize (300, 200); } void showDocumentWindow (bool native) { auto* dw = new ColourSelectorWindow ("Document Window", getRandomBrightColour(), DocumentWindow::allButtons); windows.add (dw); Rectangle<int> area (0, 0, 300, 400); RectanglePlacement placement ((native ? RectanglePlacement::xLeft : RectanglePlacement::xRight) | RectanglePlacement::yTop | RectanglePlacement::doNotResize); auto result = placement.appliedTo (area, Desktop::getInstance().getDisplays() .getPrimaryDisplay()->userArea.reduced (20)); dw->setBounds (result); dw->setResizable (true, ! native); dw->setUsingNativeTitleBar (native); dw->setVisible (true); } void showTransparentWindow() { auto* balls = new BouncingBallsContainer (3); balls->addToDesktop (ComponentPeer::windowIsTemporary); windows.add (balls); Rectangle<int> area (0, 0, 200, 200); RectanglePlacement placement (RectanglePlacement::xLeft | RectanglePlacement::yBottom | RectanglePlacement::doNotResize); auto result = placement.appliedTo (area, Desktop::getInstance().getDisplays() .getPrimaryDisplay()->userArea.reduced (20)); balls->setBounds (result); balls->setVisible (true); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsDemo) };
5,226
317
<reponame>philippQubit/hbase-indexer /* * Copyright 2013 NGDATA nv * * 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.ngdata.hbaseindexer.parse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.solr.common.SolrInputDocument; import org.junit.Test; public class SolrInputDocumentBuilderTest { @Test public void testAdd() { SolrInputDocumentBuilder builder = new SolrInputDocumentBuilder(); SolrInputDocument docA = new SolrInputDocument(); SolrInputDocument docB = new SolrInputDocument(); docA.addField("fieldA", "valueA1"); docA.addField("fieldA", "valueA2"); docB.addField("fieldB", "valueB"); builder.add(docA); builder.add(docB); SolrInputDocument merged = builder.getDocument(); assertEquals(Sets.newHashSet("fieldA", "fieldB"), merged.keySet()); assertEquals(Lists.newArrayList("valueA1", "valueA2"), merged.getField("fieldA").getValues()); assertEquals(Lists.newArrayList("valueB"), merged.getField("fieldB").getValues()); } @Test public void testAdd_WithBaseDocument() { SolrInputDocument baseDocument = new SolrInputDocument(); baseDocument.addField("baseField", "baseValue"); SolrInputDocumentBuilder builder = new SolrInputDocumentBuilder(baseDocument); SolrInputDocument additionalDocument = new SolrInputDocument(); additionalDocument.addField("additionalField", "additionalValue"); builder.add(additionalDocument); SolrInputDocument merged = builder.getDocument(); assertSame(merged, baseDocument); assertEquals(Sets.newHashSet("baseField", "additionalField"), merged.keySet()); } @Test public void testAdd_WithPrefix() { SolrInputDocumentBuilder builder = new SolrInputDocumentBuilder(); SolrInputDocument docA = new SolrInputDocument(); SolrInputDocument docB = new SolrInputDocument(); docA.addField("fieldA", "valueA"); docB.addField("fieldB", "valueB"); builder.add(docA, "A_"); builder.add(docB); SolrInputDocument merged = builder.getDocument(); assertEquals(Sets.newHashSet("A_fieldA", "fieldB"), merged.keySet()); assertEquals(Lists.newArrayList("valueA"), merged.getField("A_fieldA").getValues()); assertEquals(Lists.newArrayList("valueB"), merged.getField("fieldB").getValues()); } @Test public void testAdd_OverlappingFields() { SolrInputDocumentBuilder builder = new SolrInputDocumentBuilder(); SolrInputDocument docA = new SolrInputDocument(); SolrInputDocument docB = new SolrInputDocument(); docA.addField("field", "A1", 0.5f); docA.addField("field", "A2", 0.5f); docB.addField("field", "B1", 1.5f); docB.addField("field", "B2", 1.5f); builder.add(docA); builder.add(docB); SolrInputDocument merged = builder.getDocument(); assertEquals(Sets.newHashSet("field"), merged.keySet()); assertEquals(Lists.newArrayList("A1", "A2", "B1", "B2"), merged.get("field").getValues()); // The boost of the first-added definition of a field is the definitive version assertEquals(0.5f * 0.5f * 1.5f * 1.5f, merged.getField("field").getBoost(), 0f); } }
1,679
852
<filename>CondFormats/HcalObjects/interface/HcalInterpolatedPulse.h #ifndef CondFormats_HcalObjects_HcalInterpolatedPulse_h_ #define CondFormats_HcalObjects_HcalInterpolatedPulse_h_ #include "CondFormats/HcalObjects/interface/InterpolatedPulse.h" // Use some number which is sufficient to simulate at least 13 // 25 ns time slices with 0.25 ns step (need to get at least // 3 ts ahead of the 10 time slices digitized) typedef InterpolatedPulse<1500U> HcalInterpolatedPulse; #endif // CondFormats_HcalObjects_HcalInterpolatedPulse_h_
185
1,338
/* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #include "PropertyEditorView.h" #include <stdio.h> #include "Property.h" #include "PropertyItemView.h" // constructor PropertyEditorView::PropertyEditorView() : BView(BRect(0.0, 0.0, 10.0, 10.0), "property item", B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE), fParent(NULL), fSelected(false) { } // destructor PropertyEditorView::~PropertyEditorView() { } // Draw void PropertyEditorView::Draw(BRect updateRect) { // just draw background FillRect(Bounds(), B_SOLID_LOW); } // MouseDown void PropertyEditorView::MouseDown(BPoint where) { if (fParent) { // forward click fParent->MouseDown(ConvertToParent(where)); } } // MouseUp void PropertyEditorView::MouseUp(BPoint where) { if (fParent) { // forward click fParent->MouseUp(ConvertToParent(where)); } } // MouseMoved void PropertyEditorView::MouseMoved(BPoint where, uint32 transit, const BMessage* dragMessage) { if (fParent) { // forward click fParent->MouseMoved(ConvertToParent(where), transit, dragMessage); } } // PreferredHeight float PropertyEditorView::PreferredHeight() const { font_height fh; GetFontHeight(&fh); float height = floorf(4.0 + fh.ascent + fh.descent); return height; } // SetSelected void PropertyEditorView::SetSelected(bool selected) { fSelected = selected; } // SetItemView void PropertyEditorView::SetItemView(PropertyItemView* parent) { fParent = parent; if (fParent) { BFont font; fParent->GetFont(&font); SetFont(&font); SetLowColor(fParent->LowColor()); } } // ValueChanged void PropertyEditorView::ValueChanged() { if (fParent) fParent->UpdateObject(); }
664