content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def replace_halogen(smiles):
"""
Replace halogens with single letters (Cl -> L and Br -> R), following
Olivecrona et al. (J Cheminf 2018).
"""
br = re.compile('Br')
cl = re.compile('Cl')
smiles = br.sub('R', smiles)
smiles = cl.sub('L', smiles)
return smiles | b3c90c8f00518d2f4edda99e4fd69335e69967cc | 680,515 |
def form_dataframe_to_arrays(df):
"""
Convert dataframes into arrays in both variables and target
"""
feature_order = list(df.filter(regex="[^M_t+\d]").columns)
X = df.filter(regex="[^M_t+\d]").values
Y = df.filter(regex="[\+]").values.flatten()
return X,Y,feature_order | 2046f0b91a12612a37414832337f18fd108abc2a | 680,518 |
from typing import Optional
import re
def _read_url_slug(file_contents: str) -> Optional[str]:
"""Returns slug parsed from file contents, None if not found."""
regex = r"""url=[^"]+\.[^"]+\/(?P<slug>[-\w]+)(\/|[\w.]+)?\""""
match = re.search(regex, file_contents, re.VERBOSE)
if match:
return m... | 61dbe2186480ed1b0591c1fb2608d419a99ed29c | 680,523 |
def permute_dimensions(x, pattern):
"""Transpose dimensions.
pattern should be a tuple or list of
dimension indices, e.g. [0, 2, 1].
"""
pattern = tuple(pattern)
return x.transpose(pattern) | 87c7215721c0a02777e40c850f6daaa66f4b0045 | 680,525 |
import base64
def _make_user_code(code: str) -> str:
"""Compose the user code into an actual base64-encoded string variable."""
code = base64.b64encode(code.encode("utf8")).decode("utf8")
return f'USER_CODE = b"{code}"' | 066c483b6224dee044275636084c25f228250817 | 680,530 |
def find_missing_items(intList):
"""
Returns missing integers numbers from a list of integers
:param intList: list(int), list of integers
:return: list(int), sorted list of missing integers numbers of the original list
"""
original_set = set(intList)
smallest_item = min(original_set)
l... | 8fcc77987834c16875f8a7062e4dcc596a7d7566 | 680,531 |
def AsList(arg):
"""return the given argument unchanged if already a list or tuple, otherwise return a single
element list"""
return arg if isinstance(arg, (tuple, list)) else [arg] | 381094573889688dda32b37b8ce8344c9ddf31e9 | 680,533 |
import io
def has_fileno(stream):
"""
Cleanly determine whether ``stream`` has a useful ``.fileno()``.
.. note::
This function helps determine if a given file-like object can be used
with various terminal-oriented modules and functions such as `select`,
`termios`, and `tty`. For m... | 5daa9f765a9c706a085b97b6d63d67ed9ebb72d3 | 680,539 |
def select_dropdown(options, id=None):
"""Generate a new select dropdown form
Parameters
----------
options: List[str]
list of options the user can select
id: str
DOM id used to refer to this input form
"""
html_options = ''.join(f'<option>{opt}</option>' for opt in options... | 001f8f61def33b33611158a34a2dc7416b6f382c | 680,540 |
def read(path):
"""
Read a file
"""
with open(path) as file_:
return file_.read() | 28143cce26b90e1fbea16554f80900da23b37ba6 | 680,546 |
def createDict(data, index):
"""
Create a new dictionnay from dictionnary key=>values:
just keep value number 'index' from all values.
>>> data={10: ("dix", 100, "a"), 20: ("vingt", 200, "b")}
>>> createDict(data, 0)
{10: 'dix', 20: 'vingt'}
>>> createDict(data, 2)
{10: 'a', 20: 'b'}
... | 3afb604d81401cd4c5b1cac93fb26b05ab1fdb24 | 680,548 |
def is_port_vlan_member(config_db, port, vlan):
"""Check if port is a member of vlan"""
vlan_ports_data = config_db.get_table('VLAN_MEMBER')
for key in vlan_ports_data:
if key[0] == vlan and key[1] == port:
return True
return False | 03a0de5b285fd7295526b1ef63d12629e27d9c8e | 680,550 |
from typing import List
import random
def uniformly_split_num(
sum: int,
n: int,
) -> List[int]:
"""Generate `n` non-negative numbers that sum up to `sum`"""
assert n > 0, 'n should be > 0'
assert sum >= 0, 'sum should be >= 0'
random_numbers = [random.randint(0, sum) for _ in range(n - 1)]
... | 8136cce9bd258e7b187646967402dc428f04a764 | 680,551 |
def _update_count_down(previous_count_down_minutes, check_mail_interval, current_time, start_time, main_window) -> int:
"""
Utility method, update status message text ("count down") until next mail check begins
:param previous_count_down_minutes: current state of counter
:param check_mail_interval: give... | 8f94896afe63cf61399e1ef5341e258216a8b59d | 680,552 |
async def get_int_list(redis, key):
"""Get a list of integers on redis."""
str_list = await redis.lrange(key, 0, -1)
int_list = [int(i) for i in str_list]
return int_list | 61f84ba3122deaaaf3aba7d22312242b24161724 | 680,554 |
def swap_list_order(alist):
"""
Args:
alist: shape=(B, num_level, ....)
Returns:
alist: shape=(num_level, B, ...)
"""
new_order0 = len(alist[0])
return [[alist[i][j] for i in range(len(alist))] for j in range(new_order0)] | ad73a3e74b18e8b2b6bc12d879c7477d673f3faa | 680,555 |
def PWM_scorer(seq, pwm, pwm_dict, pwm_type):
"""
Generate score for current seq given a pwm.
"""
seq_score = 0.0
for i in range(0, len(seq)):
seq_score += pwm[pwm_dict[seq[i:i+1]]][i]
return seq_score | e15cc95d972626ace134c2525b77895bb18ee882 | 680,557 |
def _collect_facts(operators):
"""
Collect all facts from grounded operators (precondition, add
effects and delete effects).
"""
facts = set()
for op in operators:
facts |= op.preconditions | op.add_effects | op.del_effects
return facts | 61fe46177502cdd164df65b4332fb66176c10641 | 680,559 |
import math
def _brevity_penalty(candidate, references):
"""Calculate brevity penalty.
As the modified n-gram precision still has the problem from the short
length sentence, brevity penalty is used to modify the overall BLEU
score according to length.
An example from the paper. There are three r... | b56c53730b2a90581a89f8cffa51f34c5d643984 | 680,563 |
import hashlib
import json
def hash_dump(data):
"""Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes.
:param data: An arbitrary JSON-serializable object
:type data: dict or list or tuple
:rtype: str
"""
return hashlib.sha512(json.dum... | 7dc9cc75df3c3b2e9c9aa7207bfcd11c236f26c6 | 680,568 |
def clean_dict(dictionary):
""" Remove items with None value in the dictionary and recursively in other nested dictionaries. """
if not isinstance(dictionary, dict):
return dictionary
return {k: clean_dict(v) for k, v in dictionary.items() if v is not None} | 50d87d097b00cee3a8c1fb1d6e4c4f7b7237c5e0 | 680,569 |
def get_padding_prp(hparams):
"""Get padding for pad_rotate_project measurements"""
if hparams.dataset == 'mnist':
paddings = [[0, 0], [6, 6], [6, 6], [0, 0]]
elif hparams.dataset == 'celebA':
paddings = [[0, 0], [14, 14], [14, 14], [0, 0]]
else:
raise NotImplementedError
ret... | a26c6286aa6624baa2bb37de2eac29d124992586 | 680,570 |
def get_post_data(request):
"""
Attempt to coerce POST json data from the request, falling
back to the raw data if json could not be coerced.
:type request: flask.request
"""
try:
return request.get_json(force=True)
except:
return request.values | c59aa6bd4d8059517761a4ec641b1a5f35ee075d | 680,571 |
def sort_by_hw_count(user):
"""Sort students by the number of completed homeworks"""
return sum([1 if hw['status'] == 'success' else 0 for hw in user['homeworks']]) | f2d2818f207e09551ac54acae0080c689fc033e6 | 680,572 |
def getOrientation( geom , camera=True):
"""
build and return a dictionary storing the orientation for geom
orientDict <- getOrientation( geom )
"""
orientMem = {}
orientMem['rotation'] = geom.rotation[:]
orientMem['translation'] = geom.translation.copy()
orientMem['scale'] = geom.scal... | c2affdabdc3cad50c5ed673ddb6739d6a96fe589 | 680,574 |
def patch_from_tupled_dict(tupled_dict):
""" Creates a nested dictionary that f90nml can interpret as a patch."""
patch = {}
for replace_this, replace_val in tupled_dict.items():
group, field = replace_this
group, field = group.lower(), field.lower()
gdict = patch.get(group, {})
... | 325f563aea1e53560e4c3837f9f2028da9e1e504 | 680,577 |
import yaml
def yaml_to_base_type(node, loader):
"""
Converts a PyYAML node type to a basic Python data type.
Parameters
----------
node : yaml.Node
The node is converted to a basic Python type using the following:
- MappingNode -> dict
- SequenceNode -> list
- Sca... | f72650a71a7e3e7bcc1fe460c6e72acb7519fc98 | 680,578 |
import re
def find_note_contents_start(md_text_lines):
"""
Some notes in Bear contain #tags near the title. This returns the index in the list that\
isn't the title or contains tags. If no index found, return len(md_text_lines)
"""
# Start at 1 to skip the title
# Look for regex matches of tag... | d532657a78c259f60008fed6c3d14ed9779be6a9 | 680,579 |
def resize_fn(attributions, inputs, mode):
"""Mocked resize function for test."""
del inputs, mode
return attributions | dfe48a6c1cb30de8d1f7527d61e8779365df2c35 | 680,580 |
def print_module(module, print_flag=None):
"""Returns module in XML format. Accepts only {dict}.\n
- Only works with one module at a time: otherwise iteration is needed.
- Module "value" field accepts str type or [list] for datalists.
- Use print_flag to show modules' XML in STDOUT.
"""
data = d... | 9a71e6c82fc815847c0496b5468d5fb71f41fb3b | 680,582 |
def flatten(lists):
"""
flattens a list of lists x
"""
result = []
for x in lists:
for elem in x: result.append(elem)
return result | 9200d097a4e7e2f32cbfce5bcf2e7d6937e660c5 | 680,583 |
import math
def format_memory_size(bytes):
"""Return a humanly readable formatting of 'bytes' using powers of 1024.
"""
units = ('Bytes', 'KB', 'MB', 'GB', 'TB')
if bytes < 1024:
return '%d %s' % (bytes, units[0])
else:
scale = min(math.floor(math.log(bytes, 1024)), len(units)-1)
... | 17689a87473dd2a88a58365489d87749b88e0a4f | 680,585 |
def optimal_summands(n: int):
"""
Gets the maximum number of distinct prizes.
>>> optimal_summands(6)
[1, 2, 3]
>>> optimal_summands(8)
[1, 2, 5]
>>> optimal_summands(2)
[2]
"""
if n <= 2:
return [n]
opt_sum = 0
summands = []
for num in range(1, n):
... | 61f4c8f3a7e4045d33de08761eb5103717ed8389 | 680,586 |
import random
def gen_ran_len_lst(n=500):
"""Returns a random 0, n length list of 0, n random numbers."""
lst = []
for i in range(random.randrange(0, n)):
lst.append(random.randrange(0, n))
return lst | d3d443c9d365c5a93708d18dc0837a19a495e0e4 | 680,595 |
def sum_multiples(n):
"""Returns the sum of multiples of three and five below n"""
assert n >= 0
return sum([i for i in range(n) if (not i%3) or (not i%5)]) | 801c8a5c7fb0b2afc4174e33702a91a24cbc28f7 | 680,598 |
import collections
def compute_dominators(func, cfg):
"""
Compute the dominators for the CFG, i.e. for each basic block the
set of basic blocks that dominate that block. This means that every path
from the entry block to that block must go through the blocks in the
dominator set.
dominato... | 8d6c2a6bcdda860b2b91cc1742c031f4c3e6917f | 680,600 |
def structure_to_composition(series, reduce=False):
"""
Converts a Structure series to a Composition series
Args:
series: a pd.Series with pymatgen.Structure components
reduce: (bool) whether to return a reduced Composition
Returns:
a pd.Series with pymatgen Composition compone... | c80f8704ef3456b68b8f922354798d350a86d0d7 | 680,601 |
from typing import OrderedDict
import json
import warnings
def read_json(file_path, encoding='UTF-8', ordered=True):
"""Read a JSON file.
Wraps the json.load() method.
Arguments:
file_path {str} -- path of file to read
Keyword Arguments:
encoding {str} -- encoding to read the file ... | 0ec1aa1df9195cad224fe84a2e0f699183aa7c59 | 680,602 |
def rotate(scale, n):
""" Left-rotate a scale by n positions. """
return scale[n:] + scale[:n] | df57f98f30acc2e16f7792c50afee81fdf2b56d6 | 680,603 |
import torch
def sample_pdf(
bins: torch.Tensor,
weights: torch.Tensor,
N_samples: int,
det: bool = False,
eps: float = 1e-5,
):
"""
Samples a probability density functions defined by bin edges `bins` and
the non-negative per-bin probabilities `weights`.
Note: This is a direct con... | 8d706ef5952a3c4ff5081a04d22f2e5fd4b2045b | 680,607 |
from functools import reduce
def getattrs(obj, attrs, default=None):
"""
Get attrs from obj
:param obj: object
:param attrs: string or iterable object
:param default: default value
:return: obj attr value if existed, otherwise default value
"""
if not attrs:
return obj
if ... | df73db4b30b53f19a49710a0d097c7049863783e | 680,614 |
def get_comparative_word_freq(freqs):
"""
Returns a dictionary of the frequency of words counted relative to each other.
If frequency passed in is zero, returns zero
:param freqs: dictionary
:return: dictionary
>>> from gender_novels import novel
>>> novel_metadata = {'author': 'Hawthorne,... | 5d59d25a15119a8e5f934804f1b8ee4ab5ecdbc4 | 680,615 |
def triplet_pattern(t):
"""Convert an arbitrary 3-tuple into a string specifying the distinct elements."""
if t[0] == t[1] == t[2]:
return "AAA"
if t[0] == t[1]:
return "AAB"
if t[1] == t[2]:
return "ABB"
return "ABC" | 9970dca9cf87d6e85fbf4c0821083335fbce3cd7 | 680,617 |
def set_emulated_vision_deficiency(type: str) -> dict:
"""Emulates the given vision deficiency.
Parameters
----------
type: str
Vision deficiency to emulate.
**Experimental**
"""
return {"method": "Emulation.setEmulatedVisionDeficiency", "params": {"type": type}} | 906fc7b62a3d669b1a7843bf47df06c0b1862095 | 680,618 |
def parse_args(args):
"""
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz'])
"""
index = None
for arg_i, arg in enumerate(args):
if not a... | 6e02216d7ff1af7677e5df956a508d7b80af43dd | 680,619 |
import ssl
import socket
def get_ssl_serversocket(file_certchain, file_privatekey, bindoptions, password_privkey=None):
"""
Create a SSL based server socket. Useage:
conn, addr = ssock.accept()
data = conn.recv()
conn.send(data)
Certificate/private key can be create via:
openssl req -x509... | ff82d99c13b0d5de44a0a3a1fd697c4cb32ea314 | 680,620 |
def ParseCodePoint(s):
"""Parses the pua string representation.
The format of the input is either:
- empty string
- hexadecimal integer.
- hexadecimal integer leading '>'.
We're not interested in empty string nor '>'-leading codes, so returns None
for them.
Note that '>'-leading code means it is "seco... | 0fdd717d31aa2c95d4c3eb2a9b68c12e3006d82b | 680,622 |
def checksum_min_max(sheet_file):
"""Return the sum of each row's max - min"""
result = 0
with open(sheet_file) as f:
sheet_list = f.readlines()
for row in sheet_list:
int_row = [int(i) for i in row.split('\t')]
result = result + (max(int_row) - min(int_row))
re... | 216e47be6879c069ec6097a1b60c509a11ced4b7 | 680,623 |
def _isCharEnclosed(charIndex, string):
""" Return true if the character at charIndex is enclosed in double quotes (a string) """
numQuotes = 0 # if the number of quotes past this character is odd, than this character lies inside a string
for i in range(charIndex, len(string)):
if string[i] == '"':... | 70d70617fa869cc7b28abd3a7def28ea77b6a896 | 680,624 |
def soap_auth(client, tenant, username, password):
"""Authenticate to the web services"""
if not tenant:
return client.service.authenticate(
username=username, password=password
)
return client.service.authenticateTenant(
tenantName=tenant, username=username, password=pa... | 7e79d74ccbead6525d2555afbc20d9b7b28669c6 | 680,626 |
def correct_mag(m0, X, k):
"""Correct magnitude for airmass and extinction.
Parameters
----------
m0 : float
Apparent magnitude.
X : float
Airmass.
k : float
Extinction coefficient.
Returns
-------
m : float
The corrected apparent magnitude.
"""... | 807069d865cc00a984a5dfc2b6df5ff889ed78c4 | 680,628 |
def split_off_attrib(xpath):
"""
Splits off attribute of the given xpath (part after @)
:param xpath: str of the xpath to split up
"""
split_xpath = xpath.split('/@')
assert len(split_xpath) == 2, f"Splitting off attribute failed for: '{split_xpath}'"
return tuple(split_xpath) | 6a4669de50fb78fa471310735a7b7c883d4931f8 | 680,629 |
import hashlib
def hash_file(path):
"""
Returns the SHA-256 hash of a file.
Parameters
----------
path : `str`
The path of the file to be hashed.
Returns
-------
`str`
SHA-256 hash of the file.
References
----------
* https://stackoverflow.com/a/22058673
... | 7a00a0b79fe2ec6664b476f8e7171ce1a38973f5 | 680,630 |
def str2list(v):
"""
Transform user input list(arguments) to be list of string.
Multiple options needs comma(,) between each options.
ex)
--strategies ST01
--strategies ST01,ST02,ST03
:param v: (string) user input
:return: list of option string. (ex - ['ST01', 'ST02', 'ST03')
... | c31436ef7b76f894b6cd7c0c0ecf16747e5925e4 | 680,634 |
import json
def retrieve_ecli(ecli, db_session):
"""
Retrieves the ecli from a database
:param ecli: The ECLI identifier
:param db_session: a sqlalchemy session object
"""
res = db_session.execute('select * from cases where ecli=:ecli',
{"ecli":ecli})
... | 76d383182e2996a73d6d3ac1f7b672d216dc8add | 680,635 |
def conjugate_strand(strand):
"""Given a dna strand, re-write it as it's reverse complement."""
basepair = {'a': 't', 't': 'a', 'g': 'c', 'c': 'g'}
rev_strand = ''.join(basepair[s] for s in strand[::-1]
if s in basepair.keys())
return rev_strand | 05b1bbfa2a0114c7d4eec802af8455deb34de350 | 680,640 |
def binary(val):
""" validates if the value passed is binary (true/false)"""
if type(val) == bool:
return val
else:
raise ValueError("random seed is a boolean flag") | fd5c5f8229fb9b227b5aff9a50b063463b51147c | 680,643 |
def fixture_to_tables(fixture):
""" convert fixture into *behave* examples
:param fixture: a dictionary in the following form::
{
"test1name":
{
"test1property1": ...,
"test1property2": ...,
...
},
"test2nam... | f1668c302e564a0c79cc001a79e88fb5cecd5f59 | 680,651 |
def extract_message(result): # pragma: no cover
"""Extracts the original message from a parsing result."""
return result.get('text', {}) | c7179dbf1f162eb44974d5230a60e681a8f58d77 | 680,654 |
import re
def available_space(ctx, device):
"""
Determine the available space on device such as bootflash or stby-bootflash:
:param ctx:
:param device: bootflash / stby-bootflash: / harddisk: / stby-harddisk:
:return: the available space
"""
available = -1
output = ctx.send('dir ' + ... | 2d831e644ed5d843b80397472e2cab65fccced1b | 680,657 |
def ssh_host(config, host):
"""Get the full user/host pair for use in SSH commands."""
return '{}@{}'.format(config.user, host) | 0bb245de5528a4154fcdaf88228d7860921f8b14 | 680,659 |
def getKey(spc):
"""
Returns a string of the species that can serve as a key in a dictionary.
"""
return spc.label | f67bd95004f68f435d5b5032c7e381edde930d6a | 680,661 |
import operator
def get_ecdf(array, reverse=False):
"""
Generate the empirical distribution function.
:param array: array_like
:param reverse: bool
:return: float -> float
"""
n = len(array)
op = operator.ge if reverse else operator.le
def ecdf(t):
m = sum(op(x, t) for x i... | 86e6728f295c1d5f77db46e30b19f606a87f6797 | 680,663 |
import torch
def obb2poly_v1(rboxes):
"""Convert oriented bounding boxes to polygons.
Args:
obbs (torch.Tensor): [x_ctr,y_ctr,w,h,angle]
Returns:
polys (torch.Tensor): [x0,y0,x1,y1,x2,y2,x3,y3]
"""
x = rboxes[:, 0]
y = rboxes[:, 1]
w = rboxes[:, 2]
h = rboxes[:, 3]
... | a33d46e271015dd108c4db06e265cb4e4a487307 | 680,667 |
def join_url(*components: str) -> str:
"""Concatenates multiple url components into one url.
Args:
*components:
Multiple url components.
Returns:
A complete url.
"""
clean = [str(comp).strip('/') for comp in components]
return '/'.join(clean) | 75e7d1200f5db7d32aeeb6a9dc0b97964388e472 | 680,669 |
def unique_path(path):
"""
Given a path, determine if all its elements are single-valued predicates. If so, the path is unique,
regardless of length. If any one of the steps in the path has a non single-valued predicated, the path is not
unique.
:param path: a definition path
:return: True if ... | 821e6d8da4003caaa885b66917a8b028be55fa27 | 680,671 |
def _get_requirements_to_disable(old_requirements, new_requirements):
"""
Get the ids of 'CreditRequirement' entries to be disabled that are
deleted from the courseware.
Args:
old_requirements(QuerySet): QuerySet of CreditRequirement
new_requirements(list): List of requirements being ad... | 9981f7c80d2d968868c34a3e3c2d926ef5387db1 | 680,673 |
def update(cur_aggregate, new_value):
"""For a new value new_value, compute the new count, new mean, the new m_2.
* mean accumulates the mean of the entire dataset.
* m_2 aggregates the squared distance from the mean.
* count aggregates the number of samples seen so far.
"""
(count, mean, m_2) =... | 65377a65cb093c2b8ebf68e3eb2627d045429b50 | 680,674 |
def getStringForAndDifferential(a, b, c):
"""
AND = valid(x,y,out) = (x and out) or (y and out) or (not out)
"""
command = "(({0} & {2}) | ({1} & {2}) | (~{2}))".format(a, b, c)
return command | 8f0b14767468997643837a264973e79d83eaebc8 | 680,680 |
def read_data(filename):
"""
Reads raw space image format data file into a string
"""
data = ''
f = open(filename, 'r')
for line in f:
data += line.strip('\n')
f.close()
return data | a705a62c3ef92ca1189e065018a2b6ee47a3fad6 | 680,681 |
def get_descriptors_text(dl):
"""
Helper function that separates text descriptors from the mixture
of text and uris that is returned from Agritriop
Parameters
----------
dl : list
Descriptor list.
Returns
-------
list
list of text descritors only.
"""
retur... | df2572475865d4d08c5c620d54daf7bb5a0ed184 | 680,682 |
import re
def preprocess(text_string):
"""
Accepts a text string and replaces:
1) urls with URLHERE
2) lots of whitespace with one instance
3) mentions with MENTIONHERE
This allows us to get standardized counts of urls and mentions
Without caring about specific people mentioned
"""
... | 6bc82ab98c194b6c7accc777aaa78d23efc12364 | 680,683 |
def to_query_str(params):
"""Converts a dict of params to afaln actual query string.
Args:
params: dict of simple key-value types, where key is a string and
value is a string or something that can be converted into a
string. If value is a list, it will be converted to a comma-
... | 91b032d3435449885c435f70c086074f14a5568e | 680,688 |
from unittest.mock import Mock
def mock_unrestrained_apm(mock_unrestrained_component):
"""Mock a parameter manager to handle no restrained components."""
apm = Mock()
apm.components = {
"unrestrained": {
"object": mock_unrestrained_component,
"n_params": mock_unrestrained_c... | c907406ae18dc6b80b70fe4cd1f93a6c82551bc4 | 680,689 |
def writexl_new_content_types_text(db):
"""
Returns [Content_Types].xml text
:param pylightxl.Database db: database contains sheetnames, and their data
:return str: [Content_Types].xml text
"""
# location: [Content_Types].xml
# inserts: many_tag_sheets, tag_sharedStrings
# note calcCh... | 3762cfe7680fa1754885622b123c914a341aea34 | 680,691 |
import importlib
def import_object(string: str):
"""Import an object from a string.
The object can be a function, class or method.
For example: `'keras.layers.Dense.get_weights'` is valid.
"""
last_object_got = None
seen_names = []
for name in string.split("."):
seen_names.append(... | f7de516c1a731f3dbfb5ea5ce49c84c64d567ee7 | 680,694 |
def time_in_range(start, end, x):
"""
Return true if x is in the range [start, end]
"""
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end | db8cabd7fa71ea341000cc9886181c6300996734 | 680,700 |
import posixpath
def extract_version(module_name):
"""
extract the version number from the module name provided.
:param module_name: <str> the module to find version in.
:return: <int> version number.
"""
# module_name_v0000.py --> module_name, _v0000.py --> _v0000
return posixpath.splitex... | 64da954ee794379fd3943283c7569f1f541e8839 | 680,703 |
def indices(lst, element):
""" A function that searches for all occurrences of an element in a list """
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset + 1)
except ValueError:
return result
result.append(offset) | b415251d010db49a2823bd67fbd651193d980f38 | 680,704 |
def next_greatest_letter(letters: list[str], target: str) -> str:
"""Returns the the smallest element in the list that is larger than the given target
Args:
letters:
A list of sorted characters drawn from the lowercase latin
alphabet that also wraps around. For example, if the t... | 31558470d49d124375fe4d2aee8d983f6194f007 | 680,710 |
import math
def floatToJson(x):
"""Custom rule for converting non-finite numbers to JSON as quoted strings: ``"inf"``, ``"-inf"``, and ``"nan"``.
This avoids Python's bad habit of putting literal ``Infinity``, ``-Infinity``, and ``NaN``
in the JSON (without quotes)."""
if x in ("nan", "inf", "-inf"):... | dc7125ed60d8341e5e61e368b85ba34042cc5863 | 680,714 |
def points_to_vec(pt1, pt2, flip = False):
"""
Converts the coordinate of two points (pt1 > pt2) to a vector
flip: bool, default = False
If the coordinate system should be flipped such that higher y-coords
are lower (e.g. needed when working with images in opencv).
"""
vx = pt2[0]... | 9a826a790661f1d47a4bc47991fbe16a71cfad70 | 680,716 |
def rbits_to_int(rbits):
"""Convert a list of bits (MSB first) to an int.
l[0] == MSB
l[-1] == LSB
0b10000
| |
| \\--- LSB
|
\\------ MSB
>>> rbits_to_int([1])
1
>>> rbits_to_int([0])
0
>>> bin(rbits_to_int([1, 0, 0]))
'0b100'
>>> bin(rbits_to... | 57ef269f6690511c525081d542aed0d326a71c3b | 680,720 |
def esi_Delta(Delta, q):
"""
Calculate equivalent step index (esi) Delta for a graded-index fiber.
Args:
Delta : relative refractive index [-]
Returns:
equivalent relative refractive index [-]
"""
return q * (2 + q) / (1 + q)**2 * Delta | a234c8993c59a97165f4cee6aa18e89db86ca327 | 680,721 |
def read_worksheet(worksheet_name, workbook):
"""Read worksheet table to list of dicts
"""
output = []
try:
data = workbook[worksheet_name].values
except KeyError:
print("Worksheet {} not found".format(worksheet_name))
return output
keys = next(data)
data = list(data... | c4a83ebdc617fbdfab069825fe0efa0e36e9ae2f | 680,723 |
def generate_macs_args(flags):
"""
This is a helper function that takes the sim options and outputs the start the macs_args
:param flags:
:return macs_args:
"""
macs_args = None
if '-macs_file' in flags:
macs_args = [flags['-macs_file'][0][0], flags['-length'][0][0], "-I", flags['-I... | 887d867192fbebba1f9604a724346771738f0d46 | 680,724 |
def _expand(dict_in):
""" Convert {key1: list1, key2: list2} to
{list1[0]: key1, list1[1]: key1, list2[0]: key2 etc}
"""
dict_out = {}
for key in dict_in:
for item in dict_in[key]:
dict_out[item] = key
return dict_out | 5cb4a90d424427952a2c6aafad0e8003b349c857 | 680,725 |
def replacer(svgFile, toReplace, newData):
"""
Searches through SVG file until it finds a toReplace, once found, replaces it with newData
"""
for count in range(0,len(svgFile)):
found = svgFile[count].find(toReplace) #Check if the current line in the SVG file has the required string
if n... | 36cc896bb12e9e8d9539b072986ea4c255912a34 | 680,728 |
def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None):
"""Given a list, returns a string representation of that list with specified delimiter and optional string chars
_list -- the list or tuple to stringify
delimiter -- the the character to sepe... | aa8b6923414f08db1969406bf7a0308d1da87106 | 680,729 |
def get_yaml(path):
"""
Return the Yaml block of a post and the linenumbers of it.
"""
end = False
yaml = ""
num = 0
with open(path, 'r', encoding='utf-8') as f:
for line in f.readlines():
if line.strip() == '---':
if end:
break
... | dd443cb552cd625b7acacdc8e794dba794f9372a | 680,732 |
def bitcount(num):
"""
Count the number of bits in a numeric (integer or long) value. This
method is adapted from the Hamming Weight algorithm, described (among
other places) at http://en.wikipedia.org/wiki/Hamming_weight
Works for up to 64 bits.
:Parameters:
num : int
The ... | 6b71324cd3db976b86b5e56cdbb5fb086d6e3623 | 680,734 |
def _pad_binary(bin_str, req_len=8):
"""
Given a binary string (returned by bin()), pad it to a full byte length.
"""
bin_str = bin_str[2:] # Strip the 0b prefix
return max(0, req_len - len(bin_str)) * '0' + bin_str | 9be1f50e9bdc0c60daa50fe3ae1b9e4c04dff5f1 | 680,735 |
def income3(households):
"""
Dummy for for income group 3
"""
return (households['income_category'] == 'income group 3').astype(int) | 6fdd64682d3123ddc251924df027474f34ce75bd | 680,736 |
def _deep_flatten(items): # pylint: disable=invalid-name
"""Returns a list of objects, flattening sublists/subtuples along the way.
Example: _deep_flatten([1, (2, 3, (4, 5), [6, 7]), [[[8]]]]) would return
the list [1, 2, 3, 4, 5, 6, 7, 8].
Args:
items: An iterable. If elements of this iterable are lists... | b2683ddc455842d1f19ac40f021b37aeafade243 | 680,737 |
def depth2inv(depth):
"""
Invert a depth map to produce an inverse depth map
Parameters
----------
depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Depth map
Returns
-------
inv_depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Inverse depth map
"""
... | a7e2d0ccb4271bd2593f9648b0310614e0b8bb96 | 680,738 |
def get_unit_string_from_comment(comment_string):
"""return unit string from FITS comment"""
bstart = comment_string.find("[")
bstopp = comment_string.find("]")
if bstart != -1 and bstopp != -1:
return comment_string[bstart + 1: bstopp]
return None | 232c1a6446d955be172fb08c1fe0c9e7847f87da | 680,739 |
from typing import Any
import torch
def _size_repr(key: str, item: Any) -> str:
"""String containing the size / shape of an object (e.g. a tensor, array)."""
if isinstance(item, torch.Tensor) and item.dim() == 0:
out = item.item()
elif isinstance(item, torch.Tensor):
out = str(list(item.si... | 7e2b9a26070428d2f97740d37a87d1da42a4376d | 680,740 |
def _strip(json_str):
"""Strip //-prefixed comments from a JSON string."""
lines = []
for line in json_str.split('\n'):
pos = line.find('//')
if pos > -1:
line = line[:pos]
lines.append(line)
return '\n'.join(lines) | 8d0cd156c88f5d385ed1d1a4b5a22c529fd9c2fd | 680,741 |
def load_yolo_predictions(txt_path, classes=None):
"""Return a list of records from YOLO prediction file.
Each record is a list `[label, box, score]`, where the box contains
coordinates in YOLOv5 format. `score` can be None if text file does
not contain scores, and `label` is either integer, or string ... | 9e4058bbe48b8b41759fbae63fd9173e9a8dde6d | 680,742 |
def group_changes(changes):
"""Consolidate same-position insertions and deletions into single changes.
"""
insertions = [c for c in changes if c.change_type == 'insert']
deletions = [c for c in changes if c.change_type == 'delete']
mutations = [c for c in changes if c.change_type == 'mutate']
in... | e306005b1ce2d331ac5c20e573839c6f015cb61a | 680,746 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.