content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import socket
import struct
def int_to_ip(addr):
"""
Converts a the numeric representation of an ip address
to an ip address strin
Example:
>>> int_to_ip(2130706433)
'127.0.0.1'
"""
return socket.inet_ntoa(struct.pack("!I", addr)) | 6db99b4cb7e7274eb1ac2b7783a4b606d845c4a5 | 9,775 |
def aa_seq_doc(aa_sequence):
"""This function takes in an amino acid sequence (aa sequence) and adds spaces between each amino acid."""
return ' '.join([aa_sequence[i:i+1]
for i in range(0, len(aa_sequence))]) | cb497c340d5ecc29184dc079ea9530ebddc43fbd | 9,777 |
def v70_from_params_asdict(v70_from_params):
"""Converts a sparse `v70_from_params` array to a dict."""
dict_v70_from_params = {}
for i in range(v70_from_params.shape[0]):
for j in range(v70_from_params.shape[1]):
v = v70_from_params[i, j]
if v:
dict_v70_from_params[(i, j)] = str(v)
retu... | 355ba80c131d08b6aedf20680545b4b31e07832e | 9,784 |
def open_r(filename):
"""Open a file for reading with encoding utf-8 in text mode."""
return open(filename, 'r', encoding='utf-8') | 08086625a9c05738a3536001a158eff3b0718ddf | 9,785 |
def prepend_protocol(url: str) -> str:
"""Prefix a URL with a protocol schema if not present
Args:
url (str)
Returns:
str
"""
if '://' not in url:
url = 'https://' + url
return url | 856961526207510c630fe503dce77bdcfc58d0cc | 9,788 |
def chunk_by_image(boxes):
"""
turn a flat list of boxes into a hierarchy of:
image
category
[boxes]
:param boxes: list of box detections
:return: dictionary of boxes chunked by image/category
"""
chunks = {}
for b in boxes:
if b['image_id'] not in chunks:
... | d6eaf46214a97853407112a9d0a3c47a132fb3c4 | 9,791 |
from typing import Tuple
from typing import List
def split_by_commas(maybe_s: str) -> Tuple[str, ...]:
"""Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas
"""
if not maybe_s:
return ()
parts: List[str] = []
... | ca21e5103f864e65e5ae47b49c161e8527036810 | 9,794 |
def kalman_predict(m, P, A, Q):
"""Kalman filter prediction step"""
m_p = A @ m
P_p = A @ P @ A.T + Q
return m_p, P_p | a43e644693d02e317f2ac67a36f0dc684e93f3d5 | 9,797 |
def is_probably_gzip(response):
"""
Determine if a urllib response is likely gzip'd.
:param response: the urllib response
"""
return (response.url.endswith('.gz') or
response.getheader('Content-Encoding') == 'gzip' or
response.getheader('Content-Type') == 'application/x-gzip... | 30ca3774f16debbac4b782ba5b1c4be8638fe344 | 9,800 |
import random
import math
def buffon(needlesNbr, groovesLen, needlesLen):
"""Simulates Buffon's needle experiments."""
intersects = 0
for i in range(needlesNbr):
y = random.random() * needlesLen / 2
angle = random.random() * math.pi
z = groovesLen / 2 * math.sin(angle)
if y <= z:
intersects += 1
exp... | 34bbb29346690b5d0ef519282699f0b3b82d93cb | 9,801 |
def get_new_snp(vcf_file):
"""
Gets the positions of the new snp in a vcf file
:param vcf_file: py_vcf file
:return: list of new snp
"""
new_snp = []
for loci in vcf_file:
if "gff3_notarget" in loci.FILTER:
new_snp.append(loci)
return(new_snp) | 1385a5552f9ad508f5373b2783d14938ab04b9c5 | 9,803 |
def most_freq(neighbors):
"""
Returns the dominant color with the greater frequency
Example: num_dominating = [paper, paper, paper, spock, spock, spock, spock, spock]
Returns: spock
"""
return max(set(neighbors), key=neighbors.count) | 09c041b27dbf55f6e862d73bde421a86ac265f42 | 9,805 |
from datetime import datetime
def greater_than_days_cutoff(timestamp, cutoff):
""" Helper function to calculate if PR is past cutoff
"""
# Convert string to datetime object
last_update = datetime.strptime(timestamp[0:22], '%Y-%m-%dT%H:%M:%S.%f')
# Get the number of days since this PR has been la... | 2dd1a9c01112d30a77ca2f5826db32d29f26d830 | 9,807 |
def reportnulls(df):
"""
Takes a data frame and check de nulls and sum
the resutls and organizes them from highest to lowest
"""
null_counts = df.isnull().sum().sort_values(ascending=False)
# return count of null values
return null_counts | a3dc20feeaaf0f3467de76812531f1d0b791dc01 | 9,810 |
def getConstrainedTargets(driver, constraint_type='parentConstraint'):
"""
Gets all the transforms the given driver is driving through the giving constraint type.
Args:
driver (PyNode): The transform that is driving the other transform(s) through a constraint.
constraint_type (string): The... | 4e94a4cf1e72012e2413f1889ec76ccd0a76800e | 9,812 |
from typing import List
from pathlib import Path
def get_isbr2_nii_file_paths(dir_paths: List[Path], file_selector: str) -> List[Path]:
"""Returns all the .nii.gz file paths for a given file_selector type.
Arguments:
dir_paths: a list of sample dir paths, each directory holds a full scan
file_... | fc04b9fa48e2d44c532344c36bdbdefe71f24f67 | 9,813 |
def get_num_gophers(blades, remainders, M):
"""Find no. of gophers given no. of blades and remainders."""
for i in range(1, M + 1):
congruences = all([i % b == r for b, r in zip(blades, remainders)])
if congruences:
return i
return None | 0467bd7a9ab56181b03c26f0048adf52b1cc8228 | 9,814 |
import math
def __calc_entropy_passphrase(word_count, word_bank_size, pad_length, pad_bank_size):
"""
Approximates the minimum entropy of the passphrase with its possible deviation
:param word_count: Number of words in passphrase
:param word_bank_size: Total number of words in the word bank
:param... | c3597b8d8fc35387638e1e0e4923316c2b99aaa8 | 9,815 |
def join_string(list_string, join_string):
"""
Join string based on join_string
Parameters
----------
list_string : string list
list of string to be join
join_string : string
characters used for the joining
Returns
-------
string joined : string
a string whe... | bcb55fb72b9579dd5ab548b737a0ffd85cbc7f43 | 9,816 |
def parse_segments(segments_str):
"""
Parse segments stored as a string.
:param vertices: "v1,v2,v3,..."
:param return: [(v1,v2), (v3, v4), (v5, v6), ... ]
"""
s = [int(t) for t in segments_str.split(',')]
return zip(s[::2], s[1::2]) | 4adfaff824ceb12772e33480a73f52f0054f6f5d | 9,820 |
def GetFirstWord(buff, sep=None):#{{{
"""
Get the first word string delimited by the supplied separator
"""
try:
return buff.split(sep, 1)[0]
except IndexError:
return "" | ce01a470ff5ba08f21e37e75ac46d5a8f498a76a | 9,821 |
import torch
def BPR_Loss(positive : torch.Tensor, negative : torch.Tensor) -> torch.Tensor:
"""
Given postive and negative examples, compute Bayesian Personalized ranking loss
"""
distances = positive - negative
loss = - torch.sum(torch.log(torch.sigmoid(distances)), 0, keepdim=True)
return ... | 868df180dc0166b47256d64c60928e9759b80e5f | 9,825 |
def find_fxn(tu, fxn, call_graph):
"""
Looks up the dictionary associated with the function.
:param tu: The translation unit in which to look for locals functions
:param fxn: The function name
:param call_graph: a object used to store information about each function
:return: the dictionary for t... | e73783b2eddadcbbc9e9eff39073805fc158c34e | 9,828 |
def checksum(message):
"""
Calculate the GDB server protocol checksum of the message.
The GDB server protocol uses a simple modulo 256 sum.
"""
check = 0
for c in message:
check += ord(c)
return check % 256 | bfba144414f26d3b65dc0c102cb7eaa903de780a | 9,832 |
def parse_report_filter_values(request, reports):
"""Given a dictionary of GET query parameters, return a dictionary mapping
report names to a dictionary of filter values.
Report filter parameters contain a | in the name. For example, request.GET
might be
{
"crash_report|operating_... | 217a7bfdeb65952637774ebefb6ae0ea7a0d991c | 9,834 |
import itertools
def iter_extend(iterable, length, obj=None):
"""Ensure that iterable is the specified length by extending with obj"""
return itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length) | 1e6a2bdd36b8bcb3202c4472c9e7621eef9edcf1 | 9,835 |
def keyfunc(line):
"""Return the key from a TAB-delimited key-value pair."""
return line.partition("\t")[0] | 39737389cd7a9e8046ff00700004b8864a242914 | 9,839 |
def html_wrap(html_string):
"""Add an html-head-body wrapper around an html string."""
html_prefix="""<html>
<head>
<title>HTML CSS TESTS</title>
<link rel="stylesheet" type="text/css" href="tests/manual html-css tests/html-css.css">
</head>
<body>"""
html_pos... | 8510549f4de1de25ac98361f757210eafdb02631 | 9,840 |
def split(ary, n):
"""Given an array, and an integer, split the array into n parts"""
result = []
for i in range(0, len(ary), n):
result.append(ary[i: i + n])
return result | 27ae4f06603de17c993656fae9df07b61f333474 | 9,841 |
def apply_bounds(grid, lVec):
"""
Assumes periodicity and restricts grid positions to a box in x- and
y-direction.
"""
dx = lVec[1,0]-lVec[0,0]
grid[0][grid[0] >= lVec[1,0]] -= dx
grid[0][grid[0] < lVec[0,0]] += dx
dy = lVec[2,1]-lVec[0,1]
grid[1][grid[1] >= lVec[2,1]] -= dy
gri... | 34411b7cc1062ade4d45c922225a3364a6c84180 | 9,845 |
def matches_filter(graph, props):
"""
Returns True if a given graph matches all the given props. Returns False
if not.
"""
for prop in props:
if prop != 'all' and not prop in graph['properties']:
return False
return True | 8d53f198b7ad1af759203909a05cd28916512708 | 9,847 |
from typing import List
from typing import Any
from typing import Union
import re
def human_sort_key(key: str) -> List[Any]:
"""
Function that can be used for natural sorting, where "PB2" comes before
"PB10" and after "PA3".
"""
def _convert(text: str) -> Union[int, str]:
return int(text) ... | 31c163250f5b040b18f3f2374825191ce3f61ff4 | 9,848 |
def get_class(class_string):
""" Returns class object specified by a string.
Arguments:
class_string -- The string representing a class.
Raises:
ValueError if module part of the class is not specified.
"""
module_name, _, class_name = class_string.rpartition('.')
... | a25573ac9cb6115e0b8ad1d28a286f86628d8235 | 9,849 |
import hashlib
def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int):
"""
Hash string and return indices of bits that have been flipped correspondingly.
:param string: string: to be hashed and to flip bloom filter
:param bf_len: int: length of bloom filter
:param num_hash_funct: in... | c245637b86cc16b68d069bf2359b1e5c7483a8fc | 9,850 |
def largest_product(product_list):
"""Find the largest product from a given list."""
largest = 1
for products in product_list:
if largest < max(products):
largest = max(products)
return largest | 7f9f2b151afc7d0e35203a5dda665ef100279c65 | 9,852 |
import random
def shuffle_string(s: str) -> str:
"""
Mixes all the letters in the given string
Parameters:
s(str): the string to shuffle
Returns:
str: string with randomly reordered letters
Examples:
>>> shuffle_string('abc')
'cba'
>>>... | 9c68b276f539d6385e5393cb92fa971fbb6059d4 | 9,855 |
def diff_lists(old, new):
"""Returns sorted lists of added and removed items."""
old = set(old or [])
new = set(new or [])
return sorted(new - old), sorted(old - new) | 1359a2c89c20993445491ff2a986a392eaee2aed | 9,862 |
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str:
"""
Given a trait name, filters and hostname, create a url with which to query Zooma. Return this
url.
:param trait_name: A string containing a trait name from a ClinVar record.
:param filters: A dictionary containing fi... | 0fb22b1f44319c2fa8e87d8e720de248dd1a7eba | 9,876 |
from typing import Any
def ret(d: dict, key: str) -> Any:
""" Unwrap nested dictionaries in a recursive way.
Parameters
----------
d: dict
Python dictionary
key: str or Any
Key or chain of keys. See example below to
access nested levels.
Returns
----------
out... | 86d07ba6dbe2610ceabb0bcee3099b5734c770ae | 9,879 |
def is_identity(u):
"""Checks if the unit is equivalent to 1"""
return u.unitSI == 1 and u.unitDimension == (0,0,0,0,0,0,0) | afc9029eeb44739a38869f06f84ba36b2a19da6f | 9,883 |
def common(first_list, second_list):
"""Receives two lists, returns True if they have any common objects and false otherwise.
Note that this implementation should theoretically work with any container-like object for which
the in operator doesn't have a different meaning."""
# iterate over the elements ... | da48a3a559bc26a79bc5aa06ca6efa15053e1cd4 | 9,887 |
def calc_linear_crossing(m, left_v, right_v):
"""
Computes the intersection between two line segments, defined by two common
x points, and the values of both segments at both x points
Parameters
----------
m : list or np.array, length 2
The two common x coordinates. m[0] < m[1] is assum... | 3f5eeab9fa906b6858e249f97c7e175e427cb2d7 | 9,890 |
def octave_to_frequency(octave: float) -> float:
"""Converts an octave to its corresponding frequency value (in Hz).
By convention, the 0th octave is 125Hz.
Parameters
----------
octave : float
The octave to put on a frequency scale.
Returns
-------
float
The frequency value c... | d50fe69e0dd267b5418834ca2999867213b5f306 | 9,893 |
def is_bitcode_file(path):
"""
Returns True if path contains a LLVM bitcode file, False if not.
"""
with open(path, 'rb') as f:
return f.read(4) == b'BC\xc0\xde' | acfd17eee949f42994b2bc76499ee58c710eb388 | 9,898 |
from typing import List
def get_file_pattern() -> List[str]:
"""
Returns a list with all possible file patterns
"""
return ["*.pb", "*.data", "*.index"] | 8c4f471dea29dfe5c79cf3ea353cb1a335a5cf45 | 9,899 |
def get_param_cols(columns):
""" Get the columns that were provided in the file and return that list so we don't try to query non-existent cols
Args:
columns: The columns in the header of the provided file
Returns:
A dict containing all the FPDS query columns that the provi... | 8a0030c745d2de5bd2baf93af79efce4dcb4c696 | 9,906 |
import re
def depluralize(word):
"""Return the depluralized version of the word, along with a status flag.
Parameters
----------
word : str
The word which is to be depluralized.
Returns
-------
str
The original word, if it is detected to be non-plural, or the
dep... | 9d879a320da566bceb6e5db6cbfe2e7f23f9bb73 | 9,907 |
import ipaddress
def _get_network_address(ip, mask=24):
"""
Return address of the IPv4 network for single IPv4 address with given mask.
"""
ip = ipaddress.ip_address(ip)
return ipaddress.ip_network(
'{}/{}'.format(
ipaddress.ip_address(int(ip) & (2**32 - 1) << (32 - mask)),
... | bb706209cc7295ab1d0b4bf88e11d3efba10d526 | 9,909 |
def get_admin_ids(bot, chat_id):
"""
Returns a list of admin IDs for a given chat. Results are cached for 1 hour.
Private chats and groups with all_members_are_administrator flag are handled as empty admin list
"""
chat = bot.getChat(chat_id)
if chat.type == "private" or chat.all_members_are_adm... | 6bd89e1d6b7333d97cbc60fd2617a86d1b69fb2f | 9,910 |
import math
def num_tiles_not_in_position(state):
"""
Calculates and returns the number of tiles which are not in their
final positions.
"""
n = len(state)
total = 0
for row in state:
for tile in row:
try:
y = int(math.floor(float(tile)/n - (float(1)/n))... | 102d2eb616f8b459fc31e68788f355440bac97e0 | 9,912 |
def get_bool_symbols(a_boolean):
"""
:param a_boolean: Any boolean representation
:return: Symbols corresponding the to the
True or False value of some boolean representation
Motivation: this is reused on multiple occasions
"""
if a_boolean:
return "✅"
return "❌" | b95a4fc5ca29e07a89c63c97ba88d256a24a7431 | 9,915 |
def returner(x):
"""
Create a function that takes any arguments and always
returns x.
"""
def func(*args, **kwargs):
return x
return func | 43476f89cae80cd2b61d64771a3dfac5e4297b5a | 9,916 |
from typing import Counter
def get_unique_characters(rows, min_count=2):
"""Given a bunch of text rows, get all unique chars that occur in it."""
def char_iterator():
for row in rows.values:
for char in row:
yield str(char).lower()
return [
c for c, count
... | ecba44e44222bb63c2f794e7ee9e87eb3754f695 | 9,917 |
def build_data_type_name(sources, properties, statistic, subtype=None):
"""
Parameters
----------
sources: str or list[str]
type(s) of astrophysical sources to which this applies
properties: str or list[str]
feature(s)/characterisic(s) of those sources/fields to
which the st... | 103a7440dfe3b8f6ccce0fdf6cdca86202e27ac5 | 9,918 |
def get_limit_from_tag(tag_parts):
"""Get the key and value from a notebook limit tag.
Args:
tag_parts: annotation or label notebook tag
Returns (tuple): key (limit name), values
"""
return tag_parts.pop(0), tag_parts.pop(0) | e7d4858b166b2a62ec497952853d95b81a608e85 | 9,924 |
def Percent(numerator, denominator):
"""Convert two integers into a display friendly percentage string.
Percent(5, 10) -> ' 50%'
Percent(5, 5) -> '100%'
Percent(1, 100) -> ' 1%'
Percent(1, 1000) -> ' 0%'
Args:
numerator: Integer.
denominator: Integer.
Returns:
string formatted result.
"... | a0081a387a737b44268fd71ab9746c7edd72221f | 9,925 |
import json
def read_data(f_name):
"""
Given an input file name f_name, reads the JSON data inside returns as
Python data object.
"""
f = open(f_name, 'r')
json_data = json.loads(f.read())
f.close()
return json_data | 629ab7e9a8bd7d5b311022af4c9900d5942e7a23 | 9,931 |
def reverse_string_recursive(s):
"""
Returns the reverse of the input string
Time complexity: O(n^2) = O(n) slice * O(n) recursive call stack
Space complexity: O(n)
"""
if len(s) < 2:
return s
# String slicing is O(n) operation
return reverse_string_recursive(s[1:]) + s[0] | a8d22e88b1506c56693aa1a8cd346695e2b160b2 | 9,932 |
def get_closest_multiple_of_16(num):
"""
Compute the nearest multiple of 16. Needed because pulse enabled devices require
durations which are multiples of 16 samples.
"""
return int(num) - (int(num) % 16) | 333cbed27abbcb576541d5fb0b44bf85b78c9e78 | 9,939 |
def split_container(path):
"""Split path container & path
>>> split_container('/bigdata/path/to/file')
['bigdata', 'path/to/file']
"""
path = str(path) # Might be pathlib.Path
if not path:
raise ValueError('empty path')
if path == '/':
return '', ''
if path[0] == '/':
... | 53b0d1164ecc245146e811a97017f66bb1f032a7 | 9,941 |
def parse_sph_header( fh ):
"""Read the file-format header for an sph file
The SPH header-file is exactly 1024 bytes at the head of the file,
there is a simple textual format which AFAIK is always ASCII, but
we allow here for latin1 encoding. The format has a type declaration
for each field a... | d0055b3dc276facd9acb361dfde167d8c123b662 | 9,942 |
def column(matrix, i):
"""
Returning all the values in a specific columns
Parameters:
X: the input matrix
i: the column
Return value: an array with desired column
"""
return [row[i] for row in matrix] | 2a88c40d11e7fe7f28970acd4d995a8428126a4d | 9,944 |
def cubicinout(x):
"""Return the value at x of the 'cubic in out' easing function between 0 and 1."""
if x < 0.5:
return 4 * x**3
else:
return 1/2 * ((2*x - 2)**3 + 2) | 505f0c5b8dc7b9499450474dbb1991eec068b553 | 9,945 |
def remove_duplicates(string: str) -> str:
"""
Remove duplicate characters in a string
:param string:
:return:
"""
without_duplicates = ""
for letter in string:
if letter not in without_duplicates:
without_duplicates += letter
return without_duplicates | 2caafc6b38cf2b920324bd976acb3caf90660c25 | 9,946 |
import json
def dumps(dict_):
"""
Converts dictionaries to indented JSON for readability.
Args:
dict_ (dict): The dictionary to be JSON encoded.
Returns:
str: JSON encoded dictionary.
"""
string = json.dumps(dict_, indent=4, sort_keys=True)
return string | c2f3eabe0b473def6233476018d8c3a3918beb70 | 9,952 |
def jpeg_linqual(quality):
"""
See int jpeg_quality_scaling(int quality)
in libjpeg-turbo source (file ijg/jcparam.c).
Convert quality rating to percentage scaling factor
used to scale the quantization table.
"""
quality = max(quality, 1)
quality = min(quality, 100)
if quality < 50:
... | a35157416fd4d95dddfe6cf8408a99e6247703ba | 9,953 |
def pytest_funcarg__content(request):
"""
The content for the test document as string.
By default, the content is taken from the argument of the ``with_content``
marker. If no such marker exists, the content is build from the id
returned by the ``issue_id`` funcargby prepending a dash before the i... | e357042566ce22557ba5c8f83b14f56cb8025dca | 9,954 |
def split_s3_path(s3_path):
"""
Splits the complete s3 path to a bucket name and a key name,
this is useful in cases where and api requires two seperate entries (bucket and key)
Arguments:
s3_path {string} -- An S3 uri path
Returns:
bucket {string} - The bucket name
key {... | 81efc5fc125c62d4dcde577b3424029acb4a536f | 9,955 |
def dash(*txts):
"""Join non-empty txts by a dash."""
return " -- ".join([t for t in txts if t != ""]) | 53566f49991f8d7930a63f7d2d22c125d9d25073 | 9,958 |
import asyncio
import functools
def call_later(delay, fn, *args, **kwargs) -> asyncio.Handle:
"""
Call a function after a delay (in seconds).
"""
loop = asyncio.get_event_loop()
callback = functools.partial(fn, *args, **kwargs)
handle = loop.call_later(delay, callback)
return handle | 86d157ed0f5f8dc7f806af9871a71057dc36222c | 9,959 |
from typing import Tuple
def build_blacklist_status(blacklist_status: str) -> Tuple[str, str, str]:
"""Build the blacklist_status
@type blacklist_status: str
@param blacklist_status: The blacklist status from command line
@returns Tuple[str, str, str]: The builded blacklist status
"""
blackli... | 10f0c3a77169a0e9b9136d454e6d17efdd4760f6 | 9,960 |
def _check_substituted_domains(patchset, search_regex):
"""Returns True if the patchset contains substituted domains; False otherwise"""
for patchedfile in patchset:
for hunk in patchedfile:
if not search_regex.search(str(hunk)) is None:
return True
return False | e3fdeaa1ede7f041bb6080d4647c8d969b41f73d | 9,962 |
def delete_segment(seq, start, end):
"""Return the sequence with deleted segment from ``start`` to ``end``."""
return seq[:start] + seq[end:] | 1eba39d373ac2ab28ea1ea414f708a508bdf48d2 | 9,966 |
import re
def detect_arxiv(txt):
"""
Extract an arXiv ID from text data
"""
regex = r'arXiv:[0-9]{4,4}\.[0-9]{5,5}(v[0-9]+)?'
m = re.search(regex, txt)
if m is not None:
return m.group(0)
else:
return None | a855497b6eb1f027085a301096735e860e76fbe7 | 9,968 |
def powmod(a, b, m):
""" Returns the power a**b % m """
# a^(2b) = (a^b)^2
# a^(2b+1) = a * (a^b)^2
if b==0:
return 1
return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m | 33b4cadc1d23423f32e147718e3f08b04bd2fd17 | 9,974 |
def ToHex(data):
"""Return a string representing data in hexadecimal format."""
s = ""
for c in data:
s += ("%02x" % ord(c))
return s | 1566962a89967ae0d812ef416d56867a85d824fb | 9,978 |
def _parse_common(xml, the_dict):
"""
Parse things in common for both variables and functions. This should
be run after a more specific function like _parse_func or
_parse_variable because it needs a member dictionary as an input.
Parameters
----------
xml : etree.Element
The xml re... | a6606366ce9b0e4d2c848b16bc868532684b4abe | 9,979 |
def elementWise(A, B, operation):
"""
execute an operate element wise and return result
A and B are lists of lists (all lists of same lengths)
operation is a function of two arguments and one return value
"""
return [[operation(x, y)
for x, y in zip(rowA, rowB)]
for row... | 39e78ca7730bf8367daf3a55aeb617b2c0707a44 | 9,981 |
def find_spaces(string_to_check):
"""Returns a list of string indexes for each string this finds.
Args:
string_to_check; string: The string to scan.
Returns:
A list of string indexes.
"""
spaces = list()
for index, character in enumerate(string_to_check):
if character == ' ':
spaces.ap... | 8bcd1d9911efab3c65e08524293b11afd449efa0 | 9,982 |
def addr_generator(start_ip, port, count):
"""Generator a list of (ip, port).
"""
def tostr(ip):
return '.'.join([str(_) for _ in ip])
ip = [int(_) for _ in start_ip.split('.')]
addr_list = [(tostr(ip), port)]
for i in range(count-1):
ip[-1] += 1
addr_list.append((tostr(i... | 100288629f35d9108e0b364266242da0110dd8f7 | 9,994 |
import random
import time
def retry(func, *args, **kwargs):
"""Repeats a function until it completes successfully or fails too often.
Args:
func:
The function call to repeat.
args:
The arguments which are passed to the function.
kwargs:
Key-word arg... | cf6f7d3e434b54cf178b2867f7565f338e985968 | 9,996 |
def _ScatterAddNdimShape(unused_op):
"""Shape function for ScatterAddNdim Op."""
return [] | 7c59fb40e177fea1bf1cd3970c364f4583fc37f9 | 10,000 |
def find_delimiter_in(value):
"""Find a good delimiter to split the value by"""
for d in [';', ':', ',']:
if d in value:
return d
return ';' | 4a60fbe6294fff048645a6fbc397ec96fd748d67 | 10,002 |
import functools
def with_color(color_code: str):
"""Coloring decorator
Arguments:
color_code {str} -- e.g.: '\033[91m'
"""
def wrapper(func):
@functools.wraps(func)
def inner(args):
result = func(f'{color_code}{args}\033[0m')
return result
retu... | 3f5ecd79b3d4579ba4348b2492eaaa3688201907 | 10,006 |
def over(funcs):
"""Creates a function that invokes all functions in `funcs` with the
arguments it receives and returns their results.
Args:
funcs (list): List of functions to be invoked.
Returns:
function: Returns the new pass-thru function.
Example:
>>> func = over([max... | 6cd1a966366ee372c18dd35d71adf91028a04b1c | 10,008 |
def load_labels_map(labels_map_path):
"""Loads the labels map from the given path.
The labels mmap must be in the following plain text format::
1:label1
2:label2
3:label3
...
The indexes are irrelevant to this function, they can be in any order and
can start from zero,... | 8ff1e41b87fedffa053981299c48488add754ff9 | 10,009 |
import math
def bbox_to_integer_coords(t, l, b, r, image_h, image_w):
"""
t, l, b, r:
float
Bbox coordinates in a space where image takes [0; 1] x [0; 1].
image_h, image_w:
int
return: t, l, b, r
int
Bbox coordinates in given ima... | 90fb198e2d6cd170a2e7a2b648f15554a9997389 | 10,010 |
def get_attrib_recursive(element, *attribs):
"""Find the first attribute in attribs in element or its closest ancestor
that has any of the attributes in attribs.
Usage examples:
get_attrib_recursive(el, "fallback-langs")
get_attrib_recursive(el, "xml:lang", "lang")
Args:
elemen... | d04ba71a280bd1697cc61b79af21df46023473d2 | 10,012 |
def find_extra_inferred_properties(spec_dict: dict) -> list:
"""Finds if there are any inferred properties which are used.
Args:
spec_dict: Dict obj containing configurations for the import.
Returns:
List of properties that appear in inferredSpec but are not part of 'pvs' section.
"""
re... | 3be2950a227cfca8d0ab4c4413322f8aa8b22cc0 | 10,013 |
def find_corresponding_basins(pfaf_id_level6,gdf_level7):
"""
Using a pfaf_id from level 6, find all hydrobasins in level 7 that
make up the hydrobasin level 6 polygon.
"""
pfaf_id_level7_min = pfaf_id_level6*10
pfaf_id_level7_max = pfaf_id_level7_min + 9
gdf_level7_selection = gd... | d8952abfb681fc2b1c33d53b930fff6c56f6bc0a | 10,015 |
def get_content_function_ratio(content, function):
""" Calculate the content-function word ratio. """
ratio = float(len(content)) / float(len(function)) if len(function) != 0 else 0
return round(ratio, 4) | e82109ed1fd2a3f3136945c4598358efdc0985e9 | 10,016 |
def test_decorator(f):
"""Decorator that does nothing"""
return f | b60b815e336a3f1ca3f12712a2d1d207a5fe110c | 10,018 |
def in_range(target, bounds):
"""
Check whether target integer x lies within the closed interval [a,b]
where bounds (a,b) are given as a tuple of integers.
Returns boolean value of the expression a <= x <= b
"""
lower, upper = bounds
return lower <= target <= upper | ac9dee9092388d150611ab5e1a4a800b72cf8f83 | 10,022 |
def flatten_array(grid):
"""
Takes a multi-dimensional array and returns a 1 dimensional array with the
same contents.
"""
grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]
while type(grid[0]) is list:
grid = flatten_array(grid)
return grid | 4c0361cf8e63d7608b4213ddd8f8a4c498282dcf | 10,027 |
import torch
def cosine_sim(x1, x2, dim=1, eps=1e-8):
"""Returns cosine similarity between x1 and x2, computed along dim."""
x1 = torch.tensor(x1)
x2 = torch.tensor(x2)
w12 = torch.sum(x1 * x2, dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=... | a4992b3f3a4a483c96a5b18bbc3402df70a8b44d | 10,028 |
def astype(value, types=None):
"""Return argument as one of types if possible."""
if value[0] in '\'"':
return value[1:-1]
if types is None:
types = int, float, str
for typ in types:
try:
return typ(value)
except (ValueError, TypeError, UnicodeEncodeError):
... | 47d066d9d4bb5b0b96216cc722c6896d6fdcf1a4 | 10,033 |
def _minmax(*args):
""" Return the min and max of the input arguments """
min_ = min(*args)
max_ = max(*args)
return(min_, max_) | 9985ebbffd3ee0b03dc751a3c90db00e922ab489 | 10,034 |
def distance0(cell1, cell2):
"""Return 0 distance for A* to behave like Dijkstra's algorithm."""
return 0 | 7850364b245afd304e3aa3ad443d7af74b36df79 | 10,036 |
def adjacent(g,node, n):
"""
find all adjacent nodes of input node in g
g: 2D array of numbers, the adjacency matrix
node: int, the node whose neighber you wanna find
return: a list of ints
"""
result = []
for i in range(n):
if g[node][i] != 0:
result.append(i)
... | 630160dbee314ed85980ac8bd825e96cd33765f4 | 10,037 |
def complete_sulci_name(sulci_list, side):
"""Function gathering sulci and side to obtain full name of sulci
It reads suli prefixes from a list and adds a suffix depending on a given
side.
Args:
sulci_list: a list of sulci
side: a string corresponding to the hemisphere, whether 'L' or ... | 5a0e969976458b81bac01ee33cfa24bbc92659c4 | 10,042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.