content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import logging
def parse_logs_head(data: bytes) -> set[str]:
"""Retrieve object hashes from logs/HEAD file."""
ret = set()
lines = data.split(b"\n")
for line in lines:
fields = line.split(b" ")
if len(fields) < 2:
break
for i in range(2): #first two fields are ... | 03ffb95bef5951efb57d98d9adb68b66b044b797 | 570,250 |
def array_split(ary,n):
"""
>>> data = [1,2,3,4,5]
>>> array_split(data,3)
[[1, 2], [3, 4], [5]]
>>> grps = array_split(range(0,1121),8)
>>> total_len = 0
>>> for grp in grps: total_len += len(grp)
>>> assert(total_len == len(range(0,1121)))
"""
step = int(round(len(ary)/float(n)... | a36bb14778ba9b3ed8a2bd77990ad6baf0d14271 | 629,934 |
def get_message_type(msg_or_cls):
"""Returns ROS1 message type name, like "std_msgs/Header"."""
return msg_or_cls._type | 42db77fbb59ada627e66a5878247fcd030e4773a | 196,437 |
def convert_to_undirected(G):
"""Return a new undirected representation of the graph G."""
return G.to_undirected() | 018e1a1a5773a025729560ad03a9eec85dd1e198 | 680,770 |
def convert_to_coordinate(raw_data:float, sec_delim:str, min_delim:str, deg_delim:str) -> str:
"""
Description:
Converts converts float value to the geographical data
(for example, 27°16'37.9")
Arguments:
- raw_data : `float` value as degree
- sec_del... | df1a7bde98f879f3dd1091f4d70e471627485084 | 596,145 |
def _is_valid_color(colors :dict, user_color :str):
"""Returns true if user_color is a graph color provided by matplotlib
Positional Arguments:
colors : dict
- dict of all colors supported by matplotlib passed in
by the graph_colors decorator
user_color : str
... | 95acb7270a5f0d6ebd8ba2b69a4e36b434251831 | 170,758 |
def truncate_int(tval, time_int):
"""Truncate tval to nearest time interval."""
return((int(tval)/time_int) * time_int) | 3c366f417ab9e84b5337814f78d7888fca4d0265 | 36,717 |
def convert_temperature(val):
""" Convert temperature from Kelvin (unit of 1/16th K) to Celsius
"""
return val * 0.0625 - 273.15 | 24b74df84c244c87aa86b2753f93dc6a587e61ce | 398,989 |
import re
def output_to_dict(output):
"""
Convert the ROUGE output into python dictionary for further
processing.
"""
#0 ROUGE-1 Average_R: 0.02632 (95%-conf.int. 0.02632 - 0.02632)
pattern = re.compile(
r"(\d+) (ROUGE-\S+) (Average_\w): (\d.\d+) "
r"\(95%-conf.int. (\d.\d+) -... | 671165127d22ead060c49fe835cba8d9130c8c27 | 433,961 |
def follow_abspath(json, abspath):
"""json: an arbitrarily nested python object, where each layer
is a list, dict, or tuple.
abspath: a list of keys or array indices to be followed.
**Returns:** the child of json[abspath[0]][abspath[1]]...[abspath[-1]]"""
out = json
for elt in abspath:
... | f870debbd3fe8ab05f93a9f0df979364706ece87 | 480,779 |
def tree_pop_fields(root, fields):
"""deletes given fields (as iterable of keys) from root and all its children (recursively)
returnes updated root """
for f in fields:
root.pop(f)
if root['is_leaf']: return root
for i in range(len(root['children'])):
root['children'][i]['child'] = t... | 1dca88301219ad2a9c83642024ab0db08472b507 | 30,652 |
def short_version(version):
"""Get a shorter version, only with the major and minor version.
:param version: The version.
:type version: str
:return 'major.minor' version number.
:rtype float
"""
return float('.'.join(version.split('.')[0:2])) | ab8c4cca8af8eb47c9ddc6ae117fc725ce7956e6 | 176,588 |
def to_ms(s):
"""Convert from seconds to milliseconds.
Args:
s (float, int): Value in seconds.
Returns:
int: Value in milliseconds.
"""
return int(s * 1e3) | 18b735962dbc4445dfc704e58e2c625d33b9d8f7 | 524,858 |
def iconv(idata, input):
"""
compare idata and input, if it is the same return 1, if not return 0
:param idata: (char1) char1 input
:param input: (char1) char1 input
:return: returns a 1 if the values are the same or a 0 if they are not the same
"""
ret = 0
if idata == input:
ret... | 1e42e22e8f4fa78f2f1a4244dc301f62fa7fef7c | 472,710 |
def getabovethresh(inputlist,thresh):
"""creates a binary list, indicating comparison of
inputlist entries to thresh value
1 if above (exclusive), else 0"""
abovethreshlist=[1 if i>thresh else 0
for i in inputlist]
return abovethreshlist | a3b1161960a682d36d827c558b0c0a6d726b49a2 | 559,987 |
import base64
def convert_bytes_to_base64(data: bytes) -> str:
"""Convert bytes data to base64 for serialization."""
return base64.b64encode(data).decode("ascii") | a810937ffaf0c40d318d02b3838accb294a5c226 | 640,512 |
import math
def text_clip_center(text, width):
"""
Center-clip a string `text` to width `width`. That is, print starting from
the center, out.
"""
clip = 0
if len(text) > width:
clip = len(text)-width
clip1 = math.ceil(clip/2)
clip2 = clip-clip1
return text[clip1:][:-clip2] | e6cbad4d9ad1fc2ca5c7d1bbe5e022a14598f5f5 | 440,521 |
def merge_sort(arr):
"""
time complexity: O(n*logn)
space complexity: O(n)
:prarm arr: list
:return: list
"""
if not isinstance(arr, list):
raise TypeError
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid... | 7297e20fa3a01b85fa7f5cebef1921e9c17c7be9 | 70,172 |
import re
def newlines_to_spaces(text):
"""
Strips newlines and any spacing surrounding the newlines and replaces them with a single space
:param text: The text to parse
:type text: str
"""
newline_pattern = re.compile('\s*\n\s*')
return newline_pattern.sub(' ', text) | ae331ded725e59b1cf1dea2025f17131636225fd | 442,726 |
def getText(node):
""" Get textual content of an xml node.
"""
text = []
for n in node.childNodes:
if n.nodeType == n.TEXT_NODE: text.append(n.data)
return ''.join(text) | e8dda800260ba7141bd59d0c77eb3c73ac2bac0a | 113,005 |
def iso_week(date):
"""Return the week of ISO date 'date'."""
return date[1] | dd1183d60f0ffa04784d882effcd969034b9a54a | 365,873 |
def get_vgci_warnings(tc):
"""
extract warnings from the parsed test case stderr
"""
warnings = []
if tc['stderr']:
for line in tc['stderr'].split('\n'):
# For each line
if "WARNING" in line and "vgci" in line:
# If it is a CI warning, keep it
... | d167c66374754e6099cb20d05e49c5ad609b472b | 651,936 |
def _parse_duration(duration: str) -> float:
"""
Convert string value of time (duration: "25:36:59") to a float value of seconds (92219.0)
"""
try:
# {(1, "s"), (60, "m"), (3600, "h")}
mapped_increments = zip([1, 60, 3600], reversed(duration.split(":")))
seconds = sum(multiplier ... | ef2a4a14666695a226a34622e1f049dd841c2452 | 177,951 |
import requests
def s3_obj_exists(url):
"""Helper function to determine whether an s3 object exists
Args:
url (str): https URL for a public object stored in s3
"""
resp = requests.head(url)
return resp.status_code != 404 | a77431992f8d19c13055a33cd86e96afb8cdfdf8 | 348,692 |
def create_norm_peptide_column_if_needed(row_meta_df, gcp_normalization_peptide_field, gcp_normalization_peptide_id):
"""If it doesn't already exist, create a new column indicating the norm
peptide for each probe.
Modifies row_meta_df in-place.
Args:
row_meta_df (pandas df):
gcp_normal... | 2b499bb23a186a6c7bff46998a2377fa38b8f114 | 644,617 |
def job_id(config: dict) -> str:
"""The ID for the current job"""
return config["job_id"] | b03a0b77f2794e70665d8599a572e97b5aab8b31 | 554,391 |
def closest(v, L):
"""
Returns the element in L (a sorted numpy array) which is closest to v
>>> R = np.array([9,3,6])
>>> R.sort()
>>> R
array([3, 6, 9])
>>> [closest(i, R) for i in range(1,12)]
[3, 3, 3, 3, 6, 6, 6, 9, 9, 9, 9]
"""
i = L.searchsorted(v)
return L[-1 if i ==... | 8930e49e36bb191c17e0dfe4e3cdd98da67f69d0 | 55,184 |
from typing import Tuple
def process_arguments(arguments: str) -> Tuple[str, str, int]:
"""
Process the arguments given to !weather, dividing them into state, location and future
Uses default of QLD, Brisbane and 0 if not given
"""
args = arguments.split(" ") if arguments else []
if args and a... | 8bd887bab7d3bbc002973e4a327610933130021a | 31,411 |
def knight_tour(n, path, u, limit):
"""
Conduct a knight's tour using DFS.
Args:
n: current depth of the search tree.
path: a list of vertices visited up to this point.
u: the vertex we wish to explore.
limit: the number of nodes in the path.
Returns:
done (bool... | f11a2da4e740183a85dbd2f281c65dda77237dad | 16,021 |
def bitarray_to_int(b):
"""Convert a bitarray to an integer."""
if not len(b):
return 0
return int(b.to01(), 2) | 90c351e81b088a079d346313efd56f9c08344a3f | 531,452 |
def binary_to_hex(hex_format, binary_string) -> str:
"""
Convert a binary string to a hexadecimal string.
:param hex_format: hexadecimal format - "{0:0>X}" or "{0:0>2X}" etc.
:param binary_string: binary string - for example, '1110'.
:return: hexadecimal string - for example '0E', 'F'.
"""
... | e25507e09db96fbd8b60ba6e427d7f2799adfd4e | 212,088 |
def spritecollideany(sprite, group, collided=None):
"""finds any sprites in a group that collide with the given sprite
pygame.sprite.spritecollideany(sprite, group): return sprite
Given a sprite and a group of sprites, this will return return any single
sprite that collides with with the given sprite.... | 4f80e045cec8e8641bc74de15f82adc65394da1a | 39,113 |
from typing import Dict
def is_queue_not_empty(queue: Dict) -> bool:
"""Check if a data queue is not empty.
Agrs:
queue: Data queue
Returns:
False if queue is empty, else True.
"""
return queue['messages'] > 0 or queue['messages_unacknowledged'] > 0 | 85b0c68645c4d301265672293e75c76d2e46e21e | 413,376 |
def mask_sentinel_clouds(img):
"""
Function that masks out clouds from the input Sentinel-2 image. The
input image has to have the QA60 band in its bands list.
Parameters
----------
img : ee.image.Image
Single Sentinel-2 Earth Engine Image that needs cloud-masking
Returns
-----... | 83b5c231cf518e41eab6979f1354ed6e1372ca5e | 524,736 |
def solution(A):
"""
Codility -
https://app.codility.com/demo/results/trainingKC23TS-77G/
100%
Idea is to maintain the start and end point marker for each disc/circle
Sort by start position of disc/circle
On each start position count the active circle/disc
On each end position reduc... | ec2eae5c4af4b7e0c71b2487371f7b6b2aaa8f70 | 175,195 |
import re
import io
def get_version(filename):
"""
Trivial parser to extract a __version__ variable from a source file.
:param str filename: the file to extract __version__ from
:returns str: the version string for the package
"""
version_re = re.compile(r'(\d\.\d(\.\d+)?)')
with io.open(... | 6abdd829a2067f148cb3f4e500d7881e8e0b3e60 | 107,900 |
def jsonify(records):
""" Parse asyncpg record response into JSON format
"""
return [{key: value for key, value in
zip(r.keys(), r.values())} for r in records] | ae25304429f89d48f9261040dc0894833a3cd368 | 521,649 |
import csv
def parse_throughput_stats(fp):
"""
Parse throughput statistics.
:param fp: the file path that stores the statistics
:returns the number of pairs of initiator and responder clients a server can handle per second
"""
counter = 0
with open(fp) as csvfile:
csvreader = csv.D... | e9b2e3e6e29eccb315fbb7882be93c9b1c91c77e | 223,957 |
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""
Maximizes metric function over available gold spans. Because there can be
multiple legal answers, we do not penalize the model by only testing on
the first gold span.
Args:
metric_fn: Function to maximize over.
... | e5c46e08efdaedefdaaa5117a866a275554759d0 | 530,114 |
def decay_across_unit_interval(v, p, d):
""" Generalized decay function over unit interval.
Returns: initial value rescaled based on decay factor
Parameters:
v: Starting value
p: Percent completed must be in a unit interval [0,1]
... | 42138e22103d6ec5733a70209d49611a167aae65 | 241,884 |
def unescape_json(s):
"""Unescape a string that was previously encoded into JSON.
This unescapes forward slashes (optional in JSON standard),
backslashes and double quotes"""
return s.replace("\\/", '/').replace('\\"', '"').decode('string_escape') | cb2093aad453822ed8660bd0219a59472e765f56 | 179,814 |
from typing import List
import random
def sample_floats(low: float, high: float, k: int = 1) -> List[float]:
"""Return a k-length list of unique random floats in the range of low <= x <= high."""
seen = set()
for _ in range(k):
x = random.uniform(low, high)
while x in seen:
x =... | 9dcbef61809e1cfc3cc3748338137e4d48a95059 | 35,539 |
from datetime import datetime
def resample(dset, freq, weights=None, time_coord_name=None, method=None):
""" Resample given dataset and computes the mean for specified sampling time frequecy
Parameters
----------
dset : xarray.Dataset
The data on which to operate
freq : str
Time ... | 8e817c6876837e77ffd6741e48532020a99f256c | 504,384 |
from typing import Iterable
from typing import Union
def big_endian_digits_to_int(digits: Iterable[int], *,
base: Union[int, Iterable[int]]) -> int:
"""Returns the big-endian integer specified by the given digits and base.
Examples:
>>> cirq.big_endian_digits_to_int([0, ... | ba54567afa4eecd8756ad0f089bbe6045a2861e5 | 436,693 |
def cast_int(value):
"""
Cast value to 32bit integer
Usage:
cast_int(1 << 31) == -1
(where as: 1 << 31 == 2147483648)
"""
value = value & 0xFFFFFFFF
if value & 0x80000000:
value = ~value + 1 & 0xFFFFFFFF
return -value
else:
return value | 1f843d4ac82b16f5d735f4e87fb79748b979cf43 | 206,875 |
def load_queries(path):
"""Loads queries into a dict of key: query id, value: query text."""
queries = {}
with open(path) as f:
for i, line in enumerate(f):
query_id, query = line.rstrip().split('\t')
queries[query_id] = query
if i % 100000 == 0:
print('Loading queries {}'.format(i))... | c8b677965181970ee5dff90d3b611a9641a0b68d | 562,387 |
def clean_uri(uri):
"""
This method removes the url part of the URI in order to obtain just the property or class
:param uri: An uri to be cleaned
:return: The name of the property or the class
"""
if uri.find('#') != -1:
special_char = '#'
else:
special_char = '/'
ind... | 737540b4cf9381e2b315699a90dd31a7afebce08 | 512,315 |
def _tensor_max(*args):
"""Elementwise maximum of a sequence of tensors"""
maximum, *rest = args
for arg in rest:
maximum = maximum.max(arg)
return maximum | 3046b6ae14368a7275f74ade42a1b179ae38b95e | 37,710 |
def version_components(version):
"""Split version string into major1.major2.minor components."""
components = version.split(".")
num = len(components)
if num < 1:
raise ValueError("version should have at least one component.")
major1 = components[0]
if num >= 2:
major2 = compo... | fdd4d577d5140db2fa8068db6e4f1f8b1479c4c1 | 371,944 |
def most_common(lst):
"""Returns the most common element in a list
Args:
lst (list): list with any datatype
Returns:
an element of lst (any): the most common element
if commonests tie, randomly selected
Raises:
ValueError: if lst is None or empty... | 59723d3a20d04e1ec7a7f2db0d6a818d0a922135 | 394,243 |
def get_col_widths(table, tab_width=2, tab_level=0, col_padding=0):
"""Recursively get the list of max number of characters of each column in table.
Parameters:
table (dict): The table to check (has "fields" and "records" properties)
tab_width (int): The amount of space to leave for tabs. By default, 2.
... | 9d68a1e314a5956be2595caee47b6a65db19b69b | 517,010 |
from datetime import datetime
def subtract_dates(date1, date2):
"""
Takes two dates %Y-%m-%d format. Returns date1 - date2, measured in days.
"""
date_format = "%Y-%m-%d"
a = datetime.strptime(date1, date_format)
b = datetime.strptime(date2, date_format)
delta = a - b
#print(date1,"-",date2,"=",delta.... | 2000019c76c42ba881ba9b25b89b6dea295d9e19 | 291,831 |
def _project(doc, projection):
"""Return new doc with items filtered according to projection."""
def _include_key(key, projection):
for k, v in projection.items():
if key == k:
if v == 0:
return False
elif v == 1:
return... | 0f2cd190e73b39ceeec0f850054baab1dd357587 | 2,708 |
import heapq
def nlargest_indices(n, iterable):
"""Given an iterable, computes the indices of the n largest items.
Parameters
----------
n : int
How many indices to retrieve.
iterable : iterable
The iterable from which to compute the n largest indices.
Returns
-------
... | e6609150f2b9f95721288ee0d410978aaa898951 | 451,936 |
def _get_projection(el):
"""
Get coordinate reference system from non-auxiliary elements.
Return value is a tuple of a precedence integer and the projection,
to allow non-auxiliary components to take precedence.
"""
return (int(el._auxiliary_component), el.crs) if hasattr(el, 'crs') else None | 94da883c3aba5647d0619670bf1bbdc14fa36299 | 154,809 |
def find_longest(arr):
""" Find the number with the most digits.
If two numbers in the argument array have the same number of digits,
return the first one in the array.
"""
return max(arr, key=lambda x: len(str(x))) | 340bfd92ab2e88bbec071ef0e9ea584cc4c18cf0 | 595,250 |
def unify_table(table):
"""Given a list of rows (i.e. a table), this function returns a new table
in which all rows have an equal amount of columns. If all full column is
empty (i.e. all rows have that field empty), the column is removed.
"""
max_fields = max(map(lambda row: len(row), table))
... | 80de4acb372513aef2a740d18a9530e4da2cbe41 | 448,855 |
def test_input_yes_no(value) -> str:
"""This function test input argument and returns boolean result as string."""
return 'Yes' if value else 'No' | 9ed8e6563cae9947986509469d71709e98dd50d4 | 282,915 |
def process_list(string):
""" Create list from string with items separated by commas
Helper for get_sorted_emails.
"""
# Remove all spaces
no_spaces = "".join(string.split())
# Split at commas
split_lst = no_spaces.split(",")
# Remove empty strings and return
return list(filte... | 4191c63cfb3ef87a08102235152c2d2a56696749 | 598,694 |
def select_dict_keys(dictionary, keys):
"""Filters a dict by only including certain keys.
:param dictionary: dictionary
:param keys: keys to be selected
:return: dictionary with selected keys
"""
key_set = set(keys) & set(dictionary.keys())
return {key: dictionary[key] for key in key_set} | 4b3d07e340d599298453ef1c3a507c0b3f782d04 | 338,453 |
import re
def check_google_calendar_id(google_cal_id):
"""utility to verify a google calendar id passed as a parameter.
Args:
google_cal_id (str): string of the google calendar id
Returns:
bool: True if the string in parameter is a verified google calendar id, else returns False... | feffa4626b9031d199155ba43a5c48c1e01eab1b | 211,529 |
def der_order(order: int) -> str:
"""Return correct suffix for order.
>>> der_order(1)
... "1-st"
>>> der_order(4)
... "4-th"
"""
_suffix = ["st", "nd", "rd"]
if order - 1 > 3:
return f"{order}-th"
else:
return f"{order}-{_suffix[order - 1]}" | e073135851a8848c41fbdff75215cc0dfe3df7cd | 648,524 |
def flatten(iterables, start_with=None):
"""Takes a list of lists ``iterables`` and returns a list containing elements of every list.
If ``start_with`` is not ``None``, the result will start with ``start_with`` items, exactly as
if ``start_with`` would be the first item of lists.
"""
result = []
... | 10ecc77cf5642a8ac236be1ab2e1e0a37351b523 | 171,255 |
def read_reco2vol(volumes_file):
"""Read volume scales for recordings.
The format of volumes_file is <reco-id> <volume-scale>
Returns a dictionary { reco-id : volume-scale }
"""
volumes = {}
with open(volumes_file) as volume_reader:
for line in volume_reader.readlines():
if l... | 8914f0f8351f3340fa3382c7dad00c61ce0aa154 | 652,623 |
import re
def re_map(f, regexp, string):
"""Find regexp in string and map f on the matches.
Replace every occurence of regexp in string by the application of f
to the match.
>>> re_map(lambda x: '<%s>' % x.capitalize(), 'a|e|i|o|u', 'This was a triumph')
'Th<I>s w<A>s <A> tr<I><U>mph'
"""
match = re.s... | 5f13ea82834910acb96d9dbf968419f2df4232e4 | 560,205 |
def average_tweets_per_user(tweets, users_with_freq):
"""
Return the average number of tweets per user from a list of tweets.
:param tweets: the list of tweets.
:param users_with_freq: a Counter of usernames with the number of tweets in 'tweets' from each user.
:return: float. average number ... | f2fc5b725003b39a5e429a4945007fbb16640b54 | 679,261 |
import math
def distance_formula(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Distance between two points is defined as the square root of (x2 - x1)^2 + (y2 - y1) ^ 2
:raises TypeError: Any of the values are non-numeric or None.
"""
return math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2... | 5c1a4706365a2347bc23d7efcc74caa003405c0e | 28,965 |
def binary_search_recursive(list, target):
"""
Returns the index position of the target if found, else returns None
complexity: O(log n)
"""
if len(list) <= 0:
return None
midpoint = len(list)//2
if list[midpoint] == target:
return True
if list[midpoint] < target:
... | 76cc158dc0a99a7b95b5ebfe60a5ca3731475c30 | 554,873 |
def remove_none_value(data):
"""remove item from dict if value is None.
return new dict.
"""
return dict((k, v) for k, v in data.iteritems() if v is not None) | 934690c406585dd71ce2785c169133160d319801 | 440,904 |
import ast
def parseTypeFromString(value):
"""
Parse a string representation of a variable into a true, typed, python variable
"""
return ast.literal_eval(value) | 2a7664af015a60a9070e3090772c73af4ef76fb5 | 26,409 |
def build_interlock_status(device):
"""
Builds an integer representation of the interlock bit-field.
:param device: the lewis device
:return: int representation of the bit field
"""
interlocks = device.get_interlocks()
bit = 1
result = 0
for ilk in interlocks.values():
resul... | 792994d5856978ab2d82a18c7eeeaebb0c67a5b9 | 182,854 |
def filter_data(data, filter_keys):
"""Applies a key filter to a dictionary in order to return a subset of
the key-values. The insertion order of the filtered key-value pairs is
determined by the filter key sequence.
Parameters:
data (dict): key-value pairs to be filtered.
filter_keys (... | 0c6c7985d09d5c6f7414335a92346f40186e6200 | 136,750 |
def get_change(budget: float, exchanging_value: float) -> float:
"""Calculate currency left after an exchange
Args:
budget (float): amount of money you own.
exchanging_value (float): amount of your money you want to exchange now.
Returns:
float: amount left of your starting currenc... | ccfec74ecb078459bfe440160d806d50ee702ac0 | 468,970 |
def format_temp_unit(value: float, unit: str) -> str:
"""
returns formatted degrees value
Format celsius or fahrenheit degrees to nice string output.
:param value: celsius or fahrenheit degrees value
:param unit: 'C' for celsius or 'F' for fahrenheit degrees
:type value: float
... | 67fbcac2e111fb4546734c63269eaa9c6ff752aa | 176,647 |
def remove_prefix(text, prefix):
"""
Remove prefix of a string.
Ref: https://stackoverflow.com/questions/16891340/remove-a-prefix-from-a-string
"""
if text.startswith(prefix):
return text[len(prefix):]
return text | 716cff2f704c416055cf9d5d279b7d3ac2c4d4f2 | 362,742 |
def VShadowPathSpecGetStoreIndex(path_spec):
"""Retrieves the store index from the path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
int: store index or None if not available.
"""
store_index = getattr(path_spec, 'store_index', None)
if store_index is None:
location... | 28bccc75a3fb2ec13733b03aad28b68765d1d453 | 371,068 |
def _slope_lstsq(x, y):
""" Utility function which returns the slope of the linear
regression between x and y.
Parameters
----------
x : ndarray, shape (n_times,)
y : ndarray, shape (n_times,)
Returns
-------
float
"""
n_times = x.shape[0]
sx2 = 0
sx = 0
sy = 0... | d523007e56ca16223b4aa2ab80aa6e6daa42839a | 329,847 |
def is_error(data):
"""check for error indication in data"""
return data[0] == 255 | 92e13d2803567467576c2c134cb14a4401c949f0 | 180,365 |
def extract_sparse(sparse_mat):
"""
Extract a coordinate levele representation as a tuple for a PyTorch
sparse tensor.
Args:
- sparse_mat (PyTorch sparse tensor) - The sparse matrix from which to
extract coordinates and values.
Returns:
- A tuple of the indices (coordin... | aedfe8591d6856465094468a682e65ed6ee8f6a7 | 514,655 |
from typing import List
def chunk_sizes(total_size: int, num_chunks: int) -> List[int]:
"""Return list containing the sizes of chunks.
Args:
total_size: Total computation work.
num_chunks: Maximum number of chunks the work will be split into.
Returns:
List of chunks with split wo... | 9f7f50abf022c25010d44e7e154e574831fcf965 | 293,506 |
def pt_segment_dist(A, B, P):
"""
SUMMARY
computes the distance of point P from segment AB
PARAMETERS
A: endpoint of segment AB
B: other endpoint of segment AB
P: point at some distance from AB
RETURNS
float
"""
x1, y1 = A
x2, y2 = B
x3, y3 = P
... | dd072a558a8a48d7e8052d1ec3f8a73abba54c0e | 322,413 |
def merge_logfiles(log1, log2):
"""Merge two log files.
If log1 overlaps with log2, the overlapping entries in log1
are discarded.
"""
first_in_2 = log2['time'][0]
keep_from_1 = log1['time'] < first_in_2
for key in log1.keys():
log1[key] = log1[key][keep_from_1]
log1.timeseries_... | e169edd3cc7617a20bb96b9b41deea8748f3c56e | 610,784 |
def dict_list_to_bins(dict_list: list, bin_key: str, comparison_key=None) -> dict:
"""
A dictionary binning function which reduces a set of data
to a set of bins.
:param dict_list: a list of dictionaries
:param bin_key: a key for binning
:param comparison_key: a key for counting
:return: a ... | 2d56aa92d31e8a3921a805e5654764d1f267c291 | 306,018 |
import re
def _compose_comment(remote: str, sha: str, git_log: str) -> str:
"""Composes a comment describing the original (triggering) commit.
Arguments:
remote {str} -- a link to the remote git repo
sha {str} -- the hash of the commit
git_log {str} -- the git log for the commit
... | d6aac13cbf23db2b5ea94e0b6cfe9600f1900283 | 643,319 |
def get_cube_data_info(cube):
"""Return short_name, and mip from the cube."""
short_name = cube.var_name
mip = cube.attributes['mip']
return short_name, mip | fa1be8f072d3ce320225648c71c02e8fcb361fa6 | 502,613 |
def format_perm(model, action):
"""
Format a permission string "app.verb_model" for the model and the
requested action (add, change, delete).
"""
return '{meta.app_label}.{action}_{meta.model_name}'.format(
meta=model._meta, action=action) | 12f532e28f685c2a38a638de63928f07039d44c8 | 668 |
import torch
def emb_2d_dropout(training, mask_perc, tensor):
"""2D dropout of tensor where entire row gets zero-ed out with prob
mask_perc.
Args:
training: if the model is in train mode or not
mask_perc: percent to dropout
tensor: tensor to dropout
Returns: tensor after 2D d... | b0742f385054b65be60b1dcbece7b31ff385bcca | 425,050 |
def determine_type(api_version: str, kind: str):
"""Return name of Swagger model for this `api_version` and `kind`.
Example: ('Extensions/v1beta1', 'Deployment') -> 'ExtensionsV1beta1Deployment'
This is useful to convert the K8s Json response into a Swagger generated
Python object. The `api_version` a... | a92dcd595b960e197248462a0021b13b3aa521da | 470,736 |
import asyncio
from typing import Optional
def get_loop(running: bool = False, enforce_running: bool = False) -> asyncio.AbstractEventLoop:
"""Gracefully fetch a loop.
The function tries to get an event loop via :func:`asyncio.get_event_loop`.
On fail, returns a new loop using :func:`asyncio.new_event_lo... | bb387622ab1e0e50bc1c71abc2c3d2132ae085e3 | 533,591 |
def split(u, axis=0):
"""Split an array into a list of arrays on the specified axis.
Split an array into a list of arrays on the specified axis. The
length of the list is the shape of the array on the specified axis,
and the corresponding axis is removed from each entry in the list.
This function d... | 8e793853d39909838003cefd3e830c5c5088dd37 | 474,486 |
def h_bubble(heigth_layer, epsi_vapor):
"""
Calculates the heigth of bubble layer.
Parameters
----------
epsi_vapor : float
The vapor content of bubble layer, [dimensionless]
heigth_layer : float
The heigth ligth layer of the liquid, [m]
Returns
-------
h_bubble : fl... | f713bd71553fce50461359fd5946113e26927937 | 621,593 |
def is_basic_scheme(all_tags):
"""
Check if a basic tagging scheme is used. Return True if so.
Args:
all_tags: a list of NER tags
Returns:
True if the tagging scheme does not use B-, I-, etc, otherwise False
"""
for tag in all_tags:
if len(tag) > 2 and tag[:2] in ('B-',... | 6333fd74029bd3ab6d689ac9792cfffd841eb3fe | 550,834 |
def transform_six_with_metaclass(node):
"""Check if the given class node is defined with *six.with_metaclass*
If so, inject its argument as the metaclass of the underlying class.
"""
call = node.bases[0]
node._metaclass = call.args[0]
return node | 611fdd207334d2bebfacfceb5a467b483336f497 | 204,158 |
from functools import reduce
def escape(raw, *chars):
"""
Prefix special characters with backslashes, suitable for encoding in a larger string
delimiting those characters.
Args:
raw (str):
Unsafe input string.
chars (str list):
Control characters to be escaped.... | d1db2b9a1bc6fc9941f8d46bcd53d6662dce7b14 | 433,943 |
def buzz(number):
""" returns whether a number is divisible by 5"""
return not number % 5 | d7b076fc998ecd70e59d87a9f3bec8f48c92ede9 | 296,430 |
def unpad_list(listA, val=-1):
"""Unpad list of lists with which has values equal to 'val'.
Parameters
----------
listA : list
List of lists of equal sizes.
val : number, optional
Value to unpad the lists.
Returns
-------
list
A list of lists without the padding... | 8354f3c78168aafa86a0a07997895d964d81cb31 | 675,015 |
def totaled_total_commits(cc, sql_time_specification): # pragma: no cover
"""Counts all the git commits in a given timeframe
Args:
cc(cursor)
sql_time_specification(str): a sql command to limit the dates of the
returned results
Return:
result(int): a count of all th... | 7270b23bb5d78684989a9a9c14afb46aeaeae291 | 417,277 |
def to_camel_case(field: str, prefix: str) -> str:
"""Convert a STAR-fusion output column name
- Remove the prefix (either "Left" or "Right"
- Convert the first character to lower case
"""
# Remove side from field name
new_field = field[len(prefix) :] # noqa: E203
# Convert to camelCase
... | 7e470110ccf180192931bd340b289278df94e706 | 384,820 |
def ipasser(inbox, i=0):
"""
Passes the "i"-th input from inbox. By default passes the first input.
Arguments:
- i(``int``) [default: ``0``]
"""
return inbox[i] | 254ed050745bd0e57f209757a45ce049c5fbee21 | 229,226 |
def get_post_fields(request):
"""parse through a request, and return fields from post in a dictionary"""
fields = dict()
for field, value in request.form.items():
fields[field] = value
return fields | 2a8e67ad05449c6a3d57fd434cce9859da3f0e94 | 209,447 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.