content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def domain_str_to_labels(domain_name):
"""Return a list of domain name labels, in reverse-DNS order."""
labels = domain_name.rstrip(".").split(".")
labels.reverse()
return labels | 63743ac059f20d0bdda7a5ada54605cdeb50bc98 | 63,082 |
def check_match(list1, list2):
"""
Check whether two lists of sites contain the same sites between the two lists
Args:
:param list1: (List) list of sites
:param list2: (List) list of sites
:return: (boolean) whether list1 and list2 have the same sites within them
"""
if set(list1) == set... | 7d8b8533ff96ec50cf3c14be3535d8ce01fb8371 | 63,083 |
def format_rest_framework_validation_errors(errors):
"""Format error messages for response.
Args:
errors (dict): Dictionary of rest framework validation errors.
Returns:
dict: {field: error message}
"""
if isinstance(errors, list):
return ". ".join(str(e) for e in errors)
... | 6ce2439428e6a8198bc8cd6806d395507fb66514 | 63,084 |
from typing import Union
def median(nums: list) -> Union[int, float]:
"""
Find median of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Median
>>> median([0])
0
>>> median([4, 1, 3, 2])
2.5
>>> median([2, 70, 6, 50, 20, 8, 4])
8
Args:
nums: List of nums
R... | 4f289718103f39e69257b3185d7f72242a47d928 | 63,089 |
def filter_dictionary(function, dictionary, by="keys"):
"""Filter a dictionary by conditions on keys or values.
Args:
function (callable): Function that takes one argument and returns True or False.
dictionary (dict): Dictionary to be filtered.
Returns:
dict: Filtered dictionary
... | 90677661923f6c2a4ed5ad5e0b119c700ef42282 | 63,098 |
def _remove_trailing_hr_tag(*, markdown: str) -> str:
"""
Remove a trailing `<hr>` tag from a specified markdown string.
Parameters
----------
markdown : str
Target markdown string.
Returns
-------
markdown : str
Result markdown string.
"""
markdown = markdown.s... | 9698c8fc98710e106008164879726ae37db13f88 | 63,100 |
def sort_unique(alist):
""" Sorts and de-dupes a list
Args:
list: a list
Returns:
list: a sorted de-duped list
"""
return sorted(list(set(alist))) | 32685421cd1b7a708447b173bb03ee6bbcad32f0 | 63,104 |
def _Backward2b_P_hs(h, s):
"""Backward equation for region 2b, P=f(h,s)
Parameters
----------
h : float
Specific enthalpy [kJ/kg]
s : float
Specific entropy [kJ/kgK]
Returns
-------
P : float
Pressure [MPa]
References
----------
IAPWS, Revised Supp... | 66f5fab41d001dc5e47671ec8731d3a383eafaaf | 63,106 |
from typing import Dict
from typing import Any
def build_config(config : Dict[str, Any]) -> Dict[str, str]:
"""Will build the actual config for Jinja2, based on SDK config.
"""
result = config.copy()
# Manage the classifier stable/beta
is_stable = result.pop("is_stable", False)
if is_stable:
... | 4e3189443d7638a1b290666d52675f6874c19ab6 | 63,110 |
import unicodedata
def character_categories(text, normalize=None):
"""Return the list of unicode categories for each character in text
If normalize is not None, apply the specified normalization before
extracting the categories.
"""
if normalize is not None:
text = unicodedata.normalize(n... | b5d85425bc65951bccf9fe578918905b522c6801 | 63,114 |
def getDepthError(depth):
"""
Return the absolute error in a depth value from a TrueDepth sensor, which
varies depending on the depth value. These are OBSERVED values from my
experimentation in phase 2 data collection.
Parameters
----------
depth : number
The depth value reported by... | 7d84cd7eff740efc98d53f01cca71782c1a89d91 | 63,115 |
def get_camera_info_from_image_topic(topic):
"""
Returns the camera info topic given an image topic from that camera
"""
topic_split = topic.split('/')
info_topic = topic_split[:-1]
info_topic.append('camera_info')
info_topic = '/'.join(info_topic)
return info_topic | 3f3cce68dc8fa467ad2bb740f3dbc937d3825c5d | 63,117 |
def charLimit(min: int, max: int, char, string):
"""Ensure that the count of occurrences of char in string lies between min and max"""
if max < min:
raise(ValueError('max less than min.'))
total = string.count(char)
return total <= max and total >= min | 8dd0e91673f2b3bd587a86df7aac7fa0abc22148 | 63,118 |
def solution(resources, args):
"""Problem 1 - Version 3
Use a formula to determine the additional sum 15 integers at a
time, then use the iterative approach for any remaining integers
in the range.
Parameters:
args.number The upper limit of the range of numbers over
... | 94a3b457d68e010c235a43e6e287821f5831d8ce | 63,120 |
import itertools
def ranges_overlap(ranges):
"""Test if ranges overlap
Args:
ranges (list): Iterable of pairs (min, max)
Returns:
bool: True if ranges overlap each other, False otherwise
"""
for r1, r2 in itertools.combinations(ranges, 2):
if r1[1] > r2[0] and r1[0] < r2[... | 742825a4abd53a14d9eb5a62375620aa335aee50 | 63,121 |
def grad_rescale(grads, k):
"""scale the gradient by a factor of k"""
y = grads.deepcopy()
for item in y:
item[:] = item * k
return y | a69570888e5924de87714f6c355e4c854b8b647f | 63,122 |
def seq(start, stop, step=1):
"""Generate a list of values between start and stop every step
:param start: The starting value
:param stop: The ending values
:param step: The step size
:return: List of steps
"""
n = int(round((stop - start) / float(step)))
if n > 1:
return [start ... | 9471500a1dc13cde41beaad31092f7b00c771cca | 63,125 |
import re
def preprocess(text, to_lower=True, remove_tags=True, digits=True, special_chars=True):
"""
Takes a text object as input and performs a sequence of processing
operations: lowercases , removes html tags and special characters
Parameters
----------
text: str
Text to be cleaned... | 086d6bc4918e9ad39d9eed3f512ed661b90da6c8 | 63,126 |
def get_the_number_of_pages(total_data, limit_size):
"""根据数据总数和每页显示数据数计算分页数
Args:
total_data 数据总数
limit_size 每页显示数据条数
"""
quotient, remainder = divmod(total_data, limit_size)
if remainder > 0:
quotient = quotient + 1
return quotient | 0d3ff3de0c6355e623d091d71a3ab9dc3c085d01 | 63,135 |
def s3_download(s3_bucket, file_key, output_path):
"""Download a file from S3."""
print(f"downloading [{file_key}] from [{s3_bucket.name}] to [{output_path.resolve().as_posix()}]")
s3_bucket.download_file(file_key, output_path.resolve().as_posix())
return output_path | 8a966b6f0230ffe037d054d798e05ff462036dbd | 63,139 |
def x2cx(x, e):
"""Transform from *x* value to column *x* index value, using the
*e.css('cw')* (column width) as column measure."""
# Gutter
gw = e.gw
cw = e.css('cw', 0)
# Check on division by 0
if cw + gw:
return (x - e.parent.pl) / (cw + gw)
return 0 | f2ac3a87589ded75e22c5aadfd5a95767c1d038e | 63,140 |
import re
def get_iter_num(fname):
"""Extracts the iteration number from the filename"""
matches = re.match(r"^iter_(\d+).csv$", fname)
if matches is None:
return None
return matches.group(1) | a150aad1333bb61fd6bb01e37aee00df6d28b542 | 63,141 |
import re
from datetime import datetime
def format_date(row):
""" Extracts the unix timestamp from the string and converts it to a datetime object, best if used with map
:param row: row from a dataframe """
row=str(row)
unix = [int(s) for s in re.findall(r'-?\d+\.?\d*', row)]
dt_object = datetime.... | b9c3fc5445e7e9985b62ace145faece86576dd25 | 63,144 |
def adapt_dbm_reset_ast(dbm_reset_ast):
"""Transforms the expression ast of a reset into a clock reset ast.
Args:
dbm_reset_ast: The reset expression ast.
Returns:
The clock reset ast.
"""
clock = dbm_reset_ast["expr"]["left"]
val = dbm_reset_ast["expr"]["right"]
return {"c... | 7614c2a4edfa3c6c4b7b728de1604f8ca6e81553 | 63,148 |
def convert_words_to_string(paragraph_words):
"""
Convert the resulting list of words aka a paragraph into a string
"""
word_texts = []
for paragraph_word in paragraph_words:
word_texts.append(''.join([
symbol.text for symbol in paragraph_word.symbols
]))
return ' '.j... | 59e2485a7c03027d697a91928a67a079cba26f18 | 63,150 |
def is_palindrome(s):
"""Returns boolean test of whether s is a palindrome."""
for i in range(len(s)):
if s[i] == s[len(s) - 1 - i]:
continue
else:
return False
return True | 1371e62988a9e1d5754d40e5a2e85e48ff9d9a2d | 63,152 |
def check_format(path):
"""Check if a file is an Tripos MOL2.
Check for "@<TRIPOS>"
Parameters
----------
path : str or Path
"""
result = True
with open(path, "r") as fd:
for line in fd:
line = line.strip()
if "@<TRIPOS>" in line:
result ... | 1fc8ab1f5669bf0a9d6a38063bd2ddf03a5bdcef | 63,158 |
import time
def get_timestamp() -> int:
"""
Return the current millisecond timestamp.
Return
------
ts : number
milliseconds since the epoc
"""
ts = int(time.time() * 1000)
return ts | 663945a97a418bb54850ad913a72b7955f5dbff0 | 63,160 |
def nonNullIntersection(dataList):
"""
Takes a list of dataframes and returns the list of dataframes with rows that contain a null value in
any dataframe removed. This is so that the row can be used for training ML Powerflow
Input:
dataList: a list of pandas dataframes of the same number of row... | 845d153a0f3df1bd3e00a1c61c12b66eef3f3cfa | 63,163 |
def sum_multiples(num1,num2,limit):
"""take two numbers and find the sum of their multiples from 1 to some upper limit. this DOES NOT double-count numbers which are multiples of BOTH num1 and num2."""
sum = 0
if num1 > limit and num2 > limit:
return sum
for i in range(1,(limit+1)):
if i % num1 == 0 or i % num... | 0966730d3ac650bf46914b6a5b76df62edd93a24 | 63,164 |
import binascii
def unhexlify(text):
"""Unhexlify raw text, return unhexlified text."""
return binascii.unhexlify(text).decode('utf-8') | 81927f86c07e77894a9f47bb9e444caad0ef75b5 | 63,165 |
def find_duplicates(iterable):
"""Find duplicate elements in an iterable.
Parameters
----------
iterable : iterable
Iterable to be searched for duplicates (i.e., elements that are
repeated).
Returns
-------
set
Repeated elements in `iterable`.
"""
# modifie... | b5d5bc6b85cd2cfafe3bd0f88ef2daa0e28e538e | 63,166 |
import re
def find_substring(substring, string):
"""
Find a substring inside a string and return it.
If there is no match, return 0.
Args:
substring (str): Substring to find (supports regex)
string (str): String to search
Returns:
match (str): The first occurence of the s... | dd3e8d2187454aa69e9c4d59404a5a87b6d813f8 | 63,167 |
def isPrime(n: int)->bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
A no. is prime if it is divisible only by 1 & itself.
1- is neither Prime nor Composite
We will use Naive approach.
. Check Divisibity of n with all numbers smaller tha... | 57eddd0aba0d53faa6ee1f4f5ff566a1c3b3ef85 | 63,172 |
def overlaps(tupl1, tupl2):
"""
Takes two ranges as tuples and returns a boolean
determining if they overlap inclusively
Parameters:
r1, r2 - a tuple range
"""
return (tupl1[0] <= tupl2[0] <= tupl1[1]) or (tupl1[0] <= tupl2[1] <= tupl1[0]) | 145cbf7a75ae619e848427169377752532735861 | 63,174 |
def cols_to_drop(statistic, threshold, greater):
"""
Compiles a list of columns to be dropped by drop_cols(), using the given
summary statistics.
Parameters:
_________________
statisic: Statistic to use for feature evaluation; should have
<lr_model>.summary.<statisti... | 70f6b225950affbc5156d4d25f531d62e60cb8e0 | 63,177 |
def mix_string (str):
"""Convert all string to lowercase letters, and replaces spaces with '_' char"""
return str.replace(' ', '_').lower() | 5e07f99b0222cd9d31b692aadb638878a9b502a6 | 63,178 |
def precision_at(k):
"""Returns a function operating on a data frame, which calculates P@k"""
return lambda s: s[:k].sum() / s[:k].count() | 089bbb9e10a1025faa195ae8411ad5fb0f3f1eb4 | 63,186 |
from textwrap import dedent
def skip_comment(line):
"""Return True if a comment line should be skipped based on contents."""
line = dedent(line)
return not line or "to_remove" in line or "uncomment" in line.lower() | beda4e72faee0b062ddf6a12b3d449c884554127 | 63,191 |
def device_settings(string):
"""Convert string with SoapySDR device settings to dict"""
if not string:
return {}
settings = {}
for setting in string.split(','):
setting_name, value = setting.split('=')
settings[setting_name.strip()] = value.strip()
return settings | ef16df671bea6247be35b1256b13951cda91290a | 63,192 |
def v_equil(alpha, cli, cdi):
"""Calculate the equilibrium glide velocity.
Parameters
----------
alpha : float
Angle of attack in rad
cli : function
Returns Cl given angle of attack
cdi : function
Returns Cd given angle of attack
Returns
-------
vbar : float... | 16bd758f7349dd7c79a8441118191155730b1644 | 63,194 |
def gcd(a, b):
""" Find greatest common divisior using euclid algorithm."""
assert a >= 0 and b >= 0 and a + b > 0
while a > 0 and b > 0:
if a >= b:
a = a % b
else:
b = b % a
return max(a, b) | 33be26cdb143df526ade519a0f0e3a216e9d3529 | 63,195 |
import math
def dwpf(tmpf, relh):
"""
Compute the dewpoint in F given a temperature and relative humidity
"""
if tmpf is None or relh is None:
return None
tmpk = 273.15 + (5.00 / 9.00 * (tmpf - 32.00))
dwpk = tmpk / (1 + 0.000425 * tmpk * -(math.log10(relh / 100.0)))
return int(fl... | 49031b6fb76f0311ec2554aae01671b2b935eaf7 | 63,198 |
def normalize_TPU_addr(addr):
"""
Ensure that a TPU addr always has the form grpc://.*:8470
:param addr:
:return:
"""
if not addr.startswith("grpc://"):
addr = "grpc://" + addr
if not addr.endswith(":8470"):
addr = addr + ":8470"
return addr | a3b7dfb0fd603b7fd4a7f665f66c7465f5738e53 | 63,210 |
from typing import Union
def convert_indent(text: str, old_indent: Union[int, str], new_indent: Union[int, str]) -> str:
"""
Changes the indent of the lines in a text.
Note: empty lines will be unaffected.
Args:
text: The text to be processed.
old_indent: The indent to remove, given ... | 9829c96447daf99b2d7ac458ed64ef28b4c5a07f | 63,217 |
def load_urls(username: str, location: str = "./Resources/url_blueprints.txt") -> list:
"""
Loads the urls from the specified blueprint file and sets the username as well
:param username
:param location
:return: lisitfied urls with added usernames
"""
final_list = []
with open(location) ... | 40ad91207cfaa19f18f74cf1a61f6c68603658c3 | 63,221 |
def get_filename(path):
"""
a helper function to get the filename of an image.
This function splits a path provided by the argument by '/'
and returns the last element of the result
"""
return path.split('/')[-1] | 8a1a600216f45035dcd5b249df9511a303da634d | 63,222 |
def args_to_tuple(*args):
"""Combine args into a tuple."""
return tuple(args) | 571367c75f0a77d8a40c7383bb075c05acc6307c | 63,226 |
def is_hex_digits(entry, count):
"""
Checks if a string is the given number of hex digits. Digits represented by
letters are case insensitive.
:param str entry: string to be checked
:param int count: number of hex digits to be checked for
:returns: **True** if the given number of hex digits, **False** oth... | 78df1fb5fca790967de9a94c7cd76143f7ecc23b | 63,228 |
def weight(edge, modifiers):
"""
Gets the modified weight of the edge.
Args:
edge (DirectedEdge): Edge to get weight from.
modifiers (list): A list of objects that modify the edge weight.
These objects must support get_multiplier(edge).
"""
weight = edge.weight
for m... | 6ec9bc1fff3ea74cfcea5401c6f33376180f8830 | 63,232 |
import time
def wait_for_victim_pg(manager):
"""Return a PG with some data and its acting set"""
# wait for some PG to have data that we can mess with
victim = None
while victim is None:
stats = manager.get_pg_stats()
for pg in stats:
size = pg['stat_sum']['num_bytes']
... | 49b1977f6032ce883fffa8402760e7eb83e90b4a | 63,233 |
def bfs_shortest_path_print(graph, x, y):
"""Return shortest path between nodes x and y."""
visited = []
q = [[x]]
while q:
path = q.pop(0)
node = path[-1]
if node not in visited:
for adjacent in graph[node]:
new_path = list(path)
new_... | 65c6b276cf09b6d37de69c317a8c012eb82ffe89 | 63,236 |
def fedoralink_streams(obj):
"""
Return an iterator of tuples (field, instance of TypedStream or UploadedFile)
that were registered (via setting an instance of these classes
to any property) with the object.
:param obj: an instance of FedoraObject
:return: iterator of tuples
"""
retu... | 98442702798d1f152e98f165104890d5329078c3 | 63,241 |
def sumTuple(tList, index):
"""This function takes in the list of tuples, and the index of the tuple
It then returns the sum of all of this numbers in that specific tuple index"""
_allNums = [x[index] for x in tList]
return sum(_allNums) | b680c7cd43226a01dd19608a346fecbeed31baac | 63,243 |
def get_key_to_hash(prefix, *args, **kwargs):
"""Return key to hash for *args and **kwargs."""
key_to_hash = prefix
# First args
for i in args:
key_to_hash += ":%s" % i
# Attach any kwargs
for key in sorted(kwargs.keys()):
key_to_hash += ":%s" % kwargs[key]
return key_to_hash | 08577a67e377e2ed5fdb067e54ca4ec56ec3c0b9 | 63,247 |
def check_tr_id_full_coverage(tr_id, trid2exc_dic, regid2nc_dic,
pseudo_counts=False):
"""
Check if each exon of a given transcript ID is covered by > 0 reads.
If so return True, else False.
>>> trid2exc_dic = {"t1" : 2, "t2" : 2, "t3" : 1}
>>> regid2nc_dic = {"t1_e1":... | 7f8ec307a6faf09b6d22c9d0d1c63b1d0a181c8e | 63,248 |
def _range_exhausted(i, values, steps, stops):
"""
Check if a range at i is exhausted.
"""
return steps[i] * (values[i] - stops[i]) >= 0 | e5d6f781f5f005c248ece87dff3c26c7e10cbd22 | 63,249 |
def send_email(service, user_id, message):
"""
Send an email via Gmail API
:service: (googleapiclient.discovery.Resource) authorized Gmail API service instance
:user_id: (str) sender's email address, used for special "me" value (authenticated Gmail account)
:message: (base64) message to be sent
"""
try:
mes... | e80aeb05d0d5a43b54a892a49b496ffb007f6879 | 63,260 |
def convert_to_type(value, value_type, default_value=None):
"""
Try to convert 'value' to type
:param value: The value to convert
:param value_type: The type to convert to eg: int, float, bool
:param default_value: The default returned value if the conversion fails
:return:
"""
try:
... | 828ed0d60dcdfd4f134a1e9c2377c921424bacce | 63,262 |
from typing import Sequence
from typing import Union
import re
def _parse_problem_sizes(argument: str) -> Sequence[Union[int, Sequence[int]]]:
"""Parse a problem size argument into a possibly nested integer sequence.
Examples:
64,128 -> [64, 128]
32,32,[1,1] -> [32, 32, [1, 1]]
"""
problem_sizes = []
w... | 9ac8055a4cfb26d11d19cba2de58d1b797fc2125 | 63,263 |
def extract_eyeid_diameters(pupil_datum):
"""Extract data for a given pupil datum
Returns: tuple(eye_id, confidence, diameter_2d, and diameter_3d)
"""
return (
pupil_datum["id"],
pupil_datum["confidence"],
pupil_datum["diameter"],
pupil_datum.get("diameter_3d", 0.0),... | bb935b2c7280e3f30a274d4cd7ba22f5a5f80c2c | 63,264 |
def property_initialization(property_type, name):
"""Generate the property initialization for __init__()."""
return f' self._{name} = {property_type}()\n' | 44ed1ae42f153890a0ab8559b279fea700ab462c | 63,267 |
import re
def sanitize_file_path(file):
"""
Replaces backslashes with forward slashes and removes leading / or drive:/.
:param file: Relative or absolute filepath
:return: Relative or absolute filepath with leading / or drive:/ removed
"""
# Sanitize all backslashes (\) with forward slashes (... | 73694f4365c7cdf12b13d3b4841438562fa0bd40 | 63,268 |
def index_bisect(inlist, el):
"""
Return the index where to insert item el in inlist.
inlist is assumed to be sorted and a comparison function (lt or cmp)
must exist for el and the other elements of the list.
If el already appears in the list, inlist.insert(el) will
insert just before the leftmo... | e3db6d444706dcd6f7bd5002479dbfe9cfe6bffc | 63,269 |
def plane_edge_point_of_intersection(plane, n, p0, p1):
"""
Finds the point of intersection between a box plane and
a line segment connecting (p0, p1).
The plane is assumed to be infinite long.
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices defining the plane
n: t... | 8737be3bde6fd81299b869d3dd12406b6382230f | 63,270 |
import functools
def keep_tc_pos(func):
"""
Cache text cursor position and restore it when the wrapped
function exits.
This decorator can only be used on modes or panels.
:param func: wrapped function
"""
@functools.wraps(func)
def wrapper(editor, *args, **kwds):
""" Decorato... | 446ef8a684925c8dd209085ed91315a62d6462f1 | 63,273 |
def _rng_zero(x):
"""Return zero scalar, according to sensitivity_transform."""
return 0 | 6c8c805b37391b4577349cf1d9aaceacbba06b11 | 63,284 |
import re
def remove_version(code):
""" Remove any version directive """
pattern = r'\#\s*version[^\r\n]*\n'
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
return regex.sub('\n', code) | 0072e85aaa8787db0728131b3038d62d899d2e38 | 63,287 |
import random
def ShuffleList(feature, label):
"""
Shuffle list
:param feature: the feature to train model, which is a list
:param label: the label of the feature, which is a list
:return: the shuffled feature and label
"""
randIndex = [a for a in range(len(feature))]
random.shuffle(ra... | 291b5e5741f1a837c9777feba1622ef332818abb | 63,288 |
def replace_repeated_characters(text):
"""Replaces every 3+ repetition of a character with a 2-repetition."""
if not text:
return text
res = text[0]
c_prev = text[0]
n_reps = 0
for c in text[1:]:
if c == c_prev:
n_reps += 1
if n_reps < 2:
res += c
else:
n_reps = 0
... | 15d11aa94d6da43f1d3f17c7077cda883b788780 | 63,291 |
def whatis(seizure):
"""
Détermine si une entrée est un montant, une date ou un mode de paiement.
"""
seizure = seizure.replace(" ", "") # pour reconnaître le montant si il contient un espace
try:
seizure = float(seizure)
return "amount"
except ValueError:
try:
... | ccbb5a3feda0b4d8542fdca7cadce2e9240e485b | 63,292 |
def metabase_metadata_db_alias() -> str:
"""The db alias of the Metabase metadata database"""
return 'metabase-metadata' | b7ec73635633b1294b6548fec21bafa787869510 | 63,293 |
def wrap_filter(hook, filter_fn):
"""
takes in a hook and only applies it when the given filter function
returns a truthy value
"""
def wrap_filter_inner(hs):
if filter_fn(hs):
return hook(hs)
else:
return hs()
return wrap_filter_inner | 63048037dd1dc865de2cb98eda972191d6c14ff5 | 63,299 |
from typing import List
from typing import Dict
def gen_header(head: List[str]) -> Dict:
"""
This is a helper function meant to generate a dictionary that contains parsing information
for csvs. I.e. it stores how to manage datetimes, integers and floats. Strings are pretty much
ignored.
>>> gen_h... | 314bf2e2b7451ab7a83352fb4edb947bf5bf2c21 | 63,301 |
def pivot_bulk_data(data, values='log2_rpkm'):
"""
take long format expression data and pivot to a wider (subject x region) x gene dataframe
data: long format dataframe (gene x region x subject) x rpkm
values: metric of interest to create a (region x subject) x gene matrix of metrics
returns:
... | 7c72d1ad87649d3a541f2559266964581662c7e3 | 63,312 |
def get_cal_name(cal_id, service, http):
"""
Retrieve the name (summary) for a calendar.
@param cal_id: str, calendar id
@return: str, calendar name
"""
response = service.calendars().get(calendarId=cal_id).execute(http=http)
return response['summary'] | a57a0ea045914abcf3840bf82f0ecccf2ff540fb | 63,314 |
def _text(e):
""" Try to get the text content of this element """
try:
text = e.text_content()
except AttributeError:
text = e
return text.strip() | f447c9e189a587aab61ec1ae1d6437d0a607e381 | 63,315 |
def diff_identifiers(a, b):
"""Return list of tuples where identifiers in datasets differ.
Tuple structure:
(identifier, present in a, present in b)
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples where identifiers in datasets dif... | 5e08802654ed6da8bfb4f2850a8733c5548f9d75 | 63,317 |
def GetLiteral(parser, name):
"""Returns the literal with the given name, removing any single quotes if they exist"""
value = parser.literalNames[name]
if value.startswith("'"):
value = value[1:]
if value.endswith("'"):
value = value[:-1]
return value | 2299d22db9cfd4f2734ca3e8890c2748c288c7fe | 63,319 |
import math
def _radians_to_angle(rad):
"""
Convert radians into angle
:param rad:
:return: angle
"""
return rad * 180 / math.pi | f88aa0a2da9f0dd31a0576afcd1ffd80ba9eafc8 | 63,320 |
import re
def clean_whitespace(text: str) -> str:
"""
Replace all contiguous whitespace with single space character,
strip leading and trailing whitespace.
"""
text = str(text or '')
stripped = text.strip()
sub = re.sub(r'\s+', ' ', stripped, )
return sub | 1744f4ea82dfc538b2e095e66a2260368c5c09ac | 63,322 |
def min_approx(x1, x2, x3, y1, y2, y3):
"""
Get the x-value of the minimum of the parabola through the points (x1,y1), ...
:param x1: x-coordinate point 1
:param x2: x-coordinate point 2
:param x3: x-coordinate point 3
:param y1: y-coordinate point 1
:param y2: y-coordinate point 2
:para... | c557478554df7143b2fe193927bf9b8933ba30e7 | 63,324 |
def generate_transition_trigram_probabilities(transition_bigram_counts, transition_trigram_counts):
"""Takes in the bigram and trigram count matrices.
Creates dictionary containing the transition trigram
probabilities in the following format:
{(tag[i-2], tag[i-1], tag[i]) : probability}
where the probability is c... | 38790b31a4f15f0efaadee87e7ba6badc4249820 | 63,325 |
def get_result_from_input_values(input, result):
"""Check test conditions in scenario results input.
Check whether the input parameters of a behave scenario results record from
testapi match the input parameters of the latest test. In other words,
check that the test results from testapi come from a t... | 421fac0d76bf0ec9a861b137db7ea6ceaf3cc92a | 63,332 |
def convert_dm_ref_zp_flux_to_nanoJansky(flux, dm_ref_zp=27):
"""Convert the listed DM coadd-reported flux values to nanoJansky.
Eventually this function should be a no-op. But presently
The processing of Run 1.1, 1.2 to date (2019-02-17) have
calibrated flux values with respect to a reference ZP=27 m... | b3eb1828a1f8621bc76bf6d8a4da2ede58b5cf2b | 63,333 |
def compress(nparray, newMax=1, newMin=0):
"""compress an numpy array, default is from range 0 to 1"""
minimum = min(nparray)
maximum = max(nparray)
if(maximum - minimum) == 0:
return nparray
return (((nparray - minimum)/ ( max(nparray) - minimum)) * newMax + newMin) | 99c67c099ee4ffc3399731674a0c376a2a8b5af2 | 63,342 |
def create_tsv(df, filename=None):
"""Convert pandas DataFrame to text-based table for SISSO.
Args:
df (pandas DataFrame): Dataframe of samples and features.
filename: Path for writing file (optional).
Returns (if filename==None):
table (string)
"""
table = df.to_string()
... | c43372835837922f21fd5131f421d295eb7298c6 | 63,343 |
from typing import Tuple
def _ingresar_coordenadas() -> Tuple[int, int]:
"""Ingreso de coordenadas.
:return: Coordenadas x e y
:rtype: Tuple[int, int]
"""
x = int(input("x: "))
y = int(input("y: "))
return x, y | 2e1f3d122ac68a6ed7f8785291f2d2310af198c9 | 63,345 |
import importlib
def _object_from_name(object_name):
"""Creates an object from its name as a python string.
Args:
object_name: the name of the object to be created as a string.
Returns: the object that the string refers to, dynamically imported.
"""
module_name, top_name = object_name.rs... | 8d5b88487c0cdac7ec6797030cdb0667e0399f97 | 63,349 |
def dist_to_conc(dist, r_min, r_max, rule="trapezoid"):
""" Converts a swath of a size distribution function to an actual number
concentration.
Aerosol size distributions are typically reported by normalizing the
number density by the size of the aerosol. However, it's sometimes more
convenient to ... | 5c6dedfa49842e32dcb246bdc1e9dfc445b304ec | 63,350 |
def fmt_option_val(option):
"""Format a single option (just a value , no key)."""
if option is None:
return ""
return str(option) | 410269228c0feb0a763edef8c0c7595ed4b22946 | 63,353 |
import json
def prepareJSONstring(message_type, data, signature=None, verification=None):
"""
Prepares the JSON message format to be sent to the Buyer
:param message_type: MENU/SESSION_KEY/DATA/DATA_INVOICE
:param data: Corresponding data
:param signature: Signed Data
:param verification: Address o... | c0db35ccb80fa1c13457358c5889cb66bd90ac76 | 63,354 |
import math
def nCr(n: int, r: int) -> float:
"""Computes nCr
Args:
n: Total number
r: Number to sample
Returns:
nCr
"""
if r > n or n < 0 or r < 0:
return 0
f = math.factorial
return f(n) // f(r) // f(n - r) | fcdaa2db1a71644faa881e18c080e655ecbfd5c2 | 63,357 |
def climbStairs(n):
"""
LeetCode 70:爬楼梯
建模为斐波那契数列问题:f(n) = f(n-1) + f(n-2)
"""
dp = [1, 2]
if n < 3: return dp[n-1]
for i in range(3, n+1):
tmp = sum(dp)
dp = [dp[1], tmp]
return dp[1] | 1f9b039a2996480cb0a6ca28d79d0076ab08eed7 | 63,358 |
def particao(a, b, N):
"""
Dados os pontos inicial $a$ e final $b$, e o número $N$
de subintervalos da partição regular desejada, esta função
retorna a partição regular com tais características, sob
a forma de uma lista
"""
lista = [a]
delta = (b - a)/N
for j in range(1, N+1):
... | e167870ffea5f45581d5f683e0d77b226ab53997 | 63,363 |
def get_compat_files(
file_paths,
compat_api_version):
"""Prepends compat/v<compat_api_version> to file_paths."""
return ["compat/v%d/%s" % (compat_api_version, f) for f in file_paths] | 1974762e850e24d0ba1a00abefebe625a3243c84 | 63,364 |
def transformed_potential_energy(potential_energy, inv_transform, z):
"""
Given a potential energy `p(x)`, compute potential energy of `p(z)`
with `z = transform(x)` (i.e. `x = inv_transform(z)`).
:param potential_energy: a callable to compute potential energy of original
variable `x`.
:par... | ec8f27658cd573bd28c77eebf34b68800f1962b4 | 63,365 |
def _hex_to_rgb(_hex):
""" Convert hex color code to RGB tuple
Args:
hex (str): Hex color string, e.g '#ff12ff' or 'ff12ff'
Returns:
(rgb): tuple i.e (123, 200, 155) or None
"""
try:
if '#' in _hex:
_hex = _hex.replace('#', "").strip()
if len(_hex) != 6:
... | ff268246dd20aa50e2fdad711811784f5c1f5de5 | 63,370 |
from datetime import datetime
def generate_report_name(report_instance):
"""
Generate a filename for a report based on the current time and attributes of an
individual :model:`reporting.Report`. All periods and commas are removed to keep
the filename browser-friendly.
"""
def replace_chars(re... | f92d54d3bb14068526b292ce36061ede001c2e97 | 63,373 |
import math
def UTM_EPSG(longitude, latitude):
"""Find UTM EPSG code of a longitude, latitude point."""
zone = str((math.floor((longitude + 180) / 6) % 60) + 1)
epsg_code = 32600
epsg_code += int(zone)
if latitude < 0:
epsg_code += 100
return epsg_code | dfdfd1df086a400cece576a54a55f20ee72d494a | 63,375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.