content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def read_data_names(filepath: str):
"""
function to read class names & attributes
:param filepath: the relative path to the file containing the specifications of the attribute_values
:return: a tuple of lists
classes: is a one-dimensional list containing the class names
attr... | 1111bd25970e5d41c596eaefa9517992186fba8d | 65,280 |
def field_is_void(field):
"""Check if the field in the parameter is void, otherwise return False"""
if field == '':
return "Field not available"
else:
return False | c110176f8bc15d20cbda65f7a53ac9068a26c601 | 65,284 |
def fillNoneValues(column):
"""Fill all NaN/NaT values of a column with an empty string
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Series with filled NaN values.
"""
if column.dtype == object:
column.fillna('', inplace=True)
return col... | 7def3345decd08a0f410e1e13ee00ccc864615ef | 65,287 |
def smooth_n_point(scalar_grid, n=5, passes=1):
"""Filter with normal distribution of weights.
Parameters
----------
scalar_grid : array-like or `pint.Quantity`
Some 2D scalar grid to be smoothed.
n: int
The number of points to use in smoothing, only valid inputs
are 5 and ... | 41f65a0794ad42bc74abdaf05defdb33a6921cc6 | 65,288 |
def encode_inpt(row, col):
"""
Converts integers row, col to chess piece string in form "a1"
:param row: int
:param col: int
:return: string in form "a1"
"""
num = str(row + 1)
letter = chr(col + ord("a"))
return letter + num | cbc45ba74f5238bb957e477ee8420797d5b45162 | 65,293 |
def execute_cmd(conn, sqlcmd):
""" Execute the sqlcmd statement
params: conn: Connection Object
sqlcmd: An sql statement
returns the rows returned by executing the statement
"""
with conn:
cur = conn.execute(sqlcmd)
rows = cur.fetchall()
return rows | 9ea8a9c4529d46f0aeaac75491b11e9ae6ec4dd0 | 65,296 |
import uuid
def generate_job_id(group_uuid):
"""
Generates a job ID
"""
return "{}.{}".format(group_uuid, uuid.uuid4()) | a0aab5e36899930af720e156e0856b43041b5f67 | 65,302 |
def retrieve_data_from_paper(client, paper):
"""Given the url of a venue retrieves the data to a csv file
Args:
client (Client object from openreview): Specifies the base URL
and the login infomation
paper (string): Piece of text that identifies the paper in the venue
Returns:
A list of strin... | 7e45cebcac4c1c8047366350033a5fdcbf4dd583 | 65,305 |
def gcd(a: int, b: int) -> int:
"""Get greater common divisor (GCD) of two numbers
Args:
a, b: Numbers
Returns:
GCD of a and b
Examples:
>>> gcd(16, 28)
4
"""
return gcd(b, a % b) if b else a | 9ed29b10613f679bf168fe884f1e0f4cb2680aea | 65,308 |
def heading_depth(line):
"""Returns depth of heading indent
'# heading' returns 1
'### heading' returns 3
Args:
line (str): line in a markdown page
"""
assert line.startswith('#')
n = 0
while line[n:n + 1] == '#':
n += 1
return n | d4e9179ea91faab1450a1d615604c5601dcdd461 | 65,315 |
def create_option(name, ty, docstring, default_factory=lambda: None):
"""Creates a type-checked property.
Args:
name: The name to use.
ty: The type to use. The type of the property will be validated when it
is set.
docstring: The docstring to use.
default_factory: A callable that takes no arg... | abf646c7b8ddbd71bf7761c8f94989bcbc9f107b | 65,317 |
def parse_bsub(output):
"""Parse bsub output and return job id.
:param output: stdout of bsub command
:type output: str
:returns: job id
:rtype: str
"""
for line in output.split("\n"):
if line.startswith("Job"):
return line.split()[1][1:-1] | 557377cbc28ba9e1bd516a3ce68132ced5b05b7b | 65,320 |
def numeric_to_binary(data):
""" Convert numeric to binary """
if not data:
return ''
if not data.isdigit():
raise Exception('Numeric mode support only 0..9 characters!')
result = ''
for i in range(0, len(data), 3):
bin_val = bin(int(data[i:i + 3], 10))[2:]
if len(dat... | 9d5f96f79706df00c832e83ff17813cca8c0fa74 | 65,325 |
def split_byte(byte):
"""Return the 8-bit `byte` as two 4-bit unsigned integers.
Parameters
----------
byte : bytes
The byte to split, if more than one byte is supplied only the first
will be split.
Returns
-------
2-tuple of int
The (4 most significant, 4 least sig... | e8f5eeb1dd8dbd60d3797d47871738bd05eb5dd6 | 65,327 |
def remove_punctuation(string: str) -> str:
"""
Removes all non-letter, non-space characters from a string
:param string: a string
:return: a string containing only letters and spaces
"""
return ''.join([c for c in string if c.isalpha() or c.isspace()]) | f414479daa41a700997bc7405ecd7fcc97b5e7e6 | 65,328 |
def human_readable_number(number, suffix=""):
"""
Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string
"""
for unit in ["",... | 83c63a300966794ae5654cee6f6e39bc644856eb | 65,332 |
def get_account_deploy_count(accounts: int, account_idx: int, deploys: int) -> int:
"""Returns account index to use for a particular transfer.
"""
if accounts == 0:
return 1
q, r = divmod(deploys, accounts)
return q + (1 if account_idx <= r else 0) | 8668fd9619fd8e64e55833dc85ebcf9358e183dc | 65,340 |
def get_cube_intersection(a, b):
"""
Find the intersection of two cubes. Note: method returns invalid cube if input cubes do not actually intersect
:param a: cube a, tuple of min, max tuple of coords
:param b: cube a, tuple of min, max tuple of coords
:return: intersecting volume, tuple of min, max... | e359c1675fc92eeb9551d329679b3594d1c42f58 | 65,342 |
def cheating_matrix(seating_chart):
"""
Calculate and return the probabilities of cheating for each position in a rxc grid
:param seating_chart: A nested list representing a rxc grid
:return: A nested list, the same size as seating_chart, with each element representing that
position's cheati... | f9eaa1eb187ceeb0252d208002c739da3f70743c | 65,347 |
def format_container_output(output: bytes) -> str:
"""
Format the output of a Docker container for printing or logging.
Args:
output: Raw bytes output by the container.
Returns:
Output formatted as a string.
"""
# Decode bytestring, remove trailing newlines that get inserted.
r... | 53024b28dbae4c6ed929233af410385e1ffc1ffa | 65,350 |
def get_worker_count(cores):
"""
Get number of workers to run depending on server core count
"""
return cores * 2 | 58c8755a0c0409ab41266549fd530f885993077f | 65,357 |
import torch
def torch_generate_spatial_feature(bounding_box, W, H):
"""
This function generate spatial features.
:param bounding_box: set of bounding boxes in format [xmin, ymin, xmax, ymax]
:param W: images width.
:param H: images height.
:return: set of spatial features.
"""
res_1 =... | 896f0c34b07c2142d588349e51cb72f976cd1794 | 65,360 |
import torch
def metric_fixed_point(cost_matrix, gamma=0.99, eps=1e-7):
"""DP for calculating PSM (approximately).
Args:
cost_matrix: DIST matrix where entries at index (i, j) is DIST(x_i, y_j)
gamma: Metric discount factor.
eps: Threshold for stopping the fixed point iteration.
"""
d = torch.zer... | 1d84e1cb3232bd2905f005013f81b7ffc77e5f15 | 65,365 |
def normalize_pose_arr(data_arr, data_mean, data_std):
"""
Normalizes a pose array.
Parameters:
data_arr: ndarray(nTimePoints, nJoints=16, nCoords=(2 or 3)) of float64
data_mean, data_std: ndarray(nJoints=16, nCoords=(2 or 3)) of float64
"""
return (data_arr - data_mean) / data_std | 674da0636cb39fb2e2f1c6dca1ea96789e7f42f4 | 65,368 |
from textwrap import dedent
def dedent_sql(command):
"""Dedent a SQL command string."""
lines = command.split('\n')
return dedent('\n'.join([l for l in lines if not set(l).issubset({' '})])) | c87c3fc4752623762feed368558a4035954df439 | 65,369 |
def get(cluster_id, client):
"""Requests information on certain cluster."""
return client.get_cluster(str(cluster_id)) | aeef1add213bf66ad3ea55aea938edb9de25c998 | 65,379 |
def binary_encoder(msg: str) -> str:
"""Encodes user message into binary presentation
Parameters:
msg: user input to be encoded
Returns:
str: binary representation of input"""
return ' '.join(format(ord(i), 'b') for i in msg.strip()) | 168babf980bcf6c127cbea1f561f2148a550cae6 | 65,381 |
def _list_bcast_where(F, mask, new_val_l, old_val_l):
"""Broadcast where. Implements out[i] = new_val[i] * mask + old_val[i] * (1 - mask)
Parameters
----------
F : symbol or ndarray
mask : Symbol or NDArray
new_val_l : list of Symbols or list of NDArrays
old_val_l : list of Symbols or list ... | 36415acdf900ad1f255e08906e66484836864efc | 65,385 |
def parseFasta(file):
"""Returns sequence string from FASTA format."""
f=open(file)
ref=''
for i in f:
if i[0]!='>':
ref+=i.rstrip()
for l in 'RYLMKSWHBVD':
ref=ref.replace(l,'N')
return ref | fae4efb6f3625f2278e427579c8738e429c21638 | 65,387 |
from typing import Optional
from typing import Sequence
from typing import Dict
import dataclasses
def asdict_filtered(obj, remove_keys: Optional[Sequence[str]] = None) -> Dict:
"""Returns the attributes of a dataclass in the form of a dict, with unwanted attributes removed.
Each config group has the term 'na... | d6b11b41a4ce7265b5cba870239dccf73dd6f330 | 65,388 |
def parse_apbs_output(apbs_file):
"""Parse APBS output files for SASA information.
:param file apbs_file: file-like object with APBS output data
:returns: list of per-atom SASAs
:rtype: list(float)
"""
sasa_values = []
for line in apbs_file:
line = line.strip()
if line.st... | 73dd4fe398cb45bd13ebfcf6e91fb994ee3407ca | 65,389 |
import base64
def decode(encoded):
"""Decode urlsafe base64"""
decoded = base64.urlsafe_b64decode(encoded).decode()
return decoded | f374af33c07b0d5eef003da05ae26d0fcbb909f3 | 65,392 |
def raw_hostname(ip):
"""
For now, return raw IP
"""
return ip | 36fd431ba4ceb422cf3c2dde8fdbaa59efb18ce6 | 65,395 |
def leftPadItems(alist):
"""Add a space to the begining of each string in a given list."""
return [' ' + item for item in alist] | 8cd74bdf74c021a81532c8209774975fa5b6f9b4 | 65,399 |
def exempt_parameters(src_list, ref_list):
"""Remove element from src_list that is in ref_list"""
res = []
for x in src_list:
flag = True
for y in ref_list:
if x is y:
flag = False
break
if flag:
res.append(x)
return res | b22e62c4f5d284d9f5888c7c720c18d36f8d9146 | 65,400 |
def schema_table_exists(schema, table, conn):
"""Determines if the given table exists in the schema"""
query = """
SELECT EXISTS(
SELECT *
FROM information_schema.tables
WHERE
table_schema = '{0}' AND
table_name = '{1}'
);
... | e463f26aefaf716b1715baa39eaab93d30bc645e | 65,405 |
import re
def ordered_char_list_regex(chars):
"""
Turn a list of characters into a regex pattern that matches them all in order
"""
return ".*?".join(re.escape(char) for char in chars) | eb523775162cb9ac3475138618f3925141dc8f01 | 65,406 |
def multiply(data, scale):
"""
Multiply DATA by a factor of SCALE.
"""
op_output = {
'data': scale * data
}
return op_output | 64965fa09d0717d77ac5de3d83af6ffb22847c1a | 65,407 |
def get_body(html):
"""
Extract HTML code inside ``body`` tag.
"""
start = html.index('<body>') + 6
stop = html.rindex('</body>')
return html[start:stop] | f77b3c54708f640b5d02de4cbe0dace965360b20 | 65,410 |
def fixCertStr(certStr):
"""
Remove spaces after newlines.
When certificate is put in header by NGINX, one space is put after each
newline character, which breaks certificate. This function fixes
certificate string by removing those spaces.
"""
newCertStr = certStr.replace('\n ', '\n')
... | fa276cc1eea3db820858328e15c309305b4faba0 | 65,414 |
def check_polygon(nums: list[float]) -> bool:
"""
Takes list of possible side lengths and determines whether a
two-dimensional polygon with such side lengths can exist.
Returns a boolean value for the < comparison
of the largest side length with sum of the rest.
Wiki: https://en.wikipedia.org/w... | 114ae7120e661e19f32a7424895e37493f530ee6 | 65,415 |
import time
def test_engine(engine):
""" Tests SQLAlchemy engine and returns response time """
if not engine:
return {'status': 'ERROR', 'error': 'No engine defined'}
try:
start = time.time()
connection = engine.connect()
if not connection.closed:
connection.clo... | ced48c2d21480124ff4673630a7070772d370335 | 65,416 |
import random
def get_random_hashtags(input, number):
"""Gets a user-specified number of random hashtags from input
Parameters:
input (list): list of hashtags e.g. from fileIO.get_hashtags()
number (int): number of random hashtags the we wanna get out
Returns:
Array of random hashtags
"""... | 218ecbdc681c0eaf9ebae05c485de77e4c70c9d5 | 65,419 |
def SimpleElement(tag, value):
"""
Args:
tag: xml tag name
value: character data
Returns:
XML: <tag>value</tag>
"""
return '<%s>%s</%s>\n' % (tag, value, tag) | 8684d661f0fbf04c6d6cb4153041201378a258cc | 65,422 |
def underline_filter(text):
"""Jinja2 filter adding =-underline to row of text
>>> underline_filter("headline")
"headline\n========"
"""
return text + "\n" + "=" * len(text) | 417340cef3dce0348e197d7af9150b8407a8fa5e | 65,423 |
import re
def remove_shortwords(text, length=3):
"""Returns a string with all short words of a particular length or less removed
params:
length: Specify the length of words you want to remove
default is 3 letter word length or less
"""
token_words = re.split(r"\W+", text)
long_words_list... | 2e1d1a2b86505a2e693f38d67915c5fdc2b0af3e | 65,424 |
def RestMethod(url, http_methods):
"""Decorator to define a method's REST URL parameters."""
def WrapFunction(fn):
fn.is_rest_method = True
fn.rest_url = url
fn.rest_http_methods = http_methods
return fn
return WrapFunction | 6e317645732373c957288b033340caf01f1ddee2 | 65,425 |
def power(a, p):
"""
Function that returns a to the p
"""
return a ** p | 65bda2861ab82da93918a900d668f0c361322b73 | 65,427 |
import functools
import time
def timer(f):
""" Add this @decorator to a function to print its runtime after completion """
@functools.wraps(f)
def t_wrap(*args, **kwargs):
t_start = time.perf_counter()
ret = f(*args, **kwargs)
t_run = round((time.perf_counter() - t_start)/60)
... | 4c2d91bd492caa5ec78ce855d979a4e63f75f199 | 65,431 |
def calc_angular_radius(km):
"""calculate the angular radius for a given distance in kilometers"""
earth_radius = 6371.0 # in km
return km / earth_radius | d768de974f1ebb2fe5514b54200cb91e68866e30 | 65,433 |
def _get(result, field, mandatory=False, default="", transform=lambda x: x):
"""Retrieve a given field if available, return default or exception otherwise. Result may be manipulated by transformation function"""
if field in result:
return transform(result[field])
else:
if mandatory:
raise KeyError("... | 94f4975036a210fa1b2882438e5f05faababfe5a | 65,435 |
def date_to_str(dt, with_timezone=False):
"""
Convert datetime to str
Parameters
----------
dt : datetime
datetime to convert
with_timezone : bool, default False
Include timezone or not
Returns
-------
datetime_str : str
Datetime string
"""
if with_t... | fb3d8d10a95feec96e385af13490399bbe2d3172 | 65,450 |
import pathlib
import re
def find_files(pattern, min=None, max=None, check_parent=True, partial_match_is_error=True):
"""Find files matching a pattern with a sequence number.
The sequence number is represented using {N} in the input pattern,
which can be repeated.
Parameters
----------
patte... | 738e936c022fe38a5f0f8314011ec0a79969a5d0 | 65,452 |
def OpenFileForRead(filename):
""" Exception-safe file open for read
Args:
filename: local file name
Returns:
file: if open succeeded
None: if open failed
"""
try:
f = open(filename, 'r')
return f
except:
return None | 0f2a65e4136f5b91320320cc7eb027d4a7b99ab3 | 65,453 |
import secrets
def random(b: int) -> bytes:
""" Helper function to create a sequence of `b` random bytes using a cryptographically secure source of randomness.
"""
return secrets.token_bytes(b) | a6498cf3cb45c9d3dc6c364e6b8f8a4830fff6d6 | 65,457 |
def widget_type(field):
"""Determine a field's widget type on the fly.
:rtype: str
Example:
.. code::
{% if field|widget_type == "Textarea" %}
...
{% endif %}
"""
try:
return field.field.widget.__class__.__name__
except AttributeError:
return fiel... | f53cdef299b2f945c98d30607abaeeab4307e912 | 65,461 |
def _global_toc(cog, text):
""" Returns a single item for an unordered list with link to other file in same folder """
return f' * [{text}]({cog}.md#{text})\n' | e2ef80db14af15af59b3f860ce8b85be5574861d | 65,462 |
def get_update_url(d_included, base_url):
"""Parse a dict and returns, if present, the post URL
:param d_included: a dict, as returned by res.json().get("included", {})
:type d_raw: dict
:param base_url: site URL
:type d_raw: str
:return: post url
:rtype: str
"""
try:
urn =... | e4e2ba9f02b1718b220fe820c7eea95f5c0172c0 | 65,463 |
def is_palindrome(sequence):
"""
Checks if sequence is a palindrome, returns true or false
"""
sequence = str(sequence).lower()
for index, letter in enumerate(sequence):
if letter != sequence[(index + 1) * -1]:
return False
return True | b12325d89ecbcb77ef905b58485e39da945265de | 65,466 |
def invalid_resource(message, response_code=400):
"""
Returns the given message within in bad request body, and sets the response
code to given response code. Defaults response code to 404, if not provided.
"""
return {"message": message, "code": response_code} | 9cb9ac48d4cfaeeb05b94ffeba0abc68922313a6 | 65,467 |
import heapq
def nlargest_ref_heapq(n, iterable):
"""Vanilla implementation from the heapq module."""
return heapq.nlargest(n, iterable)[::-1] | 81ad93e4ffd8cc4918c7a833310b09a9bd94eea0 | 65,468 |
def group_locations(obj, ids):
"""
Return vertex locations for possible group of cells.
:param obj : geoh5py object containing cells, vertices structure.
:param ids : list of ids (or possibly single id) that indexes cells array.
:return locations : tuple of n locations arrays where n is length of ... | 97f9ad1b0a637eaf6b098ad8347ea0b8391ebdc2 | 65,469 |
import re
from typing import List
def parse_input(s) -> List[tuple]:
"""
Parses the search input query and creates a data structure:
( column_to_search_in, string_to_search, should we filter filter for quoted string)
:param s: input string to parse
:return: the list of the search terms to perform ... | 8b7b388e82d69723875a2281a21e625fce34c063 | 65,471 |
def merge_dicts(*dict_args):
"""
Merge all dicts passed as arguments, skips None objects.
Repeating keys will replace the keys from previous dicts.
"""
result = None
for dictionary in dict_args:
if dictionary is not None:
if result is None:
result = dictionar... | fe66414408aaf945ed45ac6a092e2865e775280c | 65,475 |
def strip_unexecutable(lines):
"""Remove all code that we can't execute"""
valid = []
for l in lines:
if l.startswith("get_ipython"):
continue
valid.append(l)
return valid | f52fcf9c4afd0262f39bbe51d13860e5826606fb | 65,476 |
def csvdata(nodelist):
"""
Returns the data in the given node as a comma separated string
"""
data = ""
for subnode in nodelist:
if (subnode.nodeType == subnode.ELEMENT_NODE):
try:
data = data + "," + subnode.childNodes[0].data
except:
... | c3fc1a220a501691a654c87a74860ab6cdd73fb0 | 65,478 |
def is_active(collection_name, document):
"""Return whether the given node settings document is active, e.g. has an external
account or is configured.
"""
if collection_name == 'addonfigsharenodesettings':
return any([
document['figshare_type'],
document['figshare_id'],
... | c9afeee58b94cfc86f160db1158e73d658cf8b3f | 65,483 |
def row_is_simple_header(row):
"""
Determine whether the row is a header row. The
three cols must be "lane","sample" and "index", in order
:type row: list[string]
:rtype: bool
"""
return len(row) == 3 \
and row[0].lower() == 'lane' \
and row[1].lower() == 'sample' \
... | 3efca9963c3be1cdfaf994549f5f32180c7a3612 | 65,484 |
import re
def url_get_scheme( url, clean=False ):
"""
Given a URL it returns the scheme.
If clean is 'True', it returns the scheme without '://'.
If there is not scheme it will return 'None'.
"""
# Regular Expression to get the scheme
scheme_pattern = "^.*://"
res = re.search( scheme_... | a315bd589aa58b8e948677c5b8d3032e6fad1f76 | 65,487 |
from pathlib import Path
def find_confounds_file(nii_file):
"""Finds the corresponding confounds.tsv file for a bold.nii.gz
Parameters:
nii_file: pathlib.Path
Returns:
confounds_file: pathlib.Path
"""
confounds_options = [str(fname).replace("desc-confounds_timeseries.tsv", "") fo... | 12f61251d0ddc9f7c0789922157ea8771fda3cda | 65,491 |
def simple_accuracy(preds, labels):
"""Returns the accuracy of the prediction."""
return (preds == labels).mean() | 63a64d9c024581492738e3bf4891cff526c5d705 | 65,499 |
def pt_agent_country(country):
"""Clean the country"""
c = country.strip()
if c.lower() == 'unknown':
return ''
return c | e87389b3a6713933b1ee4a578c7d6ab048d1ac0f | 65,501 |
def conjugate_par(par_dict):
"""Given a dictionary of parameter values, return the dictionary where
all CP-odd parameters have flipped sign.
This assumes that the only CP-odd parameters are `gamma` or `delta` (the
CKM phase in the Wolfenstein or standard parametrization)."""
cp_odd = ['gamma', 'del... | f92c73b34d884928119dace81622088c79e30e77 | 65,502 |
def get_individual_positions(individuals):
"""Return a dictionary with individual positions
Args:
individuals(list): A list with vcf individuals in correct order
Returns:
ind_pos(dict): Map from ind_id -> index position
"""
ind_pos = {}
if individuals:
for i, ind in enu... | e3ef0ced7f6fd3bc2c7ee060abc4afd9f09ed06c | 65,504 |
def splitLine(text):
"""split a line of text on the first space character and return
two strings, the first word and the remaining string. This is
used for parsing the incoming messages from left to right since
the command and its arguments are all delimited by spaces and
the command may not contain... | 82ce7005f18c22de6af438fd810a59760471b3d9 | 65,506 |
def restrict_encode( content, tool ):
"""
Disable the random interval ENCODE tool
This tool filter will disable all the ENCODE tool when enabled.
"""
if tool.id == 'random_intervals1':
return False
return True | d2fa098934aa842986f5a59762ea4d85660779ac | 65,510 |
def ZFrequencyList_to_TFrequencyList(Z_frequency_list,Z01=complex(50,0),Z02=complex(50,0)):
""" Converts z parameters into T parameters. Z-parameters should be in the form [[f,Z11,Z12,Z21,Z22],...]
the port 1 (Z01) and port 2 (Z01) impedances can be specified, default is 50. Returns data in the form
[[f,T11... | 410b4cf43600c333f6c0a6f337885c2d3a126ed8 | 65,511 |
def overlaps(mc1, mc2):
"""Compare two motifs and/or clusters to see if their location ranges overlap."""
return (mc1.start < mc2.end) and (mc1.end > mc2.start) | f87622c473d58172448ffa0bbe3d4fab99cc1fb7 | 65,517 |
def transceive(spi,csPin,busyPin,cmd: int,len: int) -> bytearray:
"""
Method to receive data by an SPI slave after sending a command.
Parameters
-----
spi : spi object from busio.SPI
csPin : control slave pin from board.D##
cmd : opcode of command
len : number of bytes to receive
... | 45b92a583ec654764abf97c3a12ae051d650ae86 | 65,520 |
def dataset_info(graph):
"""Returns information on the dataset (number of users, links ...)"""
n_users = len(graph.ids[0])
n_songs = len(graph.ids[1])
n_tags = len(graph.ids[2])
n_user_song_links = graph.n_links(0, 1)
n_song_tag_links = graph.n_links(1, 2)
user_song_volume = [
(us... | 2787b79ac5ad2fe6b0b2f0ec744fda6dec5ab827 | 65,521 |
def decode_erd_bytes(value: str) -> bytes:
"""Decode a raw bytes ERD value sent as a hex encoded string."""
return bytes.fromhex(value) | e30acf5a7ad78850f2a822fb8d9d097488baf0db | 65,525 |
def _improve_segmentation(doc):
"""
Helper function to improve spacy sentence segmentation specifically for product descriptions.
A lot of descriptions contain lists that spacy does not properly handle. To fix that, this function marks every
token that is followed by an empty token (i.e. newline) as the... | aff9c3ce57ef02074d69924a0388c0028afc90ca | 65,528 |
import random
import string
import time
def generate_random_filename(randlen=2, suffix=None):
"""
Generates a random string with a specified prefix, useful for generating
random filenames. No two filenames will be the same if executed on the same
machine.
*randlen* specifies the length of the fil... | 4091e1e57d7efa9d148e8dc3ae88c42cb9941a85 | 65,529 |
def uniq_srt(it):
"""Returns the input sequence unified and sorted (according to the values)
>>> uniq_srt([3, 3, 5, 3, 4, 2, 4])
[2, 3, 4, 5]
>>> uniq_srt('abrakadabra')
['a', 'b', 'd', 'k', 'r']
"""
return sorted(set(it)) # your solution | dc5d8e7152a8ec5580f19960043bdb9ab4b5fa42 | 65,533 |
def _IsOutputField(help_text):
"""Determines if the given field is output only based on help text."""
return help_text and help_text.startswith('[Output Only]') | 256d51383c6493deed5f3c041a8b34d22789bf8f | 65,538 |
def calc_eaf(delta_T, N_lay, P_i, A_i, v, A_p, D_i, t_p, alpha, E_p, thick=False):
"""Return the effective axial force [N], negative in compression."""
if thick:
return (
N_lay
- P_i * A_i
+ 2 * P_i * v * (A_p / 4) * (D_i / t_p - 1)
- alpha * delta_T * E_p... | 919f50ff03cc2d92c603ec1a4249eec971f414c2 | 65,540 |
import re
def fix_type_pre(value):
"""
So far this only modifies ellipses.
>>> fix_type_pre("... ....")
' <nobr> . . . </nobr> <nobr> . . . . </nobr> '
"""
new_value = value
new_value = re.sub(r'\.{3}[^\.]',r' <nobr> . . . </nobr> ', new_value)
new_value = re.sub(r'\.{4}',r' <nobr> ... | ecf19286286b56a2e81462625e6c4b3a0102ef46 | 65,541 |
def _remove_nesting(ref):
"""Remove the outer layer of nesting if ref is a nested reference.
Return the original reference if it's not nested"""
return (ref['reference']
if isinstance(ref, dict) and 'reference' in ref
else ref) | 2f120a5530d4b11778f28dccf85c96ac5df2d798 | 65,543 |
def nt_escape(node_string):
"""Properly escape strings for n-triples and n-quads serialization."""
output_string = ''
for char in node_string:
if char == u'\u0009':
output_string += '\\t'
elif char == u'\u000A':
output_string += '\\n'
elif char == u'\u000D':
... | ff586a4a1cbe3236c67b8d7a276343a8299af525 | 65,544 |
import json
def lambda_handler(event, context):
"""
This is roughly the exact same handler function that AWS provides.
"""
response = {
'statusCode': 200,
'body': json.dumps("Hello world")
}
return response | 13e21c253356ff2c23551ef7e9c34d0fb0f85d60 | 65,546 |
def filter_experiments(collection, configurations):
"""Check database collection for already present entries.
Check the database collection for experiments that have the same configuration.
Remove the corresponding entries from the input list of configurations to prevent
re-running the experiments.
... | 20c26a299fb302680520fcb7ae7fe25ae0d53364 | 65,553 |
def filter_jwt(respose, response_json):
"""Replace the refresh and access token with some mock up data."""
if "refresh" in response_json and "access" in response_json:
response_json["refresh"] = "mock_refresh"
response_json["access"] = "mock_access"
return respose, response_json | 24c144978f8eecaf83674d7127b5c3b235d7924a | 65,554 |
def _propagate(P, F, B):
"""Propagate labels by one step
Parameters
----------
P : scipy sparse matrix, shape = [n_samples, n_samples]
Propagation matrix
F : numpy array, shape = [n_samples, n_classes]
Label matrix
B : numpy array, shape = [n_samples, n_classes]
Base mat... | 9946514062fdb454e0d1cdbaf14f2887fb6781de | 65,555 |
def remove_equal_start_stop(gpx):
"""Removes any sily tracks with either 1 point, or 2 points on the same location.
"""
for track in gpx.tracks:
remove = False
if len(track.segments[0].points) > 1:
remove = True
elif len(track.segments[0].points) > 2:
p0 = tra... | 3cfc2b6c644eedc84fddafa542f2702961f0961a | 65,556 |
from typing import Callable
from typing import Any
from typing import Sequence
import functools
def apply_middlewares(
func: Callable[..., Any], middlewares: Sequence[Callable[..., Any]]
) -> Callable[..., Any]:
"""
Apply a list of middlewares to a source function.
- Middlewares must be structured as... | 04685a34f401eb884e8bc352a8be285fb3b9a53e | 65,560 |
import re
def namespace(element):
"""
Gets XML namespace of element
:param element: element, whose tag carry namespace
:return: namespace of element, if element does not have one, return empty string
"""
m = re.match('\{.*\}', element.tag)
return m.group(0) if m else '' | 316baac2e99b5171f30ee69d5e4cc0274d1a6cc3 | 65,565 |
def expected_headers(auth_token='my-auth-token'):
"""
Return an expected set of headers, given an auth token
"""
return {
'content-type': ['application/json'],
'accept': ['application/json'],
'x-auth-token': [auth_token],
'User-Agent': ['OtterScale/0.0']
} | 9a7a926a8da86e0eb4ae9bdf24820b9462539966 | 65,566 |
from typing import List
from typing import Any
def columns(table: List[List[Any]]) -> List[List[Any]]:
"""Returns a list with the columns of a table.
Args:
table (List[List[Any]]): The table. Needs to be a n x m matrix.
Returns:
List[List[Any]]: The columns of the table.
Raises:
... | 0e475b1ac4c1910548c80283c22ebb3b1506a10d | 65,568 |
def isUniqueWithSet (str):
"""Given a string, checks if the string has unique charachters"""
return len(set(str)) == len(str) | 299e4eaf617fbec4b5aa55493a64abba51fd8354 | 65,571 |
import time
def wait_for(boolean_predicate, timeout_seconds=None, poll_period=0.25, exceptions_to_swallow=None):
"""
Waits a specified amount of time for the conditional predicate to be true.
:param boolean_predicate: A callable to continually evaluate until it returns a truthy value
:type boolean_pr... | bbcb36e0d7fa7a73b2ac18f02b2e23cbbc354fb8 | 65,574 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.