code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def read_excitation_energies(self): transitions = list() with zopen(self.filename, 'r') as f: line = f.readline() td = False while (line != ''): if re.search('^\\sExcitation energies and oscillator strengths:', line): td = True if td: ...
Read a excitation energies after a TD-DFT calculation. Returns: A list: A list of tuple for each transition such as [(energie (eV), lambda (nm), oscillatory strength), ... ]
codesearchnet
def __init__(self, callback): super(ThreadedXMLRPCServer, self).__init__(callback) self._rpc_thread = None self._xmlrpc_server = None
Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request.
juraj-google-style
def load_filename(self, filename, index=None): filename = str(filename) if index is None: index = self._get_tab_index() page = self.pages[index] self.load_dir, _ = os.path.split(filename) clss = page.clss_load if len(clss) == 1: ...
Loads file given filename Args: filename: index: tab index to load file into. If not passed, loads into current tab
juraj-google-style
def orient_averaged_adaptive(tm): S = np.zeros((2,2), dtype=complex) Z = np.zeros((4,4)) def Sfunc(beta, alpha, i, j, real): (S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta) s = S_ang[i,j].real if real else S_ang[i,j].imag return s * tm.or_pdf(beta) in...
Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance Returns: The amplitude (S) and phase (Z...
juraj-google-style
class GroundingDinoImageLoss(ImageLoss): def __init__(self, matcher, focal_alpha, losses): nn.Module.__init__(self) self.matcher = matcher self.focal_alpha = focal_alpha self.losses = losses def _get_target_classes_one_hot(self, outputs, targets, indices): logi...
This class computes the losses for `GroundingDinoForObjectDetection`. The process happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and box). Args: matcher (`GroundingDinoHunga...
github-repos
def __init__(self, minimum=None, maximum=None): super(IntegerTypeChecker, self).__init__(base_type=int) self.minimum = minimum self.maximum = maximum
Initialization method. Args: minimum (int): a minimum value (included). maximum (int): a maximum value (included).
juraj-google-style
def fill_datetime(self): if (not self.filled): raise SlotNotFilledError(('Slot with name "%s", key "%s" not yet filled.' % (self.name, self.key))) return self._fill_datetime
Returns when the slot was filled. Returns: A datetime.datetime. Raises: SlotNotFilledError if the value hasn't been filled yet.
codesearchnet
def shannon_entropy(time_series): if (not isinstance(time_series, str)): time_series = list(time_series) data_set = list(set(time_series)) freq_list = [] for entry in data_set: counter = 0.0 for i in time_series: if (i == entry): counter += 1 f...
Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value
codesearchnet
def rank_internal(input, name=None, optimize=True): with ops.name_scope(name, 'Rank', [input]) as name: if isinstance(input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): return gen_array_ops.size(input.dense_shape, name=name) else: input = ops.convert_to_te...
Returns the rank of a tensor. Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). optimize: if true, encode the rank as a constant when possible. Returns: A `Tensor` of type `int32`.
github-repos
def encode(self, input_ids: jnp.ndarray, attention_mask: Optional[jnp.ndarray]=None, position_ids: Optional[jnp.ndarray]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None): ...
Returns: Example: ```python >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill") >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") >>> text = "My frien...
github-repos
def create_bagit_stream(dir_name, payload_info_list): zip_file = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED) _add_path(dir_name, payload_info_list) payload_byte_count, payload_file_count = _add_payload_files( zip_file, payload_info_list ) tag_info_list = _add_tag_fil...
Create a stream containing a BagIt zip archive. Args: dir_name : str The name of the root directory in the zip file, under which all the files are placed (avoids "zip bombs"). payload_info_list: list List of payload_info_dict, each dict describing a file. - keys: pid, filename, iter, checksum, checksum_algorithm - I...
juraj-google-style
def process_document_events(events, use_buffers=True): json_events = [] references = set() buffers = [] if use_buffers else None for event in events: json_events.append(event.generate(references, buffers)) json = { 'events' : json_events, 'references' : reference...
Create a JSON string describing a patch to be applied as well as any optional buffers. Args: events : list of events to be translated into patches Returns: str, list : JSON string which can be applied to make the given updates to obj as well as any optional buffers
juraj-google-style
def get_distance_and_image(self, frac_coords1: Vector3Like, frac_coords2: Vector3Like, jimage: Optional[Union[(List[int], np.ndarray)]]=None) -> Tuple[(float, np.ndarray)]: if (jimage is None): (v, d2) = pbc_shortest_vectors(self, frac_coords1, frac_coords2, return_d2=True) fc = ((self.get_fractiona...
Gets distance between two frac_coords assuming periodic boundary conditions. If the index jimage is not specified it selects the j image nearest to the i atom and returns the distance and jimage indices in terms of lattice vector translations. If the index jimage is specified it returns the distance between the frac_co...
codesearchnet
def get_default_backend_config(appdirs): return { 'store': 'sqlalchemy', 'day_start': datetime.time(5, 30, 0), 'fact_min_delta': 1, 'tmpfile_path': os.path.join(appdirs.user_data_dir, '{}.tmp'.format(appdirs.appname)), 'db_engine': 'sqlite', 'db_path': os.path.jo...
Return a default config dictionary. Args: appdirs (HamsterAppDirs): ``HamsterAppDirs`` instance encapsulating the apps details. Returns: dict: Dictionary with a default configuration. Note: Those defaults are independent of the particular config-store.
juraj-google-style
def get(self, context_id, address_list): if (context_id not in self._contexts): return [] for add in address_list: if (not self.address_is_valid(address=add)): raise AuthorizationException(address=add) context = self._contexts[context_id] addresses_in_ctx = [add for add in ad...
Get the values associated with list of addresses, for a specific context referenced by context_id. Args: context_id (str): the return value of create_context, referencing a particular context. address_list (list): a list of address strs Returns: values_list (list): a list of (address, value) tuples Raises: Authoriza...
codesearchnet
def ResolveFlats(dem, in_place=False): if (type(dem) is not rdarray): raise Exception('A richdem.rdarray or numpy.ndarray is required!') if (not in_place): dem = dem.copy() _AddAnalysis(dem, 'ResolveFlats(dem, in_place={in_place})'.format(in_place=in_place)) demw = dem.wrap() _richde...
Attempts to resolve flats by imposing a local gradient Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. Returns: DEM modified such that all flats drain.
codesearchnet
def __init__(self, var_config, scope_config): self._substs = {} self._var_config = var_config self._scope_config = scope_config for var_id, var_value in iteritems(var_config): key = "%%{var}%%".format(var=var_id) self._substs[key] = str(var_value) for scope_id, var_config in iteri...
Initializes the substitution environment. Args: var_config: A configuration (concrete values) of pattern variables. scope_config: A configuration (concrete values) of pattern scopes.
juraj-google-style
def get_actions(self, parent_environ=None): interp = Python(target_environ={}, passive=True) executor = self._create_executor(interp, parent_environ) self._execute(executor) return executor.actions
Get the list of rex.Action objects resulting from interpreting this context. This is provided mainly for testing purposes. Args: parent_environ Environment to interpret the context within, defaults to os.environ if None. Returns: A list of rex.Action subclass instances.
juraj-google-style
def get_heading_encoding(response): encoding = wpull.protocol.http.util.parse_charset( response.fields.get('content-type', '')) if encoding: return wpull.string.normalize_codec_name(encoding) else: return None
Return the document encoding from a HTTP header. Args: response (Response): An instance of :class:`.http.Response`. Returns: ``str``, ``None``: The codec name.
juraj-google-style
def request(self, session=None): try: from .tcex_request import TcExRequest r = TcExRequest(self, session) if ((session is None) and self.default_args.tc_proxy_external): self.log.info('Using proxy server for external request {}:{}.'.format(self.default_args.tc_proxy_host, self.d...
Return an instance of the Request Class. A wrapper on the Python Requests module that provides a different interface for creating requests. The session property of this instance has built-in logging, session level retries, and preconfigured proxy configuration. Returns: (object): An instance of Request Class
codesearchnet
def build_variant_query(self, query=None, category='snv', variant_type=['clinical']): query = (query or {}) mongo_variant_query = {} LOG.debug(('Building a mongo query for %s' % query)) if query.get('hgnc_symbols'): mongo_variant_query['hgnc_symbols'] = {'$in': query['hgnc_symbols']} mongo_v...
Build a mongo query across multiple cases. Translate query options from a form into a complete mongo query dictionary. Beware that unindexed queries against a large variant collection will be extremely slow. Currently indexed query options: hgnc_symbols rank_score variant_type category Args: query(dict): A query dic...
codesearchnet
def period_start_day(self, value=None): if (value is not None): try: value = str(value) except ValueError: raise ValueError('value {} need to be of type str for field `period_start_day`'.format(value)) if (',' in value): raise ValueError('value should not ...
Corresponds to IDD Field `period_start_day` Args: value (str): value for IDD Field `period_start_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def loss_labels(self, class_queries_logits: Tensor, class_labels: List[Tensor], indices: Tuple[np.array]) -> Dict[str, Tensor]: pred_logits = class_queries_logits batch_size, num_queries, _ = pred_logits.shape criterion = nn.CrossEntropyLoss(weight=self.empty_weight) idx = self._get_predictions_permutat...
Compute the losses related to the labels using cross entropy. Args: class_queries_logits (`torch.Tensor`): A tensor of shape `batch_size, num_queries, num_labels` class_labels (`List[torch.Tensor]`): List of class labels of shape `(labels)`. indices (`Tuple[np.array])`: The indices computed by the Hungarian matcher. ...
github-repos
def ensure_dir(path): dirpath = os.path.dirname(path) if dirpath and not os.path.exists(dirpath): os.makedirs(dirpath)
Ensure directory exists. Args: path(str): dir path
juraj-google-style
def normalize_whitespace(text): return re.sub('\\s+', ' ', text, flags=re.UNICODE).strip()
Returns the given text with outer whitespace removed and inner whitespace collapsed. Args: text (str): The text to normalize. Returns: str: The normalized text.
codesearchnet
def group_device_names(devices, group_size): num_devices = len(devices) if group_size > num_devices: raise ValueError( "only %d devices, but group_size=%d" % (num_devices, group_size)) num_groups = ( num_devices (num_devices % group_size...
Group device names into groups of group_size. Args: devices: list of strings naming devices. group_size: int >= 1 Returns: list of lists of devices, where each inner list is group_size long, and each device appears at least once in an inner list. If len(devices) % group_size = 0 then each device will appear exactly ...
juraj-google-style
def _random_stateless_uniform(shape: types.IntTensor, num_digits: types.IntTensor, seed: int, validate_args: bool=False, dtype: tf.DType=None, name: str=None) -> types.IntTensor: with tf.name_scope(name or 'random_stateless_uniform'): dtype = dtype or tf.int32 shape = tf.convert_to_tensor(shape, dty...
Returns a `Tensor` drawn from a uniform distribution with a given `shape`. Args: shape: Positive scalar `Tensor` of integers with rank 1. The shape of the returned `Tensor`. num_digits: Positive scalar `Tensor` of integers with rank 0. the base-2 precision of the points which can be sampled from `generating_matrices`....
github-repos
def post_process_depth_estimation(self, outputs: 'DepthProDepthEstimatorOutput', target_sizes: Optional[Union[TensorType, List[Tuple[int, int]], None]]=None) -> Dict[str, List[TensorType]]: requires_backends(self, 'torch') predicted_depth = outputs.predicted_depth fov = outputs.field_of_view batch_size ...
Post-processes the raw depth predictions from the model to generate final depth predictions which is caliberated using the field of view if provided and resized to specified target sizes if provided. Args: outputs ([`DepthProDepthEstimatorOutput`]): Raw outputs of the model. target_sizes (`Optional[Union[TensorType, L...
github-repos
def _handle_stop_workflow(self, request): self._stop_workflow = True for (name, dag) in self._dags_running.items(): if (name not in self._stop_dags): self._stop_dags.append(name) return Response(success=True, uid=request.uid)
The handler for the stop_workflow request. The stop_workflow request adds all running dags to the list of dags that should be stopped and prevents new dags from being started. The dags will then stop queueing new tasks, which will terminate the dags and in turn the workflow. Args: request (Request): Reference to a re...
codesearchnet
def initialize(self, table): check_table_dtypes(table, self.key_dtype, self.value_dtype) with ops.name_scope(self._name, 'text_file_init', (table.resource_handle,)): filename = ops.convert_to_tensor(self._filename, dtypes.string, name='asset_filepath') init_op = gen_lookup_ops.initialize_table_f...
Initializes the table from a text file. Args: table: The table to be initialized. Returns: The operation that initializes the table. Raises: TypeError: when the keys and values data types do not match the table key and value data types.
github-repos
def potential_jumps( self ): jumps = [] if self.number_of_occupied_sites <= self.number_of_sites / 2: for occupied_site in self.occupied_sites(): unoccupied_neighbours = [ site for site in [ self.site_with_id( n ) for n in occupied_site.neighbours ] if not site.is_oc...
All nearest-neighbour jumps not blocked by volume exclusion (i.e. from occupied to neighbouring unoccupied sites). Args: None Returns: (List(Jump)): List of possible jumps.
juraj-google-style
def from_event(cls, ion_event): if (ion_event.value is not None): (args, kwargs) = cls._to_constructor_args(ion_event.value) else: (args, kwargs) = ((), {}) value = cls(*args, **kwargs) value.ion_event = ion_event value.ion_type = ion_event.ion_type value.ion_annotations = ion_ev...
Constructs the given native extension from the properties of an event. Args: ion_event (IonEvent): The event to construct the native value from.
codesearchnet
def HandleExceptionsAndRebuildHttpConnections(retry_args): retry_after = None if isinstance(retry_args.exc, (http_client.BadStatusLine, http_client.IncompleteRead, http_client.ResponseNotReady)): logging.debug('Ca...
Exception handler for http failures. This catches known failures and rebuilds the underlying HTTP connections. Args: retry_args: An ExceptionRetryArgs tuple.
juraj-google-style
def getObjective(self, name): return lock_and_call( lambda: Objective(self._impl.getObjective(name)), self._lock )
Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist.
juraj-google-style
def _convert_to_dict(data): if isinstance(data, dict): return data if (isinstance(data, list) or isinstance(data, tuple)): if _all_correct_list(data): return dict(data) else: data = zip(data[::2], data[1::2]) return dict(data) else: raise M...
Convert `data` to dictionary. Tries to get sense in multidimensional arrays. Args: data: List/dict/tuple of variable dimension. Returns: dict: If the data can be converted to dictionary. Raises: MetaParsingException: When the data are unconvertible to dict.
codesearchnet
def file_md5(filename): with zopen(filename, 'r') as f: file_string = f.read() try: file_string = file_string.decode() except AttributeError: pass return md5sum(file_string)
Generate the md5 checksum for a file Args: filename (Str): The file to be checksummed. Returns: (Str): The hex checksum Notes: If the file is gzipped, the md5 checksum returned is for the uncompressed ASCII file.
codesearchnet
def load_architecture(self, name, arch_info, disassembler, translator): self.name = name self.arch_info = arch_info self.disassembler = disassembler self.ir_translator = translator self._setup_analysis_modules()
Translate to REIL instructions. Args: name (str): Architecture's name. arch_info (ArchitectureInformation): Architecture information object. disassembler (Disassembler): Disassembler for the architecture. translator (Translator): Translator for the architecture.
juraj-google-style
def get_pattern_actual_step(self, patternnumber): _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('actualstep', patternnumber) return self.read_register(address, 0)
Get the 'actual step' parameter for a given pattern. Args: patternnumber (integer): 0-7 Returns: The 'actual step' parameter (int).
juraj-google-style
def validate(self, corpus): overflow_segments = {} for utterance in corpus.utterances.values(): utt_segments = self.validate_utterance(utterance) if len(utt_segments) > 0: overflow_segments[utterance.idx] = utt_segments passed = len(overflow_s...
Perform the validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. Returns: InvalidUtterancesResult: Validation result.
juraj-google-style
def add(self, layer, rebuild=True): if not self._layers: if getattr(layer, '_input_shape_arg', None) is not None: self.add(InputLayer(shape=layer._input_shape_arg)) if hasattr(layer, '_keras_history'): origin_layer = layer._keras_history[0] if isinstance(origin_layer, InputLa...
Adds a layer instance on top of the layer stack. Args: layer: layer instance.
github-repos
def _test_streaming(self, with_attributes): state_verifier = PipelineStateMatcher(PipelineState.RUNNING) expected_messages = self.EXPECTED_OUTPUT_MESSAGES[self.runner_name] if not with_attributes: expected_messages = [pubsub_msg.data for pubsub_msg in expected_messages] if self.runner_name == 'T...
Runs IT pipeline with message verifier. Args: with_attributes: False - Reads and writes message data only. True - Reads and writes message data and attributes. Also verifies id_label and timestamp_attribute features.
github-repos
def process_tokens(self, tokens): for (tok_type, token, (start_row, start_col), _, _) in tokens: if (tok_type == tokenize.STRING): self._process_string_token(token, start_row, start_col)
Process the token stream. This is required to override the parent class' implementation. Args: tokens: the tokens from the token stream to process.
codesearchnet
def to_numbers(self, flatten: bool=True) -> Union[List[Union[int, float, str]], utils.Nestable[Union[int, float, str]]]: if flatten: decisions = [self.value] if self.value is not None else [] for c in self.children: decisions.extend(c.to_numbers(flatten)) return decisions eli...
Returns a (maybe) nested structure of numbers as decisions. Args: flatten: If True, the hierarchy of the numbers will not be preserved. Decisions will be returned as a flat list in DFS order. Otherwise, a nestable structure of numbers will be returned. Returns: A flat list or a hierarchical structure of numbers as th...
github-repos
def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]: match = self._pattern.match(buf) if not match: raise NotParseable(buf) done = match.group(1).upper() == self.continuation buf = buf[match.end(0):] return done, buf
Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse.
juraj-google-style
def export_model(model, model_type, export_dir, model_column_fn): wide_columns, deep_columns = model_column_fn() if model_type == 'wide': columns = wide_columns elif model_type == 'deep': columns = deep_columns else: columns = wide_columns + deep_columns feature_spec = tf.feature_column.make_pa...
Export to SavedModel format. Args: model: Estimator object model_type: string indicating model type. "wide", "deep" or "wide_deep" export_dir: directory to export the model. model_column_fn: Function to generate model feature columns.
juraj-google-style
def comments(self, case_id=None, variant_id=None, username=None): logger.debug("Looking for comments") comment_objs = self.query(Comment) if case_id: comment_objs = comment_objs.filter_by(case_id=case_id) if variant_id: comment_objs = comment_objs.filte...
Return comments for a case or variant. Args: case_id (str): id for a related case variant_id (Optional[str]): id for a related variant
juraj-google-style
def put(self, url, params=None, data=None, files=None, **kwargs): return self.call_api( "PUT", url, params=params, data=data, files=files, **kwargs )
Call the API with a PUT request. Args: url (str): Resource location relative to the base URL. params (dict or None): Query-string parameters. data (dict or None): Request body contents. files (dict or None: Files to be passed to the request. Returns: An instance of ResultParser or ErrorParser.
juraj-google-style
def _load_config_file(path): with io.open(utils.abs_path(path), 'r', encoding='utf-8') as f: conf = yaml.safe_load(f) return conf
Loads a test config file. The test config file has to be in YAML format. Args: path: A string that is the full path to the config file, including the file name. Returns: A dict that represents info in the config file.
github-repos
def read_local_files(*file_paths: str) -> str: def _read_single_file(file_path): with open(file_path) as f: filename = os.path.splitext(file_path)[0] title = f'{filename}\n{"=" * len(filename)}' return '\n\n'.join((title, f.read())) return '\n' + '\n\n'.join(ma...
Reads one or more text files and returns them joined together. A title is automatically created based on the file name. Args: *file_paths: list of files to aggregate Returns: content of files
juraj-google-style
def distance_to_line(a, b, p): return distance(closest_point(a, b, p), p)
Closest distance between a line segment and a point Args: a ([float, float]): x and y coordinates. Line start b ([float, float]): x and y coordinates. Line end p ([float, float]): x and y coordinates. Point to compute the distance Returns: float
juraj-google-style
def apply_inverse(self, y, in_place=False): return cho_solve(self._factor, y, overwrite_b=in_place)
r""" Apply the inverse of the covariance matrix to the input by solving .. math:: K\,x = y Args: y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or matrix :math:`y`. in_place (Optional[bool]): Should the data in ``y`` be overwritten with the result :math:`x`? (default: ``False``)
codesearchnet
def ParseLastVisitedRow(self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs): query_hash = hash(query) hidden = self._GetRowValue(query_hash, row, 'hidden') transition = self._GetRowValue(query_hash, row, 'transition') visit_identifier = self._GetRowValue(query_hash, row, 'visi...
Parses a last visited row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row. cache (SQLiteCache): cache which contains cached results from querying the visits and urls tables. d...
codesearchnet
def button_state(self): if (self.type != EventType.POINTER_BUTTON): raise AttributeError(_wrong_prop.format(self.type)) return self._libinput.libinput_event_pointer_get_button_state(self._handle)
The button state that triggered this event. For pointer events that are not of type :attr:`~libinput.constant.EventType.POINTER_BUTTON`, this property raises :exc:`AttributeError`. Returns: ~libinput.constant.ButtonState: The button state triggering this event. Raises: AttributeError
codesearchnet
def __register_services(api_name_version_map, api_config_registry): generator = api_config.ApiConfigGenerator() protorpc_services = [] for service_factories in api_name_version_map.itervalues(): service_classes = [service_factory.service_class for service_factory in service_factories] config...
Register & return a list of each URL and class that handles that URL. This finds every service class in api_name_version_map, registers it with the given ApiConfigRegistry, builds the URL for that class, and adds the URL and its factory to a list that's returned. Args: api_name_version_map: A mapping from (api name, ...
codesearchnet
def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False): if halo_size == 0: return x block_size = block_size_dim.size partial_size = halo_size % block_size num_complete_blocks = halo_size parts = [x] for i in xrange(1, num_complete_blocks + 1): parts = ([shift(x, i, blocks_dim,...
Concat each block with the margins of adjacent blocks. Get left and right blocks_dim and concatenate along block_size_dim. Args: x: a Tensor. blocks_dim: a Dimension in x.shape block_size_dim: a Dimension in x.shape halo_size: an integer wrap: a boolean Returns: a Tensor with the same shape as x, other than in block...
juraj-google-style
def plot_correlation(self, freq=None, title=None, figsize=(12, 6), **kwargs): if (title is None): title = self._get_default_plot_title(freq, 'Return Correlation Matrix') rets = self._get_series(freq).to_returns().dropna() return rets.plot_corr_heatmap(title=title, figsize=figsize, **kwargs)
Utility function to plot correlations. Args: * freq (str): Pandas data frequency alias string * title (str): Plot title * figsize (tuple (x,y)): figure size * kwargs: passed to Pandas' plot_corr_heatmap function
codesearchnet
def tag(self, name, formatter=None): tag = Tag(name, formatter) for tag_data in self._tags: if (tag_data.name == name): tag = tag_data break else: self._tags.append(tag) return tag
Return instance of Tag. Args: name (str): The value for this tag. formatter (method, optional): A method that take a tag value and returns a formatted tag. Returns: obj: An instance of Tag.
codesearchnet
def colored(cls, color, message): return ((getattr(cls, color.upper()) + message) + cls.DEFAULT)
Small function to wrap a string around a color Args: color (str): name of the color to wrap the string with, must be one of the class properties message (str): String to wrap with the color Returns: str: the colored string
codesearchnet
def get_vmss(access_token, subscription_id, resource_group, vmss_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/',...
Get virtual machine scale set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. JSON body of scale set properties.
juraj-google-style
def _send_notification(self, handle, payload): self.bable.notify( connection_handle=self._connection_handle, attribute_handle=handle, value=payload )
Send a notification over BLE It is executed in the baBLE working thread: should not be blocking. Args: handle (int): The handle to notify on payload (bytearray): The value to notify
juraj-google-style
def get_timestamped_export_dir(export_dir_base): attempts = 0 while attempts < MAX_DIRECTORY_CREATION_ATTEMPTS: timestamp = int(time.time()) result_dir = os.path.join(compat.as_bytes(export_dir_base), compat.as_bytes(str(timestamp))) if not gfile.Exists(result_dir): return re...
Builds a path to a new subdirectory within the base directory. Each export is written into a new subdirectory named using the current time. This guarantees monotonically increasing version numbers even across multiple runs of the pipeline. The timestamp used is the number of seconds since epoch UTC. Args: export_dir...
github-repos
def _unpack(formatstring, packed): _checkString(formatstring, description='formatstring', minlength=1) _checkString(packed, description='packed string', minlength=1) if (sys.version_info[0] > 2): packed = bytes(packed, encoding='latin1') try: value = struct.unpack(formatstring, packed)[0...
Unpack a bytestring into a value. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * packed (str): The bytestring to be unpacked. Returns: A value. The type depends on the formatstring. Raises: ValueError Note that the :mod...
codesearchnet
def resolve_object_property(obj, path: str): value = obj for path_part in path.split('.'): value = getattr(value, path_part) return value
Resolves the value of a property on an object. Is able to resolve nested properties. For example, a path can be specified: 'other.beer.name' Raises: AttributeError: In case the property could not be resolved. Returns: The value of the specified property.
codesearchnet
def _WriteAttributeContainer(self, attribute_container): if attribute_container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT: timestamp, serialized_data = self._serialized_event_heap.PopEvent() else: serialized_data = self._SerializeAttributeContainer(attribute_container) if self.compressi...
Writes an attribute container. The table for the container type must exist. Args: attribute_container (AttributeContainer): attribute container.
juraj-google-style
def load(f, _dict=dict, decoder=None): if _ispath(f): with io.open(_getpath(f), encoding='utf-8') as ffile: return loads(ffile.read(), _dict, decoder) elif isinstance(f, list): from os import path as op from warnings import warn if (not [path for path in f if op.exist...
Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invali...
codesearchnet
def _read_output(self, stream, callback, output_file): if (callback is None and output_file is None) or stream.closed: return False line = stream.readline() if line: if callback is not None: callback(line.decode(), self._...
Read the output of the process, executed the callback and save the output. Args: stream: A file object pointing to the output stream that should be read. callback(callable, None): A callback function that is called for each new line of output. output_file: A file object to which the full output is written. Returns: b...
juraj-google-style
def hurst_compare_nvals(data, nvals=None): import matplotlib.pyplot as plt data = np.asarray(data) n_all = np.arange(2,len(data)+1) dd_all = nolds.hurst_rs(data, nvals=n_all, debug_data=True, fit="poly") dd_def = nolds.hurst_rs(data, debug_data=True, fit="poly") n_def = np.round(np.exp(dd_def[1][0])).ast...
Creates a plot that compares the results of different choices for nvals for the function hurst_rs. Args: data (array-like of float): the input data from which the hurst exponent should be estimated Kwargs: nvals (array of int): a manually selected value for the nvals parameter that should be plotted in comparison to ...
juraj-google-style
def valUserCert(self, byts, cacerts=None): cert = crypto.load_certificate(crypto.FILETYPE_PEM, byts) if (cacerts is None): cacerts = self.getCaCerts() store = crypto.X509Store() [store.add_cert(cacert) for cacert in cacerts] ctx = crypto.X509StoreContext(store, cert) ctx.verify_certifica...
Validate the PEM encoded x509 user certificate bytes and return it. Args: byts (bytes): The bytes for the User Certificate. cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates. Raises: OpenSSL.crypto.X509StoreContextError: If the certificate is not valid. Returns: OpenSSL.crypto.X509: The certificate, if...
codesearchnet
def add_arguments(self, parser): group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', nargs='?', type=str.lower, default='_', choices=['usb', 'ip'], help='list all the conne...
Adds the arguments for the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None``
juraj-google-style
def download_apcor(self, uri): local_file = os.path.basename(uri) if os.access(local_file, os.F_OK): fobj = open(local_file) else: fobj = storage.vofile(uri, view='data') fobj.seek(0) str = fobj.read() fobj.close() apcor_str = str return ApcorData.from_string(apcor_st...
Downloads apcor data. Args: uri: The URI of the apcor data file. Returns: apcor: ossos.downloads.core.ApcorData
codesearchnet
def read_local_files(*file_paths: str) -> str: def _read_single_file(file_path): with open(file_path) as f: filename = os.path.splitext(file_path)[0] title = f return '\n\n'.join((title, f.read())) return ('\n' + '\n\n'.join(map(_read_single_file, file_paths)))
Reads one or more text files and returns them joined together. A title is automatically created based on the file name. Args: *file_paths: list of files to aggregate Returns: content of files
codesearchnet
def _zip_request_params(self, urls, query_params, data): if (not isinstance(urls, list)): urls = [urls] if (not isinstance(query_params, list)): query_params = [query_params] if (not isinstance(data, list)): data = [data] url_count = len(urls) query_param_count = len(query_pa...
Massages inputs and returns a list of 3-tuples zipping them up. This is all the smarts behind deciding how many requests to issue. It's fine for an input to have 0, 1, or a list of values. If there are two inputs each with a list of values, the cardinality of those lists much match. Args: urls - 1 string URL or a lis...
codesearchnet
def register(self, user_dict): endpoint = os.path.join(self._config.get('napps', 'api'), 'users', '') res = self.make_request(endpoint, method='POST', json=user_dict) return res.content.decode('utf-8')
Send an user_dict to NApps server using POST request. Args: user_dict(dict): Dictionary with user attributes. Returns: result(string): Return the response of Napps server.
codesearchnet
def _set_details(self, content): try: self.details = str(content) except UnicodeEncodeError: if (sys.version_info < (3, 0)): self.details = unicode(content) else: logging.error('Unable to decode "%s" in Py3, encoding in utf-8.', content) self.details =...
Sets the `details` field. Args: content: the content to extract details from.
codesearchnet
def _get_req_fp(self, op): if(op): op = op.lower() if op == 'get': return requests.get, None if op == 'put': return requests.put, {'Content-Type': 'application/x-www-form-urlencoded'} if op == 'post': return requests.post, {'Content-Type': 'application/json'} if op == 'delete': retur...
Decisions on what verb to use and content headers happen here Args: op a string specifying a http verb
juraj-google-style
def _handle_message_for_stream(self, stream_transport, message, timeout): if (message.command not in ('OKAY', 'CLSE', 'WRTE')): raise usb_exceptions.AdbProtocolError('%s received unexpected message: %s', self, message) if (message.arg1 == stream_transport.local_id): if (message.command == 'WRTE'...
Handle an incoming message, check if it's for the given stream. If the message is not for the stream, then add it to the appropriate message queue. Args: stream_transport: AdbStreamTransport currently waiting on a message. message: Message to check and handle. timeout: Timeout to use for the operation, should be an i...
codesearchnet
def ParseDict(js_dict, message, ignore_unknown_fields=False): parser = _Parser(ignore_unknown_fields) parser.ConvertMessage(js_dict, message) return message
Parses a JSON dictionary representation into a message. Args: js_dict: Dict representation of a JSON message. message: A protocol buffer message to merge into. ignore_unknown_fields: If True, do not raise errors for unknown fields. Returns: The same message passed as argument.
juraj-google-style
def GetZipInfo(self): if (not self._zip_info): location = getattr(self.path_spec, 'location', None) if (location is None): raise errors.PathSpecError('Path specification missing location.') if (not location.startswith(self._file_system.LOCATION_ROOT)): raise errors.Pa...
Retrieves the ZIP info object. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect.
codesearchnet
def stop(self, name: str) -> None: if (not self._timing): return now = get_now_utc_pendulum() if (not self._stack): raise AssertionError('MultiTimer.stop() when nothing running') if (self._stack[(- 1)] != name): raise AssertionError('MultiTimer.stop({}) when {} is running'.format...
Stop a named timer. Args: name: timer to stop
codesearchnet
def word_list(sowpods=False, start="", end=""): location = os.path.join( os.path.dirname(os.path.realpath(__file__)), "wordlists", ) if sowpods: filename = "sowpods.txt" else: filename = "twl.txt" filepath = os.path.join(location, filename) with open(file...
Opens the word list file. Args: sowpods: a boolean to declare using the sowpods list or TWL (default) start: a string of starting characters to find anagrams based on end: a string of ending characters to find anagrams based on Yeilds: a word at a time out of 178691 words for TWL, 267751 for sowpods. Much less if eit...
juraj-google-style
def __init__(self, n, key=None, reverse=False): self._n = n self._key = key self._reverse = reverse
Creates a per-key Top operation. The arguments 'key' and 'reverse' may be passed as keyword arguments, and have the same meaning as for Python's sort functions. Args: n: number of elements to extract from pcoll. key: (optional) a mapping of elements to a comparable key, similar to the key argument of Python's sorting...
github-repos
def set_data(self, data): for name in self._fields: setattr(self, name, data.get(name)) return self
Fills form with data Args: data (dict): Data to assign form fields. Returns: Self. Form object.
juraj-google-style
def Compile(self, filter_implementation): self.attribute = self.swap_source.get(self.attribute, self.attribute) arguments = [self.attribute] op_str = self.operator.lower() operator = filter_implementation.OPS.get(op_str, None) if (not operator): raise errors.ParseError('Unknown operator {0:s...
Compiles the filter implementation. Args: filter_implementation: a filter object (instance of objectfilter.TODO). Returns: A filter operator (instance of TODO). Raises: ParserError: if an unknown operator is provided.
codesearchnet
def _unsorted_segment_N(data, segment_ids, num_segments): num_segments = ops.convert_to_tensor(num_segments) segment_ids_shape = array_ops.shape_internal(segment_ids) ones_tensor = array_ops.ones(segment_ids_shape, dtype=data.dtype) n = gen_math_ops.unsorted_segment_sum(ones_tensor, segment_ids, num_seg...
Helper function for unsorted_segment_mean/_sqrtN. Computes the number of segment entries with 0-entries set to 1 to allow division by N. Args: data: A `Tensor` with data that will be assembled in the output. segment_ids: An integer tensor whose shape is a prefix of `data.shape`. The values must be in the range `[0, n...
github-repos
def set_epsilon(value): global _EPSILON _EPSILON = value
Set the value of the fuzz factor used in numeric expressions. Args: value: float. New value of epsilon. Examples: >>> keras.config.epsilon() 1e-07 >>> keras.config.set_epsilon(1e-5) >>> keras.config.epsilon() 1e-05 >>> # Set it back to the default value. >>> keras.config.set_epsilon(1e-7)
github-repos
async def addNode(self, name, valu, props=None): try: fnib = self._getNodeFnib(name, valu) retn = await self._addNodeFnib(fnib, props=props) return retn except asyncio.CancelledError: raise except Exception: mesg = f'Error...
Add a node by form name and value with optional props. Args: name (str): The form of node to add. valu (obj): The value for the node. props (dict): Optional secondary properties for the node.
juraj-google-style
def are_equal_xml(a_xml, b_xml): a_dom = xml.dom.minidom.parseString(a_xml) b_dom = xml.dom.minidom.parseString(b_xml) return are_equal_elements(a_dom.documentElement, b_dom.documentElement)
Normalize and compare XML documents for equality. The document may or may not be a DataONE type. Args: a_xml: str b_xml: str XML documents to compare for equality. Returns: bool: ``True`` if the XML documents are semantically equivalent.
juraj-google-style
def coresight_configure(self, ir_pre=0, dr_pre=0, ir_post=0, dr_post=0, ir_len=0, perform_tif_init=True): if (self.tif == enums.JLinkInterfaces.SWD): res = self._dll.JLINKARM_CORESIGHT_Configure('') if (res < 0): raise errors.JLinkException(res) return None config_string = 'I...
Prepares target and J-Link for CoreSight function usage. Args: self (JLink): the ``JLink`` instance ir_pre (int): sum of instruction register length of all JTAG devices in the JTAG chain, close to TDO than the actual one, that J-Link shall communicate with dr_pre (int): number of JTAG devices in the JTAG chain, closer...
codesearchnet
def FormatTypeSummaryTable(self, level_name, name_to_problist): output = [] output.append('<table>') for classname in sorted(name_to_problist.keys()): problist = name_to_problist[classname] human_name = MaybePluralizeWord(problist.count, UnCamelCase(classname)) output.append(('<tr><t...
Return an HTML table listing the number of problems by class name. Args: level_name: string such as "Error" or "Warning" name_to_problist: dict mapping class name to an BoundedProblemList object Returns: HTML in a string
codesearchnet
def __init__(self, channel): self.Health = channel.unary_unary( '/health.Health/Health', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, )
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def escape(inp, quote='"'): output = "" for c in inp: if c == quote: output += '\\' output += c return output
Escape `quote` in string `inp`. Example usage:: >>> escape('hello "') 'hello \\"' >>> escape('hello \\"') 'hello \\\\"' Args: inp (str): String in which `quote` will be escaped. quote (char, default "): Specify which character will be escaped. Returns: str: Escaped string.
juraj-google-style
def _create_controller_info_record(self, controller_module_name): module = self._controller_modules[controller_module_name] controller_info = None try: controller_info = module.get_info(copy.copy(self._controller_objects[controller_module_name])) except AttributeError: logging.warning('N...
Creates controller info record for a particular controller type. Info is retrieved from all the controller objects spawned from the specified module, using the controller module's `get_info` function. Args: controller_module_name: string, the name of the controller module to retrieve info from. Returns: A records.Co...
github-repos
def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False): if os.path.isfile(filename) and overwrite == False: data_dict = load_b26_file(filename) else: data_dict = {} if instruments is not None: if 'instruments' in data_dict...
save instruments, scripts and probes as a json file Args: filename: instruments: scripts: probes: dictionary of the form {instrument_name : probe_1_of_intrument, probe_2_of_intrument, ...} Returns:
juraj-google-style
def validate(self, corpus): passed = True results = {} for validator in self.validators: sub_result = validator.validate(corpus) results[validator.name()] = sub_result if not sub_result.passed: passed = False return Combine...
Perform validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate.
juraj-google-style
def GetSortedEvents(self, time_range=None): if not self._storage_file: raise IOError('Unable to read from closed storage writer.') return self._storage_file.GetSortedEvents(time_range=time_range)
Retrieves the events in increasing chronological order. This includes all events written to the storage including those pending being flushed (written) to the storage. Args: time_range (Optional[TimeRange]): time range used to filter events that fall in a specific period. Returns: generator(EventObject): event gener...
juraj-google-style
def validate(request: Union[(Dict, List)], schema: dict) -> Union[(Dict, List)]: jsonschema_validate(request, schema) return request
Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationError
codesearchnet
def __init__(self, min_obs=10): self.min_obs = min_obs self.label_encoder = LabelEncoder(min_obs)
Initialize the OneHotEncoder class object. Args: min_obs (int): minimum number of observation to create a dummy variable label_encoder (LabelEncoder): LabelEncoder that transofrm
juraj-google-style
def removeRow(self, triggered): if triggered: model = self.tableView.model() selection = self.tableView.selectedIndexes() rows = [index.row() for index in selection] model.removeDataFrameRows(set(rows)) self.sender().setChecked(False)
Removes a row to the model. This method is also a slot. Args: triggered (bool): If the corresponding button was activated, the selected row will be removed from the model.
juraj-google-style
def overlay(self, feature, color='Blue', opacity=0.6): result = self.copy() if (type(feature) == Table): if ('feature' in feature): feature = feature['feature'] else: feature = Circle.map_table(feature) if (type(feature) in [list, np.ndarray]): for f in featur...
Overlays ``feature`` on the map. Returns a new Map. Args: ``feature``: a ``Table`` of map features, a list of map features, a Map, a Region, or a circle marker map table. The features will be overlayed on the Map with specified ``color``. ``color`` (``str``): Color of feature. Defaults to 'Blue' ``opacity`` (``float...
codesearchnet
def get_vulnerability(source, sink, triggers, lattice, cfg, interactive, blackbox_mapping): nodes_in_constraint = [secondary for secondary in reversed(source.secondary_nodes) if lattice.in_constraint(secondary, sink.cfg_node)] nodes_in_constraint.append(source.cfg_node) if sink.trigger.all_arguments_propaga...
Get vulnerability between source and sink if it exists. Uses triggers to find sanitisers. Note: When a secondary node is in_constraint with the sink but not the source, the secondary is a save_N_LHS node made in process_function in expr_visitor. Args: source(TriggerNode): TriggerNode of the source. sink(TriggerNode)...
codesearchnet