content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import TextIO
def _readline_sk(
fp: TextIO,
) -> list:
"""
Skips lines starting with '#' or '!'. Splits and returns all other
lines.
Parameters
----------
fp:
TextIOWrapper of .snt or .ptn file.
Returns
-------
arr:
The current line in 'fp' spl... | 8f8a893802759e20668df75b926e02160f69a6e9 | 409,327 |
from typing import Tuple
def auto_figure_size(figure_shape: Tuple, scaling_factor: int = 4) -> Tuple:
"""Scales figure shape to generate figure dimensions.
Args:
figure_shape (Tuple): Figure shape in determines of rows and columns.
scaling_factor (int, optional): Defaults to 4.
Returns:
... | 9c584becb9b4cb7a396b7b18647e5fd1a4bc3cc9 | 592,625 |
def exclude_blank(seq):
"""Remove empty and None items from an iterable"""
return [x for x in seq if x] | b03c539353889f9ac2d4b3b803e8ac3229f23cb1 | 463,892 |
def get_mask(img, axis=None):
"""Detect regions of interest in a thresholded image
Receive a thresholded single-channel image as a 2D uint8 numpy array.
Assuming white background, get a mask vector
indicating rows or columns (depending on the argument to `axis`)
that contain any number of non-white... | 14ada59a1429874527b22f4942b6fd8dcec56e05 | 363,692 |
def check_interval(child_span, parent_span):
"""
Given a child span and a parent span, check if the child is inside the parent
"""
child_start, child_end = child_span
parent_start, parent_end = parent_span
if (
(child_start >= parent_start)
&(child_end <= parent_end)
):
... | 6c6a8e636ad181af821d185ba35f18db41d0ce77 | 13,473 |
def input_default(prompt, default):
"""Displays the prompt, returns input (default if user enters nothing)."""
response = input("{} [{}]: ".format(prompt, default))
return response if response else default | 7c8f30c22469bc5082f26e2934296baac5a90a2e | 597,385 |
def _CompareAnomalyBisectability(a1, a2):
"""Compares two Anomalies to decide which Anomaly's TestMetadata is better to
use.
Note: Potentially, this could be made more sophisticated by using
more signals:
- Bisect bot queue length
- Platform
- Test run time
- Stddev of test
Args:
a1: The ... | ab5ea6d8a88c4df7c56dfea6785137650ba79876 | 619,696 |
from dateutil import tz
def video_in_period(latest_date, oldest_date, video_date):
"""Return a Boolean indicating if a said video was uploaded in a specified period.
:param latest_date: Upper bound of time interval.
:param oldest_date: Lower bound of time interval.
:param video_date: video's upload d... | cecde782a412323782b128806a92a4c99159201d | 165,948 |
def all_factors(num):
""" Return the set of factors of n (including 1 and n).
You may assume n is a positive integer. Do this in one line for extra credit.
Example:
>>> all_factors(24)
{1, 2, 3, 4, 6, 8, 12, 24}
>>> all_factors(5)
{1, 5}
"""
factors = set()
for i in range(1, i... | 014225dd3117106b53ad678b3258944197cd31a3 | 445,325 |
def checksum(im_path, hfunc="sha1", chunk_size=4096):
"""Compute checksum of file at given path
inputs:
im_path: String: Path to file to read
hfunc: String: hashlib function to use for hash. Options are:
sha1, sha224, sha256, sha384, sha512, blake2b
... | eaf0ea72f98d79814e2e9419cb2857613f56e38d | 382,855 |
from typing import Union
import unicodedata
def _unicode_character_name(char: str) -> Union[str, None]:
"""Get the full unicode char name"""
try:
return unicodedata.name(char)
except ValueError:
return None | 905803c632908bfa68fb52a27ce76e536182835d | 472,632 |
def _pad_jagged_sequence(seq):
"""
Pads a 2D jagged sequence with the default value of the element type to make it rectangular.
The type of each sequence (tuple, list, etc) is maintained.
"""
columns = max(map(len, seq)) # gets length of the longest row
return type(seq)(
(
... | 65285795ccf56edaea61180d42bca861df2d0794 | 620,038 |
def required_keys(expr):
"""
>>> required_keys("VAR1=='VAL1' and VAR2=='VAL2' and VAR3=='VAL3'")
['VAR1', 'VAR2', 'VAR3']
"""
return sorted({term.split("=")[0].strip() for term in expr.split("and")}) | d6818957dea84c97dd1032e3b2b41be762fbf358 | 444,794 |
def zero_float(string):
""" Try to make a string into a floating point number
and make it zero if it cannot be cast. This function
is useful because python will throw an error if you
try to cast a string to a float and it cannot be."""
try:
return float(string)
except:
return 0 | a902b8ea9fa994ccb674d65dba1e04ceb88fceb7 | 127,061 |
def rcBase(base):
"""Return the reverse complement of the base."""
base = base.upper()
if base == 'A':
return 'T'
if base == 'C':
return 'G'
if base == 'G':
return 'C'
if base == 'T':
return 'A'
return 'N' | 368f337adc24a16b324e9323b5a249cfa0971733 | 569,192 |
from typing import Iterable
from typing import List
from typing import Optional
def sorted_dedup(iterable: Iterable) -> List[Optional[int]]:
"""Sorted deduplication without removing the
possibly duplicated `None` values."""
dedup: List[Optional[int]] = []
visited = set()
for item in iterable:
... | b7b5424157bccb764c3db03fadf4ca88e6c50b02 | 677,551 |
def fun_command(func):
"""
A decorator to indicate a "fun command", one that the bot skips when it is
'exhausted'
"""
func.fun_cmd = True
return func | 33a5f5de6b00302b724f7c749ed64fbadf2db2e4 | 403,896 |
def print_with_count(resource_list):
"""Print resource list with the len of the list."""
if isinstance(resource_list, str):
return resource_list
resource_list = [str(elem) for elem in resource_list]
return f"(x{len(resource_list)}) {str(resource_list)}" | ced8277905ff3dfa166935bf5b711018d34de188 | 471,275 |
import calendar
def to_timestamp(date):
"""Convert a datetime object into a calendar timestamp object
Parameters
----------
date : datetime.datetime
Datetime object e.g. datetime.datetime(2020, 10, 31, 0, 0)
Returns
-------
cal : calendar.timegm
Calendar timestamp corresp... | 514ea392268dc94aa0a14b1dd5ce04425d1ed3bb | 35,782 |
def clean_data(df):
"""
Function to remove the duplicates and fill NA values if any.
:param df: The data frame to clean
:return: Cleaned data frame
"""
df.drop_duplicates(inplace=True)
df.fillna(value=0, inplace=True)
return df | f166658b0bafb6a692f2faded1924f30c8ae7ef3 | 180,787 |
def isEmulator(title):
"""Returns True if 'emulator' is written in stream title, False otherwise."""
return 'emulator' in title | 2bb0baf5434694abb0ae3c4d154c61317b5ffab6 | 142,208 |
def is_article(_item):
"""Item is an article
:param _item: Zotero library item
:type _item: dict
:returns: True if conf, encyArt or journalArt
"""
return _item["data"]["itemType"] in [
"conferencePaper",
"encyclopediaArticle",
"journalArticle",
] | 6b68199ed28a3dce114e0ddf97bc18f7cf9bc400 | 338,002 |
import pytz
def get_tz(tz):
"""
Pass a string and return a pytz timezone object.
This function can also infer the timezone from the city, if it is a substring of the timezone. e.g. 'Dubai' will return 'Asia/Dubai.'
"""
try:
t_z = pytz.timezone(tz)
except pytz.UnknownTimeZoneError:
... | 476f135ad76bbdcacd38acb1eb67e52bd2a59273 | 114,310 |
def normalized(expression):
"""Converts the expression to the syntax necessary for Pandas'
DataFrame.eval method.
Args:
expression: The expression to normalize
Returns:
A normalized version of the expression usable in Pandas' DataFrame.eval
method.
"""
return expression... | 527d2f82b47a12704c7cffcf5c1fd933854e8ab5 | 494,180 |
def initialize_distribution(states, actions):
"""
initialize a distribution memory
:param states: a list of states
:param actions: a list of actions
:return: a dictionary to record values
"""
dist = {}
for i in states:
dist[i] = {}
for j in actions:
dist[i][j... | d99ff9485d209590b0fa5f8fa772ebe2c1c2303d | 600,666 |
def extract_from_dict(data, path):
"""
Navigate `data`, a multidimensional array (list or dictionary), and returns
the object at `path`.
"""
value = data
try:
for key in path:
value = value[key]
return value
except (KeyError, IndexError):
return '' | e228678722226289e9cc2e1e1be8aa751159746e | 623,415 |
def as_words(string):
"""Split the string into words
>>> as_words('\tfred was here ') == ['fred', 'was', 'here']
True
"""
return string.strip().split() | 543472e536da2024d118a22575348bbb263abcaf | 75,907 |
def multi_table(number: int):
""" This function returns multiplication table for 'number'. """
return '\n'.join(f'{i} * {number} = {i * number}' for i in range(1, 11)) | deacd7db6ff67824ac8bd0b8d5cbd821a0e76dc1 | 433,240 |
import math
def distL2(x1,y1,x2,y2):
"""Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
xdiff = x2 -... | da2bfb2521a71e31fc73ec3de8121e5210adf268 | 293,046 |
def build_bitfield(left, right, num):
""" Builds a bit-field in the specified range [left:right]
with the value 'num', inside a 32-bit integer, and
returns it.
For example:
field(4, 2, 3)
=> 12
Assumptions:
* 31 >= left >= righ... | dc642dd8b8cc09b515e3c55823b6274f8ace8ba5 | 307,531 |
import hashlib
def hash_file(pathname):
"""Returns a byte string that is the SHA-256 hash of the file at the given pathname."""
h = hashlib.sha256()
with open(pathname, 'rb') as ifile:
h.update(ifile.read())
return h.digest() | bdd82aa57abacee91a4631d401af35f0274eb804 | 13,859 |
import re
def getCallConnectionInfo(call, dest, pdmssp=False):
"""
Method expects call dict input from output from getCallStatusV2() method. Extract call info - RemotePartyNumber,
CallState, CallHandle and LineID, from call if dest matches.
INPUTS: call as dict(body), dest as string
OUTPUT: R... | 9e61f245d1d237c52379dd77fd1b4a8833a12e82 | 314,696 |
def map_samples_to_indices(c):
"""Return a dict mapping samples names (key)
to sample indices in the numpy genotype arrays (value).
"""
c.execute("select sample_id, name from samples")
return {row['name']: row['sample_id'] - 1 for row in c} | 0d2d22daad51b6dd54a2b12621324e51e1f5d61d | 120,808 |
def get_parking_id(id_string):
"""Get parking ID as an integer if any, otherwise None"""
if id_string:
return int(id_string)
else:
return None | 90d87048e24f77d2fed1a9867011334ed0376b69 | 282,387 |
def get_class_annotations(cls):
"""Get variable annotations in a class, inheriting from superclasses."""
result = {}
for base in reversed(cls.__mro__):
result.update(getattr(base, "__annotations__", {}))
return result | 0cec1a752ebe453db797b0a55b107ba851d28bbb | 239,209 |
def apply_replacements(s, ren_dict):
"""Replace occurrences of keys with values in a string"""
for k, v in ren_dict.items():
s = s.replace(k,v)
return s | f10123733119532fc6313ba7e921efe26a3df1ae | 176,236 |
from typing import Dict
from typing import Any
def validate_key(config_dict: Dict[str, Any], key: str, value_type: type, default: Any):
"""
Returns config_dict[key] if the value exists and if of type value_type,
otherwise returns a default value.
"""
return (
config_dict[key]
if ke... | 4115d285f16d3b19ac79945bd3dafc4fb5f3440c | 93,313 |
def GetLinkedInUrl() -> str:
"""Returns URL to LinkedIn."""
return 'https://www.linkedin.com' | fc3fbcc694baae7d29cb1260ede1b3d8f722cd2f | 527,893 |
def get_interface_routes(context, iface):
"""
Determine the list of routes that are applicable to a given interface (if
any).
"""
return context['routes'][iface['ifname']] | 74785c7ebf761c58e378e6a17d18536460c70865 | 486,623 |
def cent(q: int, halfmod: int, logmod: int, val: int) -> int:
"""
Constant-time remainder.
:param q: Input modulus
:type q: int
:param val: Input value
:type val: int
:param halfmod: q//2
:type halfmod: int
:param logmod: ceil(log2(q))
:type logmod: int
:return: Value in th... | 33338c3cba62ba55ce42eaaa1bef3a86c7859d9d | 434,913 |
def normalize_pc_counter(dict_in):
"""
Normalize a dictionary by the sum of the total values. Meant to be used with the
net ql values from :obj:`decitala.hm.hm_utils`.
>>> d = {0: 0, 1: 0.375, 2: 0, 3: 0.25, 4: 0.375,
... 5: 0.375, 6: 0.375, 7: 0, 8: 0.75, 9: 0.25, 10: 0, 11: 0
... }
>>> for pc, norm_val in no... | e406f4b96093f4ae9293b08614ef23dbecf582e0 | 552,329 |
def _phi(speciation_initiation_rate,
speciation_completion_rate,
incipient_species_extinction_rate):
"""
Returns value of $\varphi$, as given in eq. 6 in Etienne et al.
(2014).
Parameters
----------
speciation_initiation_rate : float
The birth rate, b (the incipient speci... | dcd56555661f565d5a6648734125fb3f2e997aad | 636,122 |
def MoveStr2List(mv: str) -> list:
"""
param:
mv: str [x_src, y_src, x_dst, y_dst]
return:
mv_list: List-> [int: x_src, y_src, x_dst, y_dst]
"""
mv_list = []
if mv != " ":
mv_list = list(map(int, mv[1:-1].split(",")))
return mv_list | dedb0d2b044c5e1dd990d76fbf4986661408ebf2 | 626,913 |
def is_operator(node):
"""This function checks whether a validation node is an operator or not.
Args:
node(str): The node key you want to check.
Returns:
: bool.
"""
return node.startswith('$') | fe8136058b924f9831af1dba3d67c2bf5ed30687 | 624,682 |
def create_stack(
cfn_client,
template_path,
stack_name,
params={},
capabilities=[],
timeout=300,
interval=30,
):
"""
Creates a cloudformation stack from a cloudformation template
"""
with open(template_path) as file:
body = file.read()
stack_params = [
... | 80608a4a04e70701bbc5c1628a4300b69aec7486 | 632,909 |
import re
def get_molecular_barcode(record,
molecular_barcode_pattern):
"""Return the molecular barcode in the record name.
Parameters
----------
record : screed record
screed record containing the molecular barcode
molecular_barcode_pattern: regex pattern
... | 1507cf7ad3c39c02b6dfdfdd12c6800155346253 | 22,648 |
def find_in_list(content, token_line, last_number):
"""
Finds an item in a list and returns its index.
"""
token_line = token_line.strip()
found = None
try:
found = content.index(token_line, last_number+1)
except ValueError:
pass
return found | b53c8dd84b97404f96d3422389ad678950375cff | 413,710 |
def _parse_single_header(b3_header):
"""
Parse out and return the data necessary for generating ZipkinAttrs.
Returns a dict with the following keys:
'trace_id': str or None
'span_id': str or None
'parent_span_id': str or None
'sampled_str': ... | 10b716172bf3927b12fb0afbc13bfe15ac957108 | 415,498 |
def sum_3_multiples(y):
"""Calculate the sum of the multiples of 3."""
sum3=0
for i in range(1, y+1):
num_to_add=3*i
sum3=sum3+num_to_add
return sum3 | 9f04eb2c85d2528a4addf3332181eabf8ec66800 | 109,103 |
def get_target_ids(targetcount, targetspec):
"""Get target ids from target spec:
* a - individual item
* a:b - range a to b (non-inclusive), step 1
* a:b:c - range a to b (includes a, not b), step c (where c is
positive or negative)
"""
targetranges = []
for el in targetspec.split(","):... | 31f9eb4f48b2bbeab7cf83df77f31d0d4d83d3a0 | 337,600 |
import calendar
def get_day(date_obj):
"""Get the name of the day based on the date object."""
return calendar.day_name[date_obj.weekday()] | f872fbc1fb3166272effc2e97e7b24c8434ef4cf | 63,382 |
def get_longitude(dataset):
"""Get longitude dimension from XArray dataset object."""
for dim_name in ['lon', 'long', 'longitude']:
if dim_name in dataset.coords:
return dataset[dim_name]
raise RuntimeError('Could not find longitude dimension in dataset.') | d9152f36a2dcdea82c242fdea421779344e83286 | 514,032 |
import MySQLdb
def guess_type(m):
"""
Returns fieldtype depending on the MySQLdb Description
"""
if m in MySQLdb.NUMBER:
return 'Currency'
elif m in MySQLdb.DATE:
return 'Date'
else:
return 'Data' | 771b1c2d61214d0f376c837f93b0c452be577806 | 114,418 |
def join_byte(x, y, z):
"""Join parts of a byte: 2 bits x + 3 bits y + 3 bits z"""
return (int(x) << 3 | int(y)) << 3 | int(z) | bdcdc330802a6bf3ef5d0981bc517bed6f1b6179 | 158,963 |
def dummy_annotation_csv_file(tmpdir_factory):
"""Create csv file for testing."""
content = ("onset,duration,description\n"
"2002-12-03 19:01:11.720100,1.0,AA\n"
"2002-12-03 19:01:20.720100,2.425,BB")
fname = tmpdir_factory.mktemp('data').join('annotations.csv')
fname.writ... | 7798494d4708d29f345c07ee902634f9b8a6d49e | 526,236 |
import torch
def _pad_norm(x, implicit=False):
"""Add a channel that ensures that prob sum to one if the input has
an implicit background class. Else, ensures that prob sum to one."""
if implicit:
x = torch.cat((1 - x.sum(dim=1, keepdim=True), x), dim=1)
return x | 4439886e811d2a1e6d5241edc6cc39f0f645019b | 637,330 |
from typing import List
from pathlib import Path
import torch
def average_checkpoints(filenames: List[Path]) -> dict:
"""Average a list of checkpoints.
Args:
filenames:
Filenames of the checkpoints to be averaged. We assume all
checkpoints are saved by :func:`save_checkpoint`.
Retur... | d6a534dfa62d7d0d1dfab1d58f5261080e889bb9 | 662,005 |
def _unescape(value):
""" Unescape escapes in a python string.
Examples: \xFF \uFFFF \U0010FFFF \\ \n \t \r
"""
return value.encode('ascii').decode('unicode_escape') | b6cc88129bc9243d4093c79951bc84172ff5c4e7 | 494,258 |
import copy
def _make_dust_fA_valid_points_generator(it, min_Rv, max_Rv):
"""
compute the allowed points based on the R(V) versus f_A plane
duplicates effort for all A(V) values, but it is quick compared to
other steps
.. note::
on 2.74: SMC extinction implies f_A = 0. and Rv = 2.74
... | e31962b44c9148191ad73fa481c53d6896273311 | 252,366 |
from typing import Any
def terminal(v: Any) -> bool:
"""Detect terminal key ending in type other than non-empty dict or list."""
if isinstance(v, (dict, list)):
if v:
return False
return True | 522656cea231c0dbd5b8acfe4f9c642c32c669bb | 154,024 |
def interpret_flags(bitmask, values):
"""
Args:
bitmask: flags to check
values: array of tuples containing (value, description) pairs
Returns: string containing descriptions of flags
"""
return ', '.join(desc for num, desc in values if num & bitmask) if bitmask else None | 54835ff7d5823e0ab69772a7116b52cc1f45cd4f | 379,825 |
def split_by_unicode_char(input_strs):
"""
Split utf-8 strings to unicode characters
"""
out = []
for s in input_strs:
out.append([c for c in s])
return out | 290bb5ec82c78e9ec23ee1269fe9227c5198405e | 11,347 |
def show_fact_sheet_a(responses, derived):
"""
If the claimant is claiming special extraordinary expenses, Fact Sheet A is
indicated.
"""
return responses.get('special_extraordinary_expenses', '') == 'YES' | 551ddb54706d1f107f040ab9a8d14e4c77dd3fe6 | 169,582 |
import requests
import json
def pingCOWIN(date,district_id):
"""
Function to ping the COWIN API to get the latest district wise details
Parameters
----------
date : String
district_id : String
Returns
-------
json
"""
url = "https://cdn-api.co-vin.in/api/v2/appointme... | 65b6d994a01de601c5974ebd78fe05d8281ae7f6 | 327,255 |
def _geom_sum(r, n):
"""Computes sum of geometric series.
Use n=float('inf') for infinite series.
"""
return (1 - r**(n + 1)) / (1 - r) | 166210ad0c2de6d3be072874dcc7e1634e52361a | 182,462 |
def timezone_format(value):
""" Check the value of the timezeone offset and, if postive, add a plus sign"""
try:
if int(value) > 0:
value = '+' + str(value)
except:
value = ''
return value | e6abafec8c66b3891bba33a5f1110a4a406e9777 | 645,975 |
import time
def log_tail(contents=''):
"""return a string, which can be write to the tail of a log files"""
s = '================================================================\n'
s += '[time] ' + time.asctime(time.localtime()) + '\n'
s += '[program finish succeed!]\n'
s += contents
s += '=... | f03c68285ea8cf335a7eb8475085501eeb1c1eee | 669,398 |
def tel_type(items):
"""Return 1 if phone is ground or 2 if cellphone."""
ground_prefixes = ['12', '13', '14', '15', '16', '17', '18', '22', '23', '24',
'25', '29', '32', '33', '34', '41', '42', '43', '44', '46',
'48', '52', '54', '55', '56', '58', '59', '61', '62',... | 96dbb22f0d6845a3843d80155c4bd86ad0d70a03 | 326,577 |
def make_comment(dictobj, fieldname):
"""Render a dict's field to text.
Return
'<fieldname>: <dictobj["fieldname"]>' or ''
"""
return "{0}: {1}\n\n".format(fieldname, dictobj[fieldname]) if \
fieldname in dictobj and dictobj[fieldname] != "" else "" | d0580ec938ccf868a78d19a0bd9bd075f816abb7 | 426,018 |
def pretty_size(size, unit=1024):
"""
This function returns a pretty representation of a size value
:param int|long|float size: the number to to prettify
:param int unit: 1000 or 1024 (the default)
:rtype: str
"""
suffixes = ["B"] + [i + {1000: "B", 1024: "iB"}[unit] for i in "KMGTPEZY"]
... | abeafa97d45212c0170b981e9448e63acc1a54d2 | 17,914 |
def get_parent(vmfs):
""" From a set of VMFs, determines which one has the lowest map version
number, and is therefore the parent.
"""
# This avoids the need to subscript and slice.
vmfs = iter(vmfs)
parent = next(vmfs)
lowestRevision = parent.revision
for vmf in vmf... | bae83d2e02edc835c533873994285870246c7623 | 38,298 |
import re
def get_isotopes(ratio_text):
"""
Regex for isotope ratios.
Parameters
-----------
ratio_text : :class:`str`
Text to extract isotope ratio components from.
Returns
-----------
:class:`list`
Isotope ration numerator and denominator.
"""
forward_isotop... | 21268b3c115c487d5888f583ae5101baaf6cb18c | 263,505 |
import math, random
def split_list(data, splits={'train': 8, 'test': 2}, shuffle=True, seed=0):
"""
Split the list according to a given ratio
Args:
data (list): a list of data to split
splits (dict): a dictionary specifying the ratio of splits
shuffle (bool): shuffle the list befo... | d9b25512e666a03ec2b589850c47a45231b279a0 | 7,053 |
def count_total_deaths(D):
"""Returns total number of deaths."""
return D[-1] | c5884d13913a99c2114e06a06414c3495e4d3285 | 238,532 |
def get_full_hitmask(rect):
"""
Returns a completely full hitmask that fits the image,
without referencing the images colour_key or alpha.
"""
mask = []
for x in range(rect.width):
mask.append([])
for y in range(rect.height):
mask[x].append(True)
return mask | 3bd028a1bb15e4633ece70038b621e228e4bbfde | 566,396 |
def get_pep_dep(libname: str, version: str) -> str:
"""Return a valid PEP 508 dependency string.
ref: https://www.python.org/dev/peps/pep-0508/
"""
return f"{libname}{version}" | 2cfb972c038b56a4d9055fe3e32c4c50f7e2e02e | 249,835 |
def db_model_exists(conn, experiment, fold):
"""
Check if model already exists in database.
Args:
conn: Sqlite3 connection object.
experiment: Experiment name.
fold: Fold number.
Returns:
True if model exists, False otherwise.
"""
cur = conn.cursor()
for _ ... | bea8b102b96d62ef9020bf2fecd35345cdb6bfc3 | 509,971 |
def get_average_age(ages):
"""
Get the average age from a dictionary of age counts.
Args:
ages (dict): dictionary of age counts
Return:
float: The average age given the age count.
"""
average_age = 0
total_population = sum(ages.values())
for a in ages:
average_a... | ca09dd7ec9db75cc3a09e01733c97c4aa4fa80a5 | 166,032 |
def add_edges(graph, edges):
"""Add edge(s) to graph
Args:
graph (Graph): Graph to add edge(s) to
edges (list): List of edges
Returns:
Graph: Return the modified graph
"""
for e in edges:
if isinstance(e[0], tuple):
graph.edge(*e[0], **e[1])
els... | ad1f1320712175b125d37ca50f50f716a5e6c9f4 | 427,815 |
from typing import Union
def clean_base64(value: Union[str, bytes]) -> bytes:
"""
Force bytes and remove line breaks and spaces.
Does not validate base64 format.
:raises ValueError:
:raises TypeError:
"""
if isinstance(value, bytes):
value_base64_bytes = value
elif isinstanc... | e22d589d11c8bf3df680f8cb3a9893c5224010d0 | 367,905 |
def hex_to_rgb(color):
""" "#FFFFFF" -> [255,255,255] """
return [int(color[i:i+2], 16) for i in range(1, 6, 2)] | a16c55c0b9ea0eeea5da4f8b9f17b93969a7247f | 204,941 |
def _validate_dict(s, accept_none=False):
"""
A validation method to check if the input s is a dictionary otherwise raise error if it is not convertable
"""
if s is None and accept_none:
return None
if isinstance(s, dict):
return s
else:
raise ValueError('{} is not a dictionary!'.format(s)) | 8834142153fa2cb71d4a76e6a977324a698b8723 | 621,234 |
import six
def set_show(plotdata):
#------------------------------------------------------------------
"""
Determine which figures and axes should be shown.
plotaxes._show should be true only if plotaxes.show and at least one
item is showing or if the axes have attribute type=='empty', in which
ca... | 4f674bc3e05ad78831e0e6de818e66b2803fed71 | 609,732 |
def alpha_check(word, target_s):
"""
This function will check if every alphabets of word in target_s
:param word: str, a word want to check alphabets
:param target_s: str, a string of alphabet wanted.
:return: bool, if every alphabets of word in target_s
"""
for alpha in word:
if alp... | c921c5e3e62cd2827dbb11f9b692b7e0c4fc229c | 202,787 |
def flat(*nums):
"""
Build a tuple of ints from float or integer arguments.
Useful because PIL crop and resize require integer points.
"""
return tuple(int(round(n)) for n in nums) | f96681e8f075a4c7f51c8d735ead3fc7f61768df | 261,830 |
def is_succeeded(status, **_):
"""For when= function to test if a pod has succeeded."""
return status.get('phase') == 'Succeeded' | 508d6d0e8d7ef97785a8d0517f449850e810175e | 615,495 |
def imf_flat(x):
"""
Compute a flat IMF (useful for simulations, not for normal BEAST runs)
Parameters
----------
x : numpy vector
masses
Returns
-------
imf : numpy vector
unformalized IMF
"""
return 1.0 | 810c0aab54c98ada3e68ea11a0fcd64ba680279d | 399,130 |
def finite_diff_kauers(sum):
"""
Takes as input a Sum instance and returns the difference between the sum
with the upper index incremented by 1 and the original sum. For example,
if S(n) is a sum, then finite_diff_kauers will return S(n + 1) - S(n).
Examples
========
>>> from sympy.series.... | 224e91b82c01acc5fb781acb72d8af18f9b08f63 | 275,581 |
def join_columns_with_divider(table, decorator):
"""Join each line in table with the decorator string between each cell"""
return [decorator.join(row) for row in table] | 3c87f1ccbd6ee58dac7e4375f8eb50d61fa22388 | 599,126 |
def get_agents_with_name(name, stmts):
"""Return all agents within a list of statements with a particular name."""
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] | f9936596754264d9047bd106ac9bfd7328c3d53c | 563,034 |
def _split_dataset_id(dataset_id):
"""splits a dataset id into list of values."""
return dataset_id.split("|")[0].split(".") + [(dataset_id.split("|")[1])] | 9a1c3d23af502fd21db3de9485cfcdb75d84ba6d | 694,076 |
def add_notice_to_docstring(
doc, instructions, no_doc_str, suffix_str, notice):
"""Adds a deprecation notice to a docstring."""
if not doc:
lines = [no_doc_str]
else:
lines = doc.splitlines()
lines[0] += ' ' + suffix_str
notice = [''] + notice + [instructions]
if len(lines) > 1:
# Make ... | 3e2899bbbe4162eeae9d7384778d5592fbb10c7a | 187,184 |
import re
def extract_template(pattern):
"""Extracts a 'template' of a url pattern given a pattern
returns a string
Example:
input: '^home/city
(-(?P<city_name>bristol|bath|cardiff|swindon|oxford|reading))?$'
output: 'home/city(-{})?'
"""
pattern = pattern.strip('$^')
pattern... | 4d36c5f0b6d3ac4072b376119d78b083419143c4 | 21,156 |
def _display(stats, plot=False):
"""
Take stats dictionary and display on same format as nanowrimo.
plot - make a compact plotting format
"""
if plot:
# this is a more compact format for the plot
output = \
"""
Day {current_day} / {target_time_period}
Words: {total_words_wri... | d10a3d096a7736a7fe5493823c152ea955e51491 | 143,290 |
def _get_observer_name(spec):
"""
Gives observer name from YAML short hand naming format
"""
return spec[:1].upper() + spec[1:] + "Observer" | 1e25e44fa22d59fd0292800872ce7b236fdaabe9 | 535,283 |
import base64
def bytes2hex(data: bytes) -> str:
"""Convert bytes to a hex string."""
return base64.b16encode(data).decode('ascii').lower() | 7439d46808075730efc5b37e89ed64dc8e9536da | 380,027 |
def find(iterable, selector):
"""
Return the first item in the `iterable` that causes the `selector` to return
`True`.
"""
for x in iterable:
if selector(x):
return x | d9c91ab468edd672d23af31b21008f8bfad4f86e | 269,378 |
def strip_minijail_command(command, fuzzer_path):
"""Remove minijail arguments from a fuzzer command.
Args:
command: The command.
fuzzer_path: Absolute path to the fuzzer.
Returns:
The stripped command.
"""
try:
fuzzer_path_index = command.index(fuzzer_path)
return command[fuzzer_path_in... | a6ed7e60a685dddfcd14e2b65fb3996de8ef9443 | 151,463 |
def make_f_beta(beta):
"""Create a f beta function
Parameters
----------
beta : float
The beta to use where a beta of 1 is the f1-score or F-measure
Returns
-------
function
A function to compute the f_beta score
"""
beta_2 = beta**2
coeff = (1 + beta_2)
def... | f0e6993ac956171c58415e1605706c453d3e6d61 | 4,901 |
def indent(s, N=4):
"""indent a string"""
return s.replace("\n", "\n" + N * " ") | 78f33d0c6c01417400525196867573a3ff2ae158 | 495,412 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.