content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getGitRepositoryDownloadUrl(url: str) -> str:
"""
Takes a git repository url 'url' and returns the url to the master zip.
:param url: The url to a Github repository.
:return: The url to the master archive of the repository.
"""
return url + ('/' if url[-1] != '/' else '') + 'archive/master.... | 54d3597f521932695fd8a2fcdcca893ea3bcec65 | 619,486 |
from typing import Sequence
from typing import Any
def join_any(sep: str, args: Sequence[Any]) -> str:
"""Joins multiple values together in a string using their `str` operator."""
return sep.join([ str(arg) for arg in args ]) | 7b75ccdd08ecd949a00ba5f336b1505bfb25db48 | 619,488 |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
for i in range(0, len(seq)):
iMin = i
for j in range(i+1, len(seq)):
if seq[iMin... | 764c73287b846479bbcde935345c4c0a26fa934e | 619,489 |
import textwrap
def codeblock(block_str):
"""
Convinience function for defining code strings. Esspecially useful for
templated code.
"""
return textwrap.dedent(block_str).strip('\n') | ab51546eb9a0468e27e7c0ab86b668ef543bdcb5 | 619,490 |
from typing import Optional
from typing import List
import fnmatch
def exclude_file(
exclude: Optional[List[str]] = None,
include: Optional[List[str]] = None,
filename: str = "",
) -> bool:
"""Check if the file should be included during any operations.
Process exclude list first than use include ... | d7244b1b8beadda79ccf6a25a21d1e04cf93f534 | 619,491 |
import string
import random
def generate_identifier(size = 16, chars = string.ascii_uppercase + string.digits):
"""
Generates a random identifier (may be used as password) with
the provided constrains of length and character ranges.
This function may be used in the generation of random based
keys... | fc749c1ac2294c365c17a54ff3d096d466fb48d6 | 619,492 |
def ec2_id_to_id(ec2_id):
"""Convert an ec2 ID (i-[base 16 number]) to an instance id (int)"""
return int(ec2_id.split('-')[-1], 16) | 8068f7ec053b7f38f6cdc1e02b38d46d24badce7 | 619,493 |
import torch
def xyxy2xywh(boxes):
""" xyxy -> xywh
(xmin,ymin,xmax,ymax) and (xcenter,ycenter,width,height)
Args:
boxes: torch.FloatTensor[N,4]
"""
w = boxes[:, 2] - boxes[:, 0] + 1
h = boxes[:, 3] - boxes[:, 1] + 1
# center
x = boxes[:, 0] + 0.5 * w
y = boxes[:, 1] + 0.5 ... | 5515944414bc86feec64ebfe9500d6b12b44eb73 | 619,495 |
import zlib
import struct
def CheckFCS(frame):
"""Return true when the FCS at the end of the frame is correct, i.e. the frame is not corrupted
"""
crc32 = zlib.crc32(frame[:-4])
fcs = struct.unpack('l', frame[-4:])[0]
return fcs == crc32 | 852ed1e7d82b1a07619045154e99331f312d4c49 | 619,498 |
import array
def zeroByteArray(cb):
"""Returns an array with the given size containing 0."""
abArray = array.array('B', (0, ));
cb = cb - 1;
for i in range(cb): # pylint: disable=W0612
abArray.append(0);
return abArray; | c8d91d14b13a8e9e6944ecddbc4b1272c1f7241e | 619,500 |
def default_setpoint_array(dataset, measured_name='measured'):
""" Return the default setpoint array for a dataset """
setpoint_array = dataset.default_parameter_array(measured_name).set_arrays[0]
return setpoint_array | b5db96414c53fc051712ca8744833c5d7c0bd807 | 619,506 |
import json
def convert(x):
""" Convert a json string to a flat python dictionary
which can be passed into Pandas. """
ob = json.loads(x)
for k, v in ob.items():
if isinstance(v, list):
ob[k] = ",".join(v)
elif isinstance(v, dict):
for kk, vv in v.items():
... | 5aca3e3945a288fdc78cd266e7139b7d980b16dc | 619,507 |
def day_to_int(day):
"""
day: a string representing the day of the week
Returns an integer
e.g. "MONDAY" -> 0, "TUESDAY" -> 1, etc.
"""
days = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
return days.index(day.upper()) | a841d9ffee83ee416f9ed7739bd9f0404a999b72 | 619,508 |
from typing import Counter
def latern_fish_growth(laternfish, days, timer=8):
"""Models latern fish growth and returns number of fish after n days"""
tracker = Counter()
for i in range(timer + 1):
tracker[i] = 0
# starting values of each latern fish
for i in laternfish:
tracker[i... | c9262622694d9795ab295a1ccb915bfed8deedfd | 619,509 |
def tcl_findprd_prepd_start(prddict):
"""
Collect list of PRD entries.
:param prddict: Device:PRD dictionary.
:type prddict: dict(str: list)
"""
prda = []
for item in prddict.values():
prda.extend(item)
return prda | b85cb722d4699174fc1b6e928f3080c61b100156 | 619,510 |
def create_problem_instance(model, loaded_data):
"""
:param model: the AbstractModel Pyomo object with components added
:param loaded_data: the DataPortal object with the data loaded in and
linked to the relevant model components
:return: the compiled problem instance
Compile the problem ba... | 8e3775a8835f91e2087f837e5e7179ff78181eef | 619,516 |
def human_format(num):
"""Make a nice human readable format for numbers."""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return "%.2f%s" % (num, ["", "K", "M", "B", "T", "P"][magnitude]) | 02139008826774257a1acbb1f56a7883de866f49 | 619,518 |
def is_file_empty(file_name) -> bool:
""" Check if file is empty by reading first character in it"""
# open ile in read mode
with open(file_name, 'r') as read_obj:
# read first character
one_char = read_obj.read(1)
# if not fetched then file is empty
if not one_char:
... | 273cc34090b9aebf24b42db76ebb9778fdade68a | 619,520 |
def get_phy_intfs(host_ans):
"""
@Summary: Get the physical interfaces (e.g., EthernetX) of a DUT
@param host_ans: Ansible host instance of this DUT
@return: Return the list of active interfaces
"""
intf_facts = host_ans.interface_facts()['ansible_facts']['ansible_interface_facts']
phy_intf... | 061ef8eb77b6d08521e4a39b638d429afed837e4 | 619,521 |
def divide_chunks(a_list, n):
"""Divide a list into chunks of size n.
:param a_list: an entry list.
:param n: size of each chunk.
:return: chunks in a list object.
"""
return [a_list[i:i + n] for i in range(0, len(a_list), n)] | a5ad354d4d7b2b974b4b3eace6b9c78edc1c4dfb | 619,523 |
def find_balancing_cutoff_index(data, trials):
"""find the length of the shortest trial to balance the other experimental trials accordingly
Parameters
----------
data : dictionary
data dictionary consisting of trials from each subject
trials : list
list of experimental trials p... | 601ff10d4547aa67f97dba83603fdb21c777a8c1 | 619,524 |
async def get_page(browser, url, selector):
"""Return a page after waiting for the given selector"""
page = await browser.newPage()
await page.goto(url)
await page.waitForSelector(selector)
return page | bdb0cb478c41892f025d3f129d9fb60ed9a944aa | 619,526 |
def apply_mask(binary: str, mask: str) -> str:
"""Apply the parm mask to the parm binary number.
A 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged."""
result = ''
for place in range(36):
if mask[place] == 'X':
result += binar... | 932950a5394cbbab4b2be73434f3f9f5dd085c7d | 619,527 |
def transpose_blocks(blocks, block_len):
"""
Returns a transposition of the elements in items.
E.g. ["AB","CD"] -> [["A", "C"], ["B", "D"]]
"""
transpositions = []
for i in range(block_len):
transpositions.append([block[i] for block in blocks])
return transpositions | b252f006f092a5b95a5319630532ade46d0a89f9 | 619,530 |
def frenchTextNull(frenchInputNull):
"""
This function returns true if input is empty
"""
if frenchInputNull == '':
return True | 2c751b9c90ba57f6eae7edf7a3357423292b71e2 | 619,534 |
def gen_mock_key(func_name, key):
# type: (str, str) -> str
"""
Concate function name and the key to store in the mock DB
"""
return '{0}-{1}'.format(func_name, key) | d90eb32d5987d34b4b9652cf5994a278e6b9b2d8 | 619,535 |
def c_to_f(temp):
"""Returns Celsius temperature as Fahrenheit"""
return temp * (9/5) + 32 | d5d5f252510499f1a89c1869fffb17a3979fb382 | 619,542 |
def derive_bt_mac(base_mac,offset):
"""
Derives the BT_MAC from the BASE_MAC and the BT_MAC LSB offset.
"""
base_mac_lsb=int(str(base_mac[-1]), base=16)+offset
base_mac[-1]=format(base_mac_lsb, 'x')
bt_mac='-'.join(base_mac)
return bt_mac.strip() | 52d6d2a4fd9dc276bd90d2dea574141780873b86 | 619,543 |
def get_logging_params(verbose):
"""
Adjusts the logging verbosity based on the `verbose` parameter
0 - No logging
1 - Strategy Level logs
2 - Transaction Level logs
3 - Periodic Logs
"""
verbosity_args = dict(
strategy_logging=False,
transaction_loggi... | b71478a277509efa7c5be5e6c83267812b8186d8 | 619,544 |
def calc_workload_dis_factor(target_workload_pair, workload_pair):
"""Calculate the distance factor of the workload to the target workload.
If two workloads are not compatible at all (i.e., different compute DAG or function),
then the distance factor is "inf". Otherwise, we calculate the factor by traversin... | a8189c354870207b475403ce102098ce96f3a065 | 619,545 |
import re
import six
def rex(expr):
""" Regular expression matcher to use together with transform functions """
r = re.compile(expr)
return lambda key: isinstance(key, six.string_types) and r.match(key) | 93adf443be67c608438738f0d6291500dfef5e70 | 619,549 |
def sheet_as_dict(worksheet):
"""
Take an xsrd worksheet and convert it to a dict, using the first
row as a header (to create keys for the subsequent rows).
"""
keys = worksheet.row_values(0)
value_range = range(1, worksheet.nrows)
def to_dict(values):
return dict(zip(keys, values))... | d3d48c30444e4059fcb358f3bc3990f92f4374f4 | 619,551 |
def check_value_above_filter(value, threshold):
"""
Returns a boolean to indicate value at or above threshold.
:param value: integer from a column "*read count".
:param threshold: threshold for the filtering of these read counts.
:return: boolean whether integer is equal or greater than threshold.
... | d67802f591d3925f233249b388719cca230e5cc3 | 619,552 |
def lazyproperty(func):
"""A decorator for lazy evaluation of properties
"""
cache = {}
def _get(self):
try:
return cache[self]
except KeyError:
cache[self] = value = func(self)
return value
return property(_get) | 1b80c9990770e471bb9fd2604c00dd11a348f1c9 | 619,554 |
from typing import Iterable
from typing import Tuple
import pathlib
import click
def validate_paths(ctx, param, value: Iterable[str]) -> Tuple[pathlib.Path]:
"""Return a list of git directories in the given paths."""
git_dirs = []
for path in value:
for d in pathlib.Path(path).iterdir():
... | f98c293f69ec00198c52ba92f563d7c3c318227b | 619,557 |
def sorting_rivers(station):
"""sorting function for stations_by_rivers"""
river = station[1]
return river | f790ebcaeeff93a0859d36e4f57a78ea52d3f2b5 | 619,558 |
import re
def delete_mentions(string):
"""Delete at marks from input string
Args:
string (str): string to delete at marks
Returns:
str: string without at marks.
"""
return re.sub(r'@\S+', '', string) | 4f2492a9e492e686c259870caee485e37dd94aef | 619,560 |
def quote(lst: list) -> list:
"""Put quotation marks around every list element, which is assumed to be a str."""
return [f"\"{element}\"" for element in lst] | 805dac037a54546f99dbce9c4e0cd7129d04b6f9 | 619,569 |
def get_name_from_path(path):
"""
Return just the filename from its full path.
:param path: (str), directory path.
:return: (str), name of file.
"""
filename = path.split("/")[-1]
return filename.split(".")[0] | dc899d78fe8a22837ce6e874cf0c920eaee1aff3 | 619,570 |
def _user_in_groups(user, group_names):
"""
Function to verify if a user belongs to any of the groups given.
"""
# If the use is staff (admin, root) we dont need to verify the groups
if user.is_staff:
return True
return set(group.name
for group in user.groups.all()).intersec... | 5625eb0ff1e3b58e531f6cb228da8e0388539dfc | 619,572 |
def point_inside_circle(x,y,center_x,center_y,radius):
"""Check if a point is inside a circle.
Args:
x (float): x coordinate of the point.
y (float): y coordinate of the point.
center_x (float): x coordinate of the center of the circle.
center_y (float): y coordinate of the cent... | 9243c5c5a7e8e4318892f079c23ee85fda4707c2 | 619,573 |
import click
def valid_api_key(ctx, param, value):
"""Ensure an API has valid length (this is a click callback)."""
if value is not None and len(value) != 32:
raise click.BadParameter(
"API Key must be 32 characters long, not {}".format(str(len(value)))
)
else:
return v... | 938055755bf538f4210a0d0875c082603a6eaf30 | 619,575 |
def escapeForXML(s):
"""Replace special characters '&', "'", '<', '>' and '"' by XML entities."""
s = s.replace("&", "&") # Must be done first!
s = s.replace("'", "'")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
return s | 1794025189886ce2b351bb22b5f958e0de0ae65b | 619,577 |
import pkg_resources
def load_object(target, namespace=None):
"""This helper function loads an object identified by a dotted-notation string.
For example:
# Load class Foo from example.objects
load_object('example.objects:Foo')
If a plugin namespace is provided simple name references ar... | 53d3851744f859e514a131fa0336a3a68909dfdf | 619,578 |
def reconstruct_path(came_from, current):
"""
Helper method for astar to determine path\n
@param came_from -> Cells searched while finding path\n
@param current -> Current node where snake head is\n
@returns total_path -> Reversed list of coordinates to goal
"""
total_path = [current]
w... | 96bfd986c19795ee437bb7dc58bf103f4abbc246 | 619,583 |
def url_filter(url_list: list) -> list:
"""Filters out URLs that are to be queried, skipping URLs that responded with 204 HTTP code.
Args:
url_list: List of URL with metadata dict object.
Returns:
List of URL with metadata dict object that need to be queried.
""... | 77ae701ac919d8d9cefe66c627f6a54810295b67 | 619,585 |
import random
def generate_random_between(min, max):
""" Return a random int between min and max """
return random.randint(min, max) | 70020fb142d52f1dd914b5cb5a0a94735150400f | 619,586 |
def parse_sentences(name,data):
"""
Returns a list of natural language sentence in a dataset file
Parameters
----------
name : str
string key that contains sentences in the dataset file
data : list of dict
list of dictionaries where each dictionary contains a sentence and its an... | 2d580543236fcfcf7eb434c350eeacb96fcf5859 | 619,587 |
def iqr_score(x, q = .25):
"""Inner Quantile Range Score
The IQR score, the median centered data, scaled by the IQR. The inner quantile range can
be flexibly set with the q parameter. A q further from .5 implies a larger range, and
therefore a smaller IQR Score.
Parameters
----------... | 27091f486fea410380d35bf9e1ca36902804311a | 619,588 |
import torch
def accuracy(predictions, labels):
"""
Compute the average accuracy of the given predictions.
Inspired on
https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
Args:
predictions (torch.Tensor): Tensor containing the output of the linear
output layer of... | f80e27f342e30b6904f1856c968c61100abfcd56 | 619,591 |
def find_leaf(nodes, xi):
"""Find the leaf index containing the given features vector.
Parameters
----------
nodes : ndarray
Array of nodes with shape (n_nodes,) with node_dtype dtype
xi : ndarray
Input features vector of shape (n_features,) with uint8 dtype
Returns
------... | 435d96719b39794d9c81345934e9e9920db52ecd | 619,594 |
def get_pos(da):
"""
Takes an xarray DataArray containing veg_index values and calculates the vegetation
value and time (day of year) at peak of season (pos) for each timeseries per-pixel.
The peak of season is the maximum value in the timeseries, per-pixel.
Parameters
----------
ds: ... | fd0ce8238f3ca64d0c6b409405e188349c07b645 | 619,596 |
def get_enabled_vhost_path(version, domain):
"""
Get the path for an enabled PHP vhost file regardless of wether or not it exists.
Args:
version - The PHP version used in the file path
domain - The domain used in the file path
"""
return '/opt/php-' + version + '/etc/php-fpm.d/' + d... | 7c56d822fa960a8bde8d39aa150b38dfea76352b | 619,597 |
def dot(v, u):
"""Compute dot product of vectors *v* and *u*."""
return sum(u[i] * v[i] for i in range(len(v))) | 44ec89291f9ec20cb4c097fc98a83225b58fb06e | 619,599 |
def check_if_tag_is_compliant(resource_tags,required_tag_key,required_tag_values):
"""
Input:
resource_tags - A list of dictionaries which contains AWS tags. Example: [{"Key": "Tag1Key", "Value": "Tag1Value"}, {"Key": "Tag2Key", "Value": "Tag2Value"}]
required_tag_key - An AWS tag key as a string. Examp... | 69e61be27eb144325cacaff23833600180053941 | 619,603 |
import requests
def download_http(url):
"""
Makes an http request for the contents at the given url and returns the response body.
"""
response = requests.get(url)
response.raise_for_status()
# Encoding here prevents a UnicodeDecodeError later in make_zip_in_memory in Python 2.
response_s... | 77632bd6f89e8458c0f2e5c3db37f8acac88981b | 619,609 |
from typing import Set
from typing import Tuple
def confusion_matrix(pred: Set, gold: Set) -> Tuple[Set, Set, Set]:
"""Return a confusion matrix.
This can be used for both entity-level and mention-level
:param pred: a set of predicted entities/candidates
:type pred: set
:param gold: a set of gol... | 1511a09107e207039f647638ea99a50cc5fc08ff | 619,610 |
from typing import List
def parse_changed_files(changed_files: str) -> List[str]:
"""
Get the list of strings specified in CSV format under change_files query parameter.
:param changed_files: The CSV string.
:return: The parsed list of strings.
"""
return changed_files.split(",") | 64b49a53b7f8128a7e96fc395296408cf2fe3ec8 | 619,612 |
import re
def get_task_path_and_exc(file_path):
"""Get the task path and exception from the file by using its file path"""
with open(file_path, 'r') as f:
for line in f:
reg = re.search('Task (.*) with id (?:[0-9a-f\-]+) raised '
'exception:', line)
... | 30b94c1c0b72055aef83325b2f27f2810586b03e | 619,617 |
import requests
def is_holiday(day):
"""
判断是否节假日
参数:
day: 日期, 格式为 '20160404'
return: bool
"""
api = 'http://www.easybots.cn/api/holiday.php'
params = {'d': day}
rep = requests.get(api, params)
res = rep.json()[day if isinstance(day, str) else day[0]]
return True if res == "... | b603bb13aeee187b351986137c09c8316842f8ed | 619,621 |
def build_flags_string(flags):
"""Format a string of value-less flags.
Pass in a dictionary mapping flags to booleans. Those flags set to true
are included in the returned string.
Usage:
build_flags_string({
'--no-ttl': True,
'--no-name': False,
'--verbose':... | 55439f78e63025305fdc51121dc42fb505efecaf | 619,626 |
def emoji_of_status(status: str) -> str:
"""Returns the emoji associated to a docker container status.
The emojis are as follows:
* ``exited``: ⏹,
* ``paused``: ⏸,
* ``restarting``: ↩,
* ``running``: ▶,
* otherwise: ❓.
"""
return {
"exited": "⏹",
... | d6ba1e5b05bd1d4166d8f7a6c3965977a806cafa | 619,627 |
import re
def is_frameshift(var):
"""
Returns a boolean if the variant is a frameshift indel
"""
if 'ANN' in var.INFO:
if re.search('frameshift', var.INFO['ANN'][0]):
return True
return False | 3edb2ff2384af36497fb4f72c784368ef3758b16 | 619,630 |
import six
def encode_string(s, encoding='utf-8', errors='strict'):
"""Encode string s to bytes."""
if isinstance(s, bytes):
return s
if isinstance(s, six.text_type):
s = s.encode(encoding, errors=errors)
else:
s = str(s).encode(encoding, errors=errors)
return s | 7ba99490efe2d87f0625a2589b62289ce6b270b7 | 619,631 |
import fnmatch
def _is_excluded(name, exclude):
"""
Determine if the name is to be excluded based on the exclusion list
"""
if not exclude:
return False
return any( (fnmatch.fnmatchcase(name, i) for i in exclude) ) | be23c46e6a380e63524e07a741739353b32b211d | 619,633 |
def isnotification(request):
"""
Tests if the given request is a notification
:param request: A request dictionary
:return: True if the request is a notification
"""
if 'id' not in request:
# 2.0 notification
return True
if request['id'] is None:
# 1.0 notification
... | 91f572c7d53a99d6e638953e61da50e599b0ebe6 | 619,635 |
import struct
def decode_pair(s, pos=0):
"""
Decodes a name/value pair.
The number of bytes decoded as well as the name/value pair
are returned.
"""
nameLength = ord(s[pos])
if nameLength & 128:
nameLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
pos += 4
el... | 0f72820d405f9c5f930fb145b8e11553c7cceca5 | 619,637 |
def get_image_size(image):
"""
Returns width and height of image
"""
width = int(image.shape[1])
height = int(image.shape[0])
return width, height | bd99f53a1a3596283981416eb6e25bd3d3a745fe | 619,638 |
def getSmoothedSampledPointsOnTrackSurface(trackSurface, startProportion1, startProportion2, endProportion1,
endProportion2, elementsOut, startDerivative = None, endDerivative = None,
startDerivativeMagnitude = None, endDerivativeMagn... | 677cc28771b38cb651c652c7878526ee671d1ff8 | 619,641 |
def sqrt_bisect(n, steps=20, epsilon=10**-5):
"""Approximate square root by the bisection method."""
assert n > 0
assert epsilon > 0
low = 0
high = n
step = 1
sqrt = (low + high) / 2
while abs(sqrt**2 - n) > epsilon and step <= steps:
if sqrt**2 < n:
low = sqrt
... | f85571a0684998208b2112d42544a915c80091c0 | 619,643 |
def get_bond_features_shape(train_set):
"""Get the shape of the atom features from a MoleculeACE.GNN.dataloaders.*_graph_dataset"""
bond_features = 13 # this is the standard size
for item in train_set:
single_graph = item[1]
bond_features = single_graph.edata['e'].shape[1]
break
... | 0c1d1b4358a966091352d730772fc388b7bb496c | 619,650 |
def split_snake(text, fix=True):
"""
Split a string in snake case format into a tuple of its component words
By default the result is guaranteed to be all lowercase
:param text: Text to split
:param fix: Whether to lowercase the result, or leave capitalization as-is
:return: Tuple of str... | a344d0d8bed790307f558030147eb7a42302cf5d | 619,653 |
def set_bit(number, site, N, bit):
"""
Change the bit value of number at a single site.
:param number: the number to be changed
:param site: the index of the site starting from left
:param bit: the bit value to be changed
:returns: the changed number
"""
if bit:
return number | ... | 01225923c410f0dbb76b5aa94854e8a2f961eb68 | 619,654 |
def robot_pick_mug(agents, self_state, self_name, mug):
"""
Checks if the 'mug' is reachable by the agent (robot) and if the agent does not carry anything.
Then updates the beliefs of all the agents in the same room as the robot as for the robot having picked the 'mug'
"""
if self_name in self_state... | 1d287e0b3d0115d4ccaa22b78ef00e8303eb8341 | 619,656 |
import inspect
def function_param_order(func):
"""get names of args infunction signature"""
return list(inspect.signature(func).parameters.keys()) | 828fb936f10cedb7dfac791d314cfa30d7ea90f9 | 619,657 |
def is_wikidata_entity(entity: str) -> bool:
"""Assert that a string is a wikidata entity"""
wrong_entity_format = entity and (entity[0] != "Q" or any([j not in "0123456789" for j in entity[1:]]))
return not wrong_entity_format | 2e5f879c5ad45f69d8d0102967a71d6f3543b8d0 | 619,662 |
def overlap_common_cnvs(all_bt, common_cnvs, cnv, min_cov):
"""
Overlap regions with a BED of common CNVs, and return list of IDs ≥ min_cov
"""
if common_cnvs is not None:
bt_cov = all_bt.coverage(common_cnvs)
ids = [x[3] for x in bt_cov if x[4] == cnv and float(x[-1]) >= min_cov]
... | db39ac617b377667c3fc187c4eb9acbf95387249 | 619,665 |
import json
def get_total_audio_duration(info_file):
"""
Get duration and total clips from info JSON.
Parameters
----------
info_file : str
Path to info JSON
Returns
-------
float
Total duration of all clips
int
Total number of clips
"""
with open(... | c9adb7259634064d0c1d0063c7be793f8002231f | 619,669 |
def group_objects_by_model(objects):
""" Group objects by their models
Args:
objects (:obj:`list` of :obj:`Model`): list of model objects
Returns:
:obj:`dict`: dictionary with object grouped by their class
"""
grouped_objects = {}
for obj in objects:
if obj.__class__ no... | 5adef1236c64c5f84703eacb594417946b7ab302 | 619,673 |
def cwum_2d(x,c=0.):
"""
Correlated density with uniform marginals (CWUM)
x in [0,1], 0<=c<2
c = 1. is tensor product uniform
c = 0. # if c=0 max pdf(x) = 2. min= 0.
"""
normalization = (13.*c+3)/16.
return (c-2.*(c-1.)*((x[0,:]+1)/2.+(x[1,:]+1)/2.-2.*(x[0,:]+1)/2.*(x[1,:]+1)/2.)/4.)/nor... | 4b0cdfbb7f6a30977e87a9d66405ca4341123ba5 | 619,676 |
import re
def parse_version(version):
"""Parse a version string, discarding any suffix and returning a
3-tuple of the major, minor and patch version numbers."""
match = re.search(r'^([0-9]+)\.([0-9]+)(\.([0-9]+))?', version)
if match:
major = int(match.group(1))
minor = int(match.grou... | 8265f92112018291f12f0f8ddf20641b51da4441 | 619,677 |
def _getName(geo):
"""Given a GeoInfo object, return the value of its 'name' attribute. If there is no such attribute, return None."""
attrCtx = geo.attribContext('name', 3, 7) # 3 = per-object attribute, 7 = std::string type
if attrCtx is None:
attrCtx = geo.attribContext('name', 3, 6) # 3 = per-object attri... | e57396ca85f18480e8eaf4babe53a905909bb075 | 619,679 |
def fetch_logs_by_id(logs_df, conversation_id):
"""fetch logs by conversation id
"""
return logs_df[logs_df['conversation_id'] == conversation_id] | f9cecbd6a55fb1b7af1a73cb06baeef5a3d1a5b6 | 619,680 |
def add_variable_mod(peps:list, mods_variable_dict:dict)->list:
"""
Function to add variable modification to a list of peptides.
Args:
peps (list): List of peptides.
mods_variable_dict (dict): Dicitionary with modifications. The key is AA, and value is the modified form (e.g. oxM).
Retur... | 772150946fbb8b0d87d30c1a94f1bad77f1c3e85 | 619,681 |
def frange(a, b, n):
"""
Returns an equally spaced sequence of floats, in the interval [a, b], with
n elements. (Essentially emulates the linspace() function in numpy.)
@type a: number
@param a: start of interval
@type b: number
@param b: end of interval
@type n: number
@param n:... | 85d52cd921eaa48aa28a1213af3974ecd9a71ca2 | 619,682 |
import socket
def connect(address):
"""Connect to given address and set socket non blocking."""
try:
sock = socket.socket()
sock.connect(address)
sock.setblocking(False)
except socket.error:
return None
return sock | c34323c4c6d324b741ae0eaa2cc76b5246ae6cff | 619,684 |
from typing import List
from operator import add
def twos(bits: List[int]) -> List[int]:
"""
Converts a list of bits into its Two's Complement representation. The bits
are negated (flipped) and the list of bits is then added with 1.
Agrs:
bits: (List[int]) The bits to take Two's Complement of... | 8d89403430e08bf82b0569cb2250797bd1f78730 | 619,685 |
from typing import List
from typing import Dict
def parse_stringdb_interactions(this_line: str, header_items: List) -> Dict:
"""Methods processes a line of text from Drug Central.
Args:
this_line: A string containing a line of text.
header_items: A list of header items.
Returns:
... | dbbcc9c98c5ce9cc7cd195c3e45c4c39f9d58b29 | 619,686 |
def format_frame_number_with_leading_zeros(frame: int) -> str:
"""
Formats the given number as a 5-digit with leading zeros
"""
return "{:05d}".format(frame) | 7a13467cc29c244f0cb70b8f671c286d024562d2 | 619,688 |
import math
def zscore_p(observed, expected, N):
"""
Computes z-score for the normal distribution
:param observed: prob.
:param expected: prob.
:param N:
:return:
"""
return (observed-expected) / math.sqrt((expected*(1.0-expected))/float(N)) | 405a97e1e72a422f03d07b79885484a3339b03f2 | 619,690 |
def mean_dist_from_centroid(coordinates, centroid):
"""
Calculate mean distance between centroid and list of coordinates
:param coordinates: list of coordinates as Points
:param centroid: centroid as Point
:return: mean distance between centroid and coordinates in metres
"""
dist = sum(coord... | f6a662000167d849e7e57fa7675041d9d297e074 | 619,691 |
def get_magnet_dict(self):
"""Return a dictionnary with all the magnets of the Hole
Parameters
----------
self : Hole
A Hole object
Returns
-------
magnet_dict : {Magnet}
Dictionnary of magnet (key = magnet_X, value= Magnet or None)
"""
if hasattr(self, "magnet_dic... | 1e41eee7a236c69643a14f0a359156d8c6b321e6 | 619,693 |
def hassecret(repo):
"""utility function that check if a repo have any secret changeset."""
return bool(repo._phasecache.phaseroots[2]) | f7ffd14ca383637ae11e36e4c122e61c90bc2440 | 619,694 |
def _CompareAnomalyBisectability(a1, a2):
"""Compares two Anomalies to decide which Anomaly's TestMetadata is better to
use.
Note: Potentially, this could be made more sophisticated by using
more signals:
- Bisect bot queue length
- Platform
- Test run time
- Stddev of test
Args:
a1: The ... | ab5ea6d8a88c4df7c56dfea6785137650ba79876 | 619,696 |
def bbox_vert_aligned_left(box1, box2):
"""
Returns true if the left boundary of both boxes is within 2 pts
"""
if not (box1 and box2): return False
return abs(box1.left - box2.left) <= 2 | b90846894ec65e7e5c95403aedc5db8d8dc8c29d | 619,698 |
def getDistinctElt(transactions):
"""
Get the distinct element in a list of transactions.
"""
distinctSet = set()
for transaction in transactions:
for elt in transaction:
if not(elt in distinctSet):
distinctSet.add(elt)
return distinctSet | cd62a3d10e4a4b736fe035ec04b366c00b69771d | 619,699 |
def histogram_from_vector(backend, data, weights, bins, mask=None):
"""Fills the weighted values in a data array to a histogram specified by a sorted one-dimensional bin array.
>>> data = numpy.array([1,1,1,2,3], dtype=numpy.float32)
>>> weights = numpy.array([1,1,1,2,1], dtype=numpy.float32)
>>> bins ... | 4a392dc5a2451d2c441db7c0a9de22ca9a1c8ce1 | 619,700 |
def do_one(fns, x):
""" Try each of the functions until one works. Then stop. """
for fn in fns:
result = fn(x)
if result != x:
return result
return x | e008986dc2ba7aa4a9763104807bf28af12cace1 | 619,701 |
import json
def file_id(fqn):
"""Get the Google FileID
:param fqn: path to a json-like file which contains the key: "doc_id"
"""
with open(fqn) as json_file:
result = json.load(json_file)
return result['doc_id'] | 47d6010112d61d9d713224cb56595ac0ee01c732 | 619,702 |
from typing import List
import csv
def read_file(path: str) -> List[list]:
"""
Read the data from the file path, reconstruct the format the the data
and return a list of lines.
the shape of the output is:
[[season, home_team, away_team, full_time_performance_score],
...]
Precondition... | e48880a2fbd6d994ec28a2ca7aeac17c988f3224 | 619,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.