code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def from_mapping(cls, mapping): out = cls() for (elem, count) in mapping.items(): out._set_count(elem, count) return out
Create a bag from a dict of elem->count. Each key in the dict is added if the value is > 0. Raises: ValueError: If any count is < 0.
codesearchnet
def __init__(self, input_reader=None, output_writer=None): super(ImageExportTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._abort = False self._artifact_definitions_path = None self._artifact_filters = None self._artifacts_registry = None self._cu...
Initializes the CLI tool object. Args: input_reader (Optional[InputReader]): input reader, where None indicates that the stdin input reader should be used. output_writer (Optional[OutputWriter]): output writer, where None indicates that the stdout output writer should be used.
juraj-google-style
def get_tld(url): if url not in URLHelper.__cache: URLHelper.__cache[url] = urlparse(url) parts = URLHelper.__cache[url].netloc.split(".") if len(parts) == 1: return "" else: return parts[-1]
Get the tld of the given URL. Args: url (str): The URL to get the tld from. Returns: str: The tld
juraj-google-style
def update_subscription(self, *, subscription_id, credit_card_token): payload = { "creditCardToken": credit_card_token } fmt = 'subscriptions/{}'.format(subscription_id) return self.client._put(self.url + fmt, json=payload, headers=self.get_headers())
Update information associated with the specified subscription. At the moment it is only possible to update the token of the credit card to which the charge of the subscription is made. Args: subscription_id: Identification of the subscription. credit_card_token: Returns:
juraj-google-style
def calculate_part_visibility(self, ports): source_port_lookup = {} for part_name, port_infos in SourcePortInfo.filter_parts(ports).items(): for port_info in port_infos: source_port_lookup[port_info.connected_value] = ( part_name...
Calculate what is connected to what Args: ports: {part_name: [PortInfo]} from other ports
juraj-google-style
def point_dist2(p1, p2): v = vector(p1, p2) return np.dot(v, v)
compute the square of the euclidian distance between two 3D points Args: p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: The square of the euclidian distance between the points.
juraj-google-style
def _print_task_data(self, task): print(' {0:s} ({1:s})'.format(task['name'], task['id'])) paths = task.get('saved_paths', []) if (not paths): return for path in paths: if path.endswith('worker-log.txt'): continue if path.endswith('{0:s}.log'.format(task.get('id'))): ...
Pretty-prints task data. Args: task: Task dict generated by Turbinia.
codesearchnet
def read(self, length, timeout): self._read_messages_until_true( lambda: self._buffer_size and self._buffer_size >= length, timeout) with self._read_buffer_lock: data, push_back = ''.join(self._read_buffer), '' if length: data, push_back = data[:length], data[length:] sel...
Read 'length' bytes from this stream transport. Args: length: If not 0, read this many bytes from the stream, otherwise read all available data (at least one byte). timeout: timeouts.PolledTimeout to use for this read operation. Returns: The bytes read from this stream.
juraj-google-style
def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict: outdata = _define_output_dict() _config(mip_config_raw, outdata) _qc_metrics(outdata, qcmetrics_raw) _qc_sample_info(outdata, sampleinfo_raw) return outdata
Parse the output analysis files from MIP for adding info to trend database Args: mip_config_raw (dict): raw YAML input from MIP analysis config file qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample info file Returns: dict: parsed da...
juraj-google-style
def isnan(self: EventSetOrNode) -> EventSetOrNode: from temporian.core.operators.unary import isnan return isnan(self)
Returns boolean features, `True` in the NaN elements of the [`EventSet`][temporian.EventSet]. Note that for `int` and `bool` this will always be `False` since those types don't support NaNs. It only makes actual sense to use on `float` (or `tp.float32`) features. See also `evset.notnan()`. Example: ```python >>> a =...
github-repos
def _MergeDifferentId(self): for a in self._GetIter(self.feed_merger.a_schedule): for b in self._GetIter(self.feed_merger.b_schedule): try: self._Add(a, b, self._MergeEntities(a, b)) self._num_merged += 1 except MergeError: continue ...
Tries to merge all possible combinations of entities. This tries to merge every entity in the old schedule with every entity in the new schedule. Unlike _MergeSameId, the ids do not need to match. However, _MergeDifferentId is much slower than _MergeSameId. This method makes use of various methods like _Merge and _Mi...
codesearchnet
def categorytree(self, category, depth=5): def __cat_tree_rec(cat, depth, tree, level, categories, links): ' recursive function to build out the tree ' tree[cat] = dict() tree[cat]['depth'] = level tree[cat]['sub-categories'] = dict() tree[cat]['links'] = list() tree...
Generate the Category Tree for the given categories Args: category(str or list of strings): Category name(s) depth(int): Depth to traverse the tree Returns: dict: Category tree structure Note: Set depth to **None** to get the whole tree Note: Return Data Structure: Subcategory contains the same \ recursive structure ...
codesearchnet
def find_synonym(self, word): if (word and self.synonyms): reverse_lookup = {} for (k, v) in self.synonyms.items(): for i in v: reverse_lookup[i.lower()] = k.lower() if (word.lower() in reverse_lookup): return reverse_lookup[word.lower()] return wo...
Given a string and a dict of synonyms, returns the 'preferred' word. Case insensitive. Args: word (str): A word. Returns: str: The preferred word, or the input word if not found. Example: >>> syn = {'snake': ['python', 'adder']} >>> find_synonym('adder', syn) 'snake' >>> find_synonym('rattler', syn) 'rattler' TODO:...
codesearchnet
def _set_label(self, which, label, **kwargs): prop_default = { 'fontsize': 18, } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) setattr(self.label, which, label) setattr(self.label, which + '_kwargs', kwargs)...
Private method for setting labels. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `xlabel`/`ylabel`, and `title`. label (str): The label to be added. fontsize (int, optional): Fontsize for associated label. Default is None.
juraj-google-style
def enable_store_parameters_in_results(kernel): kernel_stack = [] while (hasattr(kernel, 'parameters') and ('inner_kernel' in kernel.parameters)): kernel_stack.append(kernel) kernel = kernel.parameters['inner_kernel'] def _recreate_kernel(kernel, parameters): new_parameters = kernel...
Enables the `store_parameters_in_results` parameter in a chain of kernels. This is a temporary utility for use during the transition period of the parameter storage methods. Args: kernel: A TransitionKernel. Returns: kernel: The same kernel, but recreated with `store_parameters_in_results` recursively set to `True` ...
codesearchnet
def __validate_args(self, func_name, args, kwargs): from pyvalid.validators import Validator for (i, (arg_name, accepted_values)) in enumerate(self.accepted_args): if (i < len(args)): value = args[i] elif (arg_name in kwargs): value = kwargs[arg_name] elif (i in s...
Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidatio...
codesearchnet
def get_video_transcript_data(video_id, language_code): video_transcript = VideoTranscript.get_or_none(video_id, language_code) if video_transcript: try: return dict(file_name=video_transcript.filename, content=video_transcript.transcript.file.read()) except Exception: ...
Get video transcript data Arguments: video_id(unicode): An id identifying the Video. language_code(unicode): it will be the language code of the requested transcript. Returns: A dict containing transcript file name and its content.
juraj-google-style
def compile_date(self): result = self._dll.JLINKARM_GetCompileDateTime() return ctypes.cast(result, ctypes.c_char_p).value.decode()
Returns a string specifying the date and time at which the DLL was translated. Args: self (JLink): the ``JLink`` instance Returns: Datetime string.
juraj-google-style
def load(self, spec): if spec.template is not None: return self.loader.unicode(spec.template, spec.template_encoding) path = self._find(spec) return self.loader.read(path, spec.template_encoding)
Find and return the template associated to a TemplateSpec instance. Returns the template as a unicode string. Arguments: spec: a TemplateSpec instance.
juraj-google-style
def get_extended_attention_mask(self, attention_mask: torch.Tensor, input_shape: Tuple[int], device: torch.device, has_query: bool=False) -> torch.Tensor: if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: extended_attention_mask...
Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`Tuple[int]`): The shape of the input to the model. device: (`torch.device`): The device of th...
github-repos
def validate_element(self, value): if (not isinstance(value, self.type)): if (isinstance(value, six.integer_types) and (self.type == float)): return float(value) if (value is None): if self.required: raise ValidationError('Required field is missing') e...
Validate single element of field. This is different from validate in that it is used on individual values of repeated fields. Args: value: Value to validate. Returns: The value casted in the expected type. Raises: ValidationError if value is not expected type.
codesearchnet
def CheckTrailingSemicolon(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] match = Match('^(.*\\)\\s*)\\{', line) if match: closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression(clean_lines, linenum, closing_brace_pos) i...
Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
codesearchnet
def _parameter_net(self, theta, kernel_shape=9): with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity) pred_fil...
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
juraj-google-style
def _concat(self): if len(self._variable_list) == 1: with ops.name_scope(None): return array_ops.identity(self._variable_list[0], name=self._name) partition_axes = self._partition_axes() if len(partition_axes) > 1: raise NotImplementedError('Cannot concatenate along more than one...
Returns the overall concatenated value as a `Tensor`. This is different from using the partitioned variable directly as a tensor (through tensor conversion and `as_tensor`) in that it creates a new set of operations that keeps the control dependencies from its scope. Returns: `Tensor` containing the concatenated valu...
github-repos
def to_dict(self): d = {} d[TestResultEnums.RECORD_NAME] = self.test_name d[TestResultEnums.RECORD_CLASS] = self.test_class d[TestResultEnums.RECORD_BEGIN_TIME] = self.begin_time d[TestResultEnums.RECORD_END_TIME] = self.end_time d[TestResultEnums.RECORD_RESULT] = self.result d[TestResultEnu...
Gets a dictionary representating the content of this class. Returns: A dictionary representating the content of this class.
github-repos
def status(self, order_id): self.logger.debug('Get status of order ' + order_id) url = '%(base_url)s/order/%(order_id)s' % { 'base_url': self.base_url, 'order_id': order_id } r = self.gbdx_connection.get(url) r.raise_for_status() return r.json().get(...
Checks imagery order status. There can be more than one image per order and this function returns the status of all images within the order. Args: order_id (str): The id of the order placed. Returns: List of dictionaries, one per image. Each dictionary consists of the keys 'acquisition_id', 'location' and 'state'.
juraj-google-style
def remove_sites_from_neighbours( self, remove_labels ): if type( remove_labels ) is str: remove_labels = [ remove_labels ] self.neighbours = set( n for n in self.neighbours if n.label not in remove_labels )
Removes sites from the set of neighbouring sites if these have labels in remove_labels. Args: Remove_labels (List) or (Str): List of Site labels to be removed from the cluster neighbour set. Returns: None
juraj-google-style
def dimension_values(self, dimension, expanded=True, flat=True): index = self.get_dimension_index(dimension) if index == 0: return np.array([self.data if np.isscalar(self.data) else self.data[index]]) elif index == 1: return [] if np.isscalar(self.data) else np.a...
Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested dimension
juraj-google-style
def Match(self, file_entry): if not file_entry: return False filename = file_entry.name.lower() return filename == self._filename
Determines if a file entry matches the filter. Args: file_entry (dfvfs.FileEntry): a file entry. Returns: bool: True if the file entry matches the filter.
juraj-google-style
def _build_request(self, verb, verb_arguments): method = getattr(self._component, verb) method_args = {str(k): v for k, v in verb_arguments.items()} return method(**method_args)
Builds HttpRequest object. Args: verb (str): Request verb (ex. insert, update, delete). verb_arguments (dict): Arguments to be passed with the request. Returns: httplib2.HttpRequest: HttpRequest to be sent to the API.
juraj-google-style
def extract_lookups(value): lookups = set() if isinstance(value, basestring): lookups = lookups.union(extract_lookups_from_string(value)) elif isinstance(value, list): for v in value: lookups = lookups.union(extract_lookups(v)) elif isinstance(value, dict): for v...
Recursively extracts any stack lookups within the data structure. Args: value (one of str, list, dict): a structure that contains lookups to output values Returns: list: list of lookups if any
juraj-google-style
def _validate_chain_strength(sampler, chain_strength): properties = sampler.properties if 'extended_j_range' in properties: max_chain_strength = - min(properties['extended_j_range']) elif 'j_range' in properties: max_chain_strength = - min(properties['j_range']) else: raise...
Validate the provided chain strength, checking J-ranges of the sampler's children. Args: chain_strength (float) The provided chain strength. Use None to use J-range. Returns (float): A valid chain strength, either provided or based on available J-range. Positive finite float.
juraj-google-style
def __init__(self, counter_factory, state_sampler): self._counter_factory = counter_factory self._state_sampler = state_sampler self._latest_step = None self.bytes_read_counter = None self.scoped_state = None
Create a new IO read counter. Args: counter_factory: A counters.CounterFactory to create byte counters. state_sampler: A statesampler.StateSampler to transition into read states.
github-repos
def partial_tile(cls, tile_assignment): if not isinstance(tile_assignment, _np.ndarray): raise TypeError('PartialTile assignment must be of type np.ndarray') dims = list(tile_assignment.shape) flattened_devices = tile_assignment.reshape(-1, order='C') return Sharding(proto=xla_data_pb2.OpShardin...
Returns a partially tiled sharding attribute. This is similar to tile(), but tile_assignment has one more dimension than the tensor, and tiles in the last dimension of tile_assignment are replicated. Args: tile_assignment: An np.ndarray describing the topology of the tiling and which device will compute which part of...
github-repos
def has_no_error(state, incorrect_msg='Your code generated an error. Fix it and try again!'): if state.reporter.get_errors(): state.do_test(incorrect_msg) return state
Check whether the submission did not generate a runtime error. Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors. By default, after the entire SCT finished executing, ``sqlwhat`` will check for errors before marking the exercise as correct. You can disable this behavior by using ``Ex...
codesearchnet
def entry_point(__func: Callable) -> Callable: if __func.__module__ == '__main__': import sys sys.exit(__func()) else: return __func
Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run
juraj-google-style
def cmd_startstop(options): statelu = {"start": "stopped", "stop": "running"} options.inst_state = statelu[options.command] debg.dprint("toggle set state: ", options.inst_state) (i_info, param_str) = gather_data(options) (tar_inst, tar_idx) = determine_inst(i_info, param_str, options.command) ...
Start or Stop the specified instance. Finds instances that match args and instance-state expected by the command. Then, the target instance is determined, the action is performed on the instance, and the eturn information is displayed. Args: options (object): contains args and data from parser.
juraj-google-style
def predict_proba(self, a, b, idx=0, **kwargs): return self.predict_dataset(DataFrame([[a, b]], columns=['A', 'B']))
Use Jarfo to predict the causal direction of a pair of vars. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 idx (int): (optional) index number for printing purposes Returns: float: Causation score (Value : 1 if a->b and -1 if b->a)
codesearchnet
def _handle_message(self, message, handle_wrte=True): if (message.command == 'OKAY'): self._set_or_check_remote_id(message.arg0) if (not self._expecting_okay): raise usb_exceptions.AdbProtocolError('%s received unexpected OKAY: %s', self, message) self._expecting_okay = False ...
Handle a message that was read for this stream. For each message type, this means: OKAY: Check id's and make sure we are expecting an OKAY. Clear the self._expecting_okay flag so any pending write()'s know. CLSE: Set our internal state to closed. WRTE: Add the data read to our internal read buffer. Note we don't ret...
codesearchnet
def parse_date(value): if (not value): return None if isinstance(value, datetime.date): return value return parse_datetime(value).date()
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
codesearchnet
def get_enabled_references(self, datas, meta_references): references = OrderedDict() for section in meta_references: references[section] = self.get_reference(datas, section) return references
Get enabled manifest references declarations. Enabled references are defined through meta references declaration, every other references are ignored. Arguments: datas (dict): Data where to search for reference declarations. This is commonly the fully parsed manifest. meta_references (list): List of enabled reference ...
juraj-google-style
def setup_gpu(required_gpus): if required_gpus == 0: return available_gpus = tf.config.experimental.list_physical_devices('GPU') if not available_gpus: raise ValueError('requires at least one physical GPU') if len(available_gpus) >= required_gpus: tf.config.set_visible_devices(av...
Sets up the GPU devices. If there're more available GPUs than needed, it hides the additional ones. If there're less, it creates logical devices. This is to make sure the tests see a fixed number of GPUs regardless of the environment. Args: required_gpus: an integer. The number of GPUs required. Raises: ValueError: ...
github-repos
def _create_route(self, env, item): if item.name in env: if isinstance(env[item.name], ApiRoutesByVersion): if item.version in env[item.name].at_version: existing_dt = env[item.name].at_version[item.version] raise InvalidSpec( ...
Constructs a route and adds it to the environment. Args: env (dict): The environment of defined symbols. A new key is added corresponding to the name of this new route. item (AstRouteDef): Raw route definition from the parser. Returns: stone.api.ApiRoutesByVersion: A group of fully-defined routes indexed by versions.
juraj-google-style
def __init__(self, unique_identifier=None, attribute_names=None): super(GetAttributesRequestPayload, self).__init__( enums.Tags.REQUEST_PAYLOAD) self._unique_identifier = None self._attribute_names = list() self.unique_identifier = unique_identifier self.at...
Construct a GetAttributes request payload. Args: unique_identifier (string): The ID of the managed object with which the retrieved attributes should be associated. Optional, defaults to None. attribute_names: A list of strings identifying the names of the attributes associated with the managed object. Optional, defaul...
juraj-google-style
def shadow_calc(data): up_shadow = abs(data.high - (max(data.open, data.close))) down_shadow = abs(data.low - (min(data.open, data.close))) entity = abs(data.open - data.close) towards = True if data.open < data.close else False print('=' * 15) print('up_shadow : {}'.format(up_shadow)) ...
计算上下影线 Arguments: data {DataStruct.slice} -- 输入的是一个行情切片 Returns: up_shadow {float} -- 上影线 down_shdow {float} -- 下影线 entity {float} -- 实体部分 date {str} -- 时间 code {str} -- 代码
juraj-google-style
def _runOneBenchmark(self, default_device, num_iters=10, static_unroll=False, steps=10): def loop_body(i, x): with ops.device('/gpu:0'): nx = nn_ops.conv2d(input=x, filter=kernel, strides=[1, 1, 1, 1], padding='SAME', data_format='NHWC', name='conv2d') ni = math_ops.add(i, 1) ...
Evaluate the while loop performance. Args: default_device: The default device to run all ops except the loop_body. loop_body is always run on GPU. num_iters: Number of iterations to run. static_unroll: If true, run unrolled version; otherwise, run while_loop. steps: Total number of repeated steps to run the loop. Ret...
github-repos
def _get_rest_doc(self, request, start_response): api = request.body_json['api'] version = request.body_json['version'] generator = discovery_generator.DiscoveryGenerator(request=request) services = [s for s in self._backend.api_services if s.api_info.name == api and s.api_info.api...
Sends back HTTP response with API directory. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns...
juraj-google-style
def attention_mask_autoregressive(query_pos, dtype=tf.float32): memory_pos = rename_length_to_memory_length(query_pos) return (mtf.cast(mtf.less(query_pos, memory_pos), dtype) * (- 1000000000.0))
Bias for self-attention where attention to the right is disallowed. Args: query_pos: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim]
codesearchnet
def unwrap_or_else(self, callback: Callable[([], U)]) -> Union[(T, U)]: return (self._val if self._is_some else callback())
Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha'
codesearchnet
def to_barrier_key(cls, barrier_index_key): barrier_index_path = barrier_index_key.to_path() (pipeline_kind, dependent_pipeline_id, unused_kind, purpose) = barrier_index_path[-4:] barrier_record_path = ( pipeline_kind, dependent_pipeline_id, _BarrierRecord.kind(), purpo...
Converts a _BarrierIndex key to a _BarrierRecord key. Args: barrier_index_key: db.Key for a _BarrierIndex entity. Returns: db.Key for the corresponding _BarrierRecord entity.
juraj-google-style
def clear_tc(self, owner, data, clear_type): batch = self.tcex.batch(owner, action='Delete') tc_type = data.get('type') path = data.get('path') if (tc_type in self.tcex.group_types): name = self.tcex.playbook.read(data.get('name')) name = self.path_data(name, path) if (name is no...
Delete threat intel from ThreatConnect platform. Args: owner (str): The ThreatConnect owner. data (dict): The data for the threat intel to clear. clear_type (str): The type of clear action.
codesearchnet
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): local_stream = BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_stream, kmip_version=kmip_version ) else: raise...
Write the data encoding the MACSignatureKeyInformation struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded....
juraj-google-style
def _get_element_by_names(source, names): if source is None: return source else: if names: head, *rest = names if isinstance(source, dict) and head in source: return _get_element_by_names(source[head], rest) elif isinstance(source, list)...
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve the specified element. Args: source (dict): set of nested objects in which the data will be searched path (list): list of attribute names
juraj-google-style
def from_unknown_text(text, strict=False): if text.startswith('+'): crs = from_proj4(text, strict) elif text.startswith(('PROJCS[', 'GEOGCS[')): crs = from_unknown_wkt(text, strict) elif text.startswith('EPSG:'): crs = from_epsg_code(text.split(':')[1]) elif text.startswith('ESRI...
Detect crs string format and parse into crs object with appropriate function. Arguments: - *text*: The crs text representation of unknown type. - *strict* (optional): When True, the parser is strict about names having to match exactly with upper and lowercases. Default is not strict (False). Returns: - CRS object.
codesearchnet
def from_structures(cls, structures, constant_lattice=True, **kwargs): frac_coords = [structure.frac_coords for structure in structures] if constant_lattice: lattice = structures[0].lattice.matrix else: lattice = [structure.lattice.matrix for structure in structu...
Convenience constructor to obtain trajectory from a list of structures. Note: Assumes no atoms removed during simulation Args: structures (list): list of pymatgen Structure objects. constant_lattice (bool): Whether the lattice changes during the simulation, such as in an NPT MD simulation. True results in Returns: (T...
juraj-google-style
def get(cls, ns, key): return getattr(db, cls.__name__).find_one((ConfigItem.namespace_prefix == ns), (ConfigItem.key == key))
Fetch an item by namespace and key Args: ns (str): Namespace prefix key (str): Item key Returns: :obj:`Configitem`: Returns config item object if found, else `None`
codesearchnet
def search(self, trace_func: Callable[([List[LineSequence], float, float, float, bool], None)]=None) -> List[LineSequence]: def search_trace(state: _STATE, temp: float, cost: float, probability: float, accepted: bool): if trace_func: (trace_seqs, _) = state trace_func(trace_seqs, te...
Issues new linear sequence search. Each call to this method starts new search. Args: trace_func: Optional callable which will be called for each simulated annealing step with arguments: solution candidate (list of linear sequences on the chip), current temperature (float), candidate cost (float), probability of accep...
codesearchnet
def CheckCompletedBlocks(self, filename, error): for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, ('Failed to find complete declaration of class %s' % obj.name)) elif isinstance(obj, _NamespaceInfo): error(filename...
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
codesearchnet
def add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): name = alias or assistant_tuple[0].name p = parser.add_parser(name, description=assistant_tuple[0].description, argument_default=argparse.SUPPRESS) for ...
Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of assistant tree (see generate_argument_parser doc) level: level of subassistants that given assistant is at
juraj-google-style
def nac_v(msg): tc = typecode(msg) if (tc != 19): raise RuntimeError(('%s: Not an airborne velocity message, expecting TC = 19' % msg)) msgbin = common.hex2bin(msg) NACv = common.bin2int(msgbin[42:45]) try: HFOMr = uncertainty.NACv[NACv]['HFOMr'] VFOMr = uncertainty.NACv[NACv...
Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit
codesearchnet
def metta_config(quarter, num_dimensions): (first_day, last_day) = quarter_boundaries(quarter) return {'start_time': first_day, 'end_time': last_day, 'prediction_window': 3, 'label_name': 'onet_soc_code', 'label_type': 'categorical', 'matrix_id': 'job_postings_{}'.format(quarter), 'feature_names': ['doc2vec_{}'...
Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test
codesearchnet
def find_library_windows(cls): dll = (cls.get_appropriate_windows_sdk_name() + '.dll') root = 'C:\\' for d in os.listdir(root): dir_path = os.path.join(root, d) if (d.startswith('Program Files') and os.path.isdir(dir_path)): dir_path = os.path.join(dir_path, 'SEGGER') ...
Loads the SEGGER DLL from the windows installation directory. On Windows, these are found either under: - ``C:\\Program Files\\SEGGER\\JLink`` - ``C:\\Program Files (x86)\\SEGGER\\JLink``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
codesearchnet
def values(self, column_major=False): if column_major: return list(map(list, zip(*self._values))) return [row[:] for row in self._values]
Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values
codesearchnet
def _notify_mutated(self, obj, old, hint=None): value = self.__get__(obj, obj.__class__) value = self.property.prepare_value(obj, self.name, value) self._real_set(obj, old, value, hint=hint)
A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container In this case, somewhat weirdly, ``old`` is a copy and the new value should already...
codesearchnet
def _sym_missing(self) -> Dict[str, Any]: missing = dict() for k, v in self._sym_attributes.items(): if pg_typing.MISSING_VALUE != v and isinstance(v, base.Symbolic): missing_child = v.sym_missing(flatten=False) if missing_child: missing[k] = missing_child ret...
Returns missing values for Functor. Semantically unbound arguments are not missing, thus we only return partial bound arguments in `sym_missing`. As a result, a functor is partial only when any of its bound arguments is partial. Returns: A dict of missing key (or path) to missing value.
github-repos
def code_string_to_enum_value_descriptor(code_string: str, enum_descriptor: descriptor.EnumDescriptor) -> descriptor.EnumValueDescriptor: value_descriptor = _get_enum_value_descriptor_memo(enum_descriptor, code_string) if value_descriptor is not None: return value_descriptor fhir_case_code_string = ...
Returns an EnumValueDescriptor for a provided EnumDescriptor and raw code. Args: code_string: A raw string representation of the code to retrieve. enum_descriptor: The EnumDescriptor the desired EnumValueDescriptor belongs to. Returns: An instance of EnumValueDescriptor that the code_string represents. Raises: fhir_...
github-repos
def _prep_noise_interpolants(self): noise_lists = {} self.noise_interpolants = {} if isinstance(self.sensitivity_curves, str): self.sensitivity_curves = [self.sensitivity_curves] if isinstance(self.noise_type_in, list): if (len(self.noise_type_in) != len(self.sensitivity_curves)): ...
Construct interpolated sensitivity curves This will construct the interpolated sensitivity curves using scipy.interpolate.interp1d. It will add wd noise if that is requested. Raises: ValueError: ``len(noise_type_in) != len(sensitivity_curves)`` ValueError: Issue with sensitivity curve type provided.
codesearchnet
def print_source(self, args, screen_info=None): del screen_info parsed = self._arg_parsers['print_source'].parse_args(args) device_name_regex = re.compile(parsed.device_name_filter) if parsed.device_name_filter else None profile_data = [] data_generator = self._get_profile_data_generator() devic...
Print a Python source file with line-level profile information. Args: args: Command-line arguments, excluding the command prefix, as a list of str. screen_info: Optional dict input containing screen information such as cols. Returns: Output text lines as a RichTextLines object.
github-repos
def is_active(self, node): if (isinstance(node.value, gast.Call) and anno.getanno(node.value, 'func', False) == utils.pop): return True for succ in gast.walk(node.value): if (isinstance(succ, gast.Name) and isinstance(succ.ctx, gast.Load) and succ.id in self.active_v...
Checks whether a statement is active. An assignment is active when its right hand side contains active variables. Args: node: an instance of gast.Assign Returns: Whether the statement is active.
juraj-google-style
def __init__(self, channel): self.ListContexts = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/ListContexts', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.ListContextsRequest.SerializeToString, response_deserializer=google_dot_...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def ReadSerializableArray(self, class_name, max=sys.maxsize): module = '.'.join(class_name.split('.')[:-1]) klassname = class_name.split('.')[-1] klass = getattr(importlib.import_module(module), klassname) length = self.ReadVarInt(max=max) items = [] try...
Deserialize a stream into the object specific by `class_name`. Args: class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block' max (int): (Optional) maximum number of bytes to read. Returns: list: list of `class_name` objects deserialized from the stream.
juraj-google-style
def DetermineType(value): object_type = type(value) if not hasattr(object_type, '__name__'): return None type_string = getattr(object_type, '__module__', '') if type_string: type_string += '.' type_string += object_type.__name__ return type_string
Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path string. None if type cannot be determined.
juraj-google-style
def SetServerInformation(self, server, port): self._host = server self._port = port logger.debug('Elasticsearch server: {0!s} port: {1:d}'.format( server, port))
Set the server information. Args: server (str): IP address or hostname of the server. port (int): Port number of the server.
juraj-google-style
def google_maps_geoloc_link(data): if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data loc = '%s,%s' % (lat, lon) return 'https: 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d...
Get a link to google maps pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to google maps pointing on this IP's geolocation.
juraj-google-style
def limit(self, count): query = query_mod.Query(self) return query.limit(count)
Create a limited query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.limit` for more information on this method. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firestore_v1beta1.query.Query: A limited query.
codesearchnet
def upload(self, resource_id, data): self.body = data self.content_type = 'application/octet-stream' self.resource_id(str(resource_id)) self._request_uri = '{}/upload'.format(self._request_uri)
Update the request URI to upload the a document to this resource. Args: resource_id (integer): The group id. data (any): The raw data to upload.
codesearchnet
def get_dataset(self, dsid, dsinfo): data = self[dsinfo.get('file_key', dsid.name)] data.attrs.update(dsinfo) data.attrs['platform_name'] = self['/attr/satellite_name'] data.attrs['sensor'] = self['/attr/instrument_name'] return data
Get dataset function Args: dsid: Dataset ID param2: Dataset Information Returns: Dask DataArray: Data
codesearchnet
def from_base_10_int(decimal, output_base=10): if decimal <= 0: return (0,) if output_base == 1: return (1,) * decimal length = digits(decimal, output_base) converted = tuple(digit(decimal, i, output_base) for i in range(length)) return converted[::-1]
Converts a decimal integer to a specific base. Args: decimal(int) A base 10 number. output_base(int) base to convert to. Returns: A tuple of digits in the specified base. Examples: >>> from_base_10_int(255) (2, 5, 5) >>> from_base_10_int(255, 16) (15, 15) >>> from_base_10_int(9988664439, 8) (1, 1, 2, 3, 2, 7, 5, 6, ...
juraj-google-style
def get_ogr_driver(filepath): (filename, file_extension) = os.path.splitext(filepath) EXTENSION = file_extension[1:] ogr_driver_count = ogr.GetDriverCount() for idx in range(ogr_driver_count): driver = ogr.GetDriver(idx) driver_extension = (driver.GetMetadataItem(str('DMD_EXTENSION')) or...
Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found
codesearchnet
def generate_exact(self, model, vcpu_num, host_cpu): nested = {'Intel': 'vmx', 'AMD': 'svm'} cpu = ET.Element('cpu', match='exact') ET.SubElement(cpu, 'model').text = model cpu.append(self.generate_topology(vcpu_num)) vendor = host_cpu.findtext('vendor') if (not nested.get(vendor)): LOGG...
Generate exact CPU model with nested virtualization CPU feature. Args: model(str): libvirt supported CPU model vcpu_num(int): number of virtual cpus host_cpu(lxml.etree.Element): the host CPU model Returns: lxml.etree.Element: CPU XML node
codesearchnet
def guess_task_type(name, task_defn): parts = name.split(':') task_type = parts[(- 1)] if (task_type == 'parent'): if is_action(task_defn): task_type = 'action' else: task_type = 'decision' if (task_type not in get_valid_task_types()): raise CoTError('Inva...
Guess the task type of the task. Args: name (str): the name of the task. Returns: str: the task_type. Raises: CoTError: on invalid task_type.
codesearchnet
def internal_convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None, as_ref=False): if not isinstance(values, collections_abc.Iterable): raise TypeError('Argument `values` must be iterable.') ret = [] for i, value in enumerate(values): if value is None: ret.append(va...
Converts `values` to a list of `Tensor` or `IndexedSlices` objects. Any `IndexedSlices` or `SparseTensor` objects in `values` are returned unmodified. Args: values: An iterable of `None`, `IndexedSlices`, `SparseTensor`, or objects that can be consumed by `convert_to_tensor()`. dtype: (Optional.) The required `DType`...
github-repos
def _decorate_block(self, start, end): color = self._get_scope_highlight_color() draw_order = DRAW_ORDERS.get('codefolding') d = TextDecoration(self.editor.document(), start_line=start, end_line=end+1, draw_order=draw_order) d.set_background(color) ...
Create a decoration and add it to the editor. Args: start (int) start line of the decoration end (int) end line of the decoration
juraj-google-style
def prepare_for_send(self, full_url=False): assert self.url assert self.method assert self.version url_info = self.url_info if ('Host' not in self.fields): self.fields['Host'] = url_info.hostname_with_port if (not full_url): if url_info.query: self.resource_path = '{0...
Modify the request to be suitable for HTTP server. Args: full_url (bool): Use full URL as the URI. By default, only the path of the URL is given to the server.
codesearchnet
def add_arguments(cls, parser): parser.add_argument( '-t', '--title', action='store', nargs='?', const='', dest='title', help="[issue] task/issue title.", ) parser.add_argument( '-b', '--body', ...
Add arguments to the parser for collection in app.args. Args: parser: `argparse.ArgumentParser`. Parser. Arguments added here are server on self.args.
juraj-google-style
def populate_ast_nsarg_orthologs(ast, species): ortholog_namespace = 'EG' if isinstance(ast, NSArg): if re.match(ortholog_namespace, ast.canonical): orthologs = bel.terms.orthologs.get_orthologs(ast.canonical, list(species.keys())) for species_id in species: if (s...
Recursively collect NSArg orthologs for BEL AST This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available Args: ast: AST at recursive point in belobj species: dictionary of species ids vs labels for or
codesearchnet
def draw_sunpath(self, hoys=None, origin=None, scale=1, sun_scale=1, annual=True, rem_night=True): assert ladybug.isplus, '"draw_sunpath" method can only be used in the [+] libraries.' hoys = (hoys or ()) origin = (origin or (0, 0, 0)) try: origin = tuple(origin) except TypeError as e: ...
Create sunpath geometry. \ This method should only be used from the + libraries. Args: hoys: An optional list of hours of the year(default: None). origin: Sunpath origin(default: (0, 0, 0)). scale: Sunpath scale(default: 1). sun_scale: Scale for the sun spheres(default: 1). annual: Set to True to draw an annual sunpat...
codesearchnet
def offTagAdd(self, name, func): if '*' in name: self.ontagaddglobs.rem(name, func) return cblist = self.ontagadds.get(name) if cblist is None: return try: cblist.remove(func) except ValueError: pass
Unregister a callback for tag addition. Args: name (str): The name of the tag or tag glob. func (function): The callback func(node, tagname, tagval).
juraj-google-style
def orthorhombic(a: float, b: float, c: float): return Lattice.from_parameters(a, b, c, 90, 90, 90)
Convenience constructor for an orthorhombic lattice. Args: a (float): *a* lattice parameter of the orthorhombic cell. b (float): *b* lattice parameter of the orthorhombic cell. c (float): *c* lattice parameter of the orthorhombic cell. Returns: Orthorhombic lattice of dimensions a x b x c.
juraj-google-style
def apply_filter(self, structure_filter): def test_transformed_structure(ts): return structure_filter.test(ts.final_structure) self.transformed_structures = list(filter(test_transformed_structure, self.transformed_structures)) for ts in self.transformed_structures: ts.append_filter(structur...
Applies a structure_filter to the list of TransformedStructures in the transmuter. Args: structure_filter: StructureFilter to apply.
codesearchnet
def UnwrapPyTree(tree): unwrapper = PyTreeUnwrapper() unwrapper.Visit(tree) llines = unwrapper.GetLogicalLines() llines.sort(key=lambda x: x.lineno) return llines
Create and return a list of logical lines from the given pytree. Arguments: tree: the top-level pytree node to unwrap.. Returns: A list of LogicalLine objects.
github-repos
def as_operation(self, timer=datetime.utcnow): now = timer() op = sc_messages.Operation(endTime=timestamp.to_rfc3339(now), startTime=timestamp.to_rfc3339(now), importance=sc_messages.Operation.ImportanceValueValuesEnum.LOW) if self.operation_id: op.operationId = self.operation_id if self.operati...
Makes an ``Operation`` from this instance. Returns: an ``Operation``
codesearchnet
def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): assert boxes.shape.ndims == 2, boxes.shape if post_nms_topk is None: post_nms_topk = pre_nms_topk topk = tf.minimum(pre_nms_topk, tf.size(scores)) topk_scores, topk_indices = ...
Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: boxes: nx4 float dtype, the proposal boxes. Decoded to floatbox already scores: n float, the logits img_shape: [h, w] pre_nms_topk, post_nms_topk (int...
juraj-google-style
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None): with tf.variable_scope(name, default_name='within_local_attention_1d', values=[q, k, v]): (batch, heads, length, depth_k) = common_layers.shape_list(q) depth_v = common_layers.shape_list(v)[(- 1)] if isinstance(...
Attention to the source and a neighborhood to the left within a block. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the query position in the corresponding block. Args: q: a Tensor with shape [batch, heads, length,...
codesearchnet
def bdp_bds_cache(func, tickers, flds, **kwargs) -> ToQuery: cache_data = [] log_level = kwargs.get('log', logs.LOG_LEVEL) logger = logs.get_logger(bdp_bds_cache, level=log_level) kwargs['has_date'] = kwargs.pop('has_date', func == 'bds') kwargs['cache'] = kwargs.get('cache', True) tickers...
Find cached `BDP` / `BDS` queries Args: func: function name - bdp or bds tickers: tickers flds: fields **kwargs: other kwargs Returns: ToQuery(ticker, flds, kwargs)
juraj-google-style
def convert(self, value): if (self._type is str): return str(value) elif (self._type is int): try: return int(value) except (UnicodeError, ValueError): raise WorkflowArgumentError('Cannot convert {} to int'.format(value)) elif (self._type is float): tr...
Convert the specified value to the type of the option. Args: value: The value that should be converted. Returns: The value with the type given by the option.
codesearchnet
def to_FIB(self, other): if (not isinstance(other, GroundedFunctionNetwork)): raise TypeError(f'Expected GroundedFunctionNetwork, but got {type(other)}') def shortname(var): return var[(var.find('::') + 2):var.rfind('_')] def shortname_vars(graph, shortname): return [v for v in gra...
Creates a ForwardInfluenceBlanket object representing the intersection of this model with the other input model. Args: other: The GroundedFunctionNetwork object to compare this model to. Returns: A ForwardInfluenceBlanket object to use for model comparison.
codesearchnet
def update_config(config): update(bigchaindb.config, update_types(config, bigchaindb.config)) bigchaindb.config['CONFIGURED'] = True
Update bigchaindb.config with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default config
juraj-google-style
def parse(self, argument): if isinstance(argument, self.enum_class): return argument if argument not in self.enum_class.__members__: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_class.__members__.keys())) else: return self.enum_class[argum...
Determines validity of argument and returns the correct element of enum. Args: argument: str or Enum class member, the supplied flag value. Returns: The first matching Enum class member in Enum class. Raises: ValueError: Raised when argument didn't match anything in enum.
juraj-google-style
def _update_field(self, uri, field): payload = None if type(field) is not StreakField: return requests.codes.bad_request, None payload = field.to_dict(rw = True) try: uri = '/'.join([ uri, field.attributes['key'] ]) except KeyError: return requests.codes.bad_r...
Updates a field with the provided attributes. Args: key reqiured identifier for the pipeline or box field StreakField object kwargs {name, type} see StreakField for details return (status code, field dict)
juraj-google-style