content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def resize_fn(attributions, inputs, mode):
"""Mocked resize function for test."""
del inputs, mode
return attributions | dfe48a6c1cb30de8d1f7527d61e8779365df2c35 | 680,580 |
import dateparser
def findTimeColumn(row):
"""Dynamically determine which column of a log file contains dates.
Parameters:
row: A row of a logfile
Returns:
iterator: An integer defining the row that contains a valid date
string.
"""
iterator = 0
for item in row:
... | c59ec1a60d18c7198dc0800216fb916734cdcb00 | 680,581 |
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 |
def semantic_alert(visitor, block):
"""
Format:
{% alert class=error %}
message
{% endalert %}
"""
txt = []
cls = block['kwargs'].get('class', '')
txt.append('<div class="ui %s message">' % cls)
text = visitor.parse_text(block['body'], 'article')
txt.appe... | b7154e6d729ee9769e49d7cfac2e5d2130fbce09 | 680,584 |
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 |
def percentage(part, whole):
""" This function calculates the percentage of a given set """
return float(part)*float(whole)/100 | be9583e2e8f3f4c010ea08c36f3555d74bdc7864 | 680,588 |
import numpy
def geterr():
"""Gets the current way of handling floating-point errors.
Returns
-------
res : dict
A dictionary with keys "divide", "over", "under", and "invalid",
whose values are from the strings "ignore", "print", "warn", and "raise".
The keys represent possi... | 48256a85c203b555ef1a56073c4c583091706139 | 680,589 |
from datetime import datetime
def months(str1, str2):
"""
获取相差月数
:param str1:
:param str2:
:return:
"""
year1 = datetime.strptime(str1[0:10], "%Y-%m-%d").year
year2 = datetime.strptime(str2[0:10], "%Y-%m-%d").year
month1 = datetime.strptime(str1[0:10], "%Y-%m-%d").month
mon... | 9b61ed780f3f3cc6f4754e7880a836f6bd994436 | 680,590 |
def parseGeneList(genesListFileName):
"""
store the selected genes in a list
"""
genesList = []
## parse the geneList file
genesListFile = open(genesListFileName)
for line in genesListFile:
genesList.append(line[:-1])
genesListFile.close()
return genesList | 7afc440b588a046a6371ab6720297f504f99f7db | 680,592 |
def save_job_status(name, model):
"""
保存或者修改job 状态
:param name: str job name
:param name: str job status
:param model: Model job status 数据模型
:return: Boolean True:成功,False:失败
"""
t_status = model()
t_status.job_name = name
... | 9979722892597c7975b2f17e5cc6a8550fe450e1 | 680,594 |
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 |
import getpass
def get_user_creds():
"""Promt user for credentials.
:return: Pair of username (first) and password (second).
"""
print("Please provide your JIRA credentials")
username = input("Username: ")
password = getpass.getpass()
return (username, password) | 392fd713411af44838568a6e07ea3a699456cfba | 680,596 |
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 |
def get_first_value(x):
"""Returns the value of the first element.
Does not work with DataFrames; use first_row().
:param x: Series
"""
return x[x.index[0]] | 640d93c1c1c5e83cff24b21276f657099a83bdf4 | 680,599 |
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 |
def replace_self(name1, str1, str2):
"""replace"""
return name1.replace(str1, str2) | bc954496689dea448607afa0ce0053b037ecb3bd | 680,604 |
from bs4 import BeautifulSoup
def get_outgoing_links(html_file):
"""Get list of outgoing links for the input html file.
Parameters
----------
html_file: str
Path to html file
Returns
-------
list_of_urls: list
List of outgoing urls
"""
... | 072db6dac53496a479f2bb98cc2b782a87814aad | 680,605 |
def cascade_attributes(decorator):
"""
Overrride default decorator behaviour to preserve docstrings etc
of decorated functions - functools.wraps didn't seem to work.
See https://stackoverflow.com/questions/6394511/python-functools-wraps-equivalent-for-classes
"""
def new_decorator(original):
... | 64ca7b7e5cb7e0ca4a45408abe37edecdfed784b | 680,606 |
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 |
import os
def convert_to_absolute(file):
"""Convert file to absolute path """
if file is not None:
return os.path.abspath(os.path.join(os.getcwd(), file))
return None | 59594041cbd38af76826fe15ea1446e5b3bef32a | 680,608 |
import base64
def base64_decode(data):
"""
Returns base64 encoded file.
Parameters
----------
data: str object
Return
------
base64 encoded object
"""
return base64.b64decode(data.encode('utf-8')) | 44410b2bc42a823c73f61ca63b8d5cddc62184d4 | 680,609 |
import os
def folder_exists(folder_name):
"""Helper: Checks whether the passed folder exists."""
folder_path = 'backups/' + folder_name
# logging.info('Checking if ' + folder_path + 'exists...')
return os.path.exists(folder_path) | aef362c84380340ad543898d1677cf5ccec454dc | 680,610 |
def get_type(object):
"""Convert a datetime.timedelta object into Days, Hours, Minutes, Seconds."""
return type(object).__name__ | 521d8131ef814e0e0f589841e6109557edd4137a | 680,612 |
def _is_permission_set(code):
"""
:param code: an integer value
:return: True if the code means successful, False otherwise.
"""
return code == 1003 | acce771cf1072a5a5f3c50e2c7c0c6f72b3430e0 | 680,613 |
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 |
import os
import json
def get_product_title(path):
"""
Reads product title from path/info.json and returns.
:param path: str, product path.
:return: str, product title, if found.
"""
if os.path.exists(os.path.join(path, 'info.json')) is False:
return None
with open(os.path.join(pat... | 10fbe1a76f43a5ac04992e941ad15b6b015c258a | 680,616 |
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 |
import numpy
def create_extension_config(name, extra_sources=None, can_use_openmp=False):
"""
Util function to create numpy extension from the current pyFAI project.
Prefer using numpy add_extension without it.
"""
include_dirs = ['src', numpy.get_include()]
if can_use_openmp:
extra_l... | 4212f3cb9b6cd426c98dc939ef39fdf04f3a04b3 | 680,621 |
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 |
import itertools
def reorder_keys(expected, actual):
"""
"""
if not isinstance(actual, dict):
return actual
result = {}
for k, expected_value in expected.items():
actual_value = actual[k]
if isinstance(expected_value, dict):
actual_value = reorder_keys(expected_... | 671d2828e4057bc7c06d26d9d307591f8533a44b | 680,625 |
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 |
import os
import tempfile
def use_tmpdir_for_files(basenames, src_dir, link_dir):
"""Generate script to copy db files to tmpdir (for speed).
- Choose tmp_dir, based on src_dir name.
- rsync basenames into tmp_dir # after 'flock', per file
- symlink from link_dir into tmp_dir.
Return list of scrip... | 6b260de2667e106b39abb69a870c659ba4d429de | 680,627 |
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 _is_zero_rgb_brightness(rgb: tuple[int, int, int]) -> bool:
"""RGB brightness is zero."""
return all(byte == 0 for byte in rgb) | 7c5f188ac409edebe02e60bdcbafbb33703f26bf | 680,631 |
import os
import requests
def convert(currency_from, currency_to, amount=1):
"""Convert from a currency to another with a given amount."""
api_key = os.getenv('CURRENCY_CONVERTER_API_KEY', None)
if not api_key:
return "Currency Converter API is not configured."
currency_from, currency_to = cur... | 2a6b3e08cf7670bb23a1351ce27b7bd219867ae5 | 680,632 |
def doc_idname(s):
"""
Returns the id_name of the operator to register shortcuts in Blender's keymaps or call from other operators.
"""
out = ".".join(map(str.lower, s.split("_OT_")))
return out | 498fb077b88da2c90b36b0ceb19f8ff6df349af8 | 680,633 |
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 |
async def html(request):
"""Return html response."""
return 'HTML content' | 90a09a7d1ef1451ef5ccafeed32af47f5b51b850 | 680,637 |
import math
def bs(arr, threshold):
"""
Binary Search
:param arr:
:param threshold:
:return:
"""
low = 0
high = len(arr)
while low < high:
mid = math.floor((low + high) / 2)
if arr[mid] == threshold:
return mid
elif arr[mid] < threshold and mi... | 5b729b9eb5a8df1c1977acb579aa47d1591660f3 | 680,638 |
def compatible_alleles_reverse_strand(A1, A2, B1, B2):
""" Checks whether alleles are compatible on the forward strand
Args:
A1, A2 (Seq): Alleles from one source
B1, B2 (Seq): Alleles from another source
Returns:
Boolean
"""
return set([A1.str(), A2.str()]) == set([B1.revcom... | 7cde93675073f6a487be2ffd20d1739dbd0937ea | 680,639 |
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 get_localizer(request):
"""
.. deprecated:: 1.5
Use the :attr:`pyramid.request.Request.localizer` attribute directly
instead. Retrieve a :class:`pyramid.i18n.Localizer` object
corresponding to the current request's locale name.
"""
return request.localizer | ef8a75f5c92f63ff779e44dc41d65456b339e9b6 | 680,644 |
def read_file(filename):
"""Reads a text file."""
try:
with open(filename, "r") as file_in:
return file_in.read()
except:
pass | e54ae47fd55557de638c2e3ab133e175913c6a92 | 680,647 |
import os
import shutil
def rm(path: str, recursive=False) -> bool:
"""
A function that removes files or directories in a separate thread. Wraps :func:`os.remove` and func:`shutil.rmtree`.
:param path: the path to remove
:param recursive: the operation should recursively descend into dirs
:return... | 24e07d724ab2e55cdf19eabdaaa7cb36e8506fe8 | 680,648 |
import json
def data_path():
"""
根据config.json文件获取数据集存储的路径
:return: 数据集对应的路径
"""
with open("D:\git仓库\GraduationProject\GraduationDesign\config.json", 'r') as f:
return json.load(f)['data_set_path'] | 6143bbe5d338a5f502d92d85cf8a4595f3dc55f4 | 680,649 |
def x_y_points(data):
"""
from array of average of points in a single 'pose_keypoints_2d' array
finds x and y corridnates and return two lists
"""
x_warrior = []
y_warrior = []
c_warrior = [] # certainity of pose
for n in range(len(data)):
if (n % 3) == 0:
x_warrior.... | ddcb8b3cdd147061e87a0f0c629a1a13b3b642f5 | 680,650 |
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 rule(*patterns):
"""Decorate a function to be called when a line matches the given pattern.
:param str patterns: one or more regular expression(s)
Each argument is a regular expression which will trigger the function::
@rule('hello', 'how')
# will trigger once on "how are you?"
... | 2129031150dceefbd07c537b4b8ad86dafa56fec | 680,652 |
import os
def remote_open(path, mode):
"""An open()-compatible interface to writing both local and remote files.
You might want to use
https://github.com/christopher-hesse/blobfile to support writing
to s3://, gs://, or other datastores as appropriate.
By default, this only supports local files.... | 817ce4f096a9150bc995bc7a619d5b22e852949b | 680,653 |
def extract_message(result): # pragma: no cover
"""Extracts the original message from a parsing result."""
return result.get('text', {}) | c7179dbf1f162eb44974d5230a60e681a8f58d77 | 680,654 |
import configparser
import ast
def build_cmd(conf: configparser.ConfigParser) -> str:
"""Rebuild the command line."""
args = []
for k, v in conf['options'].items():
if ' ' in v:
args.append(f'-D{k}="{v}"')
else:
args.append(f'-D{k}={v}')
cf = conf['properties']... | 2d18cb036175d9f445ac7c7e56cd055ce54ca8d8 | 680,655 |
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 __py_elif_condition(statements,lineno):
"""returns a valid python elif statement"""
elif_condition = statements[statements.find('(')+1:statements.find(')')]
return statements[:statements.find('else')]\
+f'elif {elif_condition}:\n'.replace('&&',' and ').replace('||',' or ').replace('!',... | 5deaffa82f3f53184a97b5621c4c2c85905305f2 | 680,658 |
def ssh_host(config, host):
"""Get the full user/host pair for use in SSH commands."""
return '{}@{}'.format(config.user, host) | 0bb245de5528a4154fcdaf88228d7860921f8b14 | 680,659 |
import sys
def log_prompt(message_text):
"""
The ``log_prompt`` function is used to prompt the user for input, strip that
input of whitespace, and return the value passed by the user to the calling
function. It can be conceived of as a substitute for the default ``input``
function that permits a b... | daf62cb10713ee95f3a78662acaacd6a8df1998b | 680,660 |
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 |
from typing import List
from typing import Any
def flatten_list(input_list: List[List[Any]]):
"""
Takes a nested list of values and flattens it. The code is written as a try/except that makes the assumption
that the data is a list/tuple/array, and in the case that it isn't will simply append the item to t... | c8646b5f559d601cd9b4fd8296ea7a2d67c9eb00 | 680,665 |
import os
def make_file_name(file_path):
"""
Create a new file name to avoid overwriting.
Parameters
----------
file_path : str
Returns
-------
str
Updated file path.
"""
file_base, file_ext = os.path.splitext(file_path)
if os.path.isfile(file_path):
nfile... | d4c0190e6d5edf18bc4c3545a3282e12ee3115ea | 680,666 |
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 _get_crs_from_coord(obj, mode='strict'):
""" Looks for dimensionless coordinate with `spatial_ref` attribute.
obj: Dataset | DataArray
mode: strict|any|all
strict -- raise Error if multiple candidates
any -- return first one
all -- return a list of all fou... | f444b6d716926abb004a3e4fa87652381e7b12a0 | 680,668 |
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 |
import numpy
def butter2d_lp_elliptic(size, cutoff_x, cutoff_y, n=3,
alpha=0, offset_x=0, offset_y=0):
"""Butterworth lowpass filter of any elliptical shape.
:Parameters:
size : tuple
size of the filter
cutoff_x, cutoff_y : float, float
relativ... | 6aee135bddfd87ef728797851a1e068beb00ccfb | 680,672 |
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 _get_comparisons_2(idx, a, b):
"""Collect comparisons of 2nd type:
If A and B are too similar & B and C are too dissimilar, are vectors A and B closer to each
other than vectors B and C?
"""
if len(a) == 0:
return []
if len(b) == 0:
return []
out = []
r1 = [int(... | 8d3af97a641e1fba4936a367a6b6e7f890c48733 | 680,675 |
def get_vni_vlans(cli_output):
"""takes str output from 'show ip igmp snooping | include "VxLAN VNI VLANS"' command'
and returns a list of vxlan vni vlans
"""
# obtain list of vni vlans & vlan ranges
vni_vlan_ranges = cli_output[19:].split(",")
vni_vlans = []
#convert list of vlan/vlan ra... | c121a6a6fcfcc0ea0424c7d47b7df7b50f77d0c6 | 680,676 |
import sys
def main():
"""Creates a file name with whitespaces and comma in it."""
# We could test ?><:*|"' and chr(1 to 32) on linux.
# We could test ?<>*|"' on OSX.
# On Windows, skip the Chinese characters for now as the log parsing code is
# using the current code page to generate the log.
if sys.plat... | e488d21950c44ae9ae640b232125854563f82d1f | 680,677 |
import io
def load_dict(conf):
"""
load swda dataset config
"""
conf_dict = dict()
fr = io.open(conf, 'r', encoding="utf8")
for line in fr:
line = line.strip()
elems = line.split('\t')
if elems[0] not in conf_dict:
conf_dict[elems[0]] = []
conf_di... | 11de5ea9d410ec8677e339f727ed0448ddc33b12 | 680,678 |
def check_value_type(value):
"""
Args:
value: the value for current key in the dictionary.
Returns:
returns a boolean value whether the value passed in is primitive.
>>> check_value_type('Perfect')
False
>>> check_value_type(10)
True
>>> check_value_type(3.1415)
True
... | 6b164db5690ceb5d8c968b07c4f9c27a97b3edf0 | 680,679 |
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 |
import os
def is_valid_file(arg_parse, arg):
"""
test if file is valid (pdf or dxf)
:param arg_parse: argument parser
:param arg: filename
:return: filename if valid
"""
if not os.path.exists(arg):
arg_parse.error("The file %s does not exist!" % arg)
elif os.path.splitext(arg)[... | 66dc7accfa1dbeef31b56812d93f50d36270a2fe | 680,685 |
def rectangles(str):
"""
Return the number of rectangles
"""
check = []
for i, row in enumerate(str):
for j, char in enumerate(row):
if char == "+":
for _a in range(j + 1, len(row)):
if str[i][_a] == "+":
for _b in r... | 591c16ef5497b475452ca067710e5fe7b29331a7 | 680,686 |
import argparse
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(description='Pack a Jupyter notebook')
... | 66a4835d1dfbc70aef8f0c99e7d14dc04577eedc | 680,687 |
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 head(tup):
"""Implement `head`."""
return tup[0] | 2493a0a0ce50f3da008a91c850bd3b7be7317d45 | 680,690 |
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 datetime
def now_time(str=True):
"""Get the current time and return it back to the app."""
if str:
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return datetime.datetime.now() | b4ea1f14b3a8716ac8aa402e9612b99fd438310e | 680,692 |
def get_parent_tool_relative_path_string():
"""Used to populate Subtool.parentMetadata"""
rel_path_to_parent = "../../common/common-metadata.yaml"
return rel_path_to_parent | cd719e759b7661ecf3a897e4b1643a5ae17df219 | 680,693 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.