code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def from_features(cls, features, types): params = cls() if features: for key in sorted(features.keys()): feature = features[key] if not isinstance(feature, tuple(types)): raise ValueError(f"Unsupported {type(feature).__name__} {feature} for key '{key}'") ...
Builds _ParseOpParams for a given set of features and allowed types. Args: features: A `dict` mapping feature keys to objects of a type in `types`. types: Type of features to allow, among `FixedLenFeature`, `VarLenFeature`, `SparseFeature`, and `FixedLenSequenceFeature`. Returns: A `_ParseOpParams` containing the raw...
github-repos
def download(self, folder=None): url = self.data.get('url', None) if not url: raise HDXError('No URL to download!') logger.debug('Downloading %s' % url) filename = self.data['name'] format = '.%s' % self.data['format'] if format not ...
Download resource store to provided folder or temporary folder if no folder supplied Args: folder (Optional[str]): Folder to download resource to. Defaults to None. Returns: Tuple[str, str]: (URL downloaded, Path to downloaded file)
juraj-google-style
def abort_collective_ops(self, code, message): self.ensure_initialized() pywrap_tfe.TFE_AbortCollectiveOps(self._handle, code, message)
Abort the collective ops. This is intended to be used when a peer failure is detected, which allows the user to handle the case instead of hanging. This aborts all on-going collectives. After all subsequent collectives error immediately, and you need to reset_context() to use collectives again. Args: code: a `tf.erro...
github-repos
def base256_encode(n, minwidth=0): if n > 0: arr = [] while n: n, rem = divmod(n, 256) arr.append(rem) b = bytearray(reversed(arr)) elif n == 0: b = bytearray(b'\x00') else: raise ValueError("Negative numbers not supported") if minw...
Encode the input with base256. Args: n (int): input value. minwidth: minimum return value length. Raises: ValueError: if a negative number is provided. Returns: bytearray:
juraj-google-style
def search_track(self, artist, album=None, track=None, full_album_art_uri=False): subcategories = [artist] subcategories.append(album or '') result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subca...
Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default ...
juraj-google-style
def diff_compute(self, text1, text2, checklines, deadline): if (not text1): return [(self.DIFF_INSERT, text2)] if (not text2): return [(self.DIFF_DELETE, text1)] if (len(text1) > len(text2)): (longtext, shorttext) = (text1, text2) else: (shorttext, longtext) = (text1, tex...
Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't run a line-level diff first to identify the changed areas. If true, then run a faster, slightly ...
codesearchnet
def __init__(self, exclude_columns, coder=coders.registry.get_coder(Any)): self.coder = coder self.exclude_columns = exclude_columns
Encodes/decodes items of a dictionary into a single element. Args: exclude_columns: list of columns to exclude from the encoding.
github-repos
def old_format(self, content: BeautifulSoup) -> List[str]: b = content.find('body') sender, date, nxt, rep_to = None, None, None, None strongs = b.findAll('strong', recursive=False) for s in strongs: field = str(s).split(">")[1].split("<")[0] if...
Extracts email message information if it uses the old Mailman format Args: content: BeautifulSoup Returns: List[str]
juraj-google-style
def CompileReport(self, mediator): lines_of_text = ['Listing domains visited by all users'] for domain in sorted(self._domains): lines_of_text.append(domain) lines_of_text.append('') report_text = '\n'.join(lines_of_text) return reports.AnalysisReport(plugin_name=self.NAME, text=report_t...
Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: the analysis report.
juraj-google-style
def subprogram_prototype(vo): plist = '; '.join(str(p) for p in vo.parameters) if isinstance(vo, VhdlFunction): if len(vo.parameters) > 0: proto = 'function {}({}) return {};'.format(vo.name, plist, vo.return_type) else: proto = 'function {} return {};'.format(vo.name, vo.return_type) el...
Generate a canonical prototype string Args: vo (VhdlFunction, VhdlProcedure): Subprogram object Returns: Prototype string.
juraj-google-style
def _pretty_print(data_item, summarize): if isinstance(data_item, tensor_lib.Tensor): arr = data_item.numpy() if np.isscalar(arr): return str(arr) else: flat = arr.reshape((-1,)) lst = [str(x) for x in flat[:summarize]] if len(lst) < flat.size:...
Format a data item for use in an error message in eager mode. Args: data_item: One of the items in the "data" argument to an assert_* function. Can be a Tensor or a scalar value. summarize: How many elements to retain of each tensor-valued entry in data. Returns: An appropriate string representation of data_item
github-repos
def transform_kernels(kernels, func, n_gates): return np.hstack([func(k) for k in np.hsplit(kernels, n_gates)])
Transforms kernel for each gate separately using given function. Args: kernels: Stacked array of kernels for individual gates. func: Function applied to kernel of each gate. n_gates: Number of gates (4 for LSTM, 3 for GRU). Returns: Stacked array of transformed kernels.
github-repos
def create_asset_accesspolicy(access_token, name, duration, permission='1'): path = '/AccessPolicies' endpoint = ''.join([ams_rest_endpoint, path]) body = (((((('{ \t\t"Name": "' + str(name)) + '", \t\t"DurationInMinutes": "') + duration) + '", \t\t"Permissions": "') + permission) + '" \t}') return do_a...
Create Media Service Asset Access Policy. Args: access_token (str): A valid Azure authentication token. name (str): A Media Service Asset Access Policy Name. duration (str): A Media Service duration. permission (str): A Media Service permission. Returns: HTTP response. JSON body.
codesearchnet
def _infer_hints_allowing_override(op1, op2, hints): hints = hints or _Hints() if hints.is_self_adjoint is None: is_self_adjoint = op1.is_self_adjoint and op2.is_self_adjoint else: is_self_adjoint = hints.is_self_adjoint if hints.is_positive_definite is None: is_positive_definite...
Infer hints from op1 and op2. hints argument is an override. Args: op1: LinearOperator op2: LinearOperator hints: _Hints object holding "is_X" boolean hints to use for returned operator. If some hint is None, try to set using op1 and op2. If the hint is provided, ignore op1 and op2 hints. This allows an override...
github-repos
def visible(self): query_results = self.map((lambda el: el.is_displayed()), 'visible').results if query_results: return all(query_results) return False
Check whether all matched elements are visible. Returns: bool
codesearchnet
def export_json(data, status, headers): dumped = json.dumps(data, ensure_ascii=False) resp = current_app.response_class(dumped, status=status, headers=headers, content_type='application/json; charset=utf-8') return resp
Creates a JSON response JSON content is encoded by utf-8, not unicode escape. Args: data: any type object that can dump to json status (int): http status code headers (dict): http headers
codesearchnet
def handle_enterprise_logistration(backend, user, **kwargs): request = backend.strategy.request enterprise_customer = get_enterprise_customer_for_running_pipeline(request, {'backend': backend.name, 'kwargs': kwargs}) if (enterprise_customer is None): return (enterprise_customer_user, _) = Enterp...
Perform the linking of user in the process of logging to the Enterprise Customer. Args: backend: The class handling the SSO interaction (SAML, OAuth, etc) user: The user object in the process of being logged in with **kwargs: Any remaining pipeline variables
codesearchnet
def add(self, text, checked=False, sort=None): node = ListItem(parent_id=self.id, parent_server_id=self.server_id) node.checked = checked node.text = text if sort is not None: node.sort = sort self.append(node, True) self.touch(True) return no...
Add a new item to the list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting.
juraj-google-style
def discount_bond_price(self, state: types.RealTensor, times: types.RealTensor, maturities: types.RealTensor, name: str=None) -> types.RealTensor: name = name or self._name + '_discount_bond_prices' with tf.name_scope(name): x_t = tf.convert_to_tensor(state, self._dtype) times = tf.convert_to_te...
Returns zero-coupon bond prices `P(t,T)` conditional on `x(t)`. Args: state: A `Tensor` of real dtype and shape compatible with `(num_times, dim)` specifying the state `x(t)`. times: A `Tensor` of real dtype and shape `(num_times,)`. The time `t` at which discount bond prices are computed. maturities: A `Tensor` of re...
github-repos
def get_summary(result): summary = {'success': result.wasSuccessful(), 'stat': {'total': result.testsRun, 'failures': len(result.failures), 'errors': len(result.errors), 'skipped': len(result.skipped), 'expectedFailures': len(result.expectedFailures), 'unexpectedSuccesses': len(result.unexpectedSuccesses)}} sum...
get summary from test result Args: result (instance): HtmlTestResult() instance Returns: dict: summary extracted from result. { "success": True, "stat": {}, "time": {}, "records": [] }
codesearchnet
def encode(self, input_audio, start_level=0, end_level=None, bs_chunks=1): audio_chunks = torch.chunk(input_audio, bs_chunks, dim=0) music_tokens_list = [] for chunk_i in audio_chunks: music_tokens_i = self._encode(chunk_i, start_level=start_level, end_level=end_level) music_tokens_list.appe...
Transforms the `input_audio` to a discrete representation made out of `music_tokens`. Args: input_audio (`torch.Tensor`): Raw audio which will be encoded to its discrete representation using the codebook. The closest `code` form the codebook will be computed for each sequence of samples. start_level (`int`, *optional*...
github-repos
def __init__(self, time_elements_tuple=None): fraction_of_second = None if time_elements_tuple: if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) millis...
Initializes time elements. Args: time_elements_tuple (Optional[tuple[int, int, int, int, int, int, int]]): time elements, contains year, month, day of month, hours, minutes, seconds and milliseconds. Raises: ValueError: if the time elements tuple is invalid.
juraj-google-style
def useQt(qtLib: str = 'PyQt5', period: float = 0.01): def qt_step(): loop.call_later(period, qt_step) if not stack: qloop = QEventLoop() timer = QTimer() timer.timeout.connect(qloop.quit) stack.append((qloop, timer)) qloop, timer = stack....
Run combined Qt5/asyncio event loop. Args: qtLib: Name of Qt library to use, can be 'PyQt5' or 'PySide2'. period: Period in seconds to poll Qt.
juraj-google-style
def percentile(self, percent): if percent >= 100: percent = 100 target = len(self) - len(self) * (percent / 100) for k in reversed(sorted(self._data.keys())): target -= self._data[k] if target < 0: ...
Return the value that is the Nth precentile in the histogram. Args: percent (Union[int, float]): The precentile being sought. The default consumer implementations use consistently use ``99``. Returns: int: The value corresponding to the requested percentile.
juraj-google-style
def _new_population_genalg(population, fitnesses, mutation_chance=0.02, crossover_chance=0.7, selection_function=gaoperators.tournament_selection, crossover_function=gaoperators.one_point_crossover): intermediate_population = selection_function(population, fitnesses) new_population = _crossover(intermediate_pop...
Perform all genetic algorithm operations on a population, and return a new population. population must have an even number of chromosomes. Args: population: A list of binary lists, ex. [[0,1,1,0], [1,0,1,0]] fitness: A list of fitnesses that correspond with chromosomes in the population, ex. [1.2, 10.8] mutation_chan...
codesearchnet
def Unregister(self, name): precondition.AssertType(name, Text) try: del self._constructors[name] except KeyError: raise ValueError(("Constructor with name '%s' is not registered" % name))
Unregisters a constructor. Args: name: A name of the constructor to unregister. Raises: ValueError: If constructor with specified name has never been registered.
codesearchnet
class MaxTimeCriteria(StoppingCriteria): def __init__(self, max_time: float, initial_timestamp: Optional[float]=None): self.max_time = max_time self.initial_timestamp = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING) ...
This class can be used to stop generation whenever the full generation exceeds some amount of time. By default, the time will start being counted when you initialize this function. You can override this by passing an `initial_time`. Args: max_time (`float`): The maximum allowed time in seconds for the generation. init...
github-repos
def ch_duration(self, *channels: List[Channel]) -> int: return self.timeslots.ch_duration(*channels)
Return duration of supplied channels. Args: *channels: Supplied channels
juraj-google-style
def add_arguments(cls, parser): parser.add_argument( '-c', '--create-missing-tasks', action='store_true', dest='create_missing_tasks', help="[sync] create asana tasks for issues without tasks" ) parser.add_argument( '-l',...
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 quick_execute(op_name, num_outputs, inputs, attrs, ctx, name=None): device_name = ctx.device_name try: ctx.ensure_initialized() tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, inputs, attrs, num_outputs) except core._NotOkStatusException as e: if name is no...
Execute a TensorFlow operation. Args: op_name: Name of the TensorFlow operation (see REGISTER_OP in C++ code) to execute. num_outputs: The number of outputs of the operation to fetch. (Explicitly provided instead of being inferred for performance reasons). inputs: A list of inputs to the operation. Each entry should b...
github-repos
def load_object(obj) -> object: if isinstance(obj, str): if (':' in obj): (module_name, obj_name) = obj.split(':') if (not module_name): module_name = '.' else: module_name = obj obj = importlib.import_module(module_name) if obj_nam...
Load an object. Args: obj (str|object): Load the indicated object if this is a string; otherwise, return the object as is. To load a module, pass a dotted path like 'package.module'; to load an an object from a module pass a path like 'package.module:name'. Returns: object
codesearchnet
def map_err(self, op: Callable[[E], F]) -> 'Union[Result[T, F], Result[T, E]]': return self if self._is_ok else cast( 'Result[T, F]', self._type.Err(op(cast(E, self._val))) )
Applies a function to the contained :meth:`Result.Err` value. Args: op: The function to apply to the :meth:`Result.Err` value. Returns: A :class:`Result` with its error value as the function result if `self` is a :meth:`Result.Err` value, otherwise returns `self`. Examples: >>> Ok(1).map_err(lambda x: x * 2) Ok(1) >...
juraj-google-style
def cv_squared(x): epsilon = 1e-10 float_size = (tf.to_float(tf.size(x)) + epsilon) mean = (tf.reduce_sum(x) / float_size) variance = (tf.reduce_sum(tf.squared_difference(x, mean)) / float_size) return (variance / (tf.square(mean) + epsilon))
The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`.
codesearchnet
def load_module(self, namespace, module_name): try: filename, src = self.typeshed.get_module_file(namespace, module_name, self.options.python_version) except OSError: return (None, None) ast = parser.parse_string(src, filename=filename, name=module_name, options=self.options) return (fil...
Load and parse a *.pyi from typeshed. Args: namespace: one of "stdlib" or "third_party" module_name: the module name (without any file extension or "__init__" suffix). Returns: (None, None) if the module doesn't have a definition. Else a tuple of the filename and the AST of the module.
github-repos
def add_spin_by_site(self, spins): if (len(spins) != len(self.sites)): raise ValueError('Spin of all sites must be specified in the dictionary.') for (site, spin) in zip(self.sites, spins): new_sp = {} for (sp, occu) in site.species.items(): sym = sp.symbol oxi_st...
Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0]
codesearchnet
def get_flights(self, search_key): url = AIRLINE_FLT_BASE.format(search_key, 100) return self._fr24.get_airline_flight_data(url)
Get the flights for a particular airline. Given a full or partial flight number string, this method returns the first 100 flights matching that string. Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline Args: search_k...
codesearchnet
def _beam_decode(self, features, decode_length, beam_size, top_beams, alpha, use_tpu=False): return self._beam_decode_slow(features, decode_length, beam_size, top_beams, alpha, use_tpu)
Beam search decoding. Models should ideally implement a more efficient version of this function. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. beam_size: number of beams. top_beams: an integer. How many of the beams to return. alpha: Float that contr...
codesearchnet
def _verify_setup(self): if not self._is_chief: for op in self._graph.get_operations(): if op.type in ['Variable', 'VariableV2'] and (not op.device): raise ValueError('When using replicas, all Variables must have their device set: %s' % op)
Check that all is good. Raises: ValueError: If something is not good.
github-repos
def delete_customer(self, customer_id): return self.client._delete(self.url + 'customers/{}'.format(customer_id), headers=self.get_headers())
Removes a user from the system. Args: customer_id: Identifier of the client to be deleted. Returns:
juraj-google-style
def __init__(self, latitude, longitude, comment=None): super(Xearth, self).__init__(latitude, longitude) self.comment = comment
Initialise a new ``Xearth`` object. Args: latitude (float): Location's latitude longitude (float): Location's longitude comment (str): Comment for location
juraj-google-style
def list_files(file_directory, file_extensions=None, include_subfolders=True, include_root=True, root_dir=None): log = logging.getLogger("%s" % (inspect.stack()[0][3])) log.setLevel(__LOG_LEVEL__) rtn_list = [] if not root_dir: r...
Returns a list of files args: file_directory: a sting path to the file directory file_extensions: a list of file extensions to filter example ['xml', 'rdf']. If none include all files include_subfolders: as implied include_root: whether to include the root in the path root_dir: the root directory to remove if include_...
juraj-google-style
def dict_load(self, ns_dict): for (prefix, uri) in ns_dict.items(): self.bind(prefix, uri, override=False, calc=False) self.__make_dicts__
Reads a dictionary of namespaces and binds them to the manager Args: ns_dict: dictionary with the key as the prefix and the value as the uri
codesearchnet
def nth(series, n, order_by=None): if (order_by is not None): series = order_series_by(series, order_by) try: return series.iloc[n] except: return np.nan
Returns the nth value of a series. Args: series (pandas.Series): column to summarize. n (integer): position of desired value. Returns `NaN` if out of range. Kwargs: order_by: a pandas.Series or list of series (can be symbolic) to order the input series by before summarization.
codesearchnet
def get_log_file_timestamp(delta=None): return _get_timestamp('%m-%d-%Y_%H-%M-%S-%f', delta)
Returns a timestamp in the format used for log file names. Default is current time. If a delta is set, the return value will be the current time offset by delta seconds. Args: delta: Number of seconds to offset from current time; can be negative. Returns: A timestamp in log filen name format with an offset.
github-repos
def Decompress(self, compressed_data): try: if hasattr(lzma, 'LZMA_VERSION'): uncompressed_data = self._lzma_decompressor.decompress( compressed_data, 0) else: uncompressed_data = self._lzma_decompressor.decompress(compressed_data) remaining_comp...
Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the XZ compressed stream cannot be decompressed.
juraj-google-style
def map_kegg_all_genes(organism_code, target_db): mapping = bs_kegg.conv(target_db, organism_code) new_mapping = {} for (k, v) in mapping.items(): new_mapping[k.replace((organism_code + ':'), '')] = str(v.split(':')[1]) return new_mapping
Map all of an organism's gene IDs to the target database. This is faster than supplying a specific list of genes to map, plus there seems to be a limit on the number you can map with a manual REST query anyway. Args: organism_code: the three letter KEGG code of your organism target_db: ncbi-proteinid | ncbi-geneid | ...
codesearchnet
def __init__(self, option=None, default=None, *args, **kwargs): super(ListOption, self).__init__(*args, **kwargs) if not isinstance(option, opt.Option): raise TypeError("Option must be an option type.") self._option = option self._default = default if defa...
Initialize the option with an option type. Args: option (option.Option): The option which is used to validate all list options. Raises: TypeError: If the given option is not an instance of option.Option. TypeError: If the default value is set but not an iterable.
juraj-google-style
def copy(self, dest): if os.path.isfile(self.path): shutil.copy2(self.path, dest) else: shutil.copytree(self.path, dest, symlinks=False, ignore=None)
Copy item to the given `dest` path. Args: * dest: destination path to copy.
codesearchnet
def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BILINEAR, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray: size = get_size_dict(size, default_to_square=False) ...
Resize an image. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its shortest edge of length `s...
github-repos
def _group_chunks_by_entities(self, chunks, entities): for entity in entities: chunks_to_concat = chunks.get_overlaps( entity['beginOffset'], len(entity['content'])) if not chunks_to_concat: continue new_chunk_word = u''.join([chunk.word for chunk in chunks_to_concat]) ...
Groups chunks by entities retrieved from NL API Entity Analysis. Args: chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed. entities (:obj:`list` of :obj:`dict`): List of entities. Returns: A chunk list. (:obj:`budou.chunk.ChunkList`)
juraj-google-style
def get_dropout_mask_for_cell(self, inputs, training, count=1): if self.dropout == 0: return None init_kwargs = dict(inputs=inputs, training=training, count=count) return self._dropout_mask_cache.setdefault(kwargs=init_kwargs)
Get the dropout mask for RNN cell's input. It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell. Args: inputs: The input tensor whose shape will be used to generate dropout mask. training: Boolean tensor, whether its in training...
github-repos
def _SanitizedMRO(obj): return_list = [] for cls in tf_inspect.getmro(obj): if cls.__name__ == '_NewClass': continue str_repr = _NormalizeType(str(cls)) return_list.append(str_repr) if 'tensorflow' not in str_repr and 'keras' not in str_repr: break ...
Get a list of superclasses with minimal amount of non-TF classes. Based on many parameters like python version, OS, protobuf implementation or changes in google core libraries the list of superclasses of a class can change. We only return the first non-TF class to be robust to non API affecting changes. The Method Res...
github-repos
def SetTimelineOwner(self, username): self._timeline_owner = username logger.info('Owner of the timeline: {0!s}'.format(self._timeline_owner))
Sets the username of the user that should own the timeline. Args: username (str): username.
codesearchnet
def add_property(self, set_property, name, starting_value, tag_name=None): def del_property(self, tag_name): try: del self._content[tag_name] except KeyError: pass def get_property(self, tag_name): try: return self._content[tag_name] except K...
Set properies of atributes stored in content using stored common fdel and fget and given fset. Args: set_property -- Function that sets given property. name -- Name of the atribute this property must simulate. Used as key in content dict by default. starting_value -- Starting value of given property. Keyword args: ta...
codesearchnet
def setup_prefix_logging(logdir): if not os.path.exists(logdir): os.mkdir(logdir) file_handler = logging.FileHandler( filename=os.path.join(logdir, 'lago.log'), ) file_formatter = get_default_log_formatter() file_handler.setFormatter(file_formatter) logging.root.addHandler(...
Sets up a file logger that will create a log in the given logdir (usually a lago prefix) Args: logdir (str): path to create the log into, will be created if it does not exist Returns: None
juraj-google-style
def query( self, url: Union[str, methods], data: Optional[MutableMapping] = None, headers: Optional[MutableMapping] = None, as_json: Optional[bool] = None, ) -> dict: url, body, headers = sansio.prepare_request( url=url, data=data, ...
Query the slack API When using :class:`slack.methods` the request is made `as_json` if available Args: url: :class:`slack.methods` or url string data: JSON encodable MutableMapping headers: Custom headers as_json: Post JSON to the slack API Returns: dictionary of slack API response data
juraj-google-style
async def msetup(self, text_channel): if self.mready: logger.warning('Attempt to init music when already initialised') return if (self.state != 'starting'): logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debu...
Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in
codesearchnet
async def on_message(message): server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return if server is not None ...
The on_message event handler for this module Args: message (discord.Message): Input message
juraj-google-style
def Matches(self, registry_key, search_depth): if (self._key_path_segments is None): key_path_match = None else: key_path_match = self._CheckKeyPath(registry_key, search_depth) if (not key_path_match): return (False, key_path_match) if (search_depth != self._number_of...
Determines if the Windows Registry key matches the find specification. Args: registry_key (WinRegistryKey): Windows Registry key. search_depth (int): number of key path segments to compare. Returns: tuple: contains: bool: True if the Windows Registry key matches the find specification, False otherwise. bool: True if...
codesearchnet
def get_data_dirs(__pkg: str) -> List[str]: dirs = [user_data(__pkg)] dirs.extend((path.expanduser(path.sep.join([d, __pkg])) for d in getenv('XDG_DATA_DIRS', '/usr/local/share/:/usr/share/').split(':'))) return [d for d in dirs if path.isdir(d)]
Return all data directories for given package. Args: __pkg: Package name
codesearchnet
def _init_pfor(self, parent_pfor, indices, cond_stacked, inputs, inputs_stacked): num_outputs = len(self._outputs) assert len(inputs) == len(self._enters) assert len(inputs_stacked) == len(self._enters) loop_var = parent_pfor.loop_var loop_len = array_ops.size(indices) pfor = PFor(loop_var, loop...
Create a PFor object for converting parts of the while_loop. Args: parent_pfor: PFor object being used for converting the while_loop. indices: int32 Tensor of ids for the iterations that are still active (i.e. did not exit the while_loop). cond_stacked: True if the while_loop condition is stacked. inputs: list of inpu...
github-repos
def stop_on_exception(self): return self._coord.stop_on_exception()
Context handler to stop the supervisor when an exception is raised. See `Coordinator.stop_on_exception()`. Returns: A context handler.
github-repos
def observations(self, main_type, sub_type, unique_id, owner=None, params=None): params = params or {} if owner: params['owner'] = owner if not sub_type: url = '/v2/{}/{}/observations'.format(main_type, unique_id) else: url = '/v2/{}/{}/{}/o...
Args: main_type: sub_type: unique_id: owner: params: Return:
juraj-google-style
def _pick_unused_port_without_server(): rng = random.Random() for _ in range(10): port = int(rng.randrange(15000, 25000)) if is_port_free(port): _random_ports.add(port) return port for _ in range(10): port = bind(0, _PROTOS[0][0], _PROTOS[0][1]) if (po...
Pick an available network port without the help of a port server. This code ensures that the port is available on both TCP and UDP. This function is an implementation detail of PickUnusedPort(), and should not be called by code outside of this module. Returns: A port number that is unused on both TCP and UDP. Raise...
codesearchnet
def send_log_message(self, message: LogMessage) -> None: print(message)
Prints the log message to be captured by cloud logging. Args: * message: LogMessage dictionary Returns: * None
github-repos
def write_worksheets(workbook, data_list, result_info_key, identifier_keys): worksheet_keys = get_worksheet_keys(data_list[0], result_info_key) for key in worksheet_keys: title = key.split('/')[1] title = utilities.convert_snake_to_title_case(title) title = KEY_TO_WORKSHEET_MAP.get(title...
Writes rest of the worksheets to workbook. Args: workbook: workbook to write into data_list: Analytics API data as a list of dicts result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc)
codesearchnet
def _ParseFileData(self, knowledge_base, file_object): text_file_object = dfvfs_text_file.TextFile(file_object, encoding='utf-8') system_product = text_file_object.readline() if system_product.startswith('Debian GNU/Linux '): system_product, _, _ = system_product.partition('\\') syst...
Parses file content (data) for system product preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_object (dfvfs.FileIO): file-like object that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessing fails.
juraj-google-style
def read_binary_array(self, key, b64decode=True, decode=False): data = None if (key is not None): data = self.db.read(key.strip()) if (data is not None): data_decoded = [] for d in json.loads(data, object_pairs_hook=OrderedDict): if b64decode: ...
Read method of CRUD operation for binary array data. Args: key (string): The variable to read from the DB. b64decode (bool): If true the data will be base64 decoded. decode (bool): If true the data will be decoded to a String. Returns: (list): Results retrieved from DB.
codesearchnet
def js_adaptor(buffer): buffer = re.sub('true', 'True', buffer) buffer = re.sub('false', 'False', buffer) buffer = re.sub('none', 'None', buffer) buffer = re.sub('NaN', '"NaN"', buffer) return buffer
convert javascript objects like true, none, NaN etc. to quoted word. Arguments: buffer: string to be converted Returns: string after conversion
juraj-google-style
def extraterrestrial_horizontal_radiation(self, value=9999.0): if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `extraterre...
Corresponds to IDD Field `extraterrestrial_horizontal_radiation` Args: value (float): value for IDD Field `extraterrestrial_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: ...
juraj-google-style
def get_elements_iterable(self, make_copy: bool=False) -> Iterable[WindowedValue]: if not self._stacked: elements = cast('List[WindowedValue]', self._elements) if self._committed and (not make_copy): return elements return list(elements) def iterable_stacked_or_elements(elem...
Returns iterable elements. Args: make_copy: whether to force returning copy or yielded iterable. Returns: unstacked elements, in the form of iterable if committed and make_copy is not True, or as a list of copied WindowedValues.
github-repos
def find_labels(model_class): model_name = model_class.__name__ framework = infer_framework(model_class) if framework == 'tf': signature = inspect.signature(model_class.call) elif framework == 'pt': signature = inspect.signature(model_class.forward) else: signature = inspect....
Find the labels used by a given model. Args: model_class (`type`): The class of the model.
github-repos
def __call__(self, shape, dtype=dtypes.float32, **kwargs): self._validate_kwargs(kwargs) dtype = _assert_float_dtype(dtype) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] return self._random_generator.truncated_normal(shape, self.mean, self.stddev, dtype)
Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. **kwargs: Additional keyword arguments. Raises: ValueError: If the dtype is not floating point
github-repos
def get_form_energy(self, entry): c = entry.composition return entry.energy - sum([c[el] * self.el_refs[el].energy_per_atom for el in c.elements])
Returns the formation energy for an entry (NOT normalized) from the elemental references. Args: entry: A PDEntry-like object. Returns: Formation energy from the elemental references.
juraj-google-style
def files_upload(self, *, file: Union[(str, IOBase)]=None, content: str=None, **kwargs) -> SlackResponse: if ((file is None) and (content is None)): raise e.SlackRequestError('The file or content argument must be specified.') if ((file is not None) and (content is not None)): raise e.SlackReques...
Uploads or creates a file. Args: file (str): Supply a file path. when you'd like to upload a specific file. e.g. 'dramacat.gif' content (str): Supply content when you'd like to create an editable text file containing the specified text. e.g. 'launch plan' Raises: SlackRequestError: If niether or both the `file` and `c...
codesearchnet
def _build(self, inputs, is_training=True, dropout_keep_prob=0.5): self._input_shape = tuple(inputs.get_shape().as_list()) net = inputs final_index = (self._num_layers - 1) for layer_id in xrange(self._num_layers): net = self._layers[layer_id](net) if ((final_index != layer_id) or self._...
Assembles the `MLP` and connects it to the graph. Args: inputs: A 2D Tensor of size `[batch_size, input_size]`. is_training: A bool or tf.Bool Tensor. Indicates whether we are currently training. Defaults to `True`. dropout_keep_prob: The probability that each element is kept when both `use_dropout` and `is_training` ...
codesearchnet
def insert(cls, cur, table: str, values: dict): keys = cls._COMMA.join(values.keys()) value_place_holder = cls._PLACEHOLDER * len(values) query = cls._insert_string.format(table, keys, value_place_holder[:-1]) yield from cur.execute(query, tuple(values.values())) return ...
Creates an insert statement with only chosen fields Args: table: a string indicating the name of the table values: a dict of fields and values to be inserted Returns: A 'Record' object with table columns as properties
juraj-google-style
def _get_corrupted_example(self, x): corruption_type = self.builder_config.corruption_type severity = self.builder_config.severity return { 'gaussian_noise': corruptions.gaussian_noise, 'shot_noise': corruptions.shot_noise, 'impulse_noise': corruptions.impulse_noise, 'd...
Return corrupted images. Args: x: numpy array, uncorrupted image. Returns: numpy array, corrupted images.
juraj-google-style
def mme_nodes(mme_base_url, token): nodes = [] if not mme_base_url or not token: return nodes url = ''.join([mme_base_url, '/nodes']) nodes = matchmaker_request(url=url, token=token, method='GET') LOG.info('Matchmaker has the following connected nodes:{}'.format(nodes)) return nodes
Return the available MatchMaker nodes Args: mme_base_url(str): base URL of MME service token(str): MME server authorization token Returns: nodes(list): a list of node disctionaries
juraj-google-style
def get_vcs_root(): for vcs in (git, hg): repo_root = vcs.repository_root() if repo_root: return (vcs, repo_root) return (None, None)
Returns the vcs module and the root of the repo. Returns: A tuple containing the vcs module to use (git, hg) and the root of the repository. If no repository exisits then (None, None) is returned.
codesearchnet
class GraniteMoeSharedMLP(nn.Module): def __init__(self, config: GraniteMoeSharedConfig): super(GraniteMoeSharedMLP, self).__init__() self.input_size = config.hidden_size self.hidden_size = config.shared_intermediate_size self.activation = ACT2FN[config.hidden_act] self.inpu...
MLP layer for shared experts Args: config: Configuration object with model hyperparameters.
github-repos
def get_system_memory(): docker_limit = None memory_limit_filename = '/sys/fs/cgroup/memory/memory.limit_in_bytes' if os.path.exists(memory_limit_filename): with open(memory_limit_filename, 'r') as f: docker_limit = int(f.read()) psutil_memory_in_bytes = None try: import ...
Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes.
codesearchnet
def split(pcoll, regex, outputEmpty=False): regex = Regex._regex_compile(regex) outputEmpty = bool(outputEmpty) def _process(element): r = regex.split(element) if r and (not outputEmpty): r = list(filter(None, r)) yield r return pcoll | FlatMap(_process)
Returns the list string which was splitted on the basis of regular expression. It will not output empty items (by defaults). Args: regex: the regular expression string or (re.compile) pattern. outputEmpty: (optional) Should empty be output. True to output empties and false if not.
github-repos
def write_graph(graph_or_graph_def, logdir, name, as_text=True): if isinstance(graph_or_graph_def, ops.Graph): graph_def = graph_or_graph_def.as_graph_def() else: graph_def = graph_or_graph_def if sys.byteorder == 'big': if hasattr(graph_def, 'node'): byte_swap_tensor.swa...
Writes a graph proto to a file. The graph is written as a text proto unless `as_text` is `False`. ```python v = tf.Variable(0, name='my_variable') sess = tf.compat.v1.Session() tf.io.write_graph(sess.graph_def, '/tmp/my-model', 'train.pbtxt') ``` or ```python v = tf.Variable(0, name='my_variable') sess = tf.compat....
github-repos
class FlaxTopPLogitsWarper(FlaxLogitsWarper): def __init__(self, top_p: float, filter_value: float=-float('Inf'), min_tokens_to_keep: int=1): if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0): raise ValueError(f'`top_p` has to be a float > 0 and < 1, but is {top_p}') if not ...
[`FlaxLogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off. Args: top_p (`float`): If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. filter_value (`float`, *optional*, defaults ...
github-repos
def cpu_halt_reasons(self): buf_size = self.MAX_NUM_MOES buf = (structs.JLinkMOEInfo * buf_size)() num_reasons = self._dll.JLINKARM_GetMOEs(buf, buf_size) if (num_reasons < 0): raise errors.JLinkException(num_reasons) return list(buf)[:num_reasons]
Retrives the reasons that the CPU was halted. Args: self (JLink): the ``JLink`` instance Returns: A list of ``JLInkMOEInfo`` instances specifying the reasons for which the CPU was halted. This list may be empty in the case that the CPU is not halted. Raises: JLinkException: on hardware error.
codesearchnet
def split_image(self, image: np.ndarray, input_data_format: Optional[Union[str, ChannelDimension]]=None): height, width = get_image_size(image, input_data_format) mid_width = width mid_height = height return [self._crop(image, 0, 0, mid_width, mid_height, input_data_format), self._crop(image, mid_widt...
Split an image into 4 equal sub-images, and the concatenate that sequence with the original image. That means that a single image becomes a sequence of 5 images. This is a "trick" to spend more compute on each image with no changes in the vision encoder. Args: image (`np.ndarray`): Images to split. input_data_format (...
github-repos
def _disconnect_from_device(self, uuid, key, client, unsolicited=False): conn_id = self._validate_connection('disconnect', uuid, key) if (conn_id is None): return conn_data = self._connections[uuid] slug = self._build_device_slug(uuid) message = {'client': client, 'type': 'response', 'operat...
Disconnect from a device that we have previously connected to. Args: uuid (int): The unique id of the device key (string): A 64 byte string used to secure this connection client (string): The client id for who is trying to connect to the device. unsolicited (bool): Whether the client asked us to disconnect or we are f...
codesearchnet
def fetches(self): return self._final_fetches
Return the unique names of tensors to fetch. Returns: A list of strings.
github-repos
def parse_table_name(name, project_id=None, dataset_id=None): _project_id = _dataset_id = _table_id = _decorator = None if isinstance(name, basestring): m = re.match(_ABS_TABLE_NAME_PATTERN, name, re.IGNORECASE) if (m is not None): (_project_id, _dataset_id, _table_id, _decorator) = ...
Parses a table name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if the name does contain a project ID and it does not match this, an exception will be t...
codesearchnet
def read_handler(Model, name=None, **kwds): async def action_handler(service, action_type, payload, props, **kwds): if action_type == get_crud_action('read', name or Model): message_props = {} if 'correlation_id' in props: ...
This factory returns an action handler that responds to read requests by resolving the payload as a graphql query against the internal schema. Args: Model (nautilus.BaseModel): The model to delete when the action received. Returns: function(type, payload): The action handler for this model
juraj-google-style
def SetValue(self, identifier, value): if (not isinstance(identifier, py2to3.STRING_TYPES)): raise TypeError('Identifier not a string type.') identifier = identifier.lower() self._values[identifier] = value
Sets a value by identifier. Args: identifier (str): case insensitive unique identifier for the value. value (object): value. Raises: TypeError: if the identifier is not a string type.
codesearchnet
def find_equivalent_sites(self, site): for sites in self.equivalent_sites: if (site in sites): return sites raise ValueError('Site not in structure')
Finds all symmetrically equivalent sites for a particular site Args: site (PeriodicSite): A site in the structure Returns: ([PeriodicSite]): List of all symmetrically equivalent sites.
codesearchnet
def substitute(expr, var_map): try: if isinstance(expr, SympyBasic): sympy_var_map = { k: v for (k, v) in var_map.items() if isinstance(k, SympyBasic)} return expr.subs(sympy_var_map) else: return expr.substitute(var_map) e...
Substitute symbols or (sub-)expressions with the given replacements and re-evalute the result Args: expr: The expression in which to perform the substitution var_map (dict): The substitution dictionary.
juraj-google-style
def get_concepts_to_recalculate(self, users, lang, concepts=None): only_one_user = False if (not isinstance(users, list)): only_one_user = True users = [users] mapping = self.get_item_concept_mapping(lang) current_user_stats = defaultdict((lambda : {})) user_stats_qs = UserStat.objec...
Get concept which have same changes and have to be recalculated Args: users (list of users or user): users whose user stats we are interesting in lang (str): language of used concepts concepts (Optional[list of concepts]): list of primary keys of concepts or concepts Defaults to None meaning all concepts. Returns: di...
codesearchnet
def _or_join(self, terms): if isinstance(terms, (tuple, list)): if len(terms) > 1: return '(' + ' OR '.join(terms) + ')' else: return terms[0] else: return terms
Joins terms using OR operator. Args: terms (list): terms to join Examples: self._or_join(['term1', 'term2']) -> 'term1 OR term2' Returns: str
juraj-google-style
def wait_for_jobs(jobs): all_running = False while (not all_running): all_running = True time.sleep(5) for job in jobs: job.refresh() scheduled = getattr(job, 'scheduled_at', None) if (scheduled is not None): logger.info(('Waiting for %...
Waits for all the jobs to be runnning. Args: jobs(list): list of the python-grid5000 jobs to wait for Raises: Exception: if one of the job gets in error state.
codesearchnet
def get_pluggable_module_information(self, id_or_uri): uri = self._client.build_uri(id_or_uri) + "/pluggableModuleInformation" return self._client.get(uri)
Gets all the pluggable module information. Args: id_or_uri: Can be either the interconnect id or uri. Returns: array: dicts of the pluggable module information.
juraj-google-style
def _batch_prepare_for_model_boxes(self, batch_text_or_text_pairs, is_pair: Optional[bool]=None, boxes: Optional[List[List[int]]]=None, word_labels: Optional[List[List[int]]]=None, add_special_tokens: bool=True, padding_strategy: PaddingStrategy=PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy=Trunca...
Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and manages a moving window (with user defined stride) for overflowing tokens Args: batch_ids_pairs: list of...
github-repos
def iter_package_families(paths=None): for path in (paths or config.packages_path): repo = package_repository_manager.get_repository(path) for resource in repo.iter_package_families(): yield PackageFamily(resource)
Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional): paths to search for package families, defaults to `config.packages_p...
juraj-google-style