content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def transpose(mat):
"""transpose
matrix transpose A[i][j]=A.T[j][i]
:param mat: original matrix
:return: matrix after transpose
"""
mat_t = [[0 for y in range(len(mat))] for x in range(len(mat[0]))]
for i in range(len(mat)):
for j in range(len(mat[0])):
mat_t[j][i] = mat[... | a5aa14601aeaa7abf722cf560759820e6cce87cc | 611,047 |
def _get_api_version_from_accept_header(api_version_header: str):
"""Split input string and return the api version.
Input must be of the format:
[something];version=[some version]
:param str api_version_header: value of 'Accept' header
:returns: api version specified in the input string.
... | 7f137451d5de53e312d5172f0bdda7b9776908fc | 611,048 |
def factorial_recursion(number):
"""Calculates factorial using recursion.
:param number: A number for which factorial should be calculated.
:return: Factorial number.
>>> factorial_recursion(-1)
1
>>> factorial_recursion(0)
1
>>> factorial_recursion(1)
1
>>> factorial_recursion... | cd40bb7d16d9d51840f9991ef7798b6e91596dee | 611,050 |
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace("_", "-").split("-")[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str... | 15a87b50f3855d1a411cd3c4631ce4846b7167a8 | 611,054 |
from typing import Union
from typing import Sequence
import fsspec
def _get_fs_sep_prefix_paths(path: Union[str, Sequence[str]]):
"""Identify separator and prefix for various filesystems.
In the case of local files, prefix is set to "" if original input path
is not prefixed with the file:// prefix.
"... | 47ddf6720ad601b0a1f23231d18b02d7bf742381 | 611,055 |
def get_name_of_env_var(key: str = "") -> str:
"""Returns the name of the Xanadu Cloud environment variable associated with the given key."""
return f"XANADU_CLOUD_{key}" | 2f40a6ee10be4f85782c9c25493677bd18fd70cc | 611,057 |
def int_to_16bit(i):
"""
return an int as a pair of bytes
"""
return ((i >> 8) & 0xff, i & 0xff) | 4432252b485bf9cfd8cd4d42df533348d1d35200 | 611,063 |
def pad(bytestring, k=16):
"""
Pad an input bytestring according to PKCS#7
"""
l = len(bytestring)
val = k - (l % k)
return bytestring + bytearray([val] * val) | 5c4917619edb5203402b9370cd1a45a370ad3dc3 | 611,065 |
def serialize_str_list(name, indent, elements, line_len=78):
"""
Given a list of strings, serialize it with the specified
initial indent, with list members SQUOTEd and separated by
COMMA SPACE. Return the serialized list as a list of one or more lines,
each of length not exceeding line_len. Newlin... | b6186183a36b23c3962c83c3cf95477ac49bfbba | 611,067 |
def parse_genome_pos(genome_pos):
"""
Parse genome position in format chrom:start-end and returns the tuple
chrom, start, end
"""
if not genome_pos:
return None, None, None
chrom, pos = genome_pos.split(":")
start, end = pos.split("-")
return chrom, start, end | 61524b8efcf694bd654f05d023eb93c7a1985e4c | 611,068 |
import itertools
def dict_product(dicts):
"""
>>> list(dict_product(dict(number=[1,2], character='ab')))
[{'character': 'a', 'number': 1},
{'character': 'a', 'number': 2},
{'character': 'b', 'number': 1},
{'character': 'b', 'number': 2}]
"""
return (dict(zip(dicts.keys(), x)) for x ... | 0aaee7675fa39d9b4ff00024b945d7c4c3e25b7a | 611,069 |
def headers_add_host(headers, address):
"""
If there is no Host field in the headers, insert the address as a Host into the headers.
:param headers: a 'dict'(header name, header value) of http request headers
:param address: a string represents a domain name
:return: headers after adding
"""
... | 99c28385a48c226ef23af5b9a1a6ad67a42f630a | 611,070 |
def date_range_to_seconds(datetime1, datetime2):
"""
Computes the number of seconds between two datetime
"""
return (datetime2 - datetime1).total_seconds() | d4f3ae25ccd935b9f2757e1005e4d1935ab31907 | 611,074 |
def YilmIndexVector(i, l, m):
"""
Compute the index of a 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of a 1D array of spherical harmonic coefficients correspond... | 1d52ab91109194972b3d8409d372ed948058b232 | 611,075 |
def is_dict(klass):
""" Determine whether klass is a Dict """
return klass.__origin__ == dict | b9a487cff4182596dc3531fe45ea0c21019d06f9 | 611,076 |
import math
def _nan_equal(a, b):
"""Return True if a and b are both the same kind of NAN.
>>> _nan_equal(Decimal('NAN'), Decimal('NAN'))
True
>>> _nan_equal(Decimal('sNAN'), Decimal('sNAN'))
True
>>> _nan_equal(Decimal('NAN'), Decimal('sNAN'))
False
>>> _nan_equal(Decimal(42), Decima... | b08047b4c61ae7040bbb137882a8a4e8218a2880 | 611,078 |
def _padded_hex(i, pad_width=4, uppercase=True):
"""
Helper function for taking an integer and returning a hex string. The string will be padded on the left with zeroes
until the string is of the specified width. For example:
_padded_hex(31, pad_width=4, uppercase=True) -> "001F"
:param i: integ... | ec9cee4075acb5ea701c2151f66fa438bec5a08c | 611,083 |
def Inherit(option_obj):
"""Clone an :class:`Option` instance for the purposes of inheritance. The returned
instance has all the same properties as the input :class:`Option` and shares items
such as the default value. Use this to avoid redefinition of reused
options.
:param option_obj: :class:`Opti... | 0cb445a9fd43c67780ce7d4f264846f0f5bce863 | 611,084 |
import requests
def fetchAPI(public_api):
"""
Fetches price data from centralized public web API endpoints
Returns: (str) ticker price from public exchange web APIs
Input: (list of str) public api endpoint with any necessary json parsing keywords
"""
try:
# Parse list input
end... | 2213ec423d343abc0302d76f5093d135e800f9ee | 611,085 |
def extract_times_from_records(simulation_records, warm_up_time):
"""Get the required times (waiting, service, blocking) out of ciw's records
where all individuals are treated the same way. This function can't distinguish
between class 1 and class 2 individuals. It returns the aggregated waiting
time, s... | b9e39fc88010dd0c75bf595dd084b9b9fcf61be4 | 611,092 |
import json
def parse_dict_ocr(result):
"""Function to parse dict or JSON OCR data.
:param result: Fetched dict OCR data
:type result: requests.models.Response
:return: Parsed OCR data
:rtype: list
"""
ocr = []
if isinstance(result, bytes):
as_string = result.decode('utf-8')
... | 15f3401690a7e2d4fdaa0fe49244b69fe1951dc1 | 611,093 |
from typing import Union
import math
def check_nan(data: Union[int, float]) -> Union[str, float, int]:
"""Check if a number is Nan.
Returns a string that can be JSON serialised.
Args:
data: Number
Returns:
str, float, int: Returns NA if not a number else number
"""
if math.is... | 7219a731c5d991bb43d8f791a663f3fe9bd02436 | 611,097 |
import copy
def deep_copy(*args):
""" Auxiliary function to perform a deep copy
Since python ``pass'' some values by reference and also make some
attributions by reference (swallow copy), without performing a deep copy of
some variables (like the grid matrix) we may face unexpected results by
hav... | aa53a31d1027b47a641a9948d2ae99795740995d | 611,098 |
def dhcp_option119(fqdn):
"""Convert a FQDN to an hex-encoded DHCP option 119 (DNS search domain list, RFC 3397).
>>> dhcp_option119("tx1.blade-group.net")
'037478310b626c6164652d67726f7570036e657400'
"""
result = ""
for component in fqdn.split("."):
result += "{:02x}{}".format(len(compo... | d43dbd01345a8f67954eaa01bdef0a616f17cf1f | 611,112 |
import click
def label_or_value_column_name(option_name, option_value, column_type, table):
"""
Parses a ``--label`` or ``--value`` option value. Possibilities are
that it's a string that matches a column name, that it's a column
index (0 being the first column, -1 being the last), or that it's
bl... | a42e627b928d907a20686ed68fe8fce082315f8e | 611,116 |
import requests
def _http_get(*args, **kwargs):
"""Make HTTP GET request with some defined cookies
Params:
all 'requests.get' params
Returns:
see 'requests.get' docs
"""
return requests.get(*args, cookies={
# load mobile version instead of desktop site
"mvp": "p"
... | 8a20fdd55568b111d57074e4838b7b1290a8b14c | 611,121 |
def get_keys(d, *keys):
"""Takes a dict and returns a new dict
where only given keys are present.
If there is no some key in original dict,
then it will be absent in the resulting dict too.
"""
return {key: value
for key, value in d.items()
if key in keys} | 56ca900527bf759637c3f6b68a1fb94b783dd8ce | 611,123 |
def get_http_request(request, slug=None):
"""
Get http request values
:param request:
:param slug: Checks if slug is provided
:return: Content/model type, request parameter and user creator
:rtype: Strings
"""
model_type = request.GET.get('type')
url_parameter = request.GET.get('pk'... | 233dcc62b86f5e970d16e9e1ab2f76c69860865b | 611,126 |
def binary_search(array, mz, error_tolerance=1e-5):
"""Binary search an ordered array of objects with :attr:`mz`
using a PPM error tolerance of `error_tolerance`
Parameters
----------
array : list
An list of objects, sorted over :attr:`mz` in increasing order
mz : float
The mz t... | e20e03ce22b88039b3075740eed483f641403be5 | 611,129 |
def climb_stairs(stair_count, max_steps):
"""
Given n number of stairs, you can climb at most m stairs at a time.
For instance, for m=3, you can climb 1, 2, or 3 stairs at a time.
Count the number of different ways that you can reach the top.
:param stair_count: No of stairs to climb.
:param ma... | 9ed7cce57d382bb60b7c6173b4b062b3f0ab35f5 | 611,132 |
def subgraph_by_types(graph, types, typing):
"""return the subgraph composed of nodes of right types"""
right_nodes = [node for node in graph.nodes() if typing[node] in types]
new_graph = graph.subgraph(right_nodes)
inclusion_mono = {node: node for node in new_graph.nodes()}
return (new_graph, inclu... | c8d713548525a269d940a5d1e606cf503da0a8c7 | 611,133 |
def get_cell_value(worksheet, cell):
"""
Gets the value of a specific cell of the current worksheet.
:param worksheet: Current worksheet to manipulate.
:param cell: A string or a tuple which denotes the cell to access.
:return: The value of a specific cell of the current worksheet.
"""
if t... | 3729ba3b9d45982dca809372484350dce42eef06 | 611,134 |
import hashlib
def sha256_hash(val):
"""
Sha256 hash of text data.
"""
return hashlib.sha256(val.encode('utf-8')).hexdigest() | a546fd0b5e4c88db8e1bd0564d5ae77a339e55ec | 611,136 |
def is_in_rule_list(elem, rulelist):
"""
Check for input elem in rulelist, return boolean.
"""
for rule in rulelist:
if elem in rule:
return True
return False | 965323e5fec6a48aff882cee09288fe00749e6a8 | 611,139 |
def _collapse_false(explanation):
"""Collapse expansions of False
So this strips out any "assert False\n{where False = ...\n}"
blocks.
"""
where = 0
while True:
start = where = explanation.find("False\n{False = ", where)
if where == -1:
break
level = 0
... | 91954dbd4a333221345c7f61350ae61f67e2fc2a | 611,142 |
import platform
def get_command(command):
"""
@brief Ensures command can be executed on each platform
@param command The commands name
@return A platform appropriate command
"""
if platform.system() == "Windows":
command += ".exe"
return command | e761078dcf70216283fcab4967fde42393d3d699 | 611,143 |
def count_feature_types(data):
"""
Get the dtype counts for a dataframe's columns.
"""
df_feature_type = data.dtypes.sort_values().to_frame('feature_type')\
.groupby(by='feature_type').size().to_frame('count').reset_index()
return df_feature_type | 68de5faffa393cdf5408edc5be578716e9873b62 | 611,146 |
import math
def factorize(number):
""" Factorizes number into two near integers.
"""
x = math.floor(math.sqrt(number))
y = math.ceil(number / x)
return (x, y) | 6f66210be9474335122d1440319e44c6d4061f2a | 611,148 |
from Array import min_in_subarray, max_in_subarray
def maximize_profit(prices):
"""
Algorithm:
1. Find MINIMUM price in whole array (0 to `len - 1`), say, `min_price` at index `i_min`.
Now find MAXIMUM price in array segment (`i_min + 1` to `len - 1`), say, `max_price` at index `i_max`,
... | 88d50f41f224460c6e997b7287c1f7d313972feb | 611,154 |
def wraps(func):
"""
Nearly identical to functools.wraps, except that it also
maintains the ``__wraps__`` attribute, which will always
be the origin function.
"""
def wrapped(wrapper):
actual = getattr(func, '__wraps__', func)
for attr in ('__module__', '__name__', '__doc__'):
... | e883725880aef5898b3690985f8709e76e8053b0 | 611,155 |
from typing import Union
def spend_pool(
annual_income: Union[int, float],
net_worth: Union[int, float],
) -> Union[int, float]:
"""Calculates the spend capacity per annum of any single investor.
Args:
annual_income (Union[int, float]): Annual income
net_worth (Union[int, float]): Net... | e86dc4499b467711266f431bd3c068c9fc8772ad | 611,157 |
def config_map(configmap, config):
"""
Map the config provided to PGWare to the client format
Map format: {ADAPTER_KEY: [PGWARE_KEY, DEFAULT_VALUE] | ...}
"""
out = dict(zip(configmap.keys(), [None] * len(configmap)))
for key, definition in configmap.items():
out[key] = config.get(*defi... | 3c662953c6513e6885afd1133851e9d76b9568f9 | 611,159 |
def first(seq):
""" Returns the first element in the sequence `seq`. """
return seq[0] | b65b824da4b006fc916fd457ee4288613078985b | 611,165 |
def is_banned(subreddit, user):
"""
Lookup whether Reddit user is banned from subreddit
:param subreddit: praw.Subreddit instance
:param user: praw.Redditor instance
:return: True if banned, False if not banned
"""
url = 'r/{}/about/banned/'.format(subreddit.display_name)
params = {'uni... | de39d3eac06ba6aae27ba072a1503326ea764afb | 611,168 |
def memoize(fun):
"""Memoizes a function of one argument."""
the_dict = {}
def wrapper_decorator(*args, **kwargs):
assert len(args) == 1, "Only works with one argument"
if args[0] not in the_dict:
the_dict[args[0]] = fun(args[0])
return the_dict[args[0]]
return wrappe... | 722d6ed6048ad7275f7debfb88cb44da7b978e67 | 611,170 |
def read_smiles(smiles_file):
"""
Read a list of SMILES from a line-delimited file.
"""
smiles = []
with open(smiles_file, 'r') as f:
smiles.extend([line.strip() for line in f.readlines() \
if line.strip()])
return smiles | 8431ca74143346fdf37e11e4a19193c3fda4fb62 | 611,172 |
def get_relative_delta(new, last):
"""
:param new: float
New value
:param last: float
Last value
:return: float
Increase (or decrease) since last value
"""
if new is None or last is None: # cannot produce result
return 0.0
new = float(new)
last = float(... | 430740c7c00212752bbcf4659f93bbad6e5bd6c0 | 611,174 |
import hashlib
def getSha224Hash(message):
"""
Get SHA-224 digest of a message
"""
if message is not None:
_m = message.encode('U8')
return hashlib.sha224(_m).hexdigest()
else:
return '' | cf55315fc720d16229d89519cc2a94fe312cf1d8 | 611,179 |
import json
def deserialize(data):
"""
Required for a data format plugin. Converts JSON into the Python objects used by `sofine`.
"""
return json.loads(data) | c4a72c85c740bc3dc5d89b970554502bb7b31db7 | 611,181 |
import glob
import click
def locate_file_by_seq(seq, tag, ext):
"""find file matching current sequence number"""
m = glob.glob('*_*_{}{}{}'.format(seq, tag, ext))
if not m:
click.echo("no file with sequence {} found!".format(seq))
return
if len(m) > 1:
click.echo("found more th... | a245073bd32e34782a0ae0a7b30d12169120ff5a | 611,184 |
import re
def extract_pages_info(pages: str) -> dict:
"""Extracts the total number of pages given string input in format <digit>-<digit>
:param pages: The pages range
:return: Tuple start_page, end_page, total_pages
"""
pages_lst = re.findall(r"\d+", pages)
if pages_lst:
start_page = i... | 524a867aafcffc2ac077aec8b109c4778a85b3e8 | 611,189 |
def setGraph(nCount, edges):
"""
Boilerplate method to set graph
returns graph
:param: nCount number of nodes in graph - n nodes
:param: edges list of edges in graph
"""
g=dict()
# setting the nodes
# create dict with key and value as node
for _t,_e in edges:
if _t not i... | 1fb904bea8809094e24c0d26d228a973ae8a9a5c | 611,193 |
import traceback
def internal_error(_):
"""Return a custom 500 error."""
return 'Sorry, unexpected error: {}'.format(traceback.format_exc()), 500 | 16d41a61b880d2ae0e9ff3fc2488af8950b929d5 | 611,194 |
import math
def probability_of_failure_for_failure_rate(f):
"""
Given a failure rate f, what's the probability of at least one failure?
"""
probability_of_no_failures = math.exp(-f)
return 1.0 - probability_of_no_failures | 5839cd378c65bf84f97a57d663a53f4e293c34e2 | 611,195 |
import re
def normalize_simapro_formulae(formula, settings):
"""Convert SimaPro formulae to Python"""
def replace_comma(match):
return match.group(0).replace(",", ".")
formula = formula.replace("^", "**")
if settings and settings.get('Decimal separator') == ',':
formula = re.sub('\d,\... | 8957fda0ec205d3f89d456d9b1c9d6e665d54bb6 | 611,196 |
def jaccard_similarity(first, second):
"""
Given two sets, returns the jaccard similarity between them
:param first: a set
:param second: a set
:return: the similarity as a double
"""
return len(first & second) / len(first | second) | 0907882e315b39adf5e07a6bfe704cf93209c2a6 | 611,197 |
def swap_header_axis(h, a0, a1):
"""
Swaps header keywords between dimensions.
Affects only keywords 'NAXIS', 'CRPIX', 'CRVAL', 'CDELT', 'CUNIT', 'CTYPE'.
Parameters
----------
h : dict
The header to update
a0 : int
First index to swap from
a1 : int
Second index ... | f1770a8d8f94363769dec7e46be814b870c78d72 | 611,204 |
def num_lecture_hours(section: tuple[str, str, tuple]) -> int:
"""Return the total number of lecture hours per week.
Preconditions:
- The input matches the format for a section described by the assignment handout.
Hint: you can use ".hour" to access the hour attribute of a datetime.time value.
... | f6ffcf2e85c9c069092f3ff21246bc9e36291db0 | 611,205 |
from typing import Dict
from typing import List
def _load_ebookconvert_params(dict_: Dict) -> List[str]:
"""Loads ebookconvert command line parameters from a dictionary.
Prepends -- to parameters that are missing it, making -- optional within the
ebookconvert_params block of the project file.
Args:
... | 800799de59891c81cd55ade817d3e50561972ab5 | 611,206 |
from typing import Container
def get_mag_frequency(plate, speed):
"""Determine frequency for KF operation
Based on plate type and the desired KF speed, determine the frequency for
the KF operation. Needed for `mix` and `release` operations.
Parameters
----------
plate: Container
Cont... | a646a8ae51652e2beea985fe270ffbce404362de | 611,207 |
import re
def valid_email(email):
"""Checks if email is valid"""
# accepts emails following x@x.x format
email_re = re.compile(r'^[\S]+@[\S]+\.[\S]+$')
return not email or email_re.match(email) | 73370d9a7709a8f46ba3f5b44ff8e599b2ef9c0d | 611,209 |
def urlpath(url:str) -> str:
""" Get url's path(strip params) """
return url.split('?', 1)[0] | 9594579e6a5d73546d25d3815d8918e32a25323e | 611,210 |
def strip(raw_input):
"""Strip strings, convert NaN and None to empty string"""
if raw_input is None or raw_input == "NaN":
return ""
return raw_input.strip() | a989fffb426b3a5abb78cb7c346f5248bc75f897 | 611,211 |
from pytz import all_timezones_set, country_timezones, country_names
def find_timezone_name(tz_name):
"""
Return list of matching timezones by name, country code, or country name.
Search is case insensitive.
"""
if tz_name in all_timezones_set:
return [tz_name]
# Case insensitive match... | c4ea244179ffcc660bb2c94d1aba77ae081a8bff | 611,214 |
def C_to_K(temperature_in_C):
"""Convert from celsius temperature to kelvin
Arguments:
temperature_in_C: temperature in degrees celsius
Returns:
temperature_in_K: temperature in Kelvin
"""
return temperature_in_C + 273.15 | 8acf1300fede5ee2776b61d3ca925772156f94bb | 611,220 |
import random
def gen_lister(minLength, maxLength):
"""Generate a list of 1s, with a random length between the given ranges"""
if type(minLength) != int:
raise OSError
if type(maxLength) != int:
raise OSError
listLength = random.randint(minLength, maxLength)
listerList = []
cou... | 5c9e005fb5d08f0e166fa2b7f039c36f9ade4c83 | 611,223 |
import logging
def get_null_logger(module_name):
"""Gets a logger with a NullHandler that actually does no logging
Args:
**module_name (str)**: Name of the module requesting the logger
Returns:
A logger using a NullHandler
"""
logger = logging.getLogger(module_name)
logger.se... | 900fb935f8bd4b5136647b99ada2ab0d9a97dafa | 611,224 |
import re
def to_camel_case(string: str) -> str:
"""
Converts a string from snake_case to camelCase.
:param string: string in snake_case notation
:return: `string` converted to camelCase
"""
if string.find('_') == -1:
return string
return re.sub(
r'(.)(_)(.)',
lam... | 1a3780584ef6ac202c83bc61d99a579a66eef516 | 611,225 |
def imgSameSize(img1, img2):
"""Check if two images have the same size."""
dimX1, dimY1 = img1.shape
dimX2, dimY2 = img2.shape
if (dimX1 == dimX2) and (dimY1 == dimY2):
return True
else:
return False | f57128c1f17cd9f9de460d6a34c30fd63155e9e6 | 611,226 |
from datetime import datetime
def normal_time_to_datetime(normal_time, day, month, year):
"""Converts normal time format to a datetime object
Arguments:
normal_time {string} -- normal time
day {int} -- normal time day
month {int} -- normal time month
year {int} -- normal time ... | 75a2e820e519895bff88d809e3a242bbf622e8c1 | 611,227 |
def sort_array(to_sort: list) -> list:
"""Sorts to_sort using the bubble sort algorithm"""
sorted = to_sort.copy()
for i in range(len(sorted)):
for j in range(len(sorted) - 1):
if sorted[j] > sorted[j + 1]:
sorted[j], sorted[j + 1] = sorted[j + 1], sorted[j]
ret... | f032da29885053a9ff910d87276f702ccadf9280 | 611,228 |
import math
def get_angle_from_vector(vector2):
""" Returns the angle from X+ axis to the given vector """
return math.atan2(-vector2[1], vector2[0]) * (180/math.pi) | 138fde8984301e9e940db9e06975082d57c7adb6 | 611,229 |
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int:
"""
Iterate through the array to find the index of key using recursion.
:param list_data: the list to be searched
:param key: the key to be searched
:param left: the index of first element
:param right: the index of las... | a567469caa72be724097594f08e971875f3bb527 | 611,230 |
def extract_squeue_format_D(value: str) -> int:
"""Extracts the node count `%D` from `squeue` output.
:param value: Node count as string.
"""
return int(value) | c170d3a784f545ec5dc5217d999da3c876405121 | 611,234 |
def tiltCompensation(x, y, z, stage_tilt):
"""
Corrects z for stage tilt.
This is pretty simple, but it is factored out to make for the
benefit of external modules.
"""
return z + stage_tilt[0] + stage_tilt[1]*x + stage_tilt[2]*y | ab3ab785a7f247d6e5a8daa8a3d0e213d077e7a0 | 611,237 |
def get_report(analytics, VIEW_ID):
"""Queries the Analytics Reporting API V4.
Args: analytics: An authorized Analytics Reporting API V4 service object.
Returns: The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
... | 817d28e1a9fa842a254d544e6554613ecab517dd | 611,240 |
def check_unordered_list(line):
""" Check whether the line is unordered list, if it is, change it into html format
:param line: str, a line in markdown file
:return: boolean, whether a line is unordered list
str, the line in html format
"""
count_space = 0
for char in line:
... | b0e6ce7a4df66700b139cdf1126343bd85b9631c | 611,257 |
def npm_homepage_url(namespace, name, registry='https://www.npmjs.com/package'):
"""
Return an npm package registry homepage URL given a namespace, name,
version and a base registry web interface URL.
For example:
>>> assert npm_homepage_url('@invisionag', 'eslint-config-ivx') == 'https://www.npmjs... | ee41e41da22cae4d51cf83e9fd6743a9a01dc650 | 611,258 |
def find_escape_floor(pac_mine, pac_their, scene):
"""
Find an escape floor which will save our pac from being eaten.
"""
# Shortcuts
escapes = scene['escape']
my_x = pac_mine['position'][0]
my_y = pac_mine['position'][1]
their_x = pac_their['position'][0]
their_y = pac_their['posit... | d4f1783748df278e27c6265ff56aa67e5a95f1f2 | 611,260 |
import torch
import math
def max_dist(traj: torch.Tensor, traj_gt: torch.Tensor, masks: torch.Tensor) -> torch.Tensor:
"""
Computes max distance of a set of trajectories with respect to ground truth trajectory.
:param traj: predictions, shape [batch_size, num_modes, sequence_length, 2]
:param traj_gt... | 07ee03f21ea70eab6f2c53869bfbc55e9f74c022 | 611,261 |
def apply_row_number(df_ordered, window): # pylint: disable=unused-argument
"""ROW_NUMBER Window Function
Determines the ordinal number of the current row within a group of rows,
counting from 1, based on the ORDER BY expression in the OVER clause. If
the optional PARTITION BY clause is present, the o... | 0b529b8ff82d329ad78e3ee66851257a09279665 | 611,262 |
def exchangeable_value(budget, exchange_rate, spread, denomination):
"""
:param budget: float - the amount of your money you are planning to exchange.
:param exchange_rate: float - the unit value of the foreign currency.
:param spread: int - percentage that is taken as an exchange fee.
:param denom... | 446377ce79a483939e1bb329f38795b5af7db8f4 | 611,268 |
def convert_netmask_to_cidr(netmask):
"""
Converts Netmask to cidr (255.255.255.0 => 24)
Args:
netmask (str): IP Netmask
Returns:
cidr (int): IP cidr
"""
return sum([bin(int(x)).count(u"1") for x in netmask.split(u".")]) | 90cce0c9b9b05b6e41522920a5413aa1bf5ee4df | 611,269 |
def get_user(rmine, username):
"""Get the user ID from the provided user name"""
users = rmine.users.query_to_list(name=username)
if not users:
raise RuntimeError('Unknown user %s' % username)
return users[0].id | ade12d2ceef26ba60873fc35fa3d45ae81d9c371 | 611,272 |
import base64
def download_data(data):
"""
Download data in .csv format
Args:
data (`pd.DataFrame`): A pandas dataframe
Returns:
str: A href link to be fed into the dashboard ui.
"""
to_download = data.to_csv(index=False)
b64 = base64.b64encode(to_download.encode()).decode(... | 8d9452c21af5cf2e5c57578559ea2110c3da47ad | 611,273 |
def is_skinned(joint):
"""
Returns True if the given joint is being used for any skinning
"""
return len(joint.outputs(type='skinCluster')) > 0 | c89b039d820eef4db2f7ac2a3645dba678ee1cde | 611,275 |
from typing import Dict
from typing import Any
from typing import Optional
def _extract_locals(
locals: Dict[str, Any], filter_out_nulls: Optional[bool] = True
) -> Dict[str, Any]:
"""Extract arguments from local variables.
If input dictionary contains `kwargs`, then it will not be included to
the res... | 4f13b2d48a7ba53d683e933175fe38c2e65d570f | 611,276 |
def tupleize(obj):
"""
Converts into or wraps in a tuple.
If `obj` is an iterable object other than a `str`, converts it to a `tuple`.
>>> tupleize((1, 2, 3))
(1, 2, 3)
>>> tupleize([1, 2, 3])
(1, 2, 3)
>>> tupleize(range(1, 4))
(1, 2, 3)
Otherwise, wraps `obj` in ... | da78325ca3d147dcbc89fb5369c215b85a2efdfe | 611,277 |
import re
def smart_title(value):
"""Converts a string into titlecase."""
"""Excludes [a, an, the, and, but, or, for, nor, of]"""
# strip smart single quotes
t = re.sub('\\u2018|\\u2019','\'', value.title())
# fix the plural
t = re.sub(r'([a-z])\'([A-Z])', lambda m: m.group(0).lower(), t)
... | e93b2ee7e0859bb0bd2df937a1f8c54f8fdedaf5 | 611,278 |
def get_set_bits(number: int) -> int:
"""
hitung jumlah bit angka 1
>>> get_set_bits(25)
3
>>> get_set_bits(52132)
8
>>> get_set_bits(-2)
Traceback (most recent call last):
...
ValueError: Angka tidak boleh negatif
"""
if number < 0:
raise ValueError("Angka tidak ... | 317ac821406b517cdf138195b31031b962792f05 | 611,279 |
def sbg_survival_rate(x, a, b):
"""
Probability that a customer alive at time x-1 is still alive at time x
"""
return (b + x - 1) / (a + b + x - 1) | 3ebe6074783363c84b03b5c924137f1893698544 | 611,280 |
def calc_current(params, an, ca):
"""
Calculates the external current from the user inputs. If a C-rate is given, calculate the battery capacity and convert this to a current. If
i_ext is given, convert the units to A/m2.
"""
# Battery capacity is the lesser of the anode and cathode capacities. ... | 58de2b9d0a910e0bdca13f424c7e8c64782efe5c | 611,281 |
import random
def can_reciprocate(person, contact, model):
"""
Determines whether or not the specified person can form a reciprocal link
with the specified contact.
Please note that this function is different than can_link_to() because
this project's user-selectable requirements have already been... | 94540ee359b1cc4c302986673aa10f9e14c7f21d | 611,286 |
import torch
def variance(data:torch.Tensor) -> torch.Tensor:
"""
Compute the variance for given input data.
Parameters
----------
data: torch.Tensor
input data
Returns
-------
variance (torch.Tensor)
"""
return data.var(-1) | 8c9f6c00ce914b43feb22f3c078aa844e0ddf99c | 611,289 |
def Radio2NormOption_Y_Variable(argument):
"""Dictionary for switching the normalisation options in the radio box"""
switcher = {
0: 'Raman_Intensity',
1: 'Vec_Norm_Intensity',
2: 'std_var_Norm_Intensity',
3: 'Zero_to_One_Intensity'
}
return switcher.get(argument, 'k-') | 9215ac57dae8f417d09a7899da334a0c975ac56e | 611,291 |
from pathlib import Path
def check_file_exists(path) -> bool:
"""
Checks if file exists at path
:param path:
:return:
"""
if isinstance(path, str):
path = Path(path)
return path.exists() | 8d41e80742c0e31dd715b83655edc2395b90b0d5 | 611,292 |
def highlight_source(linenumber, index, lines, offset=None, text_range=None):
"""Extracts a few relevant lines from a file content given as a list
of lines, adding line number information and identifying
a particular line.
When dealing with a ``SyntaxError`` or its subclasses, offset is an
integer ... | a239967168c8576e5df32dc728cf45cd3eeebd7a | 611,295 |
from typing import Counter
def document_frequency(bags_of_features):
"""
Find all the distinct features in many bags of features,
and how often each occurs (in how many bags each occurs)
:param bags_of_features: iterable of Counters
:return: Counter mapping features to their document frequencies
... | 0d211536e4076f72c2a87d34e1e80f5ec5d78dba | 611,301 |
def is_comment(line):
"""Lines starting with "#" are comments.
"""
return line.strip().startswith('#') | a3e4c7ccee93030b0f8c1c25fc11bd3aa0d993fe | 611,302 |
def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
"""
with open(source, 'rt') as file:
return file.readlines() | d8a86a99a4f8b417d1b1589a07d058ef557c2b0f | 611,303 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.