code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def create_model(self, model_server_workers=None, role=None, vpc_config_override=VPC_CONFIG_DEFAULT): role = (role or self.role) return ChainerModel(self.model_data, role, self.entry_point, source_dir=self._model_source_dir(), enable_cloudwatch_metrics=self.enable_cloudwatch_metrics, name=self._current_job_name...
Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``. Args: role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during transform jobs. If not specified, the role from the Estimator will be used. model_server_workers (int): Optional. The number of worker...
codesearchnet
def make_decorator(target, decorator_func, decorator_name=None, decorator_doc='', decorator_argspec=None): if decorator_name is None: decorator_name = inspect.currentframe().f_back.f_code.co_name decorator = TFDecorator(decorator_name, target, decorator_doc, decorator_argspec) setattr(decorator_func...
Make a decorator from a wrapper and a target. Args: target: The final callable to be wrapped. decorator_func: The wrapper function. decorator_name: The name of the decorator. If `None`, the name of the function calling make_decorator. decorator_doc: Documentation specific to this application of `decorator_func` to `ta...
github-repos
def adjust_contrast(img, contrast_factor): if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(contrast_factor) return img
Adjust contrast of an Image. Args: img (PIL Image): PIL Image to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: PIL Image: Contrast adjusted image.
juraj-google-style
def debye_temperature(self, structure): v0 = ((structure.volume * 1e-30) / structure.num_sites) (vl, vt) = (self.long_v(structure), self.trans_v(structure)) vm = ((3 ** (1.0 / 3.0)) * (((1 / (vl ** 3)) + (2 / (vt ** 3))) ** ((- 1.0) / 3.0))) td = (((1.05457e-34 / 1.38065e-23) * vm) * (((6 * (np.pi ** 2)...
Estimates the debye temperature from longitudinal and transverse sound velocities Args: structure: pymatgen structure object Returns: debye temperature (in SI units)
codesearchnet
def call_rpc(self, rpc_id, payload=bytes()): if super(ServiceDelegateTile, self).has_rpc(rpc_id): return super(ServiceDelegateTile, self).call_rpc(rpc_id, payload) async def _awaitable_wrapper(): ...
Call an RPC by its ID. Args: rpc_id (int): The number of the RPC payload (bytes): A byte string of payload parameters up to 20 bytes Returns: str: The response payload from the RPC
juraj-google-style
def add_output(self, output): if (not isinstance(output, Output)): raise TypeError('`output` must be an Output instance or None') self.outputs.append(output)
Adds an output to a Transaction's list of outputs. Args: output (:class:`~bigchaindb.common.transaction. Output`): An Output to be added to the Transaction.
codesearchnet
def __init__(self, tcex): self._tcex = tcex self._data = {} self._type = 'Owner' self._api_type = 'owners' self._api_entity = 'owner' self._utils = TcExUtils() self._tc_requests = TiTcRequest(self._tcex)
Initialize Class Properties. Args: tcex:
juraj-google-style
def _xray_clean_up_entries_for_driver(self, driver_id): xray_task_table_prefix = ( ray.gcs_utils.TablePrefix_RAYLET_TASK_string.encode("ascii")) xray_object_table_prefix = ( ray.gcs_utils.TablePrefix_OBJECT_string.encode("ascii")) task_table_objects = self.stat...
Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id.
juraj-google-style
def __init__(self, communication=collective_util.CommunicationImplementation.AUTO, cluster_resolver=None): communication_options = collective_util.Options(implementation=communication) super(_CollectiveAllReduceStrategyExperimental, self).__init__(cluster_resolver, communication_options)
Creates the strategy. Args: communication: optional `tf.distribute.experimental.CommunicationImplementation`. This is a hint on the preferred collective communication implementation. Possible values include `AUTO`, `RING`, and `NCCL`. cluster_resolver: optional `tf.distribute.cluster_resolver.ClusterResolver`. If `Non...
github-repos
def write_data(num_lines, no_data=False, directory=None, prefix=tempfile.template, eol=EOL.LF, custom_delimiter=None, line_value=b'line'): all_data = [] with tempfile.NamedTemporaryFile(delete=False, dir=directory, prefix=prefix) as f: sep_values = [b'\n', b'\r\n'] for i in range(num_lines): ...
Writes test data to a temporary file. Args: num_lines (int): The number of lines to write. no_data (bool): If :data:`True`, empty lines will be written, otherwise each line will contain a concatenation of b'line' and the line number. directory (str): The name of the directory to create the temporary file in. prefix (s...
github-repos
def write_data(msg_type, profile_name, data, cfg): if (profile_name not in cfg.data): cfg.data[profile_name] = {} cfg.data[profile_name][msg_type] = data
Write the settings into the data portion of the cfg. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :cfg: (jsonconfig.Config) config instance.
codesearchnet
def __init__(self, observ_shape, action_shape, min_duration, max_duration): self._observ_shape = observ_shape self._action_shape = action_shape self._min_duration = min_duration self._max_duration = max_duration self._random = np.random.RandomState(0) self.steps = [] self.durations = []
Generate random agent input and keep track of statistics. Args: observ_shape: Shape for the random observations. action_shape: Shape for the action space. min_duration: Minimum number of steps per episode. max_duration: Maximum number of steps per episode. Attributes: steps: List of actual simulated lengths for all e...
juraj-google-style
def set_xlim(self, xlims, dx, xscale, reverse=False): self._set_axis_limits('x', xlims, dx, xscale, reverse) return
Set x limits for plot. This will set the limits for the x axis for the specific plot. Args: xlims (len-2 list of floats): The limits for the axis. dx (float): Amount to increment by between the limits. xscale (str): Scale of the axis. Either `log` or `lin`. reverse (bool, optional): If True, reverse the axis tick mar...
juraj-google-style
def get(self, path, params=None, headers=None): response = requests.get( self._url_for(path), params=params, headers=self._headers(headers) ) self._handle_errors(response) return response
Perform a GET request, optionally providing query-string params. Args: path (str): A path that gets appended to ``base_url``. params (dict, optional): Dictionary of param names to values. Example: api_client.get('/users', params={'active': True}) Returns: A requests ``Response`` object.
juraj-google-style
def __init__(self, log_dir=DEFAULT_RESULTS_DIR, reload_interval=30, standalone=True, log_level="INFO"): self.logger = self.init_logger(log_level) self.standalone = standalone self.collector = Collector( relo...
Initialize the collector service. Args: log_dir (str): Directory of the logs about trials' information. reload_interval (int): Sleep time period after each polling round. standalone (boolean): The service will not stop and if True. log_level (str): Level of logging.
juraj-google-style
def _filter_exception(self, ex): if isinstance(ex, tuple): ex2 = ex[1] else: ex2 = ex if isinstance(ex2, self._clean_stop_exception_types): ex = None return ex
Check if the exception indicated in 'ex' should be ignored. This method examines `ex` to check if it is an exception that should be reported to the users. If yes, it returns `ex` as is, otherwise it returns None. The code returns None for exception types listed in `_clean_stop_exception_types`. Args: ex: None, an `...
github-repos
def moments_of_masked_time_series(time_series_tensor, broadcast_mask): num_unmasked_entries = tf.cast( tf.reduce_sum(input_tensor=tf.cast(~broadcast_mask, tf.int32), axis=-1), time_series_tensor.dtype) mean = (tf.reduce_sum(input_tensor=tf.where( broadcast_mask, tf.zeros_like(time_ser...
Compute mean and variance, accounting for a mask. Args: time_series_tensor: float `Tensor` time series of shape `concat([batch_shape, [num_timesteps]])`. broadcast_mask: bool `Tensor` of the same shape as `time_series`. Returns: mean: float `Tensor` of shape `batch_shape`. variance: float `Tensor` of shape `batch_shap...
juraj-google-style
def _transpile_circuit(circuit_config_tuple): circuit, transpile_config = circuit_config_tuple if transpile_config.pass_manager: pass_manager = transpile_config.pass_manager elif transpile_config.coupling_map: pass_manager = default_pass_manager(transpile_config.basis_gates, ...
Select a PassManager and run a single circuit through it. Args: circuit_config_tuple (tuple): circuit (QuantumCircuit): circuit to transpile transpile_config (TranspileConfig): configuration dictating how to transpile Returns: QuantumCircuit: transpiled circuit
juraj-google-style
def instantiate_resolver(self, name, args): if (name not in self._known_resolvers): raise ArgumentError('Attempting to instantiate unknown dependency resolver', name=name) return self._known_resolvers[name](args)
Directly instantiate a dependency resolver by name with the given arguments Args: name (string): The name of the class that we want to instantiate args (dict): The arguments to pass to the resolver factory Returns: DependencyResolver
codesearchnet
def ParseFileObject(self, parser_mediator, file_object): self._last_charset_attribute = 'ascii' self._ParseHeader(parser_mediator, file_object) data_dict = {} time_dict = {} try: for name, value in self._ParseAttributesGroup(file_object): name = self._ATTRIBUTE_NAME_TRANSLATION...
Parses a CUPS IPP file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
juraj-google-style
def write_to_hdf5(self, filename_out, *args, **kwargs): print("[Filterbank] Warning: Non-standard function to write in HDF5 (.h5) format. Please use Waterfall.") if not HAS_HDF5: raise RuntimeError("h5py package required for HDF5 output.") with h5py.File(filename_out, 'w'...
Write data to HDF5 file. Args: filename_out (str): Name of output file
juraj-google-style
def shifted_centroid_distance(item_a, time_a, item_b, time_b, max_value): ax, ay = item_a.center_of_mass(time_a) bx, by = item_b.center_of_mass(time_b) if time_a < time_b: bx = bx - item_b.u by = by - item_b.v else: ax = ax - item_a.u ay = ay - item_a.v return np...
Centroid distance with motion corrections. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distance value used as scaling value and upper constraint. Returns: D...
juraj-google-style
def insert_paulis(self, indices=None, paulis=None, pauli_labels=None): if (pauli_labels is not None): if (paulis is not None): raise QiskitError('Please only provide either `paulis` or `pauli_labels`') if isinstance(pauli_labels, str): pauli_labels = list(pauli_labels) ...
Insert or append pauli to the targeted indices. If indices is None, it means append at the end. Args: indices (list[int]): the qubit indices to be inserted paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Note: the indices refers to the localio...
codesearchnet
def __init__(self, name, func): self._func = func if name: self._var_scope = None self._name = name else: self._var_scope = tf.get_variable_scope() self._name = None self._reuse = None self._stacktrace = traceback.format_stack()[:-3]
Creates a template for the given function. Args: name: The variable_scope to use, if None the current scope is captured. func: The function to apply each time.
juraj-google-style
def wait_for_capture(self, timeout=None): raise NotImplementedError('Base class should not be called directly!')
This function waits for a capture to terminate and guarantees that the capture is saved to the capture file configured during the start_capture() method. Depending on the type of the sniffer the file may previously contain partial results (e.g. for a local sniffer) or may not exist until the stop_capture() method is ex...
github-repos
def execute(self, sensor_graph, scope_stack): parent = scope_stack[-1] alloc = parent.allocator trigger_stream, trigger_cond = parent.trigger_chain() rpc_const = alloc.allocate_stream(DataStream.ConstantType, attach=True) rpc_val = (self.slot_id.address << 16) | self.r...
Execute this statement on the sensor_graph given the current scope tree. This adds a single node to the sensor graph with the call_rpc function as is processing function. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A stack of nested scopes that may i...
juraj-google-style
def recursive_chmod(path, mode=0755): passwd_reader.set_permissions(path, mode=mode) if os.path.isfile(path): return for root, dirs, files in os.walk(path): for fn in files + dirs: passwd_reader.set_permissions(os.path.join(root, fn), mode=mode)
Recursively change ``mode`` for given ``path``. Same as ``chmod -R mode``. Args: path (str): Path of the directory/file. mode (octal int, default 0755): New mode of the file. Warning: Don't forget to add ``0`` at the beginning of the numbers of `mode`, or `Unspeakable hOrRoRs` will be awaken from their unholy sleep o...
juraj-google-style
def densifying_unary(func): @functools.wraps(func) def sparse_wrapper(x, *args, **kwargs): if isinstance(x, jax_sparse.JAXSparse): x = x.todense() return func(x, *args, **kwargs) return sparse_wrapper
Decorator to add support for `JAXSparse` tensors (including `BCOO`) to a non-zero-preserving element-wise unary operator. There are requirements on the operator for this decorator to work correctly: - The operator must be element-wise - The operator must be unary (one input tensor and one output tensor) - The operato...
github-repos
def _compile_function_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> Tenso...
Compile a function expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL function expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[size]): The batch size. Returns: :obj:`rddl2tf.fl...
juraj-google-style
def _compare_versions(v1, v2): if v1 == 'inf' and v2 == 'inf': raise RuntimeError('Cannot compare `inf` to `inf`.') rtn_dict = {'smaller': None, 'larger': None} v1_list = v1.split('.') v2_list = v2.split('.') if v1_list[0] == 'inf': v1_list[0] = str(int(v2_list[0]) + 1) if v2_lis...
Compare two versions and return information on which is smaller vs. larger. Args: v1: String that is a version to be compared against `v2`. v2: String that is a version to be compared against `v1`. Returns: Dict that stores larger version with key `larger` and smaller version with key `smaller`. e.g. {`larger`: `1.5....
github-repos
def set_extana_led(self, r, g, b, check_state=True): (r, g, b) = map(int, [r, g, b]) if ((min([r, g, b]) < LED_MIN) or (max([r, g, b]) > LED_MAX)): logger.warn('RGB channel values must be {}-{}'.format(LED_MIN, LED_MAX)) return False if (check_state and ((r, g, b) == self.led_state)): ...
Update the colour of the RGB LED on the SK8-ExtAna board. Args: r (int): red channel, 0-255 g (int): green channel, 0-255 b (int): blue channel, 0-255 check_state (bool): if True (default) and the locally cached LED state matches the given (r, g, b) triplet, pysk8 will NOT send any LED update command to the SK8. If yo...
codesearchnet
def __init__(self, lookup_map, fallback=None): super().__init__() if fallback is not None: lookup_map['*'] = fallback self._lookup_map = lookup_map
Create this visitor. You're expected to then pass this instance to node.Visit(). Args: lookup_map: A map from names to symbol tables (i.e., objects that have a "Lookup" function). fallback: A symbol table to be tried if lookup otherwise fails.
github-repos
def is_location(v) -> (bool, str): def convert2float(value): try: float_num = float(value) return float_num except ValueError: return False if not isinstance(v, str): return False, v split_lst = v.spli...
Boolean function for checking if v is a location format Args: v: Returns: bool
juraj-google-style
def _ParseDateTimeValue(self, byte_stream, file_offset): datetime_value_map = self._GetDataTypeMap('cups_ipp_datetime_value') try: value = self._ReadStructureFromByteStream(byte_stream, file_offset, datetime_value_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseEr...
Parses a CUPS IPP RFC2579 date-time value from a byte stream. Args: byte_stream (bytes): byte stream. file_offset (int): offset of the attribute data relative to the start of the file-like object. Returns: dfdatetime.RFC2579DateTime: RFC2579 date-time stored in the value. Raises: ParseError: when the RFC2579 date-ti...
codesearchnet
def return_estimator(self): estimator = self.base_learner_origin.return_estimator() estimator = estimator.set_params(**self.hyperparameters) return estimator
Returns base learner using its origin and the given hyperparameters Returns: est (estimator): Estimator object
codesearchnet
def get_sailthru_client(site_code): config = get_sailthru_configuration(site_code) if not config.get('SAILTHRU_ENABLE'): msg = 'Sailthru is not enabled for site {}'.format(site_code) log.debug(msg) raise SailthruNotEnabled(msg) key = config.get('SAILTHRU_KEY') ...
Returns a Sailthru client for the specified site. Args: site_code (str): Site for which the client should be configured. Returns: SailthruClient Raises: SailthruNotEnabled: If Sailthru is not enabled for the specified site. ConfigurationError: If either the Sailthru API key or secret are not set for the site.
juraj-google-style
async def send_command(self, command, args, validator, timeout=10.0): if (self._con is None): raise ExternalError('No websock connection established') cmd_uuid = str(uuid.uuid4()) msg = dict(type='command', operation=command, uuid=cmd_uuid, payload=args) packed = pack(msg) response_future = ...
Send a command and synchronously wait for a single response. Args: command (string): The command name args (dict): Optional arguments. validator (Verifier): A SchemaVerifier to verify the response payload. timeout (float): The maximum time to wait for a response. Defaults to 10 seconds. Returns: dict: The response pa...
codesearchnet
def create_transfer_learning_tuner(parent, additional_parents=None, estimator=None, sagemaker_session=None): parent_tuner = HyperparameterTuner.attach(tuning_job_name=parent, sagemaker_session=sagemaker_session) return parent_tuner.transfer_learning_tuner(additional_parents=additional_parents, estimator=estimat...
Creates a new ``HyperParameterTuner`` by copying the request fields from the provided parent to the new instance of ``HyperparameterTuner`` followed by addition of warm start configuration with the type as "TransferLearning" and ``parents`` as the union of provided list of ``additional_parents`` and the ``parent``. Ar...
codesearchnet
def _ExtractFileEntry(self, path_spec, destination_path, output_writer, skip_duplicates=True): file_entry = path_spec_resolver.Resolver.OpenFileEntry(path_spec) if (not file_entry): logger.warning('Unable to open file entry for path spec: {0:s}'.format(path_spec.comparable)) return if (not s...
Extracts a file entry. Args: path_spec (dfvfs.PathSpec): path specification of the source file. destination_path (str): path where the extracted files should be stored. output_writer (CLIOutputWriter): output writer. skip_duplicates (Optional[bool]): True if files with duplicate content should be skipped.
codesearchnet
def traverse_pagination(response, endpoint, content_filter_query, query_params): results = response.get('results', []) page = 1 while response.get('next'): page += 1 response = endpoint().post(content_filter_query, **dict(query_params, page=page)) results += response.get('results', [...
Traverse a paginated API response and extracts and concatenates "results" returned by API. Arguments: response (dict): API response object. endpoint (Slumber.Resource): API endpoint object. content_filter_query (dict): query parameters used to filter catalog results. query_params (dict): query parameters used to pagin...
codesearchnet
def _tf_assert_stmt(expression1, expression2): expression2_tensors = expression2() if not isinstance(expression2_tensors, list): expression2_tensors = [expression2_tensors] return control_flow_assert.Assert(expression1, expression2_tensors)
Overload of assert_stmt that stages a TF Assert. This implementation deviates from Python semantics as follows: (1) the assertion is verified regardless of the state of __debug__ (2) on assertion failure, the graph execution will fail with tensorflow.errors.ValueError, rather than AssertionError. Args: expression1: t...
github-repos
def _do_policy_eval(tf_sess, to_eval, policies, active_episodes): eval_results = {} if tf_sess: builder = TFRunBuilder(tf_sess, 'policy_eval') pending_fetches = {} else: builder = None if log_once('compute_actions_input'): logger.info('Inputs to compute_actions():\n\n{}\n...
Call compute actions on observation batches to get next actions. Returns: eval_results: dict of policy to compute_action() outputs.
codesearchnet
def start_upsert(ini_data): stack_driver = CloudStackUtility(ini_data) poll_stack = (not ini_data.get('no_poll', False)) if stack_driver.upsert(): logging.info('stack create/update was started successfully.') if poll_stack: stack_tool = None try: profi...
Helper function to facilitate upsert. Args: ini_date - the dictionary of info to run upsert Exit: 0 - good 1 - bad
codesearchnet
def clean_code(content: str) -> str: splits = content.split('"""') content = ''.join(splits[::2]) splits = content.split("'''") content = ''.join(splits[::2]) lines_to_keep = [] for line in content.split('\n'): line = re.sub(' if len(line) != 0 and (not line.isspace()): ...
Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern comments or docstings). Args: content (`str`): The code to clean Returns: `str`: The cleaned code.
github-repos
def map_fn(fn, elems, name=None, dtype=None): return map_fn_lib.map_fn(fn, elems, name=name, dtype=dtype)
Map the function fn over the elements elems and return the outputs. Args: fn: Callable that will be called upon each element in elems elems: tensor name: A string name for the map node in the graph dtype: Output data type. Returns: Tensor with dtype `dtype`.
github-repos
def normalize_batch_in_training(x, gamma, beta, reduction_axes, epsilon=0.001): if ndim(x) == 4 and list(reduction_axes) in [[0, 1, 2], [0, 2, 3]]: if not _has_nchw_support() and list(reduction_axes) == [0, 2, 3]: return _broadcast_normalize_batch_in_training(x, gamma, beta, reduction_axes, epsi...
Computes mean and std for batch then apply batch_normalization on batch. Args: x: Input tensor or variable. gamma: Tensor by which to scale the input. beta: Tensor with which to center the input. reduction_axes: iterable of integers, axes over which to normalize. epsilon: Fuzz factor. Returns: A tuple length of 3, `(...
github-repos
def _partitioner(shape, dtype): if not isinstance(shape, tensor_shape.TensorShape): raise ValueError(f'shape is not a TensorShape: {shape}') if not shape.is_fully_defined(): raise ValueError(f'shape is not fully defined: {shape}') dtype = dtypes.as_dtype(dtype) if dtype.base_dtype == dty...
Partitioner that partitions shards to have max_shard_bytes total size. Args: shape: A `TensorShape`. dtype: A `DType`. Returns: A tuple representing how much to slice each axis in shape. Raises: ValueError: If shape is not a fully defined `TensorShape` or dtype is not a `DType`.
github-repos
def while_loop_op(op): return control_flow_util.IsLoopSwitch(op) or control_flow_util.IsLoopMerge(op) or control_flow_util.IsLoopEnter(op) or control_flow_util.IsLoopExit(op) or TensorTracer.loop_cond_op(op) or (op.type in ('RefNextIteration', 'NextIteration'))
Returns true if op is one of the special ops of in a while loop. Args: op: A tf.Operation. Returns: True if the given op is one of [Switch, Merge, Enter, Exit, NextIteration, LoopCond], which are all building blocks for TF while loops.
github-repos
def get_subgraph_for_concept_pair( self, source: str, target: str, cutoff: Optional[int] = None ): paths = nx.all_simple_paths(self, source, target, cutoff=cutoff) return AnalysisGraph(self.subgraph(set(chain.from_iterable(paths))))
Get subgraph comprised of simple paths between the source and the target. Args: source target cutoff
juraj-google-style
def get(self, addresses): with self._lock: results = [] for add in addresses: self.validate_read(add) results.append(self._get(add)) return results
Returns the value in this context, or None, for each address in addresses. Useful for gets on the context manager. Args: addresses (list of str): The addresses to return values for, if within this context. Returns: results (list of bytes): The values in state for these addresses.
codesearchnet
def fit_transform_table(self, table, table_meta, transformer_dict=None, transformer_list=None, missing=None): if (missing is None): missing = self.missing else: self.missing = missing warnings.warn(DEPRECATION_MESSAGE.format('fit_transform_table'), DeprecationWarning) result = pd.Dat...
Create, apply and store the specified transformers for `table`. Args: table(pandas.DataFrame): Contents of the table to be transformed. table_meta(dict): Metadata for the given table. transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple in the keys represent the (table_name, column_na...
codesearchnet
def check_filepath(self, path, filename): settings_path = os.path.join(path, filename) if not os.path.exists(settings_path) or \ not os.path.isfile(settings_path): msg = "Unable to find settings file: {}" raise SettingsBackendError(msg.format(settings_path)) ...
Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions.SettingsBackendError: If determined filepath does not exists or is a directory. Returns: string: Settings file p...
juraj-google-style
def getParameter(self, name): return lock_and_call((lambda : Parameter(self._impl.getParameter(name))), self._lock)
Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist.
codesearchnet
def predict_image(img, model_func): orig_shape = img.shape[:2] resizer = CustomResize(cfg.PREPROC.TEST_SHORT_EDGE_SIZE, cfg.PREPROC.MAX_SIZE) resized_img = resizer.augment(img) scale = np.sqrt(resized_img.shape[0] * 1.0 / img.shape[0] * resized_img.shape[1] / img.shape[1]) boxes, probs, labels...
Run detection on one image, using the TF callable. This function should handle the preprocessing internally. Args: img: an image model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) Returns: [DetectionResult]
juraj-google-style
def std(x, axis=None, keepdims=False): if any_symbolic_tensors((x,)): return Std(axis=axis, keepdims=keepdims).symbolic_call(x) return backend.numpy.std(x, axis=axis, keepdims=keepdims)
Compute the standard deviation along the specified axis. Args: x: Input tensor. axis: Axis along which to compute standard deviation. Default is to compute the standard deviation of the flattened tensor. keepdims: If this is set to `True`, the axes which are reduced are left in the result as dimensions with size one. ...
github-repos
def affine_transform(self, image: np.array, center: Tuple[float], scale: Tuple[float], rotation: float, size: Dict[str, int], data_format: Optional[ChannelDimension]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.array: data_format = input_data_format if data_format is None else data_fo...
Apply an affine transformation to an image. Args: image (`np.array`): Image to transform. center (`Tuple[float]`): Center of the bounding box (x, y). scale (`Tuple[float]`): Scale of the bounding box with respect to height/width. rotation (`float`): Rotation angle in degrees. size (`Dict[str, int]`): Size of the desti...
github-repos
def received(self, messages): if messages: if self._queue: self._queue.put_nowait(messages) if self._callback: self._callback(messages)
Called when new messages arrive. Args: messages (tuple): Messages
codesearchnet
def __init__(self, channel, pin): self._channel = None self._pin = None self._open(channel, pin)
Instantiate a PWM object and open the sysfs PWM corresponding to the specified channel and pin. Args: channel (int): Linux channel number. pin (int): Linux pin number. Returns: PWM: PWM object. Raises: PWMError: if an I/O or OS error occurs. TypeError: if `channel` or `pin` types are invalid. ValueError: if PWM chan...
juraj-google-style
def make_innermost_setter(setter): @functools.wraps(setter) def _new_setter(kernel_results, *args, **kwargs): results_stack = [] while hasattr(kernel_results, 'inner_results'): results_stack.append(kernel_results) kernel_results = kernel_results.inner_results new_kernel_results = s...
Wraps a setter so it applies to the inner-most results in `kernel_results`. The wrapped setter unwraps `kernel_results` and applies `setter` to the first results without an `inner_results` attribute. Args: setter: A callable that takes the kernel results as well as some `*args` and `**kwargs` and returns a modified c...
juraj-google-style
def _CreateShapePointFolder(self, shapes_folder, shape): folder_name = (shape.shape_id + ' Shape Points') folder = self._CreateFolder(shapes_folder, folder_name, visible=False) for (index, (lat, lon, dist)) in enumerate(shape.points): placemark = self._CreatePlacemark(folder, str((index + 1))) ...
Create a KML Folder containing all the shape points in a shape. The folder contains placemarks for each shapepoint. Args: shapes_folder: A KML Shape Folder ElementTree.Element instance shape: The shape to plot. Returns: The Folder ElementTree.Element instance or None.
codesearchnet
def plot_brillouin_zone(bz_lattice, lines=None, labels=None, kpoints=None, fold=False, coords_are_cartesian=False, ax=None, **kwargs): (fig, ax) = plot_lattice_vectors(bz_lattice, ax=ax) plot_wigner_seitz(bz_lattice, ax=ax) if (lines is not None): for line in lines: plot_path(line, bz_la...
Plots a 3D representation of the Brillouin zone of the structure. Can add to the plot paths, labels and kpoints Args: bz_lattice: Lattice object of the Brillouin zone lines: list of lists of coordinates. Each list represent a different path labels: dict containing the label as a key and the coordinates as value. kpoin...
codesearchnet
def is_user_in_group(self, user, group): search_url = ('%s/%s/%s/%s/%s' % (self.url, 'group', group, 'user', user)) response = self.jss.get(search_url) length = len(response) result = False if (length == 1): pass elif (length == 2): if (response.findtext('ldap_user/username') == ...
Test for whether a user is in a group. There is also the ability in the API to test for whether multiple users are members of an LDAP group, but you should just call is_user_in_group over an enumerated list of users. Args: user: String username. group: String group name. Returns bool.
codesearchnet
def as_bytes(bytes_or_text, encoding='utf-8'): encoding = codecs.lookup(encoding).name if isinstance(bytes_or_text, bytearray): return bytes(bytes_or_text) elif isinstance(bytes_or_text, str): return bytes_or_text.encode(encoding) elif isinstance(bytes_or_text, bytes): return byt...
Converts `bytearray`, `bytes`, or unicode python input types to `bytes`. Uses utf-8 encoding for text by default. Args: bytes_or_text: A `bytearray`, `bytes`, `str`, or `unicode` object. encoding: A string indicating the charset for encoding unicode. Returns: A `bytes` object. Raises: TypeError: If `bytes_or_text` ...
github-repos
def resize_image(image, tuple_wh, preserve_aspect=True): if preserve_aspect: img_cpy = image.copy() img_cpy.thumbnail(tuple_wh) return img_cpy else: return image.resize(tuple_wh)
Resizes an instance of a PIL Image. In order to prevent un-intended side effects, this function always returns a copy of the image, as the resize function from PIL returns a copy but the thumbnail function does not. Args: image: An instance of a PIL Image. tuple_wh: A tuple containing the (width, height) for resizing...
codesearchnet
def _get_nn_shell_info(self, structure, all_nn_info, site_idx, shell, _previous_steps=frozenset(), _cur_image=(0, 0, 0)): if (shell <= 0): raise ValueError('Shell must be positive') _previous_steps = _previous_steps.union({(site_idx, _cur_image)}) possible_steps = list(all_nn_info[site_idx]) for...
Private method for computing the neighbor shell information Args: structure (Structure) - Structure being assessed all_nn_info ([[dict]]) - Results from `get_all_nn_info` site_idx (int) - index of site for which to determine neighbor information. shell (int) - Which neighbor shell to retrieve (1 == 1st NN shell) _prev...
codesearchnet
def constant(name, shape, value=0, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): shape = (shape if isinstance(shape, (tuple, list)) else [shape]) x = tf.get_variable(name, shape, dtype=dtype, initializer=tf.constant_initializer(value), regularizer=regularizer, trainable=trainable) if ...
r"""Creates a tensor variable of which initial values are `value` and shape is `shape`. Args: name: The name of new variable. shape: A tuple/list of integers or an integer. If shape is an integer, it is converted to a list. value: A Python scalar. All elements of the initialized variable will be set to this value. Def...
codesearchnet
def get_package_install_path(self, path): from rez.package_repository import package_repository_manager pkg_repo = package_repository_manager.get_repository(path) return pkg_repo.get_package_payload_path( package_name=self.package.name, package_version=self.pac...
Return the installation path for a package (where its payload goes). Args: path (str): Package repository path.
juraj-google-style
def memory_read32(self, addr, num_words, zone=None): return self.memory_read(addr, num_words, zone=zone, nbits=32)
Reads memory from the target system in units of 32-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_words (int): number of words to read zone (str): memory zone to read from Returns: List of words read from the target system. Raises: JLinkException: if memory could not be r...
juraj-google-style
def send_update(url_id, dataset): data = _convert_to_seeder_format(dataset) if (not data): return try: _send_request(url_id, json=data, req_type=requests.patch) except Exception as e: sys.stderr.write('Seeder PATCH error: ') sys.stderr.write(str(e.message)) return...
Send request to Seeder's API with data changed by user. Args: url_id (str): ID used as identification in Seeder. dataset (dict): WA-KAT dataset sent from frontend.
codesearchnet
def add_tags(self, ID3=None): if (ID3 is None): ID3 = self.ID3 if (self.tags is None): self.ID3 = ID3 self.tags = ID3() else: raise error('an ID3 tag already exists')
Add an empty ID3 tag to the file. Args: ID3 (ID3): An ID3 subclass to use or `None` to use the one that used when loading. A custom tag reader may be used in instead of the default `ID3` object, e.g. an `mutagen.easyid3.EasyID3` reader.
codesearchnet
def self_adjoint_eigvals(tensor, name=None): e, _ = gen_linalg_ops.self_adjoint_eig_v2(tensor, compute_v=False, name=name) return e
Computes the eigenvalues of one or more self-adjoint matrices. Note: If your program backpropagates through this function, you should replace it with a call to tf.linalg.eigh (possibly ignoring the second output) to avoid computing the eigen decomposition twice. This is because the eigenvectors are used to compute the...
github-repos
def _benchmarkFetch(self, name, target, size, iters): times = [] with ops.Graph().as_default(): v = variables.Variable(random_ops.random_normal([size])) with session.Session(target) as sess: sess.run(v.initializer) sess.run(v) for _ in range(iters): ...
Runs a microbenchmark to measure the cost of fetching a tensor. Reports the median cost of fetching a tensor of `size` * `sizeof(float)` bytes. Args: name: A human-readable name for logging the output. target: The session target to use for the benchmark. size: The number of floating-point numbers to be fetched. iters...
github-repos
def update_configuration(self, did, wid, eid, payload): req_headers = {'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json'} res = self._api.request('post', (((((('/api/partstudios/d/' + did) + '/w/') + wid) + '/e/') + eid) + '/configuration'), body=payload, headers=req_headers) r...
Update the configuration specified in the payload Args: - did (str): Document ID - eid (str): Element ID - payload (json): the request body Returns: - configuration (str): the url-ready configuration string.
codesearchnet
def patch(make_pool=_default_make_pool): setattr(httplib2, '_HttpOriginal', httplib2.Http) httplib2.Http = Http Http._make_pool = make_pool
Monkey-patches httplib2.Http to be httplib2shim.Http. This effectively makes all clients of httplib2 use urlilb3. It's preferable to specify httplib2shim.Http explicitly where you can, but this can be useful in situations where you do not control the construction of the http object. Args: make_pool: A function that r...
codesearchnet
def __init__(self, namespace: str, prefix: str=''): if prefix: prefix = f'{prefix}_' self._inference_counter = beam.metrics.Metrics.counter(namespace, prefix + 'num_inferences') self.failed_batches_counter = beam.metrics.Metrics.counter(namespace, prefix + 'failed_batches_counter') self._inferen...
Args: namespace: Namespace for the metrics. prefix: Unique identifier for metrics, used when models are updated using side input.
github-repos
def csv(self, ondemand=False): self._request_uri = '{}/{}'.format(self._api_uri, 'csv') self._stream = True if ondemand: self._request.add_payload('runNow', True)
Update request URI to return CSV data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation.
juraj-google-style
def _build_ring_scatter(pred_by_s_d, rank_by_s_d, chunks_by_dev): num_devices = len(chunks_by_dev) num_chunks = len(chunks_by_dev[0]) if 0 != num_chunks % num_devices: raise ValueError('Expect number of chunks per device to be divisible by num_devices') num_subchunks = int(num_chunks / num_devic...
Construct subgraph for second (scatter) pass of ring all-reduce. Args: pred_by_s_d: as produced by _ring_permutations rank_by_s_d: as produced by _ring_permutations chunks_by_dev: list of list of `tf.Tensor` indexed by ints (device, chunk) Raises: ValueError: chunks_by_dev is not well-formed Returns: list of `tf.Ten...
github-repos
def dump_in_memory_result(self, result, output_path): file_count = 0 logger.debug("Dumping in-memory processing results to output folder: %s", output_path) for k, v in iteritems(result): cur_output_path = os.path.join(output_path, k) if isinstance(v, dict): ...
Recursively dumps the result of our processing into files within the given output path. Args: result: The in-memory result of our processing. output_path: Full path to the folder into which to dump the files. Returns: The number of files generated (integer).
juraj-google-style
def from_string(input_str) -> 'MissionTime': match = RE_INPUT_STRING.match(input_str) if not match: raise ValueError(f'badly formatted date/time: {input_str}') return MissionTime( datetime.datetime( int(match.group('year')), ...
Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: input_str: string to parse Returns: MissionTime instance
juraj-google-style
class MaxLengthCriteria(StoppingCriteria): def __init__(self, max_length: int, max_position_embeddings: Optional[int]=None): self.max_length = max_length self.max_position_embeddings = max_position_embeddings @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING) def __call__(self, inpu...
This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens. Args: max_length (`int`): The maximum length that the output sequence can have in number of tokens. max_positio...
github-repos
def get_course_track_selection_url(course_run, query_parameters): try: course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']}) except KeyError: LOGGER.exception('KeyError while parsing course run data.\nCourse Run: \n[%s]', course_run) raise url = '{}{}'...
Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Raises: (KeyError): Raised when course run dict does not have 'key' key. Returns: (str): C...
codesearchnet
def create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): if (isinstance(input_order, str) and (input_order not in ('random', 'left-to-right', 'right-to-left'))): raise ValueError('Input order is not valid.') if (hidden_order not in ('random', 'left-to-right'...
Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output units always have the same degree as their associated input unit. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It doe...
codesearchnet
def __init__(self, config_block): if config_block: self._config = config_block else: logging.error('config block was garbage') raise SystemError
Cloud stack utility init method. Args: config_block - a dictionary creates from the CLI driver. See that script for the things that are required and optional. Returns: not a damn thing Raises: SystemError - if everything isn't just right
juraj-google-style
def get_service_details(self, service_id: str) -> dict: if (not self._manager): raise RuntimeError('Only the Swarm manager node can retrieve all the services details.') service = self._client.services.get(service_id) return service.attrs
Get details of a service. Only the manager nodes can retrieve service details Args: service_id (string): List of service id Returns: dict, details of the service
codesearchnet
def __call__(self, name, value): if not isinstance(value, self.base_type): raise ValueError("%s must be %s, not %s" % (name, self.base_type, value.__class__))
Call method. Args: name (str): the value's name. value (object): the value to check. Raises: ValueError: if value is not type base_type.
juraj-google-style
def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor: out = F.dropout(x, p=prob, training=training) out = residual + out return out
Dropout add function Args: x (`torch.tensor`): input tensor residual (`torch.tensor`): residual tensor prob (`float`): dropout probability training (`bool`): training mode
github-repos
def lease(queue_name, owner, count=1, timeout_seconds=60): now = datetime.datetime.utcnow() query = WorkQueue.query.filter_by(queue_name=queue_name, status=WorkQueue.LIVE).filter((WorkQueue.eta <= now)).order_by(WorkQueue.eta).with_lockmode('update').limit(count) task_list = query.all() if (not task_lis...
Leases a work item from a queue, usually the oldest task available. Args: queue_name: Name of the queue to lease work from. owner: Who or what is leasing the task. count: Lease up to this many tasks. Return value will never have more than this many items present. timeout_seconds: Number of seconds to lock the task for...
codesearchnet
def get_by_name(self, name): scopes = self._client.get_all() result = [x for x in scopes if (x['name'] == name)] return (result[0] if result else None)
Gets a Scope by name. Args: name: Name of the Scope Returns: dict: Scope.
codesearchnet
def _run_static_range_qat(src_saved_model_path: str, dst_saved_model_path: str, quant_opts: _QuantizationOptions, signature_def_map: _SignatureDefMap) -> None: logging.info('Running static-range quantization for QAT model.') pywrap_quantize_model.quantize_qat_model(src_saved_model_path, dst_saved_model_path, qu...
Runs static-range quantization for a Quantization-Aware Trained model. Runs the quantization for a model trained using QAT. Args: src_saved_model_path: Path to the source SavedModel directory. dst_saved_model_path: Path to the destination SavedModel directory. quant_opts: Quantization options. signature_def_map: Sign...
github-repos
def replace_batch_norm(model): for name, module in model.named_children(): if isinstance(module, nn.BatchNorm2d): new_module = RTDetrV2FrozenBatchNorm2d(module.num_features) if not module.weight.device == torch.device('meta'): new_module.weight.data.copy_(module.weigh...
Recursively replace all `torch.nn.BatchNorm2d` with `RTDetrV2FrozenBatchNorm2d`. Args: model (torch.nn.Module): input model
github-repos
def segment_ids_to_row_splits(segment_ids, num_segments=None, out_type=None, name=None): from tensorflow.python.ops import bincount_ops if out_type is None: if isinstance(segment_ids, tensor.Tensor): out_type = segment_ids.dtype elif isinstance(num_segments, tensor.Tensor): ...
Generates the RaggedTensor `row_splits` corresponding to a segmentation. Returns an integer vector `splits`, where `splits[0] = 0` and `splits[i] = splits[i-1] + count(segment_ids==i)`. Example: >>> print(tf.ragged.segment_ids_to_row_splits([0, 0, 0, 2, 2, 3, 4, 4, 4])) tf.Tensor([0 3 3 5 6 9], shape=(6,), dtype=int...
github-repos
def get_book_links(links): book_links = [] for link in links: data = DOWNER.download(link + "1") dom = dhtmlparser.parseString(data) book_links.extend(_parse_book_links(dom)) max_page = _get_max_page(dom) if max_page == 1: continue for i in ra...
Go thru `links` to categories and return list to all publications in all given categories. Args: links (list): List of strings (absolute links to categories). Returns: list: List of strings / absolute links to book details.
juraj-google-style
def download_kegg_gene_metadata(gene_id, outdir=None, force_rerun=False): if (not outdir): outdir = '' outfile = op.join(outdir, '{}.kegg'.format(custom_slugify(gene_id))) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): raw_text = bs_kegg.get('{}'.format(gene_id)) if (...
Download the KEGG flatfile for a KEGG ID and return the path. Args: gene_id: KEGG gene ID (with organism code), i.e. "eco:1244" outdir: optional output directory of metadata Returns: Path to metadata file
codesearchnet
def Serialize(self, writer): super(StorageItem, self).Serialize(writer) writer.WriteVarBytes(self.Value)
Serialize full object. Args: writer (neo.IO.BinaryWriter):
juraj-google-style
def update_state(self, y_true, y_pred, sample_weight=None): return metrics_utils.update_confusion_matrix_variables({metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives}, y_true, y_pred, thresholds=self.thresholds, thresholds_distribu...
Accumulates true positive and false negative statistics. Args: y_true: The ground truth values, with the same dimensions as `y_pred`. Will be cast to `bool`. y_pred: The predicted values. Each element must be in the range `[0, 1]`. sample_weight: Optional weighting of each example. Defaults to 1. Can be a `Tensor` who...
github-repos
def __init__(self, apps): try: apps = list(apps.items()) except AttributeError: pass def by_path_len(app): return len(app[0]) apps.sort(key=by_path_len, reverse=True) self.apps = [(p.rstrip('/'), a) for p, ...
Initialize path info WSGI app dispatcher. Args: apps (dict[str,object]|list[tuple[str,object]]): URI prefix and WSGI app pairs
juraj-google-style
def _FormatIPToken(self, token_data): data = ''.join(['{0:02x}'.format(byte) for byte in token_data.data]) return {'IPv4_Header': data}
Formats an IPv4 packet header token as a dictionary of values. Args: token_data (bsm_token_data_ip): AUT_IP token data. Returns: dict[str, str]: token values.
juraj-google-style
def compare_jsone_task_definition(parent_link, rebuilt_definitions): diffs = [] for compare_definition in rebuilt_definitions['tasks']: if 'taskId' in compare_definition: del(compare_definition['taskId']) compare_definition = remove_empty_keys(compare_...
Compare the json-e rebuilt task definition vs the runtime definition. Args: parent_link (LinkOfTrust): the parent link to test. rebuilt_definitions (dict): the rebuilt task definitions. Raises: CoTError: on failure.
juraj-google-style
def _GetSectionNames(self, pefile_object): section_names = [] for section in pefile_object.sections: section_name = getattr(section, 'Name', b'') try: section_name = '{0:s}'.format(section_name.decode('unicode_escape')) except UnicodeDecodeError: section_name = '{0:...
Retrieves all PE section names. Args: pefile_object (pefile.PE): pefile object. Returns: list[str]: names of the sections.
juraj-google-style
def assert_equal(first, second, msg=None, extras=None): my_msg = None try: _pyunit_proxy.assertEqual(first, second) except AssertionError as e: my_msg = str(e) if msg: my_msg = ('%s %s' % (my_msg, msg)) if (my_msg is not None): raise signals.TestFailure(my_msg...
Assert the equality of objects, otherwise fail the test. Error message is "first != second" by default. Additional explanation can be supplied in the message. Args: first: The first object to compare. second: The second object to compare. msg: A string that adds additional info about the failure. extras: An optional ...
codesearchnet