content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import asyncio
def run_sync(f):
"""Runs a coroutine in a synchronous context, blocking until result arrives."""
loop = asyncio.new_event_loop()
return loop.run_until_complete(asyncio.ensure_future(f, loop=loop)) | 1ec0d4085c6fca3498a879f83a6594585aee1bf7 | 602,358 |
def identity(t):
"""
Returns its single argument.
:returns: Its argument.
"""
return t; | 2d0420dcf41df7a45f67dde74177bcd2b69bc713 | 602,361 |
def set_buffer(library, session, mask, size):
"""Set the size for the formatted I/O and/or low-level I/O communication buffer(s).
Corresponds to viSetBuf function of the VISA library.
Parameters
----------
library : ctypes.WinDLL or ctypes.CDLL
ctypes wrapped library.
session : VISASes... | 22bfaa6c388e53ae1a624ecf873e01676c19ce77 | 602,362 |
import math
def eccentricity_factor(h):
"""
Returns the eccentricity factor :math:`e_t` from given hue :math:`h` angle
for forward *CIECAM02* implementation.
Parameters
----------
h : numeric
Hue :math:`h` angle in degrees.
Returns
-------
numeric
Eccentricity fac... | a76034edf68416bc625538239632993793d72419 | 602,366 |
def str2unicode(arg):
"""Decode python2 strings (bytes) to unicode."""
if isinstance(arg, list):
return [str2unicode(s) for s in arg]
if isinstance(arg, bytes):
return arg.decode('utf-8')
return arg | 7ab8a62e07c6018b3b0f3b452ba3256b4421eef8 | 602,368 |
def podcast_info(podcast_obj):
""" Converts gpodder podcast object to a dictionary structure. """
podcast_dict = dict()
fields = ['title', 'description', 'website', 'subscribers', 'logo_url']
for f in fields:
podcast_dict[f] = podcast_obj[f]
return podcast_dict | a143d4b64e650ea38f9d6b6c6eb11f43a3c1cc3a | 602,370 |
def get_instance(compute, project, zone, instance):
"""Get GCE instance information
:param compute: GCE compute resource object using googleapiclient.discovery
:param project: string, GCE Project Id
:param zone: string, GCE Name of zone
:param instance: string, Name of the GCE instance resource
... | 0d04f3a247238345f01670f20f0c16ce8f97f58a | 602,372 |
def default(value, default):
"""Defaults a variable.
Parameters
----------
value
The value to potentially default.
default
The default value.
Returns
-------
any
If ``value`` is ``None``, then ``default`` is returned,
else ``value`` is returned.
"""
... | 9f88463d7c54074fb1706dc047c73843982f9238 | 602,378 |
from typing import Union
import pathlib
def pathlibify(path: Union[str, pathlib.Path]) -> pathlib.Path:
"""Converts string 'path' to pathlib.pathlib.Path object.
Args:
path (Union[str, pathlib.Path]): either a string representation of a
path or a pathlib.Path object.
Returns:
... | 875c119cfcbd9c44146c78600f99f7d15be006d5 | 602,379 |
def scan64(block):
"""Apply zigzag scan for one 8x8 block."""
indexes = [
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 2... | eb85670072f298ed7ddcbc1598c48449df237d59 | 602,381 |
def write_commit_header(header_path, commit_info):
"""
Write current git commit info to header file
header_path : Path to write header file
commit_info : Dict containing header info
"""
with open(header_path, 'w') as header:
for name, value in commit_info.items():
header.wr... | 7487c40275f24e595f01f9c8ff9bb4deda517d1e | 602,382 |
def mark_approx(citation):
"""Highlight approximate matches"""
return '<mark class="approx-match">%s</mark>' % citation | 391acce19d1c008577be1489c036e245ee5d4da1 | 602,383 |
def flatten (array):
"""Returns a flattened array containing all elements of subarrays."""
return [ elem for subarray in array for elem in subarray ] | b66bfc7fc7e5a0607a30bf159e8d75fd268ab108 | 602,388 |
import json
def load_json(track_fpath):
"""Load a single json as a dictionary"""
with open(track_fpath) as json_f:
track_dict = json.load(json_f)
return track_dict | 685926ac1c701e5da983da83a6a4331747b096e2 | 602,390 |
def merge(a, b):
"""
Given two clocks, return a new clock with all
values greater or equal to those of the merged
clocks.
"""
return tuple(map(max, zip(a, b))) | 3cdf31c9f32e846fcf8b65bfc2d6a7359d68b317 | 602,391 |
import math
def _measure(lon1, lat1, lon2, lat2):
"""
Getting distance between two nodes (in meters)
Arguments:
:param lon1: float
:param lat1: float
* Coordinates of first node
:param lon2: float
:param lat2: float
*... | cc7677d7d79b13f300d81bf93dc2d2aad981674e | 602,392 |
def split_shape(shape):
"""Splits a shape into its ringlet shape and frame shape
E.g., (2,3,-1,4,5) -> (2,3), (4,5)
"""
ringlet_shape = []
for i,dim in enumerate(shape):
if dim == -1:
frame_shape = shape[i+1:]
return ringlet_shape, frame_shape
ringlet_shape.append(dim)
raise ValueError("No time dimensio... | 9aace743fa561a471962f58b7e83545771170b64 | 602,394 |
def max_value(bitcount):
"""Returns the maximum (unsigned) integer representable in the given number
of bits.
"""
return ~(~0 << bitcount) | a336d6b0a66aee1ceb83bf71dea69c0d3cb0b72f | 602,396 |
import re
def calc_open_doors(descr: str):
"""Given event description, searches for the time doors open
Args:
descr (str): Show description to search
Returns:
str: Doors open time or "" if date is invalid
"""
# Doors open calculate from the description
#doors_ope... | a42ef3edbed8efdaeec7c32f8db0f0b16b3a76e3 | 602,399 |
def days_left_to_format_string(timedelta):
"""
Calculate days left from timedelta and return string message
:param timedelta: timedelta object
:return: string message with the days left
"""
return '{} day{} left'.format(timedelta.days, ('s', '')[timedelta.days == 1]) | 32d73f85c7cdfec15b11757f7b0ef549b612e9c2 | 602,400 |
import functools
import time
def slow_down(func, seconds: float):
"""Slow down `func` by adding timeouts before and after its execution."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
time.sleep(seconds)
result = func(*args, **kwargs)
time.sleep(seconds)
return re... | f98c8eb9eae368a15b2e031a158af91b406426bb | 602,404 |
def flip_1d_index_vertically(index, rows, columns):
"""Finds the index to the corresponding vertically flipped 1d matrix value.
Consider a 1d matrix [1, 2, 3, 4, 5, 6] with 3 rows and 2 columns. The
original and vertically flipped representations are shown below.
1 2 5 6
3 4 -> 3 4
... | ca8fb78915bd278b3ef397a1c9a1d3b2a6af1e15 | 602,407 |
import uuid
def _CreateBudget(client):
"""Creates the budget.
Args:
client: an AdWordsClient instance.
Returns:
a suds.sudsobject.Object representation of the created budget.
"""
budget_service = client.GetService('BudgetService', version='v201705')
# Create the campaign budget
operation = {
... | 48abe82d5abc23f257349613bc6b8887cb8478ed | 602,413 |
import itertools
def zip_longest(*collections, **kwargs):
""":yaql:zipLongest
Returns an iterator over collections, where the n-th iterable contains
the n-th element from each of collections. Iterates until all the
collections are not exhausted and fills lacking values with default value,
which i... | a618433c5b4d66127d0bdac4d6bfa53304a91a00 | 602,414 |
def coral_uniformed_version(version):
"""
Char '-' is illegal for RPM. Replace it to "_". So
in version field "-" is the same with "_".
"""
return version.replace("-", "_") | 65d3cf839d09d0fce8df88066ae90acc4549d518 | 602,415 |
def loadheader(filename):
"""
Load NAME file and parse header lines into dict.
filename -- input NAME file
"""
header = {}
with open(filename, 'r') as f:
for line in range(1, 19):
h = f.readline()
if ":" in h:
(key, val) ... | cc505761e9896bfb84692ca21311fb123c8f34e0 | 602,417 |
def calculate_accuracy(labels, pred):
"""Calculates accuracy given labels and predictions."""
return float(((pred > 0) == (labels > 0)).sum()) / labels.size()[0] | 42d28a5d42cd74b2f9157d9785894dce0454ddf9 | 602,426 |
from typing import List
import collections
def get_class_frequencies(records: List[dict]):
""" counts the number of examples belonging to each label, and returns a dict
"""
all_labels = [entry['label'] for entry in records]
counter = collections.Counter(all_labels)
return dict(counter) | 65550a4b53ebb056673ead4ed103d958a24e7856 | 602,428 |
def calculate_density(x):
"""
This function calculates the density of the number of accidents by the area of the SA2 area
:param x: geopandas geodataframe
:return: float density value
"""
return x['NUM_ACCIDENTS'] / x['AREASQKM16'] | 9eef186c603cdda33c05e037c1908e4dde9d8adb | 602,429 |
def _get_mean_var(X):
"""Calculate the mean and variance of a variable."""
mean = X.mean()
var = X.var()
return [mean, var] | b115a07dad9f76a7de417c195f98435d5e2baed5 | 602,437 |
def ngmlr_stdin_in_cmd(ref_fa, out_bam, nproc):
"""Return ngmlr call, read from stdin, output to bam.
(If does not read from stdin, try -q /dev/stdin)
"""
# NGMLR --subread-length controls minimum length of detectable alignments, default 256
# runtime using --subread-length 50 is 1.5~2 fold longer t... | 50b42fa48d17005480639ca5706a1f574f12807d | 602,439 |
def split(a_string, seperator):
""" Split a string using seperator. """
return a_string.split(seperator) | aedb5ffa2b159afd90f8ac206c92d21b2facf9d1 | 602,443 |
def slowness_to_velocity(inputvalue):
"""
Converts slowness to velocity.
Parameters
----------
inputvalue : float
Input value in slowness units.
Returns
-------
float
Returns value in velocity units.
"""
return 1000000/inputvalue | b69c7cc701746e56eec681bb0874ba44c84ae409 | 602,447 |
def _capValue(value, max=float('inf'), min=float('-inf')):
"""Clamp a value to a minimun and/or maximun value."""
if value > max:
return max
elif value < min:
return min
else:
return value | 78da770a1ed5e64ca5e13d2f11c68ae191cb0dd9 | 602,452 |
def isAnnotation(footprint):
"""
Given a footprint, decide if it is KiKit annotation
"""
info = footprint.GetFPID()
if info.GetLibNickname() != "kikit":
return False
return info.GetLibItemName() in ["Tab", "Board"] | e5d324b7528428d091440f8f409bdc9f28c9869b | 602,456 |
def load_univs_list(filename):
"""Return a set of universes in filename."""
with open(filename, 'r') as f:
return set(map(lambda x: x.strip(), f.readlines())) | 50ee637a7ae3a3ee7eb08e9f15ef413f8b1514e8 | 602,460 |
def has_completed(job) -> bool:
"""Check if the job has completed."""
return (
job.status == "Succeeded"
or job.status == "Failed"
or job.status == "Cancelled"
) | 8ad38a05959e196058ae1920154dc4c8fd34a009 | 602,474 |
def selectionsort(list, descending=False):
"""
Takes in a list as an argument, and sorts it using a "Selection Sort"-algorithm.
---
Args:
- list (list): The list to be sorted
- descending (bool): Set true if the list be sorted high-to-low. Default=False
Raises:
- T... | c5ef4bb9f8835b8a1282d3bafde4dc1ec9a80f82 | 602,477 |
def is_test_or_third_party_idl(idl_path: str) -> bool:
"""Check if an IDL file is a test file or from a third-party library."""
ignored_idls_subpaths = ["/idl/tests/", "unittest.idl", "/src/third_party/"]
for file_name in ignored_idls_subpaths:
if idl_path.find(file_name) != -1:
return ... | 62010104d85498cb7a05d9496ad41690938748e7 | 602,479 |
def get_contents(clips: set, **kwargs) -> dict:
"""
Return dictionary of category:clips (key:value) pairs from a set of Clips.\n
- "count=True" returns number of clips instead of a list of Clips.
"""
contents = {}
for clip in clips:
category = clip.category
if kwargs.get("count",... | 691e010cc245c8f095c02197a464d6331822e754 | 602,480 |
import copy
def _merge_exons(base_assembly_exons: dict, other_assembly_exons: dict) -> dict:
"""
Merge exons from two assemblies
Given exons from two assemblies, perform a full outer join on identical gene id.
A copy is returned (not an in-place merge).
For example:
>>> e1 = {1: {'exons_... | 7afe76f626edc92690dbcf11db3cb47927a4b067 | 602,482 |
def _path_len(graph, path):
"""
Returns the length of a given path in a Graph object.
:param graph: Graph object.
:param path: (list) Path over nodes in the graph.
A path is a singly connected, acyclic graph.
"""
return sum(graph[u][v].get('weight', 1) for u, v in zip(path[:-1],... | 5cfa65fb08f34f22a1a2c482155f37c0618b4b17 | 602,485 |
def build_test_git_item(modes, distinct_snapshot_length, min_freq):
"""Create a dictionary object with all required key-pair values, to be used
for testing the GIT method.
"""
return {"allowedModeList": modes,
"distinctSnapshotLength": distinct_snapshot_length,
"minSourceFrequenc... | d64e7bb11868876c0d00e1b1ae7d12166a535d2f | 602,488 |
import re
def quoted_str(x):
"""
Strips the string representation of ``x`` to make it suitable for
a ``dot2tex`` string, and especially a node label (``dot2tex``
gets confused by newlines, and braces)
EXAMPLES::
sage: sage.graphs.dot2tex_utils.quoted_str(matrix([[1,1],[0,1],[0,0]]))
... | e9e5ef1eedb8c669756606e2c771df5cc69b6c90 | 602,492 |
def PNT2Tidal_Pv10(XA):
""" TaylorT2 0PN Quadrupolar Tidal Coefficient, v^10 Phasing Term.
XA = mass fraction of object """
return 72-66*XA | 530180ed24e52d29a2cc238590db7253f82fd340 | 602,493 |
def nr_P_N(Y_data, X_data):
"""
A function to calculate the total number of P:s (positives) and N:s (negatives) in the Target data. Excludes the
padding and data from bounding boxes with a width smaller than 60 pixels.
:param Y_data: Target data
:param X_data: Feature data, used to identify padding
... | 589a901eed69e16c2ccfe4e01df650b5f1ab9b5f | 602,494 |
from typing import Optional
from typing import Sequence
from typing import Tuple
def validate_class_names(class_names: Optional[Sequence[str]], n_classes: int) -> Tuple[str, ...]:
"""Return valid names for the specified number of classes.
:param class_names: List of class names. If `None`, will return `('0',... | 612a0594c59ca07cfa8374ea085a575dd00167d6 | 602,497 |
def _PrettyPrintCLRisks(risks):
"""Pretty print a risk map as a string.
Args:
risks: The risks to print.
"""
return ', '.join([
'%s = %s' % (k, v)
for k, v in risks.iteritems()]) | e9004307c4d0ba3bcabbe5e300597b09e0bd421a | 602,504 |
def get_templates_path(self):
"""
Retrieves the templates path.
:rtype: String
:return: The templates path.
"""
return self.templates_path | dfc2af5910140f8cb3887b4825712055b8ff264f | 602,511 |
def parse_policy(policy):
"""Parses a policy of nested list of tuples and converts them
into a tuple of nested list of lists. Helps with TF serializability."""
op_names = [[name for name, _, _ in subpolicy] for subpolicy in policy]
op_probs = [[prob for _, prob, _ in subpolicy] for subpolicy in policy]
... | 79df1fdb9825cfbe35ca59e3a2e9700a3bcf26d6 | 602,513 |
def _get_dimension(shape, dim, min_rank=1):
"""Returns the `dim` dimension of `shape`, while checking it has `min_rank`.
Args:
shape: A `TensorShape`.
dim: Integer, which dimension to return.
min_rank: Integer, minimum rank of shape.
Returns:
The value of the `dim` dimension.... | 41eecf5c13f54cf961c1caaaff0f39b35f8ec729 | 602,518 |
def get_subject(proposition):
"""
Returns the subject of a given proposition
"""
return proposition[1][0] | 479018a9302026f9d1a473969bb409f04e85e8fb | 602,522 |
from typing import List
from typing import Tuple
from typing import Any
import itertools
import random
def combine_with_all(a: list, b: list, n_a_combinations: int = 1, is_random: bool = False) -> List[Tuple[Any, ...]]:
"""
>>> a = [1, 2, 3]
>>> b = ['anything_a', 'anything_b']
>>> combine_with_all(a,... | 20d3c011ecb721db58046d579a2e65d176df5bb3 | 602,528 |
def add(first_number: int, second_number: int) -> int:
"""
Adds two integers
:param first_number, second_number: two numbers to be added
:return: [int] sum of the two input numbers
:raise ValueError if the numbers are not integers
"""
if isinstance(first_number, int) and isinstance(second... | ba0273db0427c044fc6ec1bbe4f22f7f1159b8c4 | 602,529 |
def calc_residuals(actual, predicted):
"""
Helper method to make other code portions clearer
Args:
actual: 1-d array of observed values
predicted: 1-d array of predicted values
Returns:
ndarray: 1-d array of residual values
"""
return actual - predicted | cfa6652a700c2970b1b6906bc349700235d6b98b | 602,530 |
import textwrap
def indent_str(string: str, indent: int, end="\n") -> str:
"""Indent a multiline string with 4 spaces, with a newline or `end` afterwards."""
return textwrap.indent(string, " " * indent) + end | c8f4645d2ed0e9daa05a6784c54b769427e07ba5 | 602,531 |
def crop_spectrum(min_wl, max_wl, wl, flux):
""" crops the spectrum strictly between the limits provided, only works
if wl is ordered
:param min_wl: lower limit to crop
:type: numpy.ndarray
:param max_wl: upper limit to crop
:type: numpy.ndarray
:param wl: array of spectrum wl
:type wl... | 78e2d59b4d408d2e8f54b533c75f7a43adcab5c3 | 602,533 |
def edge_losses(target_sizes, insert_size):
"""Calculate coverage losses at the edges of baited regions.
Letting i = insert size and t = target size, the proportional loss of
coverage near the two edges of the baited region (combined) is:
.. math :: i/2t
If the "shoulders" extend outside the bait... | 56bb3301321c72283b1c78406c4e3ee27e8d2152 | 602,534 |
def devideContent(span, text):
"""
@param[in] span a tuple with two elements: the beginning and the end of the text to separate
@param[in] text the text to work on
@returns an tuple with 3 elements: the text before the beginning, the text to separate and the text after the end
"""
... | f3430a9613c8ef2ead4631508840cc38b8b57b4d | 602,538 |
def is_root_node(node):
"""
Return `True` if the given node is a "root" node, `False` otherwise.
"""
if not node:
return False
return node.is_root is True and node.is_child is False | 4b7177cab7b55876e115ed48fac0d1f3485a6c84 | 602,539 |
import math
def compute_probability(keyspace, trials):
"""Compute the probability of a collision.
Uses an approximation of the full sum for computational speed.
http://preshing.com/20110504/hash-collision-probabilities/
:param keyspace: keyspace size
:param trials: number of trials
:rtype fl... | da4ec9052bcc1d55541d4ba1c2669b6a51bcb202 | 602,540 |
def determine_frac_copy_num(rN, r, lengths, dev):
"""
Determines the fraction of the genome that potentially
contains copy number aberrations. Used to determine if a sample
is a reasonable sample to run THetA on.
Args:
rN (list of ints): normal read depth vector
r (list of ints): tumor read depth vector
le... | 72b0fc83659c2560bc03efe4b4662cddb4e06808 | 602,543 |
import typing
def _filter_missing_keys(keys: typing.Any,
a_dict: typing.Dict) -> typing.List[typing.Any]:
"""Given a list of keys each as a string and a dict, returns the keys in
the list that are not present in the dict or have empty values."""
return list(key for key in keys if ... | 004f9a126d7cb88d066da4f93e4db5bb3780eb3d | 602,544 |
def _unflatten_nested_keys(dictionary):
"""
Unflatten the nested values of a dictionary based on the keys that are tuples
E.g. {("a", "b"): [1], ("a", "c"): [2]} becomes {"a": {"b": [1], "c": [2]}}
"""
# Find the parameters that are nested dictionaries
nested_keys = {k[0] for k in dictionary if ... | 00a1c83767066fe1121ed0af0755e2d9d1df8a83 | 602,547 |
def _get_matched_row(rows, lookup):
"""
Return row that matches lookup fields.
"""
for index, row in enumerate(rows):
matched = True
for field, value in lookup.items():
if str(row.get(field, '')).strip() != value:
matched = False
break
... | 111d89516798aab3646488af7ea577723295e7a6 | 602,548 |
def get_range(context, range_str):
"""Should be given a range_str like '<start_index>:<end_index', e.g. '1:4'
returns a string: e.g. 1,2,3
"""
rargs = [int(s) for s in range_str.split(':')]
return ','.join([str(d) for d in range(*rargs)]) | 879ad99e2c35d18efb1a565caa800231deb17968 | 602,550 |
def has_plugin_section(model):
"""Checks whether a model is worth having a plugins' section for.
:param model: The model to check.
:type model: :class:`cibyl.models.model.Model`
:return: True if the model has enough data to build
a plugins' section with, False if not.
:rtype: bool
"""
... | c2e4c393150909049bf22184fa3aca9b6bea8c70 | 602,551 |
import math
def exp(x):
"""Return the constant "e" raised to the input value"""
return math.e**x | be722e29e8cbba9addaac89629487e02b9555275 | 602,552 |
def make_filepaths_from_dfs(top_dest_dir, dfs, data_origin):
"""
Accepts:
- a parent directory - top_dest_dir as a Path object
- a list of dataframes - dfs
containing columns and data for nation, league and season
- a string representing the original source of the data
Returns a list ... | 07feb54f332b90b727c7bfe428aea5ed49c313ea | 602,555 |
def _any_list_ele_in_other(l1, l2):
"""Returns True if any element of list l1 is found in list l2."""
return any(ele in l2 for ele in l1) | e5c9b9b71eb554a7275ce70d45638a8061c5d694 | 602,567 |
def get_intrinsic_name(signature):
"""
Get the intrinsic name from the signature of the intrinsic.
>>> get_intrinsic_name("int8x8_t vadd_s8(int8x8_t a, int8x8_t b)")
'vadd_s8'
>>> get_intrinsic_name("int32x4_t vaddl_high_s16(int16x8_t a, int16x8_t b)")
'vaddl_high_s16'
>>> get_intrinsic_n... | d98a357e17740d0661886a0e5e0af0389736ab26 | 602,568 |
import math
def _int_64_value(client, value):
"""Converts a value to a protocol buffer Int64 wrapper.
Args:
client: A google.ads.google_ads.client.GoogleAdsClient instance.
value: A number to wrap, truncated to the nearest integer.
Returns:
The value wrapped in a google.ads.googleads_v... | 654fbd05fd446a32e7388f3226e8a97189daef7b | 602,573 |
import re
def filter_url(text):
"""
Remove URLs from a given string
:param text: string of text
:return: string of text without URLs
"""
return re.sub(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", '', text) | 3b12ca8ecb2d1072e2e91776b01583e3833f2037 | 602,579 |
def gferror(reply):
"""Determines if a GF reply is an error"""
return (reply.startswith('The parser failed')
or reply.startswith('The sentence is not complete')
or reply.startswith('Warning:')
or reply.startswith('Function') and reply.endswith('is not in scope')) | c286b2c5ce399774ef0638c204f5d303bd181269 | 602,588 |
def prepare_for_diff(data):
""" Eats a list of dicts, extracts the words in lower case and
returns them as a list. (We don't want capital letters to
disturb our comparison.) """
prepared = []
for item in data:
prepared.append(item['word'].lower())
return prepared | eee67016f1998e3a110b5671f3e588fa9a214411 | 602,589 |
def is_copy(df1, df2):
"""Verify that the DataFrame one is not a view of DataFrame two"""
return df1.values.base is not df2.values.base | 5403f7fd3849295acbd3ccd06639fdf2f4d58479 | 602,591 |
from typing import Counter
def create_vocabulary(text: str, vocab_size=100000):
"""Create vocabulary dictionaries.
Args:
text(str): raw text.
Returns:
token2id(dict): token to id mapping.
id2token(dict): id to token mapping.
"""
token2id = {'<PAD>': 0, '<OOV>': 1}
id2... | 6a22847b58a2e96a165675936ce2d91aec992623 | 602,595 |
import collections
def volume_versus_size(clusters):
"""Calculate volume of clusters respect to its size.
Args:
clusters (list): list of clusters
Returns:
dict: {size (int): volume (list of floats)}
"""
stats = collections.defaultdict(list)
for cluster in clusters:
#... | 248ebfb4c539d67f21c2e2de3d654bec554e4dd3 | 602,596 |
import codecs
import json
def _load_list(file_name, object_type="licenses", id_attribute="licenseId"):
"""
Return a list version tuple and a mapping of licenses
name->id and id->name loaded from a JSON file
from https://github.com/spdx/license-list-data
"""
licenses_map = {}
with codecs.op... | 0f451050ca0f332ab25ec4f0d64383cf0fe5a000 | 602,597 |
def _dms_to_dd(degrees, minutes, seconds, direction):
"""Helper function converting Degrees/Minutes/Seconds to Decimal Degrees
Degrees, minutes, and seconds are numeric types.
Direction is a single character: 'N', 'E', 'S', or 'W'.
The type returned shall be a floating point number.
"""
if ... | cbe1ba305ad6781c0b20c3689f77b2b47997d119 | 602,599 |
def kernel_munge(kernel_name):
"""return the kernel name as it's rendered in the notebook metadata"""
return f"conda-env-miniconda3-{kernel_name}-py" | 51b70f4de782f6949d1ade29d4cd6d3245f6e8c2 | 602,600 |
def build_person(first_name, last_name, age=None):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person | 4306069ac7aa49967e1e253cc704666aca3748b9 | 602,603 |
from typing import List
def bytes_to_bitarray(the_bytes: bytes, num_bits: int) -> List[int]:
"""Convert input bytes into an array of bits.
Args:
the_bytes: Bytes to be converted.
num_bits: Number of bits to return.
Returns:
An array of bits.
"""
return [(the_bytes[i >> 3]... | 18c9a3c55167b1a0cc53a676fd1da13734412c6a | 602,604 |
def reconcile_taxids(taxid):
"""
Sometimes Ensembl taxid and ENA/Expert Database taxid do not match,
so to reconcile the differences, taxids in the ensembl_assembly table
are overriden to match other data.
"""
taxid = str(taxid)
if taxid == "284812": # Ensembl assembly for Schizosaccharomy... | d9dbbba213cb4bac7b2f492d6a273a7877c17dd4 | 602,605 |
def monkeypatch_method(cls, patch_name):
# This function's code was inspired from the following thread:
# "[Python-Dev] Monkeypatching idioms -- elegant or ugly?"
# by Robert Brewer <fumanchu at aminus.org>
# (Tue Jan 15 19:13:25 CET 2008)
"""
Add the decorated method to the given class; replace... | a871825ad67ca0f4e67ccd2ab7cbd9362f01ab59 | 602,609 |
def PBIAS(y_pred, y_true):
"""
Calculate the percent bias.
"""
return 100 * sum(y_true - y_pred) / sum(y_true) | 6d44099e344e1af202feb712cec2a81ac734a056 | 602,612 |
def _precursor_to_interval(mz: float, charge: int, interval_width: int) -> int:
"""
Convert the precursor m/z to the neutral mass and get the interval index.
Parameters
----------
mz : float
The precursor m/z.
charge : int
The precursor charge.
interval_width : int
T... | f690cc9abdbadb5f5802c5b70fd68cc1e294eb6d | 602,618 |
def _parse_float(value, default=0.0):
"""
Attempt to cast *value* into a float, returning *default* if it fails.
"""
if value is None:
return default
try:
return float(value)
except ValueError:
return default | b4d1cdbb6913075783fa53843e92bf4e517bb352 | 602,619 |
def combo_to_int(value, replace_string='None', replace_with=0):
"""
Used for the values of combo quants with numerical values and one string value.
The default use case is to replace the 'None' option with a 0.
"""
if value == replace_string:
return int(replace_with)
else:
return... | 7a8b49062a015689c67e83bc00ea9da6da0eeffb | 602,625 |
import re
def search_name_regexp(needle, name, obj):
"""Match if regexp needle matches name"""
return name and re.search(needle, name) | 96663e9d9653ce2e2b9b64e79d4c018560503d90 | 602,627 |
def get_color_between(color1, color2, i):
""" i is a number between 0 and 1, if 0 then color1, if 1 color2, ... """
if i <= 0:
return color1
if i >= 1:
return color2
return (int(color1[0] + (color2[0] - color1[0]) * i),
int(color1[1] + (color2[1] - color1[1]) * i),
... | 36d735ad6fc964af8c67407082459e586049ca0a | 602,632 |
import pickle
import dill
def load_pickle(filename, use_dill=False):
""" Basic dill/pickle load function.
Args:
filename (str): Location of the object.
use_dill (bool): Set True to load with dill.
Returns:
python object: The loaded object.
"""
with open(filename, 'rb') as f... | e7e8c679b73fdcb7cdea74ec587e52441c45303d | 602,636 |
def object_merge(old, new):
"""
Recursively merge two data structures
Thanks rsnyman :)
https://github.com/rochacbruno/dynaconf/commit/458ffa6012f1de62fc4f68077f382ab420b43cfc#diff-c1b434836019ae32dc57d00dd1ae2eb9R15
"""
if isinstance(old, list) and isinstance(new, list):
for item in ol... | 67a41286629351503d055c2944e979b3c35add19 | 602,637 |
def get_locale_and_nickname(account, message):
"""Returns a locale and nickname for the given account and email message."""
if account:
locale = account.locale or 'en'
nickname = account.nickname or account.email
else:
locale = 'en'
nickname = message.sender
return (local... | 2e71ed528a58f483937688559a5da487d288d4d3 | 602,638 |
def raman_intensity(R):
"""
Scattering intensity
Args:
R (3x3 numpy array): Susceptibility tensor
Returns:
float: scattering intensity according to Eq 7, Phys Rev B 73, 104304 2006
"""
return (
4 * (R[0, 0] ** 2 + R[1, 1] ** 2 + R[2, 2] ** 2)
+ 7 * (R[0, 1] ** 2... | 82e7f4caed5fe38f15c60a585aa31bd33498d30d | 602,639 |
from pathlib import Path
def convert_path(object_path):
"""
Convert path or list of paths to Path() objects.
If None type, returns None.
:param object_path: string, Path() object, None, or a list of these.
:return: Path() object, None, or a list of these.
"""
if isinstance(object_path, li... | 5b9b9bd398ec0434dd88b22687cd8a8374445232 | 602,641 |
def calc_bias_abc(second_order_influence):
"""
Calculates the approximate bias of the MLE estimates for use in calculating
the approximate bootstrap confidence (ABC) intervals.
Parameters
----------
second_order_influence : 2D ndarray.
Should have one row for each observation. Should ha... | 583426cbf266adfd00601a02c9f59ae343ddeb55 | 602,642 |
def xxyy2yolo(size, box):
"""convert XMin XMax YMin YMax coordinates to yolo format
Args
----
size (tuple): (width, height)
box (tuple): (xmin, xmax, ymin, ymax)
Returns
-------
yolo (tuple): (ratio-bbox-centre-x, ratio-bbox-centre-y, ratio-bbox-w, ratio-bbox-h)
"""
width =... | ea5bdaa4ea5db83f1390661afe7e395d3681d26c | 602,645 |
def _get_luminance_avg(r, g, b):
"""Computes a weighted average of the given RGB values.
Color weights were retrieved from the Wikipedia article on Grayscale
conversion
(https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale).
Args:
r (int): Red value of ... | 2a3dc330497211d3d736ac40c543ee319a9cc976 | 602,647 |
import typing
def dict2items(
value: typing.Mapping,
key_name: str = 'key',
value_name: str = 'value',
) -> typing.List[typing.Dict[str, typing.Any]]:
"""Convert a mapping to a list of its items.
For example, converts
.. code-block:: yaml
milk: 1
eggs: 10
bread: 2
... | fd67f843ec0a915b35cf87565b65e249cbec08a7 | 602,648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.