content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pkg_resources
def find_plugins(plug_type):
"""Finds all plugins matching specific entrypoint type.
Arguments:
plug_type (str): plugin entrypoint string to retrieve
Returns:
dict mapping plugin names to plugin entrypoints
"""
return {
entry_point.name: entry_point.l... | f6d6e4debdaec478b14c87582b7e69a9a9bf929b | 26,754 |
from typing import List
def _read_resultset_columns(cursor) -> List[str]:
""" Read names of all columns returned by a cursor
:param cursor: Cursor to read column names from
"""
if cursor.description is None:
return []
else:
return [x[0] for x in cursor.description] | cacefb20b12f327647d1f77bb12216c80388fcd6 | 26,755 |
def max_dict(d):
"""Return dictionary key with the maximum value"""
if d:
return max(d, key=lambda key: d[key])
else:
return None | 446c185a2e986c8a58672d0571f0f100340be7e4 | 26,758 |
import typing
def hex_to_color(color: str) -> typing.Tuple[int, int, int]:
"""
Helper method for transforming a hex string encoding a color into a tuple of color entries
"""
return int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16) | 40f0c580822effde33a96027863acafb781e44f9 | 26,760 |
import six
def truncate_rows(rows, length=30, length_id=10):
"""
Truncate every string value in a dictionary up to a certain length.
:param rows: iterable of dictionaries
:param length: int
:param length_id: length for dict keys that end with "Id"
:return:
"""
def trimto(s, l):
... | db0d02e39f4152ea8dc15a68ab968ae8500bc320 | 26,761 |
def find_adjacent(left, line):
"""
find the indices of the next set of adjacent 2048 numbers in the list
Args:
left: start index of the "left" value
line: the list of 2048 numbers
Returns:
left, right: indices of the next adjacent numbers in the list
if there are ... | 0bca5a7683d5a7d7ab7c25ae416e6448044823f8 | 26,762 |
def max_power_rule(mod, g, tmp):
"""
**Constraint Name**: GenVar_Max_Power_Constraint
**Enforced Over**: GEN_VAR_OPR_TMPS
Power provision plus upward services cannot exceed available power, which
is equal to the available capacity multiplied by the capacity factor.
"""
return (
mod.... | 03cfd061867ce68dcab7068c38eaece69b9906ca | 26,765 |
import itertools
def powerset(iterable):
"""Yield all subsets of given finite iterable.
Based on code from itertools docs.
Arguments:
iterable -- finite iterable
We yield all subsets of the set of all items yielded by iterable.
>>> sorted(list(powerset([1,2,3])))
[(), (1,), (1, 2), (1... | 8bcc95585393e2790a8081337aeb6e9d54173b3d | 26,767 |
import re
def clean_str(s):
""" Clean a string so that it can be used as a Python variable name.
Parameters
----------
s : str
string to clean
Returns
-------
str
string that can be used as a Python variable name
"""
# http://stackoverflow.com/a/3305731
# http... | 26801f0258b61eed5cb2ea7b2da31ccfffad074c | 26,768 |
import fileinput
def get_all_ints(fn):
"""Returns a list of integers from 'fn'.
Arguments:
- fn - a string representing input file name. If None or equal to '-' - read
from STDIN; fn is treated as a single input integer if it is a digit.
"""
if fn is None:
fn = '-'
if ... | fc0fa992258c87220a674275429ac9a04f999a05 | 26,774 |
def check_answers(answers, answer_key):
"""
Check students’ answers against answer key.
Inputs: answers, a tuple of tuples of strs.
answer_key, a tuple of strs.
Returns: tuple of tuples of ints.
"""
def check_section(current, start, end):
"""
Mark answers in a secti... | 3138247b05f6d33d162ac5dc00bb2e1590ff5fe1 | 26,777 |
from typing import Optional
from typing import List
def parse_match_phase_argument(match_phase: Optional[List[str]] = None) -> List[str]:
"""
Parse match phase argument.
:param match_phase: An optional list of match phase types to use in the experiments.
Currently supported types are 'weak_and' a... | 4d70a4936ebf09e0eb8276bf0477895b726941c2 | 26,780 |
def getMaxMinFreq(msg):
"""
Get the max and min frequencies from a message.
"""
return (msg["mPar"]["fStop"], msg["mPar"]["fStart"]) | 3c28882dce3f2ddd420700997c6f65ed906ec463 | 26,781 |
def l(lam, f, w):
"""Compute l"""
return lam * f * w | 1dca0c85aac1832033fd46b2cf6c9e9045a3c210 | 26,788 |
def isRunning( proc ):
"""is the process running?
Parameters:
* proc (psutil.Popen): Process to be checked
Returns:
* bool: True if the process is running.
"""
if proc == None:
return
proc.poll()
return proc.is_running() | 207afdbf6c6ba5f7a32dcf58f0d0a19cb5ad6085 | 26,789 |
def clean_dict(source, keys=[], values=[]):
"""Removes given keys and values from dictionary.
:param dict source:
:param iterable keys:
:param iterable values:
:return dict:
"""
dict_data = {}
for key, value in source.items():
if (key not in keys) and (value not in values):
... | f521ecd878ec0f1a5706d19fec13841d2381745d | 26,795 |
def compute_target(difficulty_target_bits):
"""
Calculate a target hash given a difficulty.
"""
return 2 ** (256 - difficulty_target_bits) | 65f4a5c9e01acf5f829edc949154171b6de96c19 | 26,796 |
def is_available(event):
"""
Checks if the event has the transparency attribute.
:param event: is the event to check.
:return: True if it is transparent and False if not
"""
if 'transparency' in event:
available = True
else:
available = False
return available | 40fe7bb61d2f02a0a030f578cfe44ece79e16d52 | 26,797 |
def is_raisable(obj) -> bool:
"""
Test if object is valid in a "raise obj" statement.
"""
return isinstance(obj, Exception) or (
isinstance(obj, type) and issubclass(obj, Exception)
) | 64c4233b6b8fa0b1f9b8542dd1f06f658e10bf5d | 26,798 |
import re
def check_if_url(string: str) -> bool:
"""Checks if a string passed in is an URL.
Args:
string (str): string to check
Returns:
bool: True if it is, False otherwise
"""
regex = re.compile(
r"^(http://www\.|https://www\.|http://|https://)?[a-z0-9]+([\-.][a-z0-9]+)... | badf75a2280fa0e88a162bd853f5f33f231d0137 | 26,799 |
def color_list(s):
"""Convert a list of RGB components to a list of triples.
Example: the string '255,127,0:127,127,127:0,0,255' is converted
to [(255,127,0), (127,127,127), (0,0,255)]."""
return (map(int,rgb.split(',')) for rgb in s.split(':')) | e3c48a2e9c0a2b86c39670317a18916f1cb8ddff | 26,805 |
import json
def read_corpus(file_path):
"""
读取给定的语料库,并把问题列表和答案列表分别写入到 qlist, alist 里面。 在此过程中,不用对字符换做任何的处理(这部分需要在 Part 2.3里处理)
qlist = ["问题1", “问题2”, “问题3” ....]
alist = ["答案1", "答案2", "答案3" ....]
务必要让每一个问题和答案对应起来(下标位置一致)
:param file_path: str, 问答对文件路径
:return:
qlist: list 问题列表
... | b760e92c6dd71336c34d166b668f4cd105357bd4 | 26,809 |
def set_server(client, server_url):
"""Select a Windchill server.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
None
"""
data = {"server_url": server_url}
return client._creoson_post("windchill", "set_server", data) | 8ba2ad33ad68e41da74804a1a801328fec917f2c | 26,813 |
def dictify(storage_obj):
"""Create a dict object from storage_obj"""
return dict(storage_obj.items()) | 78d09322f27d5e9c4c3d87e63b3cdc46937e7f92 | 26,819 |
from typing import Union
def keycap_digit(c: Union[int, str]) -> str:
"""Returns a keycap digit emoji given a character."""
return (str(c).encode("utf-8") + b"\xe2\x83\xa3").decode("utf-8") | 8db72c79acc173f8e325faca96274b1c08061eb7 | 26,821 |
def worksheet_as_list_of_lists(ws):
"""Convert a Worksheet object to a 2D list."""
table = []
for row in ws.rows:
table.append([c.value for c in row])
return table | a6988996cdd6c64521b20ba3fe23339978dc941d | 26,822 |
def compress(traj, copy=True, **kwds):
"""Wrapper for :meth:`Trajectory.compress`.
Parameters
----------
copy : bool
Return compressed copy or in-place modified object.
**kwds : keywords
keywords to :meth:`Trajectory.compress`
Examples
--------
>>> trc = compress(tr, co... | 42ebefdddeaecd67f61dd884dab31a3ec7f864c9 | 26,823 |
import socket
def binary_ip(host):
"""binary_ip(host) -> str
Resolve host and return IP as four byte string.
Example:
>>> binary_ip("127.0.0.1")
'\\x7f\\x00\\x00\\x01'
"""
return socket.inet_aton(socket.gethostbyname(host)) | d32d8e243e684bbc87ea1e68f91e9a030a5c78c8 | 26,825 |
def _get_integer_intervals(xmin, xmax):
"""
For a given interval [xmin, xmax], returns the minimum interval [iXmin, iXmax] that contains the original one where iXmin and iXmax are Integer numbers.
Examples: [ 3.45, 5.35] => [ 3, 6]
[-3.45, 5.35] => [-4, 6]
[-3.45, -2.... | 7fa1fd68b960d793c49bc5266d65999c362357ac | 26,826 |
def multByScalar(t , n = 100.0):
"""
Multiply a tuple by a scalar
"""
new = tuple([x * n for x in t])
return new | e91e01b4d45a5b8f200bf65a0eb0466f1e30856a | 26,828 |
def xstr(s):
"""Creates a string object, but for null objects returns
an empty string
Args as data:
s: input object
Returns:
object converted to a string
"""
if s is None:
return ""
else:
return str(s) | b7ea8e906598d259244cc8a7cbb9cb1a142ba3d8 | 26,829 |
import json
def list_to_json_array(value_list, array_name, value_name=None, start=True, stop=True):
"""
Creates a json array from a list. If the optional value_name is passed then the list becomes a json array of dictionary objects.
"""
if start:
start_brace = "{"
else:
start_brace... | 271530c5c318bba12cbb5bfe3e7c908874211923 | 26,830 |
def word(name):
"""\
Function decorator used to tag methods that will be visible in the RPN
builtin namespace.
"""
def decorate_word(function):
function.rpn_name = name.lower()
return function
return decorate_word | 78d76a2a4d260a50aa82f188fde7064d7795ce2c | 26,832 |
import torch
def tensor(data, *args, **kwargs):
"""
In ``treetensor``, you can create a tree tensor with simple data structure.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.tensor(True) # the same as torch.tensor(True)
tensor(True)
... | 438710f3733886646005367c04e97021c361f7bb | 26,834 |
from typing import Mapping
def isdict(obj):
"""Return True if the obj is a mapping of some sort."""
return isinstance(obj, Mapping) | 641fea1920e9ed17fec2a51116cd8bcad816487a | 26,836 |
def calc_multiplicity(mut_series, purity, cr_diff, c0):
"""Calculate multiplicity for the mutation"""
mu_min_adj = (mut_series['mu_minor'] - c0) / cr_diff
mu_maj_adj = (mut_series['mu_major'] - c0) / cr_diff
# returns the multiplicity * CCF for this mutation
return mut_series['VAF'] * (purity * (mu... | 9b9b818ef7c13a653134ea27dc8518c7619d9428 | 26,838 |
def dictElement(element, prefix=None):
"""Returnss a dictionary built from the children of *element*, which must be
a :class:`xml.etree.ElementTree.Element` instance. Keys of the dictionary
are *tag* of children without the *prefix*, or namespace. Values depend on
the content of the child. If a child... | 20fe0475815fb6bbf685a45b54330738426987fd | 26,853 |
def time_like(line):
"""Test if a line looks like a timestamp"""
# line might be like '12:33 - 12:48' or '19:03'
if line.count(':') == 2:
if line.count('-') >= 1:
line_without = line.replace(':', '')
line_without = line_without.replace('-', '')
line_without = line... | 19675238633cafd1e30051ff18bb4d1a783663f6 | 26,856 |
def find1Dpeak(arr):
"""
Finds a 1D peak in a list of comparable types
A 1D peak is an x in L such that it is greater
than or equal to all its neighbors.
ex. [1, 1, 2, 1] in this list, the elements at
index 0 and index 2 are peaks.
Complexity: O(log(n))
where n = len(list)
"""
n = len(arr)
if ... | e8dc8c0ccf453a0246fa0d59e288e0e4591216e6 | 26,859 |
def set_origin(cut_plane, center_x1=0.0, center_x2=0.0):
"""
Establish the origin of a CutPlane object.
Args:
cut_plane (:py:class:`~.tools.cut_plane.CutPlane`):
Plane of data.
center_x1 (float, optional): x1-coordinate of origin.
Defaults to 0.0.
center_x2 (... | f29ecbb82450adeecebdd2652392d37828751348 | 26,863 |
import hashlib
def _hash(mapping: dict) -> str:
"""
Return a hash of an entire dictionary.
Args:
mapping: a dictionary of hash-able keys to hash-able values, i.e.,
__str__ should return a unique representation of each object
Returns:
a hash of the dictionary
"""... | 3e608ad0739480bb4fba1367ed2534d09d9a2ed8 | 26,869 |
def parse_arg_type(arg):
"""
Parses the type of an argument based on its string value.
Only checks ints, floats, and bools, defaults to string.
For instance, "4.0" will convert to a float(4.0)
:param arg: The argument value
:return: The value converted to the proper type.
"""
if type(ar... | c2897f57f2d6df2e7e1c4a5c41cd35d04a386597 | 26,870 |
def is_substring_divisible(num: tuple) -> bool:
"""
Returns True if the pandigital number passes
all the divisibility tests.
>>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9))
False
>>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9))
False
>>> is_substring_divisible((1, 4,... | bf212de2c82890c950e00fc81bdc781efc608ab7 | 26,874 |
def fizz_buzz_custom_2(string_one="Fizz", string_two="Buzz", num_one=3, num_two=5):
"""
>>> not 0
True
>>> not 5 % 5
True
>>> not 6 % 5
False
>>> "Test" * True
'Test'
>>> "Test" * False
''
>>> "" or 1
1
"""
return [
f"{string_one * (not d % num_one)}{... | 6faed46a42fb3383a6c0cb42f7807657d82e0aa6 | 26,879 |
def get_threshold(rows, bands):
"""Approximate threshold from bandwidth and number of rows
:param rows: rows per band
:param bands: number of bands
:return: threshold value
:rtype: float
"""
return (1. / bands) ** (1. / rows) | 3c5a5e417e96797e18b571cb7c09597442cb5f44 | 26,886 |
def keypoint_2d_loss(criterion_keypoints, pred_keypoints_2d, gt_keypoints_2d, has_pose_2d):
"""
Compute 2D reprojection loss if 2D keypoint annotations are available.
The confidence (conf) is binary and indicates whether the keypoints exist or not.
"""
conf = gt_keypoints_2d[:, :, -1].unsqueeze(-1).... | d5ffabe27443d6c9ea251a0d8205e8ca33f724c8 | 26,887 |
def getInt(s, notFoundReturn=-1):
""" attempt to find a positive integer in a string
@param s [string]
@param notFoundReturn = value to be returned if no integer is found
@return int
"""
firstIx = -1
for i, c in enumerate(s):
if c in "0123456789":
firstIx = i
... | 5f5c5b7bac0b160eddedfde1d2008c628dd7a9a6 | 26,893 |
import curses
def create_window(start_x, start_y, width, height):
"""Create window helper method with sane parameter names."""
return curses.newwin(height, width, start_y, start_x) | 8ba73d8cad2e2b730ea2f79795dd6407d6565192 | 26,901 |
def _get_metadata_revision(metadata_repo, mongo_repo, project, revision):
"""Get the metadata revision that corresponds to a given repository, project, revision."""
for metadata_revision in metadata_repo.list_revisions():
reference = metadata_repo.get_reference(metadata_revision, project)
if not... | 35436be9b586319d5e60dd99e0ff4a3ef6bed042 | 26,903 |
def _positive(index: int, size: int) -> int:
"""Convert a negative index to a non-negative integer.
The index is interpreted relative to the position after the last item. If
the index is smaller than ``-size``, IndexError is raised.
"""
assert index < 0 # noqa: S101
index += size
if index... | ee23eb6ffba4d539d333cd649304b5bd879f43df | 26,907 |
def parse_field_configured(obj, config):
"""
Parses an object to a Telegram Type based on the configuration given
:param obj: The object to parse
:param config: The configuration:
- is array?
- is array in array?
- type of the class to be loaded to
:return: the parsed object
... | e03acf6149653b86b8565a492bfd1eeea15464b6 | 26,909 |
def _compute_lineline_intersection(line1_pt1, line1_pt2,
line2_pt1, line2_pt2):
"""Algorithm to compute a line to line intersection, where the
two lines are both defined by two points. Based on this article:
https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection... | ec34a6f2aca4fc918d1e384d3ac1fb7615af4f35 | 26,919 |
def actionable(msg):
"""
Make instructions to actionable items green so they stand out from generic logging.
"""
return f'\033[92m{msg}\033[0m' | 49a350ee1429baeb39d6affbfc5b8dbc8351172f | 26,926 |
def _create_cg_with_member(vnx_gf):
""" Helper function to create a cg with a lun
:param vnx_gf: the vnx general test fixture
:return: created cg
"""
lun_name = vnx_gf.add_lun_name()
lun = vnx_gf.pool.create_lun(lun_name)
cg_name = vnx_gf.add_cg_name()
cg = vnx_gf.vnx.create_cg(cg_name... | 98f5646cb61b2ae8aecf07865461e45edf4dcb64 | 26,929 |
def get_all_headers(message, key):
"""
Given an HTTPMessage, return all headers matching a given key.
"""
return message.get_all(key) | 079d0e7c6ea3d55228ba3c74f4590a1bf4ee325d | 26,930 |
def as_unsigned_int32_array(byte_array):
"""Interprets array of byte values as unsigned 32 bit ints."""
def uint32(a, b, c, d):
return a + (b << 8) + (c << 16) + (d << 24)
return [uint32(*byte_array[i:i + 4]) for i in range(0, len(byte_array), 4)] | dcfb5b5504056d3784c43a4adda876a6bc51f6ae | 26,931 |
def normalise_period(val):
"""Return an integer from 1 to 12.
Parameters
----------
val : str or int
Variant for period. Should at least contain numeric characters.
Returns
-------
int
Number corresponding to financial period.
Examples
--------
>>> normalise_... | bf1d5e334d49d98404193fbbc2047bf41f7b24e5 | 26,937 |
from datetime import datetime
def humanize_timestamp(utc_timestamp, verbose=False):
"""
Convert a utc timestamp into a human readable relative-time.
"""
timedelta = datetime.utcnow() - datetime.utcfromtimestamp(utc_timestamp)
seconds = int(timedelta.total_seconds())
if seconds < 60:
... | 62a402607f8c96775606892771850d07795a160b | 26,939 |
def get_marker(label, chunk):
"""
Returns marker instance from chunk based on the label correspondence
"""
for marker in chunk.markers:
if label == marker.label:
return marker
print("Marker not found! " + label)
return False | e479568f5b6bc96be0bcdfbf7a428820ab953cce | 26,941 |
def check_default_empty(default):
"""Helper function to validate if a default parameter is empty based on type"""
if isinstance(default, str) or isinstance(default, list):
return len(default) == 0
elif isinstance(default, int):
return False
elif isinstance(default, dict):
return ... | 19b94f3b25450d39c5c2b3ddc0af2758e1fc1b5f | 26,943 |
import itertools
def flatten(iterable):
"""Reduce dimensionality of iterable containing iterables
Args:
iterable: A multi-dimensional iterable
Returns:
A one dimensional iterable
"""
return itertools.chain.from_iterable(iterable) | 3869bbc5f2e1377d5c893ce7e35c3b91988916a7 | 26,945 |
def check_lead_zero(to_check):
"""Check if a number has a leading 0.
Args:
to_check (str): The number to be checked.
Returns:
True if a leading 0 is found or the string is empty, False otherwise.
"""
if str(to_check) in (None, ''):
return True
elif str(to_check[0]) != '... | 39302f3f57ac2d9714d3057a744130cd3a5e5aa9 | 26,948 |
def dec2bin(x: int, n: int = 2) -> str:
"""Converts a single decimal integer to it binary representation
and returns as string for length >= n.
"""
return str(int(bin(x)[2:])).zfill(n) | cf5713c5f8855c5f737e4533f780ac75ee3abfa1 | 26,950 |
import math
def convert_bytes_to_string(number: int) -> str:
"""Returns the conversion from bytes to the correct
version (1024 bytes = 1 KB) as a string.
:param number: number to convert to a readable string
:return: the specified number converted to a readable string
"""
num = number
fa... | ca8f5d3417ad989bc12b2bf9cb76a561c735c548 | 26,954 |
def _get_location(location_text):
"""Used to preprocess the input location_text for URL encoding.
Doesn't do much right now. But provides a place to add such steps in future.
"""
return location_text.strip().lower() | 979471af5d40f0a58a2c4e4e7e26af18779ca890 | 26,955 |
import fnmatch
def _match_in_cache(cache_tree, list_of_names):
"""
:type cache_tree: defaultdict
:description cache_tree: a defaultdict initialized with the tree() function. Contains names
of entries in the kairosdb, separated by "." per the graphite convention.
:type li... | e559125f4b62a87956e0d30f5d8c3e4b2c7abef8 | 26,956 |
def range_intersect(a, b, extend=0):
"""
Returns the intersection between two reanges.
>>> range_intersect((30, 45), (55, 65))
>>> range_intersect((48, 65), (45, 55))
[48, 55]
"""
a_min, a_max = a
if a_min > a_max:
a_min, a_max = a_max, a_min
b_min, b_max = b
if b_min > ... | 9184172de3921cfb74bccaeee9b15405045a1327 | 26,958 |
import codecs
def rot13(s: str) -> str:
"""ROT-13 encode a string.
This is not a useful thing to do, but serves as an example of a
transformation that we might apply."""
return codecs.encode(s, "rot_13") | a2413c3bd835dc09b445eb030aa6179e14411e17 | 26,960 |
from typing import Any
def is_numeric_scalar(x: Any) -> bool:
"""
Returns if the given item is numeric
>>> is_numeric_scalar("hello")
False
>>> is_numeric_scalar("234")
True
>>> is_numeric_scalar("1e-5")
True
>>> is_numeric_scalar(2.5)
True
"""
if isinstance(x, (float, ... | 7a0b8bd35be91b4ad6bda49d6a3543c1ca8f5ac7 | 26,963 |
def is_file_image(filename):
"""Return if a file's extension is an image's.
Args:
filename(str): file path.
Returns:
(bool): if the file is image or not.
"""
img_ex = ['jpg', 'png', 'bmp', 'jpeg', 'tiff']
if '.' not in filename:
return False
s = filename.split('.')... | 68df1997c4874cd990ca24739c91555378fc73fd | 26,964 |
def _get_jgroup(grouped_data):
"""Get the JVM object that backs this grouped data, taking into account the different
spark versions."""
d = dir(grouped_data)
if '_jdf' in d:
return grouped_data._jdf
if '_jgd' in d:
return grouped_data._jgd
raise ValueError('Could not find a dataf... | 99b2ac71cd6d0ccf98976df43966ccabf14bcb98 | 26,967 |
def parse_fasta (lines):
"""Returns 2 lists: one is for the descriptions and other one for the sequences"""
descs, seqs, data = [], [], ''
for line in lines:
if line.startswith('>'):
if data: # have collected a sequence, push to seqs
seqs.append(data)
da... | 4dea579720f43f348389e53751c0308f1c493296 | 26,968 |
def is_bool(obj):
"""Returns ``True`` if `obj` is a ``bool``."""
return isinstance(obj, bool) | 6b63b9479c8a388a056c80cc62be74c548ac3504 | 26,974 |
def files_are_identical(pathA, pathB):
"""
Compare two files, ignoring carriage returns,
leading whitespace, and trailing whitespace
"""
f1 = [l.strip() for l in pathA.read_bytes().splitlines()]
f2 = [l.strip() for l in pathB.read_bytes().splitlines()]
return f1 == f2 | 60eeba55aa443577e98c45a46c10c1dc585e6c9f | 26,975 |
import uuid
def _maybe_convert(value):
"""Possibly convert the value to a :py:class:`uuid.UUID` or
:py:class:`datetime.datetime` if possible, otherwise just return the value
:param str value: The value to convert
:rtype: uuid.UUID|datetime.datetime|str
"""
try:
return uuid.UUID(value... | 66e70d33bd9b09c19c762ca66d4f50638a225821 | 26,976 |
import pickle
def load(name: str) -> object:
"""load an object using pickle
Args:
name: the name to load
Returns:
the unpickled object.
"""
with open(name, "rb") as file:
obj = pickle.load(file)
return obj | b8e11b703bea907386e2248c313c390429453a99 | 26,978 |
def decodeAny(string):
"""Try to decode the string from UTF-8 or latin9 encoding."""
if isinstance(string, str):
return string
try:
return string.decode('utf-8')
except UnicodeError:
# decoding latin9 never fails, since any byte is a valid
# character there
return... | 4acd087710118e72d8e142a230b36c57a5b70253 | 26,979 |
import pkg_resources
def python_package_version(package: str) -> str:
"""
Determine the version of an installed Python package
:param package: package name
:return: version number, if could be determined, else ''
"""
try:
return pkg_resources.get_distribution(package).version
exce... | 53f8de290418b1d64355f44efde162bed3a36b45 | 26,982 |
def set_extension(path, ext):
"""Set the extension of file.
Given the path to a file and the desired extension, set the extension of the
file to the given one.
Args:
path: path to a file
ext: desired extension
Return:
path with the correct extension
"""
ext = ext.re... | 5764e085a204aa209f085dbeb8d043c710734e11 | 26,983 |
import re
def get_select_cols_and_rest(query):
"""
Separate the a list of selected columns from
the rest of the query
Returns:
1. a list of the selected columns
2. a string of the rest of the query after the SELECT
"""
from_loc = query.lower().find("from")
raw_select_clau... | 33b397e7894792c0b354c41f219c609dc4df5927 | 26,984 |
def getTableHTML(rows):
""" Binds rows items into HTML table code.
:param list rows: an array of row items
:return: HTML table code with items at rows
:rtype: str
>>> getTableHTML([["Name", "Radek"], ["Street", "Chvalinska"]])
'<table><tr><td>Name</td><td>Radek</td></tr><tr><td>Street</td><td... | 931c8af65052c6a4455feae7f2f3a0f65d33a347 | 26,990 |
def build_complement(c):
"""
The function convert alphabets in input c into certain alphabets.
:param c: str, can be 'A','T','G','C','a','t','g','c'
:return: The string of converted alphabets.
"""
c = c.upper() # The Str Class method changes input c into capital.
total = ''
for i in ran... | 6fece325432ac061d5f7577c85cb59c19918ed83 | 26,992 |
def normalise_reward(reward, prev_lives, curr_lives):
"""
No reward normalisation is required in pong; -1 indicates opponent has
scored, 0 indicates game is still in play and 1 indicates player has
scored.
"""
return reward | ff3c537ac6090692a05c7ee8c6f5bde890ed4d40 | 26,996 |
import torch
def _make_input(t, requires_grad=False, device=torch.device('cpu')):
"""Make zero inputs for AE loss.
Args:
t (torch.Tensor): input
requires_grad (bool): Option to use requires_grad.
device: torch device
Returns:
torch.Tensor: zero input.
"""
inp = tor... | c65c4ba243d786471b810d48af2251fff94c5d5f | 26,997 |
import torch
def bce_loss(pred, target, false_pos_weight=1.0, false_neg_weight=1.0):
"""Custom loss function with options to independently penalise
false positives and false negatives.
"""
norm = torch.tensor(1.0 / float(len(pred)))
tiny = torch.finfo(pred.dtype).tiny
false_neg = torch.sum(tar... | b9ed60d886212bc821fed3f21c4e58e6953b1e02 | 26,999 |
def bernoulli_kl(q_probs, p_probs):
"""
computes the KL divergence per batch between two Bernoulli distributions
parametrized by q_probs and p_probs
Note: EPS is added for numerical stability, see
https://github.com/pytorch/pytorch/issues/15288
Args:
q_probs (torch tensor): mea... | 52253d4cd07b6ceb5081236ea5167b87b754c2fc | 27,001 |
def formatGpuCount(gpuCount):
"""
Convert the GPU Count from the SLurm DB, to an int
The Slurm DB will store a string in the form "gpu:1" if a GPU was requested
If a GPU was not requested, it will be empty
"""
if gpuCount:
intGpuCount = int("0"+gpuCount.split(":")[1])
return intG... | bb15f87da94d5994c9a08ff0614f5381eb3265de | 27,002 |
from typing import MutableMapping
from typing import Any
def to_nested_dict(d: dict):
"""
Converts a flat dictionary with '.' joined keys back into
a nested dictionary, e.g., {a.b: 1} -> {a: {b: 1}}
"""
new_config: MutableMapping[str, Any] = {}
for k, v in d.items():
if "." in k:
... | 18230ecf0798ee5f2c9b74dccfb90b28547354e8 | 27,004 |
from typing import Any
def validate_boolean(var: Any) -> bool:
"""Evaluates whether an argument is boolean True/False
Args:
var: the input argument to validate
Returns:
var: the value if it passes validation
Raises:
AssertionError: `var` was not boolean
"""
assert is... | 67d8751a60fa6621f0fb366ab44cd017dfe3bd8c | 27,008 |
import functools
def or_none(fn):
"""
Wraps `fn` to return `None` if its first argument is `None`.
>>> @or_none
... def myfunc(x):
... return 2 * x + 3
>>> myfunc(4)
11
>>> myfunc(None)
"""
@functools.wraps(fn)
def wrapped(arg, *args, **kw_args):
... | 54346619090c1aab12498297a31bb017d85377f5 | 27,012 |
def get_segment_output_path(output_path, muxing_output_path):
"""
Returns the output path for a stream segment.
"""
segment_path = muxing_output_path
substr = muxing_output_path[0:len(output_path)]
if substr == output_path:
return muxing_output_path[len(output_path):]
return segmen... | 7c35c5becf6b6eb4f20399f6fa5b3367bce5af79 | 27,018 |
def read_flat_parameters(fname):
"""Read flat channel rejection parameters from .cov or .ave config file"""
try:
with open(fname, 'r') as f:
lines = f.readlines()
except:
raise ValueError("Error while reading %s" % fname)
reject_names = ['gradFlat', 'magFlat', 'eegFlat', 'e... | 34ca5d9f4946d8ee087126b7932596949081b0c3 | 27,019 |
def get_rectangle_coordinates(win):
"""
Gets the coordinates of two opposite points that define a rectangle and
returns them as Point objects.
"""
point_1 = win.getMouse()
point_2 = win.getMouse()
return point_1, point_2 | 75a605ea628c8d9c6817bf727de3542894ac555f | 27,021 |
def identifyL23(addition):
"""Check if it is L2 or L3 delta request."""
return 'L3' if 'routes' in list(addition.keys()) else 'L2' | 63c47a0de8142ddae8559d2e4cc236e2f5e972fd | 27,024 |
def find_border_crossing(subset, path, final_state):
"""
Find the transition that steps outside the safe L{subset}.
@param subset: Set of states that are safe.
@type subset: C{set} of L{State}
@param path: Path from starting state to L{final_state}, sequence of state
and its outg... | 8cf7953897066af2453c4bb428fb01326a4aa25f | 27,026 |
def randomize(df, seed):
"""Randomizes the order of a Pandas dataframe"""
return df.sample(len(df), random_state=seed).reset_index(drop=True) | deb6f1327b993a5a39255bdf2a2b22bc61cdd0a3 | 27,028 |
import re
def count_expr_arity(str_desc):
""" Determine the arity of an expression directly from its str
descriptor """
# we start by extracting all words in the string
# and then count the unique occurence of words matching "x", "y", "z" or "t"
return len(set(var for var in re.findall("\w+", ... | 6e94b6da17b90de4b6b4734add65311842af467d | 27,031 |
from pkg_resources import EntryPoint
def resolveDotted(dotted_or_ep):
""" Resolve a dotted name or setuptools entry point to a callable.
"""
return EntryPoint.parse('x=%s' % dotted_or_ep).resolve() | 504b73a7a3735753db57ae8b86361594b580a3cd | 27,040 |
def get_request_header(headers):
"""
Get all headers that should be included in the pre-signed S3 URL. We do not add headers that will be
applied after transformation, such as Range.
:param headers: Headers from the GetObject request
:return: Headers to be sent with pre-signed-url
"""
new_h... | 97af84f361bc4265d934dbd2cf5398ad4f744e1e | 27,043 |
def check_game(board, last_move):
"""
check if any player has managed to get 3 marks in a row, column or diagonally.
:param {String[]} board : current board with marker locations of both players
:param {int} last_move : between 1-9 where the most recent marker was put.
:return {Boolean} : True if player who play... | 59bc4f5e38b469cd49b59b342ca402b50d591948 | 27,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.