content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import re
def identificador(soup):
"""
Return Lattes ID (number)
"""
ID = soup.find("li")
ID_num = re.findall('lattes.cnpq.br/(.+?)<', str(ID))[0]
return ID_num
|
67dbbc361901af9a1ea23e6e426d907279c4253d
| 551,591 |
def remove_numbers(words):
"""Remove all numbers from word list.
Unlike words, numbers without any context are not expected to provide any explanatory value for topic classification.
Parameters
----------
words : string
Original word-token list
Returns
-------
new_words : list of strings
List with all remaining word-tokens
"""
new_words = []
for word in words:
if not word.isdigit():
new_words.append(word)
else:
pass
return new_words
|
5231b3c84aa926b9898927c251a11d87de4c07e4
| 478,427 |
import torch
def train(model, iterator, optimizer, criterion, clip):
"""
TRAINING: At each iteration:
get the source and target sentences from the batch, $X$ and $Y$
zero the gradients calculated from the last batch
feed the source and target into the model to get the output, $\hat{Y}$
as the loss function only works on 2d inputs with 1d targets we need to flatten each of them with .view
we slice off the first column of the output and target tensors as mentioned above
calculate the gradients with loss.backward()
clip the gradients to prevent them from exploding (a common issue in RNNs)
update the parameters of our model by doing an optimizer step
sum the loss value to a running total
Finally, we return the loss that is averaged over all batches.
"""
model.train()
epoch_loss = 0
for i, batch in enumerate(iterator): # trg is labels, src is input
src = batch.src
trg = batch.trg
optimizer.zero_grad()
output = model(src, trg)
# trg = [trg len, batch size]
# output = [trg len, batch size, output dim]
output_dim = output.shape[-1] # ?
output = output[1:].view(-1, output_dim) # prediction
trg = trg[1:].view(-1) # labels
loss = criterion(
output, trg
) # calculates both the log softmax as well as the negative log-likelihood of our predictions.
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), clip) # prevent explosion
optimizer.step() # gradient descent / adam
epoch_loss += loss.item() # sum all the loss
return epoch_loss / len(iterator)
|
5bea27ca9b0ad40f04034ccf0e33109f17c9460a
| 104,098 |
import six
def is_iterable(value):
"""
Custom iterable test that excludes string types
Parameters
----------
value: object
The value to test if iterable
Returns
-------
iterable: bool
True if the value is iterable and not a string, false otherwise
"""
if isinstance(value, six.string_types):
return False
try:
[vi for vi in value]
return True
except TypeError:
return False
|
b9dfed21aafd63148642668c5cac018f7a008ffd
| 171,910 |
def remove_exotic_char(entry):
"""remove any exotic character from the text to make it more compatible"""
no_tag_pattern = {u"œ": u"oe", u"": u"oe", u"Œ": u"Oe", u"Æ": u"Ae", u"æ": u"ae"}
for key, value in no_tag_pattern.items():
entry = entry.replace(key, value)
return entry
|
33f8697fc16b9e737f036f8b5939b0735adf540b
| 363,260 |
def sanitize_smiles_file_name(file_name):
"""Sanitizes a file name which contains smiles patterns.
Currently this method simply replaces any `/` characters
with a `_` character.
Parameters
----------
file_name: str
The file name to sanitize
Returns
-------
The sanitized file name.
"""
return file_name.replace('/', '_')
|
7b9922403fd598492b419db1d796bae0de8e920c
| 65,951 |
def is_candidate(wordlist, word):
"""True if word is a candidate for the homophone problem, in that
it's five letters long, and removing either of the first two
letters also results in a word.
wordlist: dictionary of words
word: string
"""
word1 = word[1:]
word2 = word[0]+word[2:]
# Python evaluates and clauses left to right, so `p and q and r` is like
# saying if p, then if q, then if r, return true. Otherwise return false.
return len(word)==5 and word1 != word2 and word[1:] in wordlist and \
word[0]+word[2:] in wordlist
|
46c86199993ab180fb430631568633f72f75a147
| 478,447 |
import inspect
def is_bound_builtin_method(meth):
"""Helper returning True if meth is a bound built-in method"""
return (inspect.isbuiltin(meth)
and getattr(meth, '__self__', None) is not None
and getattr(meth.__self__, '__class__', None))
|
a7a45f0f519119d795e91723657a1333eb6714e4
| 705,879 |
import functools
import warnings
def deprecated(func):
"""Decorator that marks functions or classes as deprecated (emits a warning when used)."""
@functools.wraps(func)
def inner(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(f"Call to deprecated function {func.__name__}.", category=DeprecationWarning, stacklevel=2)
warnings.simplefilter('default', DeprecationWarning)
return func(*args, **kwargs)
return inner
|
983e7a47a6d7c7a2da5af818a1fb253681fd61da
| 207,028 |
def distNDx(pt1, pt2, limit=0):
"""Returns distance between two nD points (as two n-tuples)
It ignores items if they are not numeric, and also has
an option to limit length of tuples to a certain
length defined by the `limit` argument"""
if limit > 0:
return (sum((vv2 - vv1)**2.0 for i, (vv1, vv2) in enumerate(zip(pt1, pt2))
if isinstance(vv1, (int, float))
and isinstance(vv2, (int, float))
and i < limit))**0.5
else:
return (sum((vv2 - vv1)**2.0 for vv1, vv2 in zip(pt1, pt2)
if isinstance(vv1, (int, float))
and isinstance(vv2, (int, float))))**0.5
|
3d832dbb83c9fb6af84601c245f189302b43845f
| 197,968 |
def get_xpath_for_date_of_available_time_element(day_index: int) -> str:
"""
The element showing date of the available time is found in the div having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span'
^
where N is the day of the week from 2 to 8.
"""
return f'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[{day_index}]/span'
|
81a3cd1a88c47cfd2cb1b815354ce4a6d2f9dca8
| 655,557 |
def is_valid_output_minimize(ext):
""" Checks if output file format is compatible with Obminimize """
formats = ["pdb", "mol2"]
return ext in formats
|
fcc99113009f8821194f1a87150da4fb8a12a6d3
| 354,150 |
from typing import Any
def is_less_than(value: Any, *, upper_bound: Any = 10) -> bool:
"""Checks whether the value is less than the upper_bound
:param value: The value to check if is less than
:param upper_bound: The upper bound
:return: Whether the value is less than upper_bound
"""
return value < upper_bound
|
0699fc80e34b772d97c81823d23a466c8884ac17
| 64,651 |
def import_words(filename):
"""Imports words from a given .txt file and returns it.
"""
# Initialize resuts variable
results = []
# This with statement ensures the file is only open for a certain amount of time.
# This can save RAM and processing speeds in larger projects
# Rename the sprits.txt as inputfile within this with statement
with open(filename,"r",encoding = "utf-8") as inputfile:
# Loop through each line in the defined inputfile variable
for line in inputfile:
# Create a new list from each line, and split it at each space " "
for word in line.strip().split(" "):
# Individually append every word to the results variable
results.append(word)
return(results)
|
56954768e1bcff7c857c1b104cf1b5dff93e1124
| 643,367 |
def get_call_uri(ad, call_id):
"""Get call's uri field.
Get Uri for call_id in ad.
Args:
ad: android device object.
call_id: the call id to get Uri from.
Returns:
call's Uri if call is active and have uri field. None otherwise.
"""
try:
call_detail = ad.droid.telecomCallGetDetails(call_id)
return call_detail["Handle"]["Uri"]
except:
return None
|
b524891c0f3f66540889a156c93d666fbf240ce2
| 129,557 |
def find_multiples(integer, limit):
"""
Finds all integers multiples.
:param integer: integer value.
:param limit: integer value.
:return: a list of its multiples up to another value, limit.
"""
return [x for x in range(1, limit + 1) if x % integer == 0]
|
36b438541f6f067a92aad6317f3ce919b6e4bde2
| 637,504 |
def create_alignment(df):
"""
Map the sentence position indexes of the abstract sentences for a whole
papers dataframe. Used later to map the separately calculated sentence
embeddings (due to performance gains in SBERT batch embedding) to
the correct paper.
:param df: The papers dataframe.
:return alignment: The sentence-to-position alignment dictionary.
"""
alignment = {}
current_start = 0
current_end = 0
for index, row in df.iterrows():
abstract = row.abstract_sentences
current_end += len(abstract)
alignment[index] = {"start": current_start, "end": current_end}
current_start = current_end
return alignment
|
071a51b05e63b20716ae9449aabbbde9c8f5f37b
| 241,103 |
def sense_instances(instances, sense):
"""
Returns the list of instances in **instances** that have the sense **sense**.
Example:
sense_instances(senseval.instances('hard.pos'), 'HARD1')
"""
return [instance for instance in instances if instance.senses[0] == sense]
|
28f6c17f2308a424d3e7776a08aade60a058763c
| 116,554 |
def lustre_ost_id(fsname, ost_index):
"""
Return the Lustre client ID
"""
return "%s:%s" % (fsname, ost_index)
|
582845e7762f8705d930a023a296dc68344d41b0
| 640,060 |
from typing import MutableMapping
def is_mapping(obj):
"""
Checks if the object is an instance of MutableMapping.
:param obj: Object to be checked.
:return: Truth value of whether the object is an instance of
MutableMapping.
:rtype: bool
"""
return isinstance(obj, MutableMapping)
|
ac909c3bbb5a67a17f322df8ba380b09076bb50c
| 407,223 |
import uuid
def generate_event_id(worker_id):
"""
Return a unique id to use for identifying a packet for a worker.
"""
return '{}_{}'.format(worker_id, uuid.uuid4())
|
8f5c3ef9efc098c60161d8f22d41f2fc14a83f64
| 467,728 |
from typing import Dict
from typing import Any
def dict_without(data: Dict[str, Any], omit_key: str) -> Dict[str, Any]:
"""Return a dictionary without a given key if present."""
return {k: data[k] for k in data if k != omit_key}
|
7f3ecbe65ecfbc96d3de315ed7c31cf1887bd0f4
| 415,377 |
def Set(state,command,name,value=True):
"""Set the state variable
Sets a state variable with 'name' to 'value'. If 'value' is not specified, variable is set to True.
"""
state.vars[name]=value
return state
|
c489a7459f635e8dec6d21ad5d80a5253604ec05
| 420,591 |
import json
def pretty_json(json_str):
"""Generates a pretty-print json from any json."""
return json.dumps(json.loads(json_str), indent=4)
|
e1d16fcc91c7d212130af115eb0cad2fbd73a99c
| 648,117 |
def remove_cell_with(cell, pattern):
"""
If a string string contains the specified pattern, None is returned.
"""
if pattern in cell:
return None
else:
return cell
|
d8617f42d413f0ab7fcccc9118a9d240cf7cd214
| 194,469 |
def LCS(value: str) -> bytes:
"""
pack a string into a LCS
"""
return b'\x84' + str.encode(value) + b'\x00'
|
1b3d30685d72d9afff07ae875247ed5114df977d
| 85,236 |
def isPrime(i):
"""
This function returns if i is a prime number or not.
"""
if i <= 1:
return False
for k in range(2, int(i**0.5)+1):
if i%k == 0:
return False
return True
|
145d46ff63ebb4d5ff028986679de24a3b77c0e4
| 153,245 |
def encode_member(member):
"""Encode a team member and return fields:
- name
- profileUrl (optional)
"""
res = {
'name': member.name,
}
if member.profile_url:
res['profileUrl'] = member.profile_url
return res
|
3522a8343823385a1e93af0f34c68a1cde286fe4
| 377,806 |
def title_case(sentence):
"""
Capitalize the first letter of every word in a sentence.
Parameters
----------
sentence: string
Sentence to be converted to title case
Returns
-------
result: string
Input string converted to title case
Example
-------
>>> title_case('This iS a sampLe.')
This Is A Sample.
"""
# error checking
if not isinstance(sentence, str):
raise TypeError('Input to title_case must be string')
# convert entire sentence to lower case then split it into words
words = (sentence.lower()).split()
# capitalize each word
for i in range(len(words)):
words[i] = words[i].capitalize()
# put the words back together into a sentence, separating them with spaces
result = ' '.join(words)
return result
|
6c75490af1d6d6fd9bf47ebdebcaca11773950cc
| 504,926 |
from bs4 import BeautifulSoup
def parse_pypi_index(text):
"""Parses the text and returns all the packages
Parameters
----------
text : str
the html of the website (https://pypi.org/simple/)
Returns
-------
List[str]
the list of packages
"""
soup = BeautifulSoup(text, "lxml")
return [i.get_text() for i in soup.find_all("a")]
|
68d831aab69f3ffdd879ea1fa7ca5f28fc1b1e75
| 4,380 |
def KFold(num, n_folds=5):
"""
k折叠交叉验证算法,如果份数不能整除数据的数量
会尽量分成相近的数量
:param num: 所有数据的数量
:param n_folds: k,分成k份
:return:
"""
folds = []
indics = list(range(num))
for i in range(n_folds):
# 将一部分数据作为验证集
valid_indics = indics[(i * num // n_folds):((i + 1) * num // n_folds)]
# 剩余部分作为测试集
train_indics = [index for index in range(0, (i * num // n_folds))]
train_indics.extend([index for index in range((i + 1) * num // n_folds, num)])
folds.append([train_indics, valid_indics])
return folds
|
c515588dfa71f3cd2529a8a26786cdd7cd997159
| 414,640 |
def sq_dist(p1, p2):
"""
Calculate the non-square-root distance between two points.
Args:
p1, p2: 1x3 point coordinates.
"""
return (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2
|
5d576b274c3d93b755f56565f15e280538d7c541
| 494,156 |
import tree_sitter
from typing import Tuple
def get_positional_bytes(node: tree_sitter.Node) -> Tuple[int, int]:
"""
Extract start and end byte.
:param node: node on the AST.
:return: (start byte, end byte).
"""
start = node.start_byte
end = node.end_byte
return start, end
|
08252fa9c6f63d7c81e92116cf95ad5f425edfda
| 316,682 |
def get_overlap(i1, i2, j1, j2):
"""
Get overlap between spans
"""
A = set(range(i1, i2))
B = set(range(j1, j2))
overlap = A.intersection(B)
overlap = sorted(list(overlap))
return overlap
|
4a968b6cc85ad4e376a27e98161906ad96b42d30
| 177,013 |
def split_snake_case_name_to_words(name):
""" 'snake_case_name' -> ['snake', 'case', 'name'] """
return [n for n in name.split('_') if n]
|
cf91f5bd86df4fd8ee290dcbb30999217af224ff
| 405,950 |
def get_leaf_decision(l_yes, l_no, parent_decision) -> int:
"""returns leaf decision with majority decision if not equal else returns it's parent decision"""
leaf_value = 0
if l_yes > l_no:
leaf_value = 1
elif l_yes == l_no:
leaf_value = 1 if parent_decision else 0
return leaf_value
|
6e065617fbdbbf963a7e103a8154972e317dd586
| 566,656 |
def calculate_num_modules(slot_map):
"""
Reads the slot map and counts the number of modules we have in total
:param slot_map: The Slot map containing the number of modules.
:return: The number of modules counted in the config.
"""
return sum([len(v) for v in slot_map.values()])
|
efbb82a54843f093a5527ebb6a1d4c4b75668ebb
| 704,085 |
def index2label(index, label):
"""
Converts an indices tensor into its labelled values counterpart
Parameters
----------
index : LongTensor
the indices tensor
label : list
the labels values
Returns
-------
list
a list of labels
"""
return [label[i] for i in index]
|
728a10d866fba0149fe933d56927e6caad146390
| 210,998 |
def dummy_address_check( address ):
"""
Determines if values contain dummy addresses
Args:
address: Dictionary, list, or string containing addresses
Returns:
True if any of the data contains a dummy address; False otherwise
"""
dummy_addresses = [ "", "0.0.0.0", "::" ]
if isinstance( address, dict ):
# Go through each property and check the value
for property in address:
if dummy_address_check( address[property] ):
return True
elif isinstance( address, list ):
# Go through each index and check the value
for value in address:
if dummy_address_check( value ):
return True
elif isinstance( address, str ):
if address in dummy_addresses:
return True
return False
|
59b8a5fa1606a1898e20d3b95b74310e38752957
| 543,390 |
import uuid
def create_id() -> str: # pragma: no cover
"""Creates an uuid."""
return str(uuid.uuid4())
|
a22df1382bc2da7d730aed6e9131301749720919
| 646,710 |
def my_task(**kwargs) -> None:
"""
Function used for testing, returns nothing.
"""
return None
|
3839c4ddb7ad6f9358fb6faac3fce50e9072647a
| 99,766 |
def inv_power(x, d):
"""Computes the d-th root of x if it is an integer.
x must be >= 0 and d must be >= 1.
Args:
x (int): Integer x.
d (int): Integer d.
Raises:
ValueError: Thrown when x < 0 or d < 1.
Returns:
int: The d-th root of x if it is an integer, otherwise None.
"""
if x < 0 or d < 1:
raise ValueError
if x == 0:
return 0
# Since 2 ** b <= x < 2 ** (b + 1)
# We get 2 ** (b//d) <= x ** (1/d) < 2 ** ((b + 1)/d) <= 2 ** (b//d + 1)
b = x.bit_length() - 1
low = 1 << (b // d)
high = 1 << (b // d + 1)
while low < high:
mid = (low + high) // 2
if x < mid ** d:
high = mid
else:
low = mid + 1
x_d = low - 1
if x_d ** d == x:
return x_d
return None
|
4a425a56c0dde003229d32acaa6e69e1e0cd46bf
| 439,164 |
import random
import string
def randomstring(N):
""" Generate a random string of length N """
return "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(N)
)
|
914c21e180c4921ab29b48b704e36f008a213e81
| 595,035 |
def abi_crs(G, reference_variable="CMI_C01"):
"""
Get coordinate reference system for the Advanced Baseline Imager (ABI).
Parameters
----------
G : xarray.Dataset
An xarray.Dataset to derive the coordinate reference system.
reference_variable : str
A variable in the xarray.Dataset to use to parse projection from.
Returns
-------
Three objects are returned
1. cartopy coordinate reference system
2. data projection coordinates in x direction
3. data projection coordinates in y direction
"""
# We'll use the `CMI_C01` variable as a 'hook' to get the CF metadata.
dat = G.metpy.parse_cf(reference_variable)
crs = dat.metpy.cartopy_crs
# We also need the x (north/south) and y (east/west) axis sweep of the ABI data
x, y = (dat.x, dat.y)
return crs, x, y
|
b420ea4cda12f1acd4b9af6ecd9c2f70c756f761
| 24,097 |
def get_unit(a):
"""Extract the time unit from array's dtype"""
typestr = a.dtype.str
i = typestr.find('[')
if i == -1:
raise TypeError("Expected a datetime64 array, not %s", a.dtype)
return typestr[i + 1: -1]
|
22f132af5ab751afdb75c60689086874fa3dfd99
| 674,274 |
def age_correction(start_year, T, age_vec):
"""Takes a start year, current year T and age vector of the upper bound of the age group (a_u)
returns a vector of 0 and 1 to avoid transition to unwanted age groups """
vec = (T - start_year) > age_vec
return vec.astype(int)[:-1]
|
6af68325be25fd85efeee97c67fba66c87183ed4
| 166,915 |
def length(*t, degree=2):
"""Computes the length of the vector given as parameter. By default, it computes
the Euclidean distance (degree==2)"""
s=0
for x in t:
s += abs(x)**degree
return s**(1/degree)
|
8f781651da482fd780266367b41baa844fac93c5
| 422,470 |
import filecmp
def comp_fnames_file_equality(fname1, fname2):
"""
Compare filenames: File equality:
Check if contents of files are identical.
Equality = True/False.
Uses filecmp byte-comparison (more efficient than md5).
"""
equality = filecmp.cmp(fname1, fname2, shallow=True)
if equality is True: ## if os.stat seems the same...
equality = filecmp.cmp(fname1, fname2, shallow=False) ## ...check contents to confirm identical
return equality
|
61647f46d8d25484d15167f332f670c08ea1ad5b
| 104,625 |
def is_key_translated(verbose, obj_id, key, object_json):
""" Checks if the given key of an object is translated in input JSON """
if key in object_json:
return True
if verbose:
print(f"No translation for {obj_id} string '{key}' in dump file -- skipping")
return False
|
b7c3966204463a06f019924b6df0cb78fca2052b
| 160,562 |
from typing import Union
from typing import Callable
from typing import Any
def complement(
expr: Union[bool, Callable[[Any], bool]]
) -> Union[bool, Callable[[Any], bool]]:
"""Takes in a predicate or a Boolean expression and
returns a negated version of the predicate or expression.
>>> complement(True)
>>> False
>>> def fn(el): # returns the Boolean of el
return bool(el)
>>> negated_fn = complement(fn)
>>> fn(1)
>>> True
>>> negated_fn(1)
>>> False
Added in version: 0.1.0
"""
if not isinstance(expr, Callable):
# Wrapped around bool to handle cases like not_(1).
# where 1 returns a boolean value of true.
return not bool(expr)
else:
def negated(*args, **kwargs):
return not expr(*args, **kwargs)
return negated
|
eb768723701205b5ef4e2c2b79ed0f91cb632437
| 432,150 |
def as_si(x: float, decimals: int) -> str:
"""
Convert a number to scientific notation
Parameters
----------
x : float
number to convert
decimals: float
number of decimal places
Returns
-------
x_si : string
x formatted in scientific notation
"""
s = "{x:0.{ndp:d}e}".format(x=x, ndp=decimals)
m, e = s.split("e")
x_si = r"{m:s} × $10^{{{e:d}}}$".format(m=m, e=int(e))
return x_si
|
5adbec315cf9eed2fd6e947f90d2f127f416fcc0
| 354,561 |
def replace_consts_with_values(s, c):
"""
Replace the constants in a given string s with the values in a list c.
:param s: A given phenotype string.
:param c: A list of values which will replace the constants in the
phenotype string.
:return: The phenotype string with the constants replaced.
"""
for i in range(len(c)):
s = s.replace("c[%d]" % i, str(c[i]))
return s
|
c04b44e338288709130ad930b833d6de4f3fece2
| 671,143 |
def normalize(hypotheses, index=-1):
"""Normalize probabilities."""
total = 0
for probs in hypotheses.values():
total += probs[index]
for probs in hypotheses.values():
probs[index] /= total
return total
|
11d239c09d146cdb9d67b3532bababe0e20517ba
| 518,648 |
def get_file_id(service, file_name, mime_type=None, parent_id=None):
"""Return the ID of a Google Drive file
:param service: A Google Drive API service object
:param file_name: A string, the name of the file
:param mime_type: A string, optional MIME type of file to search for
:param parent_id: A string, optional id of a parent folder to search in
:return file_id: A string, file ID of the first found result
"""
file_id = None
query = """name='{}'
and trashed=False
""".format(file_name)
if parent_id:
query += "and parents in '{}'".format(parent_id)
if mime_type:
query += "and mimeType in '{}'".format(mime_type)
try:
results = service.files().list(
q=query,
fields='files(name, id)').execute()
if len(results['files']) > 1:
print('Multiple files found, retrieving first from list')
file_id = results['files'][0]['id']
except Exception as e:
print('An error occurred: {}'.format(e))
return file_id
|
e8e371ea740ca4be55b35baa74c28207ca6b7b4d
| 697,787 |
def is_indent(xxx):
"""is character xxx part of indentation?"""
return xxx in ['\t', '|', ' ', '+', '-', '\\', '/']
|
a50f5d44a97479d34f42f280fae9ea3f790f61d4
| 356,949 |
def question_json_maker(question_id, question, answer, answer_index=1, question_type='MC', difficulty=1, points=10):
"""
Generates JSON file for each question.
:param question: input question.(str)
:param answer: output answer(str or int)
:param answer_index: index of the correct answer(int)
:param question_type: type of question ex: MC (Multiple Choice).(str)
:param difficulty: difficulty level of the question(1 to 5)(int)
:param points : points for each right answer. (int)
:return: a question.(JSON)
"""
questions_template = {
"questionID": question_id,
"question": question,
"questionType": question_type,
"answerSelectionType": "single",
"answers": answer,
"correctAnswer": answer_index,
"messageForCorrectAnswer": "Correct Answer",
"messageForIncorrectAnswer": "Incorrect Answer",
"difficulty": difficulty,
"point": points
}
return questions_template
|
bae0b4d02a687f7680ac2e98171f14b4e9bf5baf
| 370,100 |
def warshall_floyd(dist):
"""
Args:
Distance matrix between two points.
Returns:
Matrix of shortest distance.
Landau notation: O(n ** 3).
"""
v_count = len(dist[0])
for k in range(v_count):
for i in range(v_count):
for j in range(v_count):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
|
9d13c48aca39d69ab07b6a9c4be716102c6cc19b
| 408,465 |
def get_fragment(uri):
"""
Get the final part of the URI.
The final part is the text after the last hash (#) or slash (/), and is
typically the part that varies and is appended to the namespace.
Args:
uri: The full URI to extract the fragment from.
Returns:
The final part of the given URI.
"""
fragment_delimiters = ('#', '/')
alternatives = tuple(
uri.rsplit(delimiter, maxsplit=1)[-1]
for delimiter in fragment_delimiters
if delimiter in uri
)
# Return whatever alternative is shortest
return min(alternatives, key=len)
|
f1abd66c97b4e7d11873550d61755bb8e2fea78f
| 549,597 |
import requests
def submit_request(url: str, token: str, query: str) -> requests.Response:
"""Post a query to an API access point, along with an authentication token.
Retry with a progressive timeout window.
"""
MAX_REQUESTS = 3
TIMEOUT_INCREMENT = 5
response = None
req_count = 1
while (not response):
try:
response = requests.get(
url,
params={"v": "3", "t": token, "q": query},
headers={"user-agent": "Java"},
timeout=req_count * TIMEOUT_INCREMENT,
)
except requests.exceptions.Timeout:
if req_count >= MAX_REQUESTS:
raise
else:
print("Request Timeout, re-sending...")
req_count += 1
return response
|
9ccc1ef966b15ece39c3d2260adb06f4d327c9de
| 619,729 |
import json
def json_pretty(obj):
"""Convert obj into pretty-printed JSON"""
return json.dumps(obj, indent=4, sort_keys=True)
|
2c240eb7eb0c413f3da6d3477949968ea90ef5f9
| 621,319 |
def read_distance_file(dist_file, threshold):
"""
Read a previously created distance file and store it as a hash
:param threshold: The threshold for the distances
:type threshold: float
:param dist_file: The file to read
:type dist_file: str
:return: A hash of rxn1 rxn2 -> distance
:rtype: dict
"""
distances = {}
with open(dist_file, 'r') as f:
for l in f:
p = l.strip().split("\t")
if float(p[2]) > threshold:
continue
if p[0] not in distances:
distances[p[0]] = {}
if p[1] not in distances:
distances[p[1]] = {}
distances[p[0]][p[1]] = float(p[2])
distances[p[1]][p[0]] = float(p[2])
return distances
|
7e38543106e35fadb0a45fd158289e5985014477
| 111,670 |
import math
def get_distance(a, b):
"""Return Euclidean distance between points a and b."""
return math.sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2))
|
89c66e586a37a88dbce25460ad3310a035044c73
| 43,031 |
from typing import Iterable
def _n_name(invars: Iterable[str]) -> str:
"""Make sure that name does not exist in invars"""
name = "n"
while name in invars:
name = "n" + name
return name
|
fc3b5da0e762e1b212248c403ceda66c311a60f9
| 27,592 |
def createFromDocument(doc):
"""
Create an empty JS range from a document
@param doc DOM document
@return a empty JS range
"""
return doc.createRange()
|
3bd55c4f60b25bb089b592f9dfe65ea299230be8
| 688,185 |
def get_auth_dict(auth_string):
"""
Splits WWW-Authenticate and HTTP_AUTHORIZATION strings
into a dictionaries, e.g.
{
nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"',
opaque : "34de40e4f2e4f4eda2a3952fd2abab16"',
realm : "realm1"',
qop : "auth"'
}
"""
amap = {}
for itm in auth_string.split(", "):
(k, v) = [s.strip() for s in itm.split("=", 1)]
amap[k] = v.replace('"', '')
return amap
|
adb2c6dbcea429ae94c133b5b00148236da216e2
| 679,124 |
def extract_uuidlist_from_record(uuid_string_list):
"""Extract uuid from Service UUID List
"""
start = 1
end = len(uuid_string_list) - 1
uuid_length = 36
uuidlist = []
while start < end:
uuid = uuid_string_list[start:(start + uuid_length)]
start += uuid_length + 1
uuidlist.append(uuid)
return uuidlist
|
f6f4acdbdbfdf9aac909669d7ea3ad8492bed685
| 643,289 |
from typing import Union
from typing import List
from typing import KeysView
from typing import ItemsView
from typing import Any
def copyList(tocopy: Union[ List, KeysView, ItemsView] ) -> List[Any]:
"""
Copies an iterable to another list
:param tocopy: itarable to copy
:return: the copied list
"""
return [ x for x in tocopy]
|
01b306225e33ee74e47421e94721d21ce0638cb3
| 347,686 |
def spacify(string):
"""Add 2 spaces to the beginning of each line in a multi-line string."""
return " " + " ".join(string.splitlines(True))
|
2403f3fc1f193ae59be2dcfe2ac4911d542701cd
| 77,442 |
def window(x, win_len, win_stride, win_fn):
"""
Apply a window function to an array with window size win_len, advancing at win_stride.
:param x: Array
:param win_len: Number of samples per window
:param win_stride: Stride to advance current window
:param win_fn: Callable window function. Takes the slice of the array as input
:return: List of windowed values
"""
n = x.shape[0]
n_win = ((n - win_len)//win_stride)+1
x_win = [win_fn(x[i*win_stride:(i*win_stride)+win_len]) for i in range(n_win)]
return x_win
|
95ac180a57b6f0e3ca4517bdc8559f8875e94f94
| 676,710 |
import string
def capwords(value, sep=None):
"""
Split the argument into words using str.split(), capitalize each word using
str.capitalize(), and join the capitalized words using str.join(). If the
optional second argument sep is absent or None, runs of whitespace characters
are replaced by a single space and leading and trailing whitespace are
removed, otherwise sep is used to split and join the words.
"""
return string.capwords(value, sep=sep)
|
e481cab8af670b41130a1728869fa424e07ed5b8
| 689,786 |
def get_num_fsaverage_verts_per_hemi(fsversion=6):
"""
Return the number of vertices per fsaverage hemisphere.
Returns
-------
vertcount: int
The number of vertices per fsaverage hemisphere.
"""
if fsversion == 6:
return 163842
else:
raise ValueError("Currently the only supported FreeSurfer version is 6.")
|
c4db648da7b2746cf8304330d20c6fc31363d839
| 155,509 |
def to_format(phrase: str, param: str):
"""
The 'phrase' string is formatted taking 'param' parameter
:param phrase: it must contain a {} that will be replaced by the 'param' parameter
:param param: parameter
:return: formatted string
"""
return phrase.format(param)
|
e85ff63425f9fbda909d4ed75544ee5c182daa29
| 113,130 |
def get_default_alignment_parameters(adjustspec):
"""
Helper method to extract default alignment parameters as passed in spec and return values in a list.
for e.g if the params is passed as "key=value key2=value2", then the returned list will be:
["key=value", "key2=value2"]
"""
default_alignment_parameters = []
if (
"defaultAlignmentParams" in adjustspec
and adjustspec["defaultAlignmentParams"] is not None
):
default_alignment_parameters = adjustspec["defaultAlignmentParams"].split()
return default_alignment_parameters
|
79ab15863ef12269c3873f41020d5f6d6a15d745
| 674,510 |
async def ping():
"""Inspects if the API instance is running."""
return {"ping": "pong"}
|
fb2cb7128a66bda332e0a0e65314bfd5e9fee305
| 630,524 |
def fahrenheit_to_celsius(temp_in_f):
"""
Actually does the conversion of temperature from F to C.
PARAMETERS
--------
temp_in_f: float
A temperature in degrees Fahrenheit.
RETURNS
-------
temp_in_c: float
The same temperature converted to degrees Celsius.
"""
return (temp_in_f-32)*5/9
|
702b501739f4fe482884280bf7b685a2f7cd6073
| 563,434 |
def extractdata(line):
"""For each line, return the x and y values, check whether there is reference value
and if so return the reference value, otherwise return a reference value of 1 """
newArray = (line.split(',')) #
if len(newArray) == 8:
# convert the strings to floats
xvalue = float(newArray[3])
yvalue = float(newArray[5])
refvalue = float(newArray[7])
return xvalue, yvalue, refvalue
if len(newArray) == 6:
# convert the strings to floats
xvalue = float(newArray[3])
yvalue = float(newArray[5])
refvalue = 1
return xvalue, yvalue, refvalue
else:
print("Houston, we have a problem, This line does not appear to be data!:")
print(line)
|
c7cb553bedef333cf9950588757906c7f114d535
| 50,143 |
from typing import Counter
import itertools
def build_vocab(texts):
"""
Builds a vocabulary mapping from word to index based on the sentences.
Returns vocabulary mapping and inverse vocabulary mapping.
"""
# Build vocabulary
word_counts = Counter(itertools.chain(*texts))
# Mapping from index to word
vocabulary_invariable = [x[0] for x in word_counts.most_common()]
vocabulary_invariable = list(sorted(vocabulary_invariable))
# Mapping from word to index
vocabulary = {x: i for i, x in enumerate(vocabulary_invariable)}
inverse_vocabulary = {v: k for k, v in vocabulary.items()}
return [vocabulary, inverse_vocabulary]
|
2f464abc4d8cc1ccef312907f4265d0882c8a6de
| 560,551 |
def get_building_coords(town):
"""
Generates a dictionary of all (x,y) co-ordinates that are within buildings
in the town, where the keys are the buildings' numbers (or "pub" for the
pub) and the values are lists of co-ordinates associated with the building.
Data must have 25 houses (numbered as multiples of 10 from 10 to 250) and
1 pub.
Parameters
----------
town : list
List (cols) of lists (rows) representing raster data of the town.
Returns
-------
building_coords : dict
Keys are the buildings' numbers (or "pub" for the pub) and the values
are lists of all co-ordinates that are within the building.
"""
#Create empty dictionary to collect building co-ordinates
building_coords = {}
# Create list of co-ordinates for each building in the town
# Dictionary key is either "pub" or building number and value is list of
# coords
for n in [1, *range(10, 260, 10)]:
if n == 1:
building_name = "pub"
else:
building_name = n
building_coords[building_name] = []
for y in range(len(town)):
for x in range(len(town[y])):
if town[y][x] == n:
building_coords[building_name].append((x, y))
return building_coords
"""
# Make pub clearer for plotting
for i in range(len(town)):
for j in range(len(town[i])):
if town[i][j] == 1:
town[i][j] = -50
"""
|
085c95d40d9d84569180155f5b0b150334dbc526
| 695,908 |
from typing import Iterable
import glob
def find_onewire_devices() -> Iterable[str]:
"""Get the list of files corresponding to devices
on the one-wire bus.
Args:
Returns:
Iterable[str]: The file paths.
"""
return glob.glob('/sys/bus/w1/devices/28*/w1_slave')
|
354f9927b24c41b2e121c8c44ae8f3e0c3cf9bc0
| 117,779 |
import pytz
def utc_datetime_to_button_format(utc_dt):
"""
Convert a UTC datetime obj to the the date and time
format we need for slack buttons in Eastern time.
"""
eastern = pytz.timezone('US/Eastern')
east_conv = utc_dt.astimezone(eastern)
time_text = east_conv.strftime("%H:%M")
date_text = east_conv.strftime("%m/%d")
return date_text, time_text
|
81bce6e8f44f62eaba595d9384b28f15db6d4de0
| 576,172 |
def delta_f(kA, kB, NA, NB):
"""
Difference of frequencies
"""
return kA / NA - kB / NB
|
e96b70a2aaccff6a3e13693dd83c8df171e019ba
| 203,513 |
def rgba(color):
""" Return 4-element list of red, green, blue, alpha values. """
if color.startswith('rgba'):
values = [int(v) for v in color[5:-1].split(',')]
else:
values = [int(v) for v in color[4:-1].split(',')]
values.append(1)
return values
|
e5468a52b74100bce23a26c51a4e395b7a0d2fe6
| 102,192 |
def check_all_matching_tags(tag_arg_dict, target_tag_dict):
"""
Return True if all tag sets in `tag_arg_dict` is a subset of the
matching categories in `target_tag_dict`.
"""
return all(
[
tags_set.issubset(target_tag_dict.get(tag_name, set()))
for tag_name, tags_set in tag_arg_dict.items()
]
)
|
9b3ef0df9e34a515ecb17c02e0fb95c5491ffa11
| 288,980 |
def readSampleFile(filepath):
"""
Parse sample file into dictionary.
Return sample dictionary and sample order list.
"""
samples = {}
sOrder = []
with open(filepath, "r") as fh:
for l in fh:
l = l.rstrip("\n")
s, r = l.split("\t")
try:
samples[s]
except KeyError:
samples[s] = []
samples[s].append(r)
sOrder.append((s, r))
return samples, sOrder
|
6de5a601286cd17936eeda2bacd41ff28636c4ff
| 132,395 |
def gettypes(*a):
"""
Convert a list of objects to their types
"""
return list(map(type, a))
|
ff7bbf719cd115c178afd12c2cbd67243c7ecab7
| 168,492 |
import hashlib
def hash(text):
"""Make a hash of the text
:param text: text to make the hash
:returns: hashed version of the text
"""
return hashlib.sha256(text.encode('utf-8')).hexdigest()
|
a4f1210f86fd520346a196bacd6c603ee6859eec
| 217,413 |
def glue_tracks(tracks):
"""
This functions glues all tracks in a single one,
using the specified fade for each track, and
returns the resulting audio.
"""
final = tracks[0][0]
for audio, fade in tracks[1:]:
final = final.append(audio, crossfade=fade)
return final
|
d2fd8a0334a5d71f41045fd4495a4c7be2389365
| 263,240 |
def _text_repr(text, max_len=1000):
"""
Return the input text as a Python string representation (i.e. using repr())
that is limited to a maximum length.
"""
if text is None:
text_repr = 'None'
elif len(text) > max_len:
text_repr = repr(text[0:max_len]) + '...'
else:
text_repr = repr(text)
return text_repr
|
350e6fdfba1f1b95914002ab1a38005da3c79fbc
| 154,293 |
from typing import Counter
def sock_merchant(colors: list[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([1, 2, 1, 2, 1, 3, 2])
2
"""
return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values())
|
5493bfea83141e253e94ad2f7090f5c19922360c
| 580,592 |
def get_9s(percentile):
"""
Method that gets the amount of 9s in a percentile
Args:
percentile: The percentile to get the amount of 9s for
Returns:
The amount of 9s of the percentile, so 0.4->0, 0.92->1, 0.994->2, etc.
"""
counter = 1
# Limit to 20 nines, probably won't ever see higher amount than this due to exponential growth
while counter < 20:
if percentile + 1/(10 ** counter) < 1.0:
break
counter += 1
return counter - 1
|
9eb99415a5477818b309b04ac8aa80a421943860
| 321,672 |
import torch
def count_parameters(model: torch.nn.Module) -> int:
"""Return the number of trainable parameters of a model.
Taken from: https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/7.
Parameters
----------
model : torch.nn.Module
The model to count the parameters from.
Returns
-------
int
The number of trainable parameters of the given model.
"""
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
f27b24834144a327df284f3c2961649da225807b
| 244,837 |
def ensure_complete_modality(modality_dict, require_rpc=False):
"""
Ensures that a certain modality (MSI, PAN, SWIR) has all of the required files for computation
through the whole pipeline.
:param modality_dict: Mapping of a certain modality to its image, rpc, and info files.
:type modality_dict: dict
:param require_rpc: Whether or not to consider the rpc file being present as a requirement for
a complete modality.
:type require_rpc: bool
"""
keys = ['image', 'info']
if require_rpc:
keys.append('rpc')
return all(key in modality_dict for key in keys)
|
a35543009470c3f0f80cfc8f4137913aa26bfe80
| 287,506 |
import random
def guess_by_random(agent, words):
"""A word-selection action that simply chooses a word from the given list
of words at random, using `random.choice()`.
Parameters:
`agent`: An instance of an agent class that derives from `BaseRLAgent`
`words`: The list of words to choose from
"""
guess = random.choice(words)
agent.guesses.append(guess)
return guess
|
8a61ed7b2252863ca3ec59b3137d68ae0a2f032f
| 165,673 |
def set_serialization_options(opts, output_folder=""):
""" Enable / disable the serialization to disk of the compiled executables.
.. code-block:: python
# Create a device that will save to disk all the compiled executables.
opts = create_ipu_config()
opts = set_serialization_options(opts,
output_folder="/tmp/my_network")
ipu.utils.configure_ipu_system(opts)
with tf.Session() as s:
...
Args:
output_folder: Where to save the compiled executables.
Set to "" to disable serialization.
Returns:
The IpuOptions configuration protobuf.
"""
opts.serialization_folder = output_folder
return opts
|
0bb11e812917cf94b9ccde7957e1d5c8b503b833
| 547,094 |
def submit(ds, entry_name, molecule, index):
"""
Submit an optimization job to a QCArchive server.
Parameters
----------
ds : qcportal.collections.OptimizationDataset
The QCArchive OptimizationDataset object that this calculation
belongs to
entry_name : str
The base entry name that the conformation belongs to. Usually,
this is a canonical SMILES, but can be anything as it is represents
a key in a dictionary-like datastructure. This will be used as an
entry name in the dataset
molecule : QCMolecule
The JSON representation of a QCMolecule, which has geometry
and connectivity present, among others
index : int
The conformation identifier of the molecule. This is used to make
the entry names unique, since each conformation must have its own
unique entry in the dataset in the dataset
Returns
-------
(unique_id, success): tuple
unique_id : str
The unique_id that was submitted to the dataset. This is the name
of the new entry in the dataset.
success : bool
Whether the dataset was able to successfully add the entry. If this
is False, then the entry with the name corresponding to unique_id
was already present in the dataset.
"""
# This workaround prevents cmiles from crashing if OE is installed but has
# no license. Even though rdkit is specified, protomer enumeration is OE-
# specific and still attempted.
# oe_flag = cmiles.utils.has_openeye
# cmiles.utils.has_openeye = False
# attrs = cmiles.generator.get_molecule_ids(molecule, toolkit="rdkit")
# cmiles.utils.has_openeye = oe_flag
CIEHMS = "canonical_isomeric_explicit_hydrogen_mapped_smiles"
molecule["extras"] = {CIEHMS: entry_name}
attrs = {CIEHMS: entry_name}
unique_id = entry_name + f"-{index}"
success = False
try:
ds.add_entry(unique_id, molecule, attributes=attrs, save=False)
success = True
except KeyError:
pass
return unique_id, success
|
50a30a25af59906ce5636ce8a176e29befd27d60
| 1,861 |
def restore_path(p: list, v):
"""
Convert predecessors list to path list
Parameters
----------
p : list
predecessors
v
searched node
Returns
-------
path : list
path[i] is the node visited in the ith step
"""
path = [v]
u = p[v]
while u != -1:
path.append(u)
u = p[u]
return list(reversed(path))
|
6e2f970d2e08e16efb97ab20b774369a7f2edab7
| 281,190 |
import torch
def compute_pdist_matrix(batch, p=2.0):
"""
Computes the matrix of pairwise distances w.r.t. p-norm
:param batch: torch.Tensor, input vectors
:param p: float, norm parameter, such that ||x||p = (sum_i |x_i|^p)^(1/p)
:return: torch.Tensor, matrix A such that A_ij = ||batch[i] - batch[j]||_p (for flattened batch[i] and batch[j])
"""
mat = torch.zeros(batch.shape[0], batch.shape[0], device=batch.device)
ind = torch.triu_indices(batch.shape[0], batch.shape[0], offset=1, device=batch.device)
mat[ind[0], ind[1]] = torch.pdist(batch.view(batch.shape[0], -1), p=p)
return mat + mat.transpose(0, 1)
|
ae997a59c7e208fca4dc80ee1f7865320edeff86
| 681,634 |
import copy
def merge_objects(obj_of_values, obj_of_default_values):
"""
obj_of_values represents a sub sets of values, for example a selection of options values.
obj_of_default_values represents the complete list of possible option values and their default values
returns obj_of_values with all missing properties set to the values in obj_of_default_values.
"""
if not (isinstance(obj_of_values, object) and isinstance(obj_of_default_values, object)):
raise ValueError("merge_objects one of the arguments is not an object")
new_obj_of_values = copy.deepcopy(obj_of_values)
d1 = new_obj_of_values.__dict__
d2 = obj_of_default_values.__dict__
keys = list(d2.keys())
for k in keys:
v = d2[k]
if not (k in d1.keys()):
d1[k] = v
elif d1[k] is None:
d1[k] = v
return new_obj_of_values
|
f2315e6165c9342c0177675ff9a65beb46d0f5cf
| 325,849 |
def get_col_names(cursor, table):
"""
Helper function to retrieve columns from SQLite memory table
:param cursor:
:param table:
:return:
"""
cursor.execute('SELECT * FROM "{table}"'.format(table=table))
return [member[0] for member in cursor.description]
|
47c92e4317bd3d77ba62a9998ec3607d7ad67860
| 248,607 |
import gzip
def open_file_helper(filename, compressed, mode="rt"):
"""
Supports reading of gzip compressed or uncompressed file.
Parameters:
----------
filename : str
Name of the file to open.
compressed : bool
If true, treat filename as gzip compressed.
mode : str
Reading mode.
Returns:
--------
file handle to the opened file.
"""
return gzip.open(filename, mode=mode) if compressed else open(filename, mode)
|
a682924f68158f88552b96197c43735bb596afaa
| 604,130 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.