Best Python code snippet using behave
BUILD
Source:BUILD
1# Copyright 2019 The MediaPipe Authors.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http:@mediapipe//www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14load(15 "@mediapipe//mediapipe/framework/tool:mediapipe_graph.bzl",16 "mediapipe_simple_subgraph",17)18licenses(["notice"])19package(default_visibility = ["//visibility:public"])20mediapipe_simple_subgraph(21 name = "hand_detection_cpu",22 graph = "hand_detection_cpu.pbtxt",23 register_as = "HandDetectionSubgraph",24 deps = [25 "@mediapipe//mediapipe/calculators/image:image_properties_calculator",26 "@mediapipe//mediapipe/calculators/image:image_transformation_calculator",27 "@mediapipe//mediapipe/calculators/tflite:ssd_anchors_calculator",28 "@mediapipe//mediapipe/calculators/tflite:tflite_converter_calculator",29 "@mediapipe//mediapipe/calculators/tflite:tflite_custom_op_resolver_calculator",30 "@mediapipe//mediapipe/calculators/tflite:tflite_inference_calculator",31 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_detections_calculator",32 "@mediapipe//mediapipe/calculators/util:detection_label_id_to_text_calculator",33 "@mediapipe//mediapipe/calculators/util:detection_letterbox_removal_calculator",34 "@mediapipe//mediapipe/calculators/util:detections_to_rects_calculator",35 "@mediapipe//mediapipe/calculators/util:detections_to_render_data_calculator",36 "@mediapipe//mediapipe/calculators/util:non_max_suppression_calculator",37 "@mediapipe//mediapipe/calculators/util:rect_transformation_calculator",38 ],39)40mediapipe_simple_subgraph(41 name = "multi_hand_detection_cpu",42 graph = "multi_hand_detection_cpu.pbtxt",43 register_as = "MultiHandDetectionSubgraph",44 deps = [45 "@mediapipe//mediapipe/calculators/core:begin_loop_calculator",46 "@mediapipe//mediapipe/calculators/core:clip_vector_size_calculator",47 "@mediapipe//mediapipe/calculators/core:end_loop_calculator",48 "@mediapipe//mediapipe/calculators/image:image_properties_calculator",49 "@mediapipe//mediapipe/calculators/image:image_transformation_calculator",50 "@mediapipe//mediapipe/calculators/tflite:ssd_anchors_calculator",51 "@mediapipe//mediapipe/calculators/tflite:tflite_converter_calculator",52 "@mediapipe//mediapipe/calculators/tflite:tflite_custom_op_resolver_calculator",53 "@mediapipe//mediapipe/calculators/tflite:tflite_inference_calculator",54 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_detections_calculator",55 "@mediapipe//mediapipe/calculators/util:detection_label_id_to_text_calculator",56 "@mediapipe//mediapipe/calculators/util:detection_letterbox_removal_calculator",57 "@mediapipe//mediapipe/calculators/util:detections_to_rects_calculator",58 "@mediapipe//mediapipe/calculators/util:non_max_suppression_calculator",59 "@mediapipe//mediapipe/calculators/util:rect_transformation_calculator",60 ],61)62mediapipe_simple_subgraph(63 name = "hand_landmark_cpu",64 graph = "hand_landmark_cpu.pbtxt",65 register_as = "HandLandmarkSubgraph",66 deps = [67 "@mediapipe//mediapipe/calculators/core:split_normalized_landmark_list_calculator",68 "@mediapipe//mediapipe/calculators/core:split_vector_calculator",69 "@mediapipe//mediapipe/calculators/image:image_cropping_calculator",70 "@mediapipe//mediapipe/calculators/image:image_properties_calculator",71 "@mediapipe//mediapipe/calculators/image:image_transformation_calculator",72 "@mediapipe//mediapipe/calculators/tflite:tflite_converter_calculator",73 "@mediapipe//mediapipe/calculators/tflite:tflite_custom_op_resolver_calculator",74 "@mediapipe//mediapipe/calculators/tflite:tflite_inference_calculator",75 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_classification_calculator",76 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_floats_calculator",77 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_landmarks_calculator",78 "@mediapipe//mediapipe/calculators/util:detections_to_rects_calculator",79 "@mediapipe//mediapipe/calculators/util:landmark_letterbox_removal_calculator",80 "@mediapipe//mediapipe/calculators/util:landmark_projection_calculator",81 "@mediapipe//mediapipe/calculators/util:landmarks_to_detection_calculator",82 "@mediapipe//mediapipe/calculators/util:landmarks_to_render_data_calculator",83 "@mediapipe//mediapipe/calculators/util:rect_transformation_calculator",84 "@mediapipe//mediapipe/calculators/util:thresholding_calculator",85 "@mediapipe//mediapipe/graphs/hand_tracking/calculators:hand_landmarks_to_rect_calculator",86 ],87)88mediapipe_simple_subgraph(89 name = "multi_hand_landmark_cpu",90 graph = "multi_hand_landmark.pbtxt",91 register_as = "MultiHandLandmarkSubgraph",92 deps = [93 ":hand_landmark_cpu",94 "@mediapipe//mediapipe/calculators/core:begin_loop_calculator",95 "@mediapipe//mediapipe/calculators/core:end_loop_calculator",96 "@mediapipe//mediapipe/calculators/util:filter_collection_calculator",97 ],98)99mediapipe_simple_subgraph(100 name = "renderer_cpu",101 graph = "renderer_cpu.pbtxt",102 register_as = "RendererSubgraph",103 deps = [104 "@mediapipe//mediapipe/calculators/util:annotation_overlay_calculator",105 "@mediapipe//mediapipe/calculators/util:detections_to_render_data_calculator",106 "@mediapipe//mediapipe/calculators/util:labels_to_render_data_calculator",107 "@mediapipe//mediapipe/calculators/util:landmarks_to_render_data_calculator",108 "@mediapipe//mediapipe/calculators/util:rect_to_render_data_calculator",109 ],110)111mediapipe_simple_subgraph(112 name = "multi_hand_renderer_cpu",113 graph = "multi_hand_renderer_cpu.pbtxt",114 register_as = "MultiHandRendererSubgraph",115 deps = [116 "@mediapipe//mediapipe/calculators/core:begin_loop_calculator",117 "@mediapipe//mediapipe/calculators/core:end_loop_calculator",118 "@mediapipe//mediapipe/calculators/util:annotation_overlay_calculator",119 "@mediapipe//mediapipe/calculators/util:detections_to_render_data_calculator",120 "@mediapipe//mediapipe/calculators/util:landmarks_to_render_data_calculator",121 "@mediapipe//mediapipe/calculators/util:rect_to_render_data_calculator",122 ],123)124mediapipe_simple_subgraph(125 name = "hand_detection_gpu",126 graph = "hand_detection_gpu.pbtxt",127 register_as = "HandDetectionSubgraph",128 deps = [129 "@mediapipe//mediapipe/calculators/image:image_properties_calculator",130 "@mediapipe//mediapipe/calculators/image:image_transformation_calculator",131 "@mediapipe//mediapipe/calculators/tflite:ssd_anchors_calculator",132 "@mediapipe//mediapipe/calculators/tflite:tflite_converter_calculator",133 "@mediapipe//mediapipe/calculators/tflite:tflite_custom_op_resolver_calculator",134 "@mediapipe//mediapipe/calculators/tflite:tflite_inference_calculator",135 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_detections_calculator",136 "@mediapipe//mediapipe/calculators/util:detection_label_id_to_text_calculator",137 "@mediapipe//mediapipe/calculators/util:detection_letterbox_removal_calculator",138 "@mediapipe//mediapipe/calculators/util:detections_to_rects_calculator",139 "@mediapipe//mediapipe/calculators/util:non_max_suppression_calculator",140 "@mediapipe//mediapipe/calculators/util:rect_transformation_calculator",141 ],142)143mediapipe_simple_subgraph(144 name = "multi_hand_detection_gpu",145 graph = "multi_hand_detection_gpu.pbtxt",146 register_as = "MultiHandDetectionSubgraph",147 deps = [148 "@mediapipe//mediapipe/calculators/core:begin_loop_calculator",149 "@mediapipe//mediapipe/calculators/core:clip_vector_size_calculator",150 "@mediapipe//mediapipe/calculators/core:end_loop_calculator",151 "@mediapipe//mediapipe/calculators/image:image_properties_calculator",152 "@mediapipe//mediapipe/calculators/image:image_transformation_calculator",153 "@mediapipe//mediapipe/calculators/tflite:ssd_anchors_calculator",154 "@mediapipe//mediapipe/calculators/tflite:tflite_converter_calculator",155 "@mediapipe//mediapipe/calculators/tflite:tflite_custom_op_resolver_calculator",156 "@mediapipe//mediapipe/calculators/tflite:tflite_inference_calculator",157 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_detections_calculator",158 "@mediapipe//mediapipe/calculators/util:detection_label_id_to_text_calculator",159 "@mediapipe//mediapipe/calculators/util:detection_letterbox_removal_calculator",160 "@mediapipe//mediapipe/calculators/util:detections_to_rects_calculator",161 "@mediapipe//mediapipe/calculators/util:non_max_suppression_calculator",162 "@mediapipe//mediapipe/calculators/util:rect_transformation_calculator",163 ],164)165mediapipe_simple_subgraph(166 name = "hand_landmark_gpu",167 graph = "hand_landmark_gpu.pbtxt",168 register_as = "HandLandmarkSubgraph",169 deps = [170 "@mediapipe//mediapipe/calculators/core:split_normalized_landmark_list_calculator",171 "@mediapipe//mediapipe/calculators/core:split_vector_calculator",172 "@mediapipe//mediapipe/calculators/image:image_cropping_calculator",173 "@mediapipe//mediapipe/calculators/image:image_properties_calculator",174 "@mediapipe//mediapipe/calculators/image:image_transformation_calculator",175 "@mediapipe//mediapipe/calculators/tflite:tflite_converter_calculator",176 "@mediapipe//mediapipe/calculators/tflite:tflite_custom_op_resolver_calculator",177 "@mediapipe//mediapipe/calculators/tflite:tflite_inference_calculator",178 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_classification_calculator",179 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_floats_calculator",180 "@mediapipe//mediapipe/calculators/tflite:tflite_tensors_to_landmarks_calculator",181 "@mediapipe//mediapipe/calculators/util:detections_to_rects_calculator",182 "@mediapipe//mediapipe/calculators/util:landmark_letterbox_removal_calculator",183 "@mediapipe//mediapipe/calculators/util:landmark_projection_calculator",184 "@mediapipe//mediapipe/calculators/util:landmarks_to_detection_calculator",185 "@mediapipe//mediapipe/calculators/util:rect_transformation_calculator",186 "@mediapipe//mediapipe/calculators/util:thresholding_calculator",187 "@mediapipe//mediapipe/graphs/hand_tracking/calculators:hand_landmarks_to_rect_calculator",188 ],189)190mediapipe_simple_subgraph(191 name = "multi_hand_landmark_gpu",192 graph = "multi_hand_landmark.pbtxt",193 register_as = "MultiHandLandmarkSubgraph",194 deps = [195 ":hand_landmark_gpu",196 "@mediapipe//mediapipe/calculators/core:begin_loop_calculator",197 "@mediapipe//mediapipe/calculators/core:end_loop_calculator",198 "@mediapipe//mediapipe/calculators/util:filter_collection_calculator",199 ],200)201mediapipe_simple_subgraph(202 name = "renderer_gpu",203 graph = "renderer_gpu.pbtxt",204 register_as = "RendererSubgraph",205 deps = [206 "@mediapipe//mediapipe/calculators/util:annotation_overlay_calculator",207 "@mediapipe//mediapipe/calculators/util:detections_to_render_data_calculator",208 "@mediapipe//mediapipe/calculators/util:labels_to_render_data_calculator",209 "@mediapipe//mediapipe/calculators/util:landmarks_to_render_data_calculator",210 "@mediapipe//mediapipe/calculators/util:rect_to_render_data_calculator",211 ],212)213mediapipe_simple_subgraph(214 name = "multi_hand_renderer_gpu",215 graph = "multi_hand_renderer_gpu.pbtxt",216 register_as = "MultiHandRendererSubgraph",217 deps = [218 "@mediapipe//mediapipe/calculators/core:begin_loop_calculator",219 "@mediapipe//mediapipe/calculators/core:end_loop_calculator",220 "@mediapipe//mediapipe/calculators/util:annotation_overlay_calculator",221 "@mediapipe//mediapipe/calculators/util:detections_to_render_data_calculator",222 "@mediapipe//mediapipe/calculators/util:landmarks_to_render_data_calculator",223 "@mediapipe//mediapipe/calculators/util:rect_to_render_data_calculator",224 ],...
container.py
Source:container.py
1import abc2import copy3import inspect4import threading5from . import rel6from . import scope7from typing import Dict, Tuple, List8class DependencyResolutionError(Exception):9 pass10class _ComponentRegistration(metaclass=abc.ABCMeta):11 def __init__(self, component_scope):12 self.component_scope = component_scope13 @abc.abstractmethod14 def _create(self, component_context, overriding_args):15 """16 Creates a new instance of the component using the given container17 to resolve dependencies regardless of the scope.18 :param component_context: The context to resolve dependencies from.19 :param overriding_args: Overriding arguments to use (by name) instead of resolving them.20 :return: An instance of the component.21 """22 pass23 def create(self, component_context, overriding_args):24 """25 Creates a new instance of the component, respecting the scope.26 :param component_context: The context to resolve dependencies from.27 :param overriding_args: Overriding arguments to use (by name) instead of resolving them.28 :return: An instance of the component.29 """30 return self.component_scope.instance(lambda: self._create(component_context, overriding_args))31class _ConstructorRegistration(_ComponentRegistration):32 """33 Creates a component via the constructor.34 """35 def __init__(self, class_type, component_scope):36 super().__init__(component_scope)37 self.class_type = class_type38 # map of argument name -> argument type39 self.argument_types = {}40 self._inspect_constructor()41 def _find_constructor(self):42 """43 Finds the constructor from the class_type.44 :return: The constructor function.45 """46 def isconstructor(object):47 return inspect.isfunction(object) and object.__name__ == '__init__'48 # find all the dependencies from the constructor49 constructors = inspect.getmembers(self.class_type, predicate=isconstructor)50 if constructors:51 name, func = constructors[0]52 return func53 # No explicit __init__54 return None55 def _inspect_constructor(self):56 constructor = self._find_constructor()57 if constructor is not None:58 self.argument_types = constructor.__annotations__59 def _create(self, component_context, overriding_args):60 argument_map = overriding_args or {}61 for (arg_name, arg_type) in self.argument_types.items():62 # not already provided, try resolve the argument63 if arg_name not in argument_map:64 argument_map[arg_name] = component_context.resolve(arg_type)65 return self.class_type(**argument_map)66class _CallbackRegistration(_ComponentRegistration):67 def __init__(self, callback, component_scope):68 super().__init__(component_scope)69 self._callback = callback70 def _create(self, component_context, overriding_args):71 return self._callback(component_context)72class _InstanceRegistration(_ComponentRegistration):73 def __init__(self, instance):74 # the scope doesn't matter, but SingleInstance is what it'll always be75 super().__init__(scope.SingleInstance())76 self._instance = instance77 def _create(self, component_context, overriding_args):78 return self._instance79 def __deepcopy__(self, memo):80 # We don't want to have this copy self._instance when building the container from a builder81 return self82class _ComponentContext(object):83 """84 The context of a component resolve operation.85 A context will be created from a top-level resolve, and then all dependencies will be resolved within that context.86 """87 def __init__(self, container):88 self._container = container89 def resolve(self, component_type, **kwargs):90 # TODO: split off _container, even though we're an internal class. Still isn't great.91 if isinstance(component_type, rel.Relationship):92 # expand the relationship93 # note that relationships get the container as they're all currently lazy94 # this *could* support the context in future, but the context shouldn't be stored95 return component_type.resolve(self._container)96 # Se for descrito como uma lista97 _GenericAlias = type(List)98 if isinstance(component_type, _GenericAlias): #issubclass(component_type, List):99 for component in self._container.registry_map:100 #print(List[component])101 if component_type is List[component]:102 registration = self._container.registry_map[component]103 result = list()104 for register in registration:105 result.append(register.create(self, kwargs))106 return result107 108 # normal component109 elif component_type not in self._container.registry_map:110 raise DependencyResolutionError(111 "The requested type %s was not found in the container. Is it registered?" % component_type.__name__)112 # Independente de várias dependencias serem registradas, caso o argumento não seja uma lista113 # Retorna só a ultima dependencia registrada114 registration = self._container.registry_map[component_type]115 return registration[-1].create(self, kwargs)116class Container(object):117 """118 IoC container.119 """120 def __init__(self, registry_map):121 """122 Creates a new container123 :param registry_map: A map of type -> ComponentRegistration124 """125 self.registry_map = registry_map126 # The resolve lock is recursive as a constructor may call a factory (which calls container.resolve()),127 # without a recursive lock, this would be a deadlock128 self._resolve_lock = threading.RLock()129 def resolve(self, component_type, **kwargs):130 """131 Resolves an instance of the component type.132 :param component_type: The type of the component (e.g. a class).133 :param kwargs: Overriding arguments to use (by name) instead of resolving them.134 :return: An instance of the component.135 """136 with self._resolve_lock:137 context = _ComponentContext(self)138 return context.resolve(component_type, **kwargs)139class Module(metaclass=abc.ABCMeta):140 """141 Module to help structure building of the container.142 """143 @abc.abstractmethod144 def load(self, builder):145 """146 Register dependencies from this module.147 :param builder: The container builder to register components to.148 """149 pass150class ContainerBuilder(object):151 """152 Builds a container from the registered configuration.153 """154 def __init__(self):155 self.registry = {}156 def _register(self, class_type, registration, register_as):157 if register_as is None:158 register_as = class_type159 # if we didn't get a tuple or a list, put it in a lists160 if type(register_as) is not list and type(register_as) is not tuple:161 register_as = [register_as]162 for available_as in register_as:163 if available_as not in self.registry:164 self.registry[available_as] = list()165 #print(register_as)166 self.registry[available_as].append(registration)167 def register_class(self, class_type, component_scope=scope.InstancePerDependency, register_as=None):168 """169 Registers the given class for creation via its constructor.170 :param class_type: The class type.171 :param component_scope: The scope of the component, defaults to instance per dependency.172 :param register_as: The types to register the class as, defaults to the given class_type.173 """174 registration = _ConstructorRegistration(class_type, component_scope())175 self._register(class_type, registration, register_as)176 def register_callback(self, class_type, callback, component_scope=scope.InstancePerDependency, register_as=None):177 """178 Registers the given class for creation via the given callback.179 :param class_type: The class type.180 :param callback: The function to call to create/get an instance, of the form fn(component_context)181 :param component_scope: The scope of the component, defaults to instance per dependency.182 :param register_as: The types to register the class as, defaults to the given class_type.183 """184 registration = _CallbackRegistration(callback, component_scope())185 self._register(class_type, registration, register_as)186 def register_instance(self, class_type, instance, register_as=None):187 """188 Registers the given instance (already created).189 :param class_type: The class type.190 :param instance: The instance to register.191 :param register_as: The types to register the class as, defaults to the given class_type.192 """193 registration = _InstanceRegistration(instance)194 self._register(class_type, registration, register_as)195 def register_module(self, module):196 """197 Registers the module instance.198 :param module: The module to register.199 """200 module.load(self)201 def build(self):202 """203 Builds a new container using the registered components.204 :return: A container205 """206 # copy the registry so built containers are isolated207 registry_copy = copy.deepcopy(self.registry)...
parameters.py
Source:parameters.py
1# -*- coding: utf-8 -*-2"""Parameters."""3__all__ = [4 # functions5 "solar_system_vesc_params",6 "vesc_sun_at_R",7]8##############################################################################9# IMPORTS10# BUILT-IN11import typing as T12# THIRD PARTY13from astropy.utils.state import ScienceState14from astropy import units as u15import numpy as np16##############################################################################17# PARAMETERS18_KMS = u.km / u.s19_ref_B = (20 "Explanatory Supplement to the Astronomical Almanac. "21 "1992. K. P. Seidelmann, Ed., p.706 (Table 15.8) and p.316 "22 "(Table 5.8.1), University Science Books, Mill Valley, California."23)24_ref_C = (25 "Seidelmann, P.K. et al. 2007. 'Report of the IAU/IAG Working "26 "Group on cartographic coordinates and rotational elements: 2006' "27 "Celestial Mech. Dyn. Astr. 98:155-180."28)29_ref_D = (30 "Archinal, B.A. et al. 2018. 'Report of the IAU/IAG Working Group "31 "on cartographic coordinates and rotational elements: 2015' "32 "Celestial Mech. Dyn. Astr. 130:22."33)34##############################################################################35# CODE36##############################################################################37class solar_system_vesc_params(ScienceState):38 """Solar System Parameters."""39 _latest_value = "default"40 _references = None41 _value = None42 _registry = {43 "DEFAULT": {44 "params": {45 "Sun": 617.5 * _KMS,46 "Mercury": 4.25 * _KMS,47 "Venus": 10.36 * _KMS,48 "Earth": 11.19 * _KMS,49 "Mars": 5.03 * _KMS,50 "Jupiter": 60.20 * _KMS,51 "Saturn": 36.09 * _KMS,52 "Uranus": 21.38 * _KMS,53 "Neptune": 23.56 * _KMS,54 "Pluto": 1.21 * _KMS,55 },56 "references": {57 "_source": "https://ssd.jpl.nasa.gov/?planet_phys_par",58 "Sun": (_ref_B, _ref_C, _ref_D),59 "Mercury": (_ref_B, _ref_C, _ref_D),60 "Venus": (_ref_B, _ref_C, _ref_D),61 "Earth": (_ref_B, _ref_C, _ref_D),62 "Mars": (_ref_B, _ref_C, _ref_D),63 "Jupiter": (_ref_B, _ref_C, _ref_D),64 "Saturn": (_ref_B, _ref_C, _ref_D),65 "Uranus": (_ref_B, _ref_C, _ref_D),66 "Neptune": (_ref_B, _ref_C, _ref_D),67 "Pluto": (_ref_B, _ref_C, _ref_D),68 },69 }70 }71 @classmethod72 def get_solar_params_from_string(cls, arg):73 """Get parameters from registry."""74 # Resolve the meaning of 'latest'75 if arg == "latest":76 arg = cls._latest_value77 if arg.lower() == "default":78 info = cls._registry["DEFAULT"]79 elif arg in cls._registry:80 info = cls._registry[arg]81 else:82 raise ValueError(83 f"Invalid string input to retrieve solar "84 f'parameters for Galactocentric frame: "{arg}"'85 )86 return info["params"], info["references"]87 # /def88 @classmethod89 def validate(cls, value):90 """Validate `value`, from string or dict."""91 if value is None:92 value = cls._latest_value93 if isinstance(value, str):94 params, refs = cls.get_solar_params_from_string(value)95 cls._references = refs96 return params97 elif isinstance(value, dict):98 return value99 else:100 raise ValueError(101 "Invalid input to retrieve solar parameters."102 "Input must be a string, or dict"103 )104 # /def105 @classmethod106 def register(cls, name: str, params: dict, references: dict):107 """Register a set of parameters.108 Parameters109 ----------110 name : str111 params : dict112 references : dict113 """114 cls._registry[name] = {"params": params, "references": references}115 # /def116 @classmethod117 def set(118 cls,119 value: dict,120 register_as: T.Optional[str] = None,121 references: T.Optional[dict] = None,122 ):123 """Set (see ScienceState) with optional registering.124 Parameters125 ----------126 value : dict127 register_as : str, optional128 the name of the science state to set129 references : dict, optional130 references for `value`. Only used if `register_as` is str.131 """132 super().set(value)133 if isinstance(register_as, str):134 cls._registry[register_as] = {135 "params": value,136 "references": references or {},137 }138 # /def139# /class140# -------------------------------------------------------------------141vesc_sun_at_earth = 42.1 * _KMS142"""Solar escape velocity, from 1 AU to infinity [1]_.143References144----------145.. [1] https://en.wikipedia.org/wiki/Escape_velocity146"""147# -------------------------------------------------------------------148@u.quantity_input(R="length")149def vesc_sun_at_R(R):150 r"""Escape velocity from the sun, starting at position R.151 The Newtonian escape velocity from a spherical mass distribution,152 starting at a position r_0, is :math:`v_0=\sqrt{2gr_0}`. If this value153 is known at some position r0, than it is known at all R by virtue154 of ratios. We calculate this value for the sun relative to the155 known value at the earth -- 42.1 km / s.156 Parameters157 ----------158 R : :class:`~astropy.coordinates.Distance` or |Quantity|159 From the sun.160 Returns161 -------162 vesc : |Quantity|163 Same shape as `R`164 .. |Quantity| replace:: :class:`~astropy.units.Quantity`165 """166 ratio = R.to_value(u.AU) # b/c r_earth = 1 AU167 return np.sqrt(ratio) * vesc_sun_at_earth168# /def169##############################################################################...
client_socket.py
Source:client_socket.py
1"""2client_socket.py:3Socket used to attach to the TCP server as a client and read/write data.4"""5import select6import socket7import threading8from fprime.constants import DATA_ENCODING9from fprime_gds.common.handlers import DataHandler10# Constants for public use11GUI_TAG = "GUI"12FSW_TAG = "FSW"13class ThreadedTCPSocketClient(DataHandler):14 """15 Threaded TCP client that connects to the socket server that serves packets from the flight16 software17 """18 def __init__(self, sock=None, dest=FSW_TAG):19 """20 Threaded client socket constructor21 Keyword Arguments:22 sock {Socket} -- A socket for the client to use. Created own if23 None (default: {None})24 """25 if sock is None:26 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)27 else:28 self.sock = sock29 # NOTE can't do this b/c EINPROGRESS: self.sock.setblocking(0)30 self.dest = dest31 self.__distributors = []32 self.__select_timeout = 133 self.__data_recv_thread = threading.Thread(target=self.recv)34 self.stop_event = threading.Event()35 def get_data_bytes(self, string_data):36 """37 Convert the data bytes from string to bytes38 :param string_data: data in string format39 :return: data in bytes format40 """41 return string_data.encode(DATA_ENCODING)42 def get_data_string(self, bytes_data):43 """44 Convert the data bytes from string to bytes45 :param bytes_data: data in bytes format46 :return: data in string format47 """48 return bytes_data.decode(DATA_ENCODING)49 def register_distributor(self, distributor):50 """Registers a fprime.gds.distributor object with this socket51 Arguments:52 fprime.gds.distributor {Distributor} -- Distributor must implement data_callback53 """54 self.__distributors.append(distributor)55 def register_to_server(self, register_as):56 """57 Registers the caller to the server as type register_as58 This function assumes the socket connects to an fprime TCP server59 Args:60 register_as (string): How to identify this process to the TCP server61 Can be either "FSW" or "GUI"62 """63 data = "Register %s\n" % register_as64 self.sock.send(self.get_data_bytes(data))65 def connect(self, host, port):66 """Connect to host at given port and start the threaded recv method.67 Arguments:68 host {string} -- IP of the host server69 port {int} -- Port of the host server70 """71 try:72 self.sock.connect((host, port))73 self.__data_recv_thread.start()74 except OSError:75 print("There was a problem connecting to the TCP Server")76 exit(-1)77 def disconnect(self):78 """Disconnect the socket client from the server and stop the internal thread."""79 self.stop_event.set()80 self.__data_recv_thread.join()81 self.sock.close()82 def data_callback(self, data, sender=None):83 """84 Handles incoming data by sending it to a socket.85 :param data: data to send to the client socket86 :param sender: sender source of the data87 """88 self.send(data, self.dest)89 def send(self, data, dest):90 """91 Send data to the server92 All necessary headers are added in this function.93 Arguments:94 data {binary} -- The data to send (What you want the destination95 to receive)96 dest {String} -- Where to send the data to. Either "FSW" or "GUI"97 """98 self.sock.send(b"A5A5 %s %s" % (self.get_data_bytes(dest), data))99 def recv(self):100 """101 Method run constantly by the enclosing thread. Looks for data from the server.102 """103 while not self.stop_event.is_set():104 ready = select.select([self.sock], [], [], self.__select_timeout)105 if ready[0]:106 chunk = self.sock.recv(1024)107 for d in self.__distributors:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!