content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def notas(* num, sit=False):
"""notas
Parâmetros:
num (array): É a lista de notas que será recebido para calcular os dados do aluno
sit (bool, optional): É o parâmetro para mostrar ou não a situação do aluno. Defaults to False.
Returns:
dados (dict): Dicionário com as informações d... | d8f5af3f95076ec9930b43c956be4ba280254416 | 617,155 |
def int_to_ordinal(num: int) -> str:
"""
Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.
"""
n = int(num)
if 4 <= n <= 20:
return f"{n}th"
elif n == 1 or (n % 10) == 1:
return f"{n}st"
elif n == 2 or (n % 10) == 2:
return f"{n}nd"
... | 1c76ab1352860d9808c9d4854224a3273fe22c19 | 617,157 |
def get_parametrize_markers_args(node):
"""In pytest 3.6 new API to access markers has been introduced and it deprecated
MarkInfo objects.
This function uses that API if it is available otherwise it uses MarkInfo objects.
"""
return tuple(arg for mark in node.iter_markers("parametrize") for arg in ... | b143d8be0d967bad6f6e7bee59828a45da9dea6a | 617,159 |
def update_vertex_properties(g, v, prop_dict):
"""
Helper method for updating several vertex properties at once in a graph-tool
graph.
Args:
g (gt.Graph): a graph-tool Graph object.
v (gt.Vertex or int): a graph-tool Vertex object (or its index) for a vertex
in the provided ... | 408dbacb5171cc408adc9a402465b3c2a6c908cd | 617,163 |
import torch
def smape(y, y_):
"""
Symmetric mean absolute percentage error.
:param y: target
:param y_: prediction
:return: SMAPE
"""
return torch.mean(
torch.sum(torch.abs(y_ - y) / (torch.abs(y) + torch.abs(y_)), dim=1)
* (1.0 / y.shape[1]),
dim=0,
) | 40ae362b38d9edc25be56a793f412e1a2aaf8791 | 617,164 |
def invert_dict_mapping_all(mapping_dictionary):
"""
Args:
mapping_dictionary: mapping from keys to values which is not necessarily
injective, e.g., node_id to community_id mapping
Returns: inverted mapping with unique values as keys and lists of former keys as
values, e.g., com... | e7b79e863453f0981b6f4b2f2b0844f99c313726 | 617,167 |
import wave
def wavfile_duration(wavfile):
"""Return the duration of a wav file in seconds."""
wave_fp = wave.open(wavfile, 'rb')
sample_rate = wave_fp.getframerate()
nframes = wave_fp.getnframes()
return nframes/sample_rate | 9f58d16cacaa41e598b33ed056d191afd55a359b | 617,168 |
def ht_cm_sqm(ht):
"""Converts height from centimeter to squared meter
Parameters
----------
ht: double
height in cms
Returns
-------
double
height in squared meter.
Examples
--------
>>> ht_cm_sqm(175)
1.75
"""
return (ht / 100) ** 2 | 3805311529ebd7f749de1ff3d546280bc75d8962 | 617,170 |
def expand(fluid, p_final, eta):
"""Adiabatically expand a fluid to pressure p_final, using
a turbine with isentropic efficiency eta."""
h0 = fluid.h
s0 = fluid.s
fluid.SP =s0, p_final
h1s = fluid.h
isentropic_work = h0 - h1s
actual_work = isentropic_work * eta
h1 = h0 - actual_work
... | d8fe7b14a0b5d8677446298b72d672934d89a02d | 617,171 |
def to_hex(v, nb_bits=16):
""" Convert the value 'v' into a hexadecimal string (without the prefix 0x)"""
try:
v_hex = v.hex()
except AttributeError:
v_hex = hex(v)[2:]
return '0'*(nb_bits//4-len(v_hex)) + v_hex | 0509c993fa613766b84463bda67216f71e31184b | 617,177 |
def xywh_to_xyminmax(x, y, w, h):
"""convert box coordinates from (x, y, w , h) form to (xmin, ymin, xmax, ymax) form"""
return [x, y, x + w, y + h] | 9852e9e7b8bb0224d0a4c4c03bc6f54b382b5eb4 | 617,178 |
def format_with_braces(*vars: str):
"""This is a demo exercise of using format() with positional {} in order to insert variables into the string.
Examples:
>>> format_with_braces('hi','there','fella')\n
hi there fella\n
['hi', 'there', 'fella']\n
'blah hi blah there blah fella'
... | 5d4019b00e500f80c8f4d0c0270fa6f491b18718 | 617,179 |
def _static_framework_transition_impl(_settings, _attr):
"""Attribute transition for static frameworks to enable swiftinterface generation."""
return {
"@build_bazel_rules_swift//swift:emit_swiftinterface": True,
} | 57e700fca4e7438f1de758a5837c04b94d90f42a | 617,181 |
def _get_sequential_table( seqType ):
"""
Generates the table to fill sequence data in order to create
a :class:`.SequenceFrame`
:param seqType: Type of sequence: ``protein``, ``protein_sse``,
``dna``, ``rna``.
:type seqType: :class:`str`
:return: :class:`dict`
:raise:
:Va... | ebb42d711172b9abb5c602a879c11706b9fc1e5b | 617,184 |
import pathlib
def is_expanded_digital_asset_dir(path: pathlib.Path) -> bool:
"""Check if a folder is an expanded digital asset.
We say a folder is an expanded digital asset if it has a "Sections.list" file inside.
:param path: The folder to check.
:return: Whether the folder is an expanded digital ... | 38fb588b41f636bc6486eb3802241966e1effd2b | 617,187 |
def to_boolean(value):
"""
Convert a string to boolean, case insensitively,
where true values are: true, t, and 1 and false values are: false, f, 0.
Raise a ValueError for all other values.
"""
if isinstance(value, bool):
return value
if isinstance(value, str):
lower_value =... | 10f7e56edc4eb8f15f05e1683578e12658e4f266 | 617,192 |
async def cmd_rename(ctx):
"""
Usage``:
rename <groupname>
Description:
Set the name of your current group to `groupname`.
Arguments::
groupname: The new name for your group, less than `20` charachters long.
Related:
join, status, groups
"""
timer = ctx.client... | 9d842e97e8fd93c4d9839c18f36bb1e0bf7eb7ca | 617,193 |
def are_all_elements_unique(elements):
"""Check if there are any repeated element in the list of elements. If yes return False otherwise return True."""
unique_elements = set()
for element in elements:
if element in unique_elements:
return False
unique_elements.add(element)
r... | 74eec835d625ecc90c3eff91682a09f99c8401f4 | 617,195 |
def is_buzz(replace_array, count):
"""
This function checks whether the count is a multiple of any of the numbers in replace_array[0] are replaces the
output with the text with the same index in replace_array[1]. If it is not a multiple with any of the numbers it
will return the number as a string.
... | 5f0b94fe588bcc5eb9f7bc2d6061f57716b0b9c0 | 617,199 |
def copy_to_device(item, device, criterion_func):
"""
Return a copy of tensor on specified device.
Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts.
Parameters:
item: tensor to copy or (possibly nested) container of tensors to copy.
device: target dev... | d00d90f91149f254baef22e778b246c45ce34ba6 | 617,202 |
def aspect(df):
"""Return the aspect ratio of a Geopandas dataset"""
tb = df.total_bounds
return abs((tb[0] - tb[2]) / (tb[1] - tb[3])) | 8d744b2157655bbabb09ef2c0928fbfd9249bcf3 | 617,203 |
def read_file(file_name):
"""Read file and return its contents."""
with open(file_name, "r") as f:
return f.read() | 31881d8a1ab92c117baae4aca99455dc2760ba10 | 617,204 |
import logging
def unwrap_state_dict(checkpoint, verbose=True):
"""Remove `module.` prefix for `state_dict`."""
with_wrapper = False
new_checkpoint = {}
for key, val in checkpoint.items():
if with_wrapper: # all keys consistent
assert key.startswith('module.')
if key.start... | 56c91e562945c571ef235c15bca9765f46067519 | 617,205 |
def getSZLen(abData, off):
"""
Get the length of a zero-terminated string field, in bytes.
Returns -1 if off is beyond the data packet or not properly terminated.
"""
cbData = len(abData);
if off >= cbData:
return -1;
offCur = off;
while abData[offCur] != 0:
offCur = off... | 88bc2841b1948103b0fd03314700d7a9f1e08ea3 | 617,206 |
def create_iam_policy(bindings_spec):
""" Create an IAM policy for the resource. """
return {
'gcpIamPolicy': {
'bindings': bindings_spec
}
} | 2d4149622a91affcb1c88cdf70c2e92c26736355 | 617,211 |
def cidr_mask_clears_minimum_size(cidrs: list, min_size: int):
"""
Verify all subnet masks in a list of CIDR blocks are larger than a minimum
Args:
cidrs: list of CIDR block strings
min_size: smallest size allowed for mask
Returns: bool
"""
return all([int(cidr.split("/")[1]) <... | 6b44ea6aaff6e724dee773c381385aacf04bd752 | 617,213 |
async def get_int_set(redis, key):
"""Get a set of integers on redis."""
str_set = await redis.smembers(key)
int_set = [int(i) for i in str_set]
return int_set | 5dcceb2e3f0f5bdaffa747e425ebf852d8fa49d5 | 617,216 |
def scale(x, copy=True):
"""Scale `x` to unity.
Subtract min and divide by (max-min).
Parameters
----------
x : array_like
copy : bool
copy `x` before scaling
Returns
-------
x_scaled
"""
xx = x.copy() if copy else x
xx = xx - xx.min()
xx /= xx.max()
re... | 3586d83fd01951b4724fabdb7c1fd0dcb28603ac | 617,217 |
def clone_task_definition(client, task_definition):
"""
Given a task definition ARN, clone the associated task.
Returns the new task definition ARN.
"""
resp = client.describe_task_definition(taskDefinition=task_definition)
taskDefinition = resp['taskDefinition']
# The task definition cont... | 35abba7c3d927c184837d90eaff7a5e4c8195da3 | 617,220 |
import shutil
def move_file(source, destination):
"""Move a file"""
shutil.move(source, destination)
return True | 0034c0d96e72504cd6a3664d2c959de0666d31a7 | 617,223 |
from datetime import datetime
def unpackTimecode(timecode):
"""unpacks a timecode to minutes, seconds, and milliseconds"""
if "." in timecode:
x = datetime.strptime(timecode, '[%M:%S.%f]')
else:
x = datetime.strptime(timecode, '[%M:%S]')
minutes = x.minute
seconds = x.second
m... | 3f107d8102e291987c476b1b5886cb5eaa7f8504 | 617,224 |
import requests
def rGetJSON(url: str):
"""GET the contents of an URL and return its response as a JSON object"""
response = requests.get(url)
return response.json() | eeb6e74220dc9fb9ff23b7bb9dc8d94621a26af2 | 617,228 |
from typing import Counter
import itertools
def build_vocab(sentences1, sentences2):
"""
Builds a vocabulary mapping from word to index based on the sentences.
Returns vocabulary mapping and inverse vocabulary mapping.
"""
# Build vocabulary
word_counts1 = Counter(itertools.chain(*sentences1))... | 8c936ec4ca41f9c00a37f9cc7d1cbc476a6030ad | 617,234 |
def pers_name(data):
"""
extract text from TEI element <persName>
"""
try:
return data.find(".//persName", namespaces=data.nsmap).text
except AttributeError:
pass
return None | 5e6455ac49c8dbc0f2e662a80542ffdecd61f20d | 617,235 |
def same_type(values, types):
"""Check if values are belongs to same type or type tuple.
:param collections.Iterable values: values to check type similarity
:param tuple|type types: type or tuple of types
"""
return all(map(lambda it: isinstance(it, types), values)) | 6f28a83242a19e6712d5cbd2a6fa9573a6074dcc | 617,238 |
def calculate_cells(anchor_point_list_dict, cell_size_meters, utm_bounds=[]):
""" Calculate boundaries for image cells (chips) from anchor points.
This function takes the output from :func:`calculate_anchor_points` as well
as a desired cell size (`cell_size_meters`) and outputs
``(W, S, E, N)`` tuples ... | 72cfca4974562b7284a2760a4c2e1534d96096b4 | 617,244 |
def getWordPattern(word: str) -> str:
"""Get word pattern
Returns a string of the pattern form of the given word.
Args:
word: String containing word to convert into word pattern.
Example:
>>> import pythontutorials.books.CrackingCodes.Ch17.makeWordPatterns as makeWordPatterns
>>> make... | 1bf4a64f6d05673c944997f8f083e24a593756fd | 617,245 |
import csv
def read_links(path_to_csv, index):
"""
reads csv file for project links
:param path_to_csv: path to the csv file
:param index: index to keep data from
:return: list of parsed data
"""
link_list = []
skip = True # to skip the column headings
with open(path_to_csv, "r")... | e05e15cf2dc804d863b54fac34db5adcf35c854b | 617,247 |
def solution(n: int = 1000) -> int:
"""
Returns ∑ r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1)) | c6c6e990bf5aaac8dc809aa82429a805e7241f3c | 617,251 |
from typing import List
from typing import Tuple
import pathlib
import imghdr
def sort_target_type(target_list: List[str]) -> Tuple[List[str], List[str], List[str]]:
"""sort input files by type
Args:
target_list (List[str]): list of pictures or movies or directories where pictures are stored
Returns:
... | 1b103993c2436a5f880fdcf79792b7c5f054a446 | 617,252 |
def is_subseq(l1, l2):
"""is every element of l1 also in l2? (non-unique and order sensitive)"""
it = iter(l2)
return all(d in it for d in l1) | af114ab5051e6999ed21af55a6e8a77519e41eb0 | 617,253 |
def string_list_validator(value: str) -> str:
"""
Validate if value is a str
Arguments:
value {str} -- value to validate
Raises:
ValueError: value is not a type of str
ValueError: Value can't be a empty string
Returns:
str -- unchanged input value
"""
# ra... | 8840e62e448d7861571a19021be96be021c43701 | 617,254 |
def location_to_hex(location):
"""convert location to hex for display"""
ret = "%08X" % int(location)
return ret | 5add315ef27268f4b1e41a5270101dd39101f132 | 617,258 |
from typing import Any
import json
def from_json(s: str, **kwargs: Any) -> object:
"""
Convert a JSON string to an object representation. For usage, see json.loads(...).
"""
return json.loads(s, **kwargs) | c82bbb38dc0300ddfbc2cba140536886ddbd9b14 | 617,261 |
def _should_process_segment(seg, segname):
"""Check if we should process the specified segment."""
return segname.endswith('__DATA_CONST.__mod_init_func') or \
segname == '__DATA.__kmod_init' | c0fc59f25dc523f669a63c2bf026aff26bc42877 | 617,262 |
from math import ceil # Biblioteca para arrendondamento do valor da média
def notas(*n, sit=False):
"""
-> Função de Analise: com Qdtde de notas, o valor maior; menor e média da turma.
:param n: uma ou mais notas dos alunos para analise.
:param sit: valor opcional para saber situação da média dos alu... | 3a957fb652bbf2b94b17009317b405818b81498f | 617,263 |
import re
def clean_atomtype(atomtype):
"""Removes extraneous charge info from atomtype
Atomtypes occasionally have charges such as O1+ or N1-. This function
uses regexps to replace these out.
atomtype: String
Raw atomtype extracted from PDB
"""
return re.sub(r'[0-9]+[+-]?', r'', atomtype) | 986d46a705a2be33d35168d40099a1108c2a7557 | 617,264 |
def _async_request_completed(payload):
"""Looks into an async response payload to see if the requested job has finished."""
if payload["status"] == "COMPLETED":
return True
if payload["status"] == "ERROR":
return True
return False | e41d499e1ef280fd5dc06324da307d4757c355b3 | 617,266 |
import re
def isSynchronous(key1, key2, mali, exons):
"""check if two transcripts are on synchronous positions.
Two transcripts are synchroneous, if their position in the
alignment and on the genomic sequence are both a < b.
Both front and end are taken into account. Note that they
can still be ... | 5fee931cbfe23a7974997d8459953109232a4da9 | 617,269 |
def get_assign_default_value_rule(variable_name: str, default_value_parameter_name: str):
"""
Returns a rule that sets a default value for a variable.
@param variable_name: The name of the variable whose default should be set (as a string)
@param default_value_parameter_name: The name of the parameter ... | 4423374980c32c18c8dc6f49eadcf058c49ac31b | 617,270 |
def get(lens, big):
"""
Get a value from `big` using `lens`.
"""
return lens.get(big) | 0fe5f7dcf7a79f7d0d775e21ce9fdd55b3921163 | 617,275 |
def convert_reference_json(reference_json, data_object):
"""
Converts the reference JSON download from DSS into the DOS message
and returns the DOS message.
:param reference_json:
:param data_object:
:return:
"""
# {u'content-type': u'application/octet-stream',
# u'crc32c': u'e2a2bc0... | bf6d1e33cb20292e419e5c0dde9e0349b9f648a2 | 617,276 |
def none_if_na(s):
"""Return None if s == 'N/A'. Return s otherwise."""
return None if s == 'N/A' else s | b0788485d3f836c8a1f4c73595b098a6d87860ab | 617,280 |
def encode_str(s):
"""Returns the hexadecimal representation of ``s``"""
return ''.join("%02x" % ord(n) for n in s) | 092ca9a4b5394b601233f1f54ad8e0e492f4e742 | 617,282 |
def _StaticValueInner(value, ctx, _): # pylint: disable=W0613
"""Returns a static value.
"""
return value | 10e520798c2d68ff25997ac8f488d7acf0e3a74f | 617,283 |
def pct_max_weekly_submissions(quiz_df, quiz_meta_df):
"""
Helper function to compute student weekly submissions as a percentage of max # of submissions, and as a percentage of the highest number of student submissions that week.
:param quiz_df: pd.DataFrame of quiz submission data.
:param quiz_meta_df:... | 67db9c2890395bc121a53d933676944cda071417 | 617,286 |
def dthandler(obj):
"""ISO formatting for datetime to be used in JSON.
"""
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError("Object can not be isoformatted.") | 9d36c3b97da2e7073d3c3ac66ae00d7b651a0642 | 617,290 |
def requires(modules):
"""Decorator to wrap functions with soft dependencies.
This function was inspired by the `requires` function of pysal,
which is released under the 'BSD 3-Clause "New" or "Revised" License'.
https://github.com/pysal/pysal/blob/master/pysal/lib/common.py
Parameters
------... | 3ad5a3edfe814ea0f78e9e75039ea82caebe3b00 | 617,292 |
def _get_edges(value, last_value, mask):
"""
Given two integer values representing a current and a past value,
and a bit mask, this function will return two
integer values representing the bits with rising (re) and falling (fe)
edges.
"""
changed = value ^ last_value
re = changed & value... | dfbd96e30976401892a7ee767449db4e549380e0 | 617,295 |
def post_string(descr):
"""Constructs a http POST description string from dataset description"""
output = "dsid=ds%(dsid)s&rtype=S&rinfo=dsnum=%(dsid)s;\
startdate=%(startdate)s;enddate=%(enddate)s;parameters=%(parameters)s;\
level=%(level)s;product=%(product)s;grid_definition=%(grid_definition)s;ststep=%(... | 0eb970c56e6d23ed6690a836ccf6de5fecb3a1cf | 617,296 |
def FormatIssueRef(issue_ref_tuple, default_project_name=None):
"""Format an issue reference for users: e.g., 123, or projectname:123."""
if issue_ref_tuple is None:
return ''
project_name, local_id = issue_ref_tuple
if project_name and project_name != default_project_name:
return '%s:%d' % (project_nam... | 2aaa6c4704dbf00296499cfeb500eef30d155751 | 617,297 |
import torch
def sharded_bmm(args, kwargs, pg):
"""
Handles ``__torch_function__`` dispatch for the sharded_bmm op.
Warning: For now we only supports the case when both tensors are sharded
by dim 0 so that no local communication.
Args: same as ``torch.bmm``.
Return:
local_t... | a4ee44ccb260d2207228551966d2443e03bde84d | 617,301 |
import re
def RemoveExtension(rc, stdout, stderr):
"""Stores the basename of the path in stdout to the property package_base."""
base = re.sub(r'\.[^.]+$', r'', stdout)
return {'package_base': base} | 4373c0abab452a6af478d1bcfd003c66d1fb35c9 | 617,302 |
def asciify(text):
"""Translate non-ascii charaters to ascii equivalent.
**Example:**
>>> asciify('áéíóúÁÉÍÓÚñÑ')
'aeiouaeiounn'
"""
def translate(c):
if c in ['\u00C0', '\u00C1', '\u00C2', '\u00C3', '\u00C4',
'\u00C5', '\u00E0', '\u00E1', '\u00E2', '\u00E3',
... | 4226ceb4e2d1bb5423ca560d2663dc7da12293da | 617,304 |
def input_as_string(filename:str) -> str:
"""returns the content of the input file as a string"""
with open(filename) as f:
return f.read().rstrip("\n") | 3407b2b98275c67cf3cdba17ce01418554ba0eda | 617,305 |
def jwt_auth_required(callable_obj):
"""A decorator that signs a callable object with an "auth_required"
attribute (True). We use this attribute to find which handler callbacks
require an authorized for protected access.
Args:
callable_obj (instance): A handler callable object.
Returns:
... | 6c3b8b18bbfd6c3a6b33dea21dad3a2460bbb786 | 617,307 |
import torch
def projection_simplex(u, r=1):
"""Project u unto the the r-simplex, i.e.
out = min_v || v - u ||_2^2, subject to sum(v_i)_i=1^n = r, v_i >= 0
Parameters
----------
u : torch.tensor
Vector to be projected of shape (n,).
r : positive float
Simplex constant.
... | d10016dac467746649ed5e732d812f077988f296 | 617,309 |
import json
def create_cat_to_name_dict(filepath):
"""Return a dictionary containing category names and keys from a json file
Args:
filepath (str): Directory to a json file containing category names and keys for all data in train set
Returns:
dict: A python dictionary object mapping a key to each category i... | eabacc78bdc423249dce909e589ceee900931943 | 617,312 |
def compute_gradient(tx, error_vector):
"""
Computes the gradient for the mean squared error loss function.
Args:
y: labels
error_vector: error vector computed for a specific data set and model
Returns:
gradient: the gradient vector computed according to its definition
"""
... | 82b7b338e48a3dcd212a8fa6ddc5c0f1f7c1f1a9 | 617,315 |
import copy
def remove_connected_component(cc, connected_components):
"""
Attempt to remove connected component and return the smaller set
:param Panel cc: connected component to remove
:param iterable connected_components: set of all connected components
:return: smaller set of connected componen... | e1be0e1784d89d0a2637deb6bfbf872156f7e354 | 617,316 |
def obj_of(k, v):
"""Creates an object containing a single key:value pair"""
return {k: v} | 8fe5ed7f44994ac376c143f8c8e6f2e89211f5c2 | 617,324 |
def get_by_path(dic, path):
"""
Gets a key (can be specified via dot notation) `path` in a nested `dic`
"""
parts = path.split('.')
loc = dic
for part in parts:
if part not in loc:
raise KeyError(path)
loc = loc[part]
return loc | de512b8e04b977d77282f7f49dbe364d986204d2 | 617,326 |
def _is_accepting(node):
"""Check if node is accepting."""
return node.get("type") == "Accepting" | 02e02dfa0eb9e950ca427561cf54051d1ec53120 | 617,329 |
def map_base_attributes(cube, mapper_class, naming, locale=None):
"""Map all base attributes of `cube` using mapping function `mapper`.
`naming` is a naming convention object. Returns a tuple (`fact_name`,
`mapping`) where `fact_name` is a fact table name and `mapping` is a
dictionary of attribute refer... | d6f6a04459191414ec91471972718b296c2cc975 | 617,335 |
def rm_last(*args):
"""
Remove the last index from each list
"""
if len(args) == 1:
return args[:-1]
else:
return [a[:-1] for a in args]
return | ca39d7d31b7cb80937ee6c78513f38c75e8fbbed | 617,337 |
from pathlib import Path
def get_final_path(output_path: Path, set_type: str, samp_name: str) -> Path:
"""Get path of output file
Arguments:
output_path {Path} -- root of output path
set_type {str} -- data set type
samp_name {str} -- name of sample
Returns:
Path -- comple... | 0406a6e6684c8f42b781f0a1d53a05a9ca3fb7cb | 617,338 |
def parseStr(x):
"""
function to parse a string
Parameters
----------
x : str
input string
Returns
-------
int or float or str
parsed string
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:... | 17ee3b7d8afb9828171833a82d2134439f85eac1 | 617,339 |
from typing import OrderedDict
def parse_tuple_latency(tl_file):
"""
Read the log of latencies and extract the relevant values for each time window,
returning an ordered dictionary of instant latencies per component.
"""
latencies = OrderedDict()
header = {}
ts = 0
for line in open(tl... | 3bcfc6852ea4cc1362c7096271d9d274f210384b | 617,343 |
import torch
def vectorize(data, dtype=torch.uint8):
""" Vectorizes a tuple or int into a torch tensor. """
# Don't need to vectorize an int, its broadcasted
if isinstance(data, int):
return data
elif isinstance(data, tuple):
# If the elements are the same, there is be no need for this... | e1946d5201b018eb55c85cbd2ad5604c2ccaabf7 | 617,344 |
import re
def human_sort_key(s):
"""
A key function to sort alpha-numerically, not by string
From http://nedbatchelder.com/blog/200712/human_sorting.html
This function can be used as the key for a sort algorithm to give it an understanding of numbers,
i.e. [a1, a2, a10], instead of the default (A... | 55e598b97b267c082a55431238c064fdda804baa | 617,346 |
def site_center(sites):
"""
Find the geometric center of a collection of sites.
:param sites: Tuple of Site objects
:return: Array of the cartesian coordinates of the center of the sites
"""
return sum([site.coords for site in sites]) / len(sites) | b5bd0d7470c2b1653a206bfcfa9154b72fc06d6e | 617,352 |
import re
def parseCrysolLog(logFileName):
"""Parse Crysol log file, obtain Chi2, Rg and eDens"""
# will not parse crysol_summary.txt, but the .log file
# created for each individual run
chi2 = 9999
Rg = -9999
eDens = -9999
position = -1
counter = 0
with open(logFileName, 'r') as... | aa4f80a3797b56a7d314c9a0cbbe593caa014667 | 617,354 |
import logging
def run_simulation(simulation):
"""
Fires of the simulation of a single game. Useful for the multiprocessing
map call.
Args:
simulation (Simulation): Instance of a single game simulation
Returns:
(Simulation) Completed simulation
"""
logging.info(f"Startin... | 7498408bfce0b8128d17dc37ce122546c30a8a07 | 617,355 |
import uuid
def random_uuid(use_uuid1: bool = False) -> uuid.UUID:
"""
Get a random UUID.
:param use_uuid1: Use UUID1 if True, else use UUID4.
:return: A random UUID.
"""
return uuid.uuid1() if use_uuid1 else uuid.uuid4() | 60e9f7bfa647ba5fb064ca6e780c75d824492603 | 617,356 |
import ctypes
def _get_bytes_buffer(ptr, nbytes):
"""
Get a ctypes array of *nbytes* starting at *ptr*.
"""
if isinstance(ptr, ctypes.c_void_p):
ptr = ptr.value
arrty = ctypes.c_byte * nbytes
return arrty.from_address(ptr) | 7b425bdcab62755ebaa240470e2e80ec54bc1444 | 617,358 |
import torch
def harmonic(x, k, eq, order=[2]):
"""Harmonic term.
Parameters
----------
x : `torch.Tensor`, `shape=(batch_size, 1)`
k : `torch.Tensor`, `shape=(batch_size, len(order))`
eq : `torch.Tensor`, `shape=(batch_size, len(order))`
order : `int` or `List` of `int`
Returns
... | 707c6a57eb9ddc8e399a84de04fb40ae5d5dd7cf | 617,361 |
def get_embeddings(model, data, device):
"""
Get best embeddings
Args
- model (torch object): best model
- data (Data object): dataset
- device (torch object): cpu or cuda
Return
- all_emb (tensor): best embedding for all nodes
"""
model.eval()
dat... | 35f53653c5340e76139a203fbdf6ac05b10ebaf9 | 617,362 |
def format_pytesseract_dict_results(ocr_res: dict) -> tuple:
"""Formats results from pytesseract.image_to_data(img, output_type=Output.DICT)
function.
Parameters
----------
ocr_res : dict
result of pytesseract.image_to_data(img, output_type=Output.DICT)
Returns
-------
tuple(li... | 5effcc857e9592f7985b13b2e227fec433fbb785 | 617,363 |
def __cleanup_stdout(stdout):
"""Removes empty elements from the stdout/stderr list returned by run
param stdout: string output of subprocess stdout
returns: list of lines from stdout
"""
return list(filter(None, stdout.split('\n'))) | b0f1cdd8e570bba90dd81f008c2aee7700773552 | 617,364 |
import re
def boolean_to_upper(data):
"""Convert boolean operators to uppercase"""
ops = ['and', 'or', 'not']
for op in ops:
data = re.sub(r"\b%s\b" % (op), op.upper(), data)
return data | 92669a9cd357c6ad27dd340a6f9c90b54ac48be0 | 617,369 |
def parse_style(style):
"""Parse a style string. The format is a space-separated list of
tokens, in order
<lineformat> <markerformat> <seriesformat>
Valid values:
lineformat: matplotlib line style, or dash sequence as
list of "-"-separated integers
m... | 3b26d77be60bfd839d831f8eb9d81a5ce28b550a | 617,371 |
def GetMavenGroupId(owner_domain):
"""Returns the maven group id for a given owner domain.
Args:
owner_domain: (str) The owner domain.
Returns:
(str) The group id.
"""
if owner_domain == 'google.com':
return 'com.google.apis'
else:
return '.'.join(reversed(owner_domain.split('.'))) | c8777695a559adfc12dd38380cbed2c22ed3810e | 617,373 |
def change1(line, old, new):
"""replace old with new if old in line. """
return line.replace(old, new) | caa841652431aaf679173acd12f47fdc8888c09f | 617,375 |
from typing import List
def header_content_split(string: str, delimiter: str) -> List[str]:
"""
Take a string and split it according to the passed delimiter.
It will ignore delimiter if inside between double quote, inside a value, or in parenthesis.
The input string is considered perfectly formed. Thi... | 2135da22a434d9a7c8874fa695cd73baf0fb71eb | 617,378 |
def increment_dictionary_with_dictionary(dict_a, dict_b):
"""
Function to add the values from one dictionary to the values from the same keys in another.
Args:
dict_a: First dictionary to be added
dict_b: Second dictionary to be added
Return:
The combined dictionary
"""
... | 8d5ee0c905c61a8615e9ab177ed48494387c0c49 | 617,379 |
def DistributedWaitForReadyMidasTalker (midastalker_list, immediate_return,
timeout=None) :
""" Given a list of MidasTalkers, this returns a list of all 'ready'
MidasTalkers. Take the given timeout, distribute it evenly over all
MidasTalkers so that the maximum wait (if al... | a7fee085fe7102446d4c392519d80bac48727e5c | 617,380 |
def is_ccw_xy(a, b, c, colinear=False):
"""Determine if c is on the left of ab when looking from a to b,
and assuming that all points lie in the XY plane.
Parameters
----------
a : sequence of float
XY(Z) coordinates of the base point.
b : sequence of float
XY(Z) coordinates of ... | 000f685d79020fefe8f49cc9ea14cec9f7fa9b1b | 617,382 |
def original_error(err):
"""
Returns original exception from graphql exception wrappers.
graphql-core wraps exceptions that occurs on resolvers into special type
with ``original_error`` attribute, which contains the real exception.
"""
return err.original_error if hasattr(err, 'original_error')... | dd87c4ed4a6512efbbe32ece8237890597bddfb0 | 617,383 |
def vDot(v, w):
""" Return the dot product of v . w """
return v[0]*w[0] + v[1]*w[1] + v[2]*w[2] | 1c75d7fb2b9fe4680ff11df295c19d460a806a5d | 617,392 |
def mels_len(mels):
"""Gets lenfth of log mel-spectrogram."""
return mels.shape[1] | 143e6ac88419888493654065b4b1c70f30328133 | 617,393 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.