content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def parse_affiliations(response):
"""Parse the author affiliations from a MAG API response.
Args:
response (json): Response from MAG API in JSON format. Contains all paper information.
Returns:
affiliations (:obj:`list` of :obj:`dict`): List of dictionaries with affiliation information.
... | 1ace8d2d2fbfae6086f78ae0aec1ed7bf5df143d | 567,523 |
def plugin_def_json(plugin_def):
"""Convert plugin defenition to json.
Args:
plugin_def: Plugin definition
Returns:
JSON of the plugin's definition
"""
return {
"name": plugin_def.name,
"namespace": plugin_def.namespace,
"hidden": plugin_def.hidden,
... | c8ba125ddfb25c9ccfd3d344612df4c9127d4a46 | 567,525 |
def filter_related_term_list(hpo_counts, related_terms, min_diff):
"""
Retain pairs of related terms with sample size differences < min_diff
"""
filtered_pairs = []
for termA, termB in related_terms:
countA = hpo_counts.get(termA, 0)
countB = hpo_counts.get(termB, 0)
... | 5831c8e85305dffe3fb60bd30c42e5fbd309e1ad | 567,531 |
import json
def load_config(dir_file_conf):
""" Return the json configuration of the control. """
with open(dir_file_conf) as json_data:
file = json.load(json_data)
return file | 8aea3bf6ee44be3c115dd7fa2163c5bb43ea33f1 | 567,533 |
import hashlib
def calculate_hash_for_file(an_uri):
"""Returns a sha1 hexdigest for the given file.
:param an_uri: the URI pointing to the file
:rtype: string
"""
try:
chksum = hashlib.sha1()
with open(an_uri, 'rb') as filehandle:
while True:
buf = file... | 7d1bb1e661cf362e5d76caa2341763c9ba66da33 | 567,534 |
import time
def format_time(epoch, format="%m/%d %H:%M", default="--/-- --:--"):
"""Formats time using time formatting standards.
See: https://docs.python.org/3/library/time.html
:type epoch: int
:param epoch: time as an epoch
:type format: str
:param format: desired format of output strin... | 4fbd7b586af54014bd12a97ef202014cc50a0210 | 567,536 |
def print_class_html(cls) -> str:
"""Wraps class label with code block
"""
return f"<code>{cls.get_label()}</code>" | a46183e68126b2fa1feac7ce596428f98b78b34e | 567,539 |
def egcd(a, b):
"""
Extended euclidean algorithm: Iterative version
https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
"""
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
... | 471cae16413b39a08a013b17d8a3aa5e5c4cade8 | 567,540 |
def split_list(category_list):
"""
Split list of ranges into intervals and single char lists.
:return: List of interval starting points, interval lengths and single chars
"""
unicode_category_interval_sps = []
unicode_category_interval_lengths = []
unicode_category_chars = []
for elem... | 63e6e490c9e73bde8f64a4759309a8fe7a08a8a8 | 567,542 |
from datetime import datetime
def datetime_from_csv_col(col):
"""Return datetime from passed csv col in format MM/DD/YY """
date_fields = col.split('/')
month = int(date_fields[0])
day = int(date_fields[1])
year = int("20" + date_fields[2])
return datetime(year, month, day) | a441863c065e1f536008009dc64d37e8681aed08 | 567,543 |
import hashlib
def gravatar(person_data, fallback_key, fallback_suffix):
"""
Get a gravatar for an email address.
Defaults to libravatar with a gravatar fallback
Uses the "avatar" key if it exists, or defaults to school email.
"""
email = person_data.get("avatar",
... | 4df7848e0cd22828d30e395d9f500a513dd07a4c | 567,551 |
def c_0(z: float) -> float:
"""Calculates the orography factor, taken as 1,0
Args:
z (float): vertical distance
Returns:
float: orography factor
"""
return 1.0 | 6580885fd5a7241e26a50a70206f10ea1293d027 | 567,555 |
import codecs
def open_strings_file(file_path, mode):
""" Open the strings file
Args:
file_path (str): The path to the strings file
mode (str): string representation of the mode in which to open the file (read, write, append, etc.)
"""
return codecs.open(file_path, mode, "utf-16") | 110269e8c1e65579f3c06aede6e972d4b0fe06a3 | 567,564 |
def str2dicts(data):
"""
Create a list of dictionaries from a whitespace and newline delimited text.
For example, this:
cpu 1100
ram 640
cpu 2200
ram 1024
becomes:
[{'cpu': '1100', 'ram': '640'}, {'cpu': '2200', 'ram': '1024'}]
"""
list_data = []
list_data.append({})
... | 85912720ce52b642354dbc60004fccc63318e3d2 | 567,566 |
def partition(start, end, cores):
"""Split a range into (exactly or almost) parts
Args:
start (int): The first index of the range.
end (int): The last index of the range.
cores (int): The number of parts to split into.
Returns:
:obj:`list` of :obj:`list` of :obj:`int`: The ... | 7ee8159f536e1083915829ad45ec47909fb5ea2b | 567,569 |
def _GetTargetCpu(arch):
"""Returns target_cpu for the GN build with the given architecture."""
if arch in ['armeabi', 'armeabi-v7a']:
return 'arm'
elif arch == 'arm64-v8a':
return 'arm64'
elif arch == 'x86':
return 'x86'
elif arch == 'x86_64':
return 'x64'
else:
... | 3a48fab1bb739dba2e3f4a2cc2abded1d8f59963 | 567,572 |
def _laguerre_gen(x, alpha, nmax):
""" Calculate generalized Laguerre polynomials
of order `alpha` up to degree `nmax` with generic algebra,
.. math:
L^{(\\alpha)}_n(x)
Parameters
----------
x : ndarray, adarray, or other algebraic object
The argument of... | c859bb8993be041fd6a70cfab2c77d4f34e5337c | 567,575 |
def _partition(data, pivot):
"""
Three way partition the data into smaller, equal and greater lists,
in relationship to the pivot
:param data: The data to be sorted (a list)
:param pivot: The value to partition the data on
:return: Three list: smaller, equal and greater
"""
less, equal, ... | 8b8f45b25612343cb3b70aed39c8d440d83059f2 | 567,576 |
def find_existing_path(dict_: dict, path: list) -> tuple:
"""Return a tuple consisting of:
- A pointer to any part of the path that already exists in the declared
dict.
- The remaining part of the path that needs to be created.
"""
try:
subfolder = path.pop(0)
except IndexError:
... | be187c84a267876d0e591ade126edc1dee4933e5 | 567,578 |
def get_block(matrix, i, j, row_range, col_range):
"""
Extract a submatrix of a matrix
Parameters:
-----------
matrix the big matrix:
matrix = [ M11, M12, ..., M1m;
M21, M22, ..., M2m;
... ;
Mn1, Mn2, ..., Mnm]
i: row block index
j: column bl... | c133c3c919e29a4d8738a331c3ad3cca03aebcf7 | 567,579 |
def get_priority(severity):
"""
Fetch defined priority for Jira based on Sonarqube issue priority.
:return: Jira priority
:rtype: String
"""
if severity in ("BLOCKER", "CRITICAL"):
return "Major (P2)"
elif severity == "MAJOR":
return "Minor (P3)"
elif severity in ("MIN... | 75120e81e5a63a461c99b40a601ab9f57d90003e | 567,581 |
from base64 import b64encode
def encode_message(message):
"""Encode a message using base64."""
return b64encode(message.encode()).decode() | e9b87eb507820ef880511248a5d36e2379706278 | 567,589 |
def life(cash_flows):
"""Calculates the life of the cash flows.
:param cash_flows: The cash flows.
:return: The life.
"""
return max(cash_flow.time for cash_flow in cash_flows) | 82117274b722a56eacb7e7203cb2daeb7c6f304c | 567,594 |
import importlib
def import_module_by_name(mod_name):
"""
Executes an "import" statement dynamically.
Parameters
----------
mod_name : str
Name of the module to be imported.
Returns
-------
module
The imported module.
"""
return importlib.__import__(mod_name) | 9320e0bc729983ea6698e89597254fbc66c8f9a2 | 567,596 |
def friendly_size(size: float) -> str:
"""Convert a size in bytes (as float) to a size with unit (as a string)"""
unit = "B"
# Reminder: 1 KB = 1024 B, and 1 MB = 1024 KB, ...
for letter in "KMG":
if size >= 1024:
size /= 1024
unit = f"{letter}B"
# We want to keep 2 ... | 10feac3aa43991d469bf29e883ba53e477fac5e1 | 567,598 |
def is_pangram(text):
"""
Checks if a string is a pangram.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
text = text.lower()
for letter in alphabet:
if letter not in text:
return False
return True | 4048ef72957cbff5dc050ebf4ca37769be6bb6c3 | 567,608 |
def _IsLimitedDocCheck(filename, limited_doc_files):
"""Whether this this a limited-doc file.
Args:
filename: The filename.
limited_doc_files: Iterable of strings. Suffixes of filenames that should
be limited doc check.
Returns:
Whether the file should be limited check.
"""
... | 0135796a40bbf4c937c0f83d7011910d4aac977e | 567,609 |
import re
def exclude(path: str):
"""Does the path meet any rules for exclusion?"""
EXCLUDES = {r'__.*__', r'/\.'}
NO_LINKS = {r'\.xmf', r'\.h5', 'run'}
return any(re.search(exclude, str(path)) for exclude in EXCLUDES.union(NO_LINKS)) | ce8054a4e12d3843a6c87d78b05f137c25309520 | 567,610 |
def is_valid_drive_letter(string):
"""
Drive letters are one character in length and between "A" and "Z". Case does not matter.
"""
return (len(string) == 1
and string[0].isalpha()) | 3ae5b86a579f316dde9c64d27e69fe2279ec41b3 | 567,611 |
import unicodedata
def preprocess(string, punctuation):
"""Transform the raw txt into a list of word for TTS
Parameters
----------
string : str
Raw text file
punctuation : dict
Dictionnary with the punctation to pronounce
Returns
-------
list
List of preproces... | 504696438d7be35a6fcfd1c4e02a42bebe2152ce | 567,612 |
import math
def eq4623d2(L1, W1, W, NL):
"""Eq. 4.6.2.3-2: Equivalent strip width for two lanes.
The equivalent width of lingitudinals strips per lane
for both shear and moment with more than one lane
loaded may be determined as
E = min(84.0 + 1.44*math.sqrt(L1*W1), (12.0*W)/NL)
Arg... | 6dd39cac541ca7f4f5660da00f8ac242bd9e0f6c | 567,616 |
from pathlib import Path
import textwrap
def modules_legacy_python_protocol_file(tmp_path: Path) -> Path:
"""Get an on-disk, minimal fixture of legacy python protocol w/ modules."""
path = tmp_path / "protocol-name.py"
path.write_text(
textwrap.dedent(
"""
# my protocol
... | e5242376f2861c93c7940839b36e0d2ea702bd03 | 567,622 |
def get_truth_cand_ratio(t_err_cand, dm_err_cand, t_err_truth, dm_err_truth):
""" Calculate ratio of truth region to candidate region,
to test upper limit of False Positives
"""
area_cand = t_err_cand*dm_err_cand
area_truth = t_err_truth*dm_err_truth
return area_truth/area_cand | 4f3e18bee7bea240270d362883f9c579eabe34a2 | 567,623 |
def solution(data):
"""
SW Expert Academy 1221번 GNS - D3
어짜피 0 ~ 9까지의 숫자로 이뤄져있으므로 이 숫자들을 하나의 dict로 모은 다음 얼마나 존재하는지 counting함
:param data: 정렬되지 않은 어느 행성의 숫자들
:return: 어느 행성의 숫자로 정렬된 list
"""
gns = {"ZRO": 0, "ONE": 1, "TWO": 2, "THR": 3, "FOR": 4, "FIV": 5, "SIX": 6, "SVN": 7, "EGT": 8, "NI... | 7b6e5f1d019279290597d657e5ce6771e3c12720 | 567,626 |
import re
def get_genotype_lists(glstring):
"""
Take a GL String, and return a list of genotype lists
"""
parsed = re.split(r'[\^]', glstring)
genotype_lists = []
for genotype_list in parsed:
if "|" in genotype_list:
genotype_lists.append(genotype_list)
return genotype_... | 2b609d9ae87f7f8866fd217590a786fb300eb863 | 567,631 |
def local_url(url, code=None):
"""Replace occurences of `{locale_code} in URL with provided code."""
code = code or "en-US"
return url.format(locale_code=code) | b5f9cb32f2fd722ce05cf792fdf3b2dd40880154 | 567,632 |
def findAllHome(tx):
"""
Method that finds all the nodes House in the data base
:param tx: is the transaction
:return: a list of nodes
"""
query = (
"MATCH (h:House) "
"RETURN h , ID(h);"
)
results = tx.run(query).data()
return results | abca6fef05166b45d734d20fccf2c005328a5089 | 567,635 |
import json
def json_load(obj, error=True, **kwargs):
"""Deserialize a json str into an object.
Args:
obj (:obj:`object`): str to deserialize into obj
error (:obj:`bool`, optional): default ``True`` -
* if ``True`` If json error happens, raise it
* if ``False`` If jso... | 8f970223169bf4f380082a494bc929519767c462 | 567,637 |
def get_sql_result_as_dict_list(res):
"""Returns the result set as a list of dicts
Args:
res: (object): The sql result set
Returns:
A list of dicts
"""
if not res:
return []
col_names = res.get_column_names()
rows = res.fetch_all()
dict_list = []
for row ... | ac27b02eef87adac3f4d266c88c6f9e7cccc2df6 | 567,638 |
import torch
def generate_noise_for_model_test(x: torch.Tensor) -> torch.Tensor:
"""Generates noisy inputs to test the model out of distribution
Args:
x (torch.Tensor): testing inputs
Returns:
torch.Tensor: Noisy inputs
"""
hypercube_min, _ = torch.min(x, dim=0)
hypercube_max... | 332547d4a0da822d924209497775255c7ee29852 | 567,640 |
from typing import List
from typing import Set
def binary_xor_sets(arr: List[str]) -> Set[str]:
"""
>>> binary_xor_sets(['0', '2', '1', '0', '1', '1'])
{'2'}
"""
return set(arr[0::2]) ^ set(arr[1::2]) | 2c20e0298de072f649bed86386c93b7e784f9ff5 | 567,644 |
def __message_timestamp_sort(message):
"""
Returns the Slack message timestamp for a single message.
Used to sort Slack message arrays by time.
Private function.
m: A single Slack message dict.
"""
return float(message['ts']) | bf2ed4cece17d3aa2b2d43e7c0f03eba4dbaccbb | 567,649 |
from typing import Iterable
from typing import Optional
from typing import List
from typing import Any
def unique_sequence(items: Iterable, key: Optional[str] = None) -> List:
"""
Return a new list with the unique values from the sequence.
Optionally you can also provide a lambda to generate the unique k... | 753f6edb6bd913f98d22a8dc4fe8b0ca19297ce9 | 567,650 |
def _uri(helper):
"""Returns the URL of the kvstore."""
return '/'.join((
helper.context_meta['server_uri'],
'servicesNS',
'nobody',
'Splunk_TA_paloalto',
'storage',
'collections',
'data',
'minemeldfeeds')) | d272afa2e9305a480609c215e653f3e80b1990b7 | 567,651 |
def usage(cmd='', err=''):
""" Prints the Usage() statement for the program """
m = '%s\n' %err
m += ' Default usage is to link a CR with a Task Branch (TB) on SalesForce.\n'
m += ' '
m += ' teamBranch -c lntb -s4.1 -t<Team_branch> -b<branch_Name> \n' # addTeamBranch
return m | df0666271509c84d2909462f7c75922ac3183925 | 567,657 |
def cross_product(w):
"""Returns the cross product matrix associated with w.
The matrix [w]R is the derivative of the matrix R as it rotates about
the axis w/||w|| with angular velocity ||w||.
"""
return [0.,w[2],-w[1], -w[2],0.,w[0], w[1],-w[0],0.] | abf445acaa59eebe9b8069cb2fa09fe8efb00449 | 567,659 |
def get_status(user):
"""Returns True if user is enabled, False if disabled."""
grant = user.grant()
return not grant.revoked | 11757466bf8e23c252d8a3bf9fc448c251b71ad9 | 567,661 |
def contour_length_py(verts):
"""
Compute the length of a contour. Copied from
https://arachnoid.com/area_irregular_polygon/
Parameters
----------
verts : array_like
2D shape (N,2) array of vertices. Uses scikit image convetions
(j,i indexing)
Returns
-----... | 5b1ba320d0ef9e16d43ddbf3d189ee7fff5cc167 | 567,663 |
def load_model_to_file(model, path):
"""
Persist an models object into one file.
Args:
model (ModelObject):
The model object.
path (string):
The target path stores a models.
Returns:
NoneType: None
"""
# dump(model, path)
model.write().over... | 28f252191b525fabe0cc26d3e88cfdda4df62f8a | 567,668 |
def summarize_shap_table(table,column_names,quantile=None):
"""Provide summary statistics for a shap table.
Arguments
---------
table: panda DataFrame
Data to summarize. Subsetted using column_names.
column_names: list of strings or panda index
Selection of columns to summarize
... | 8be8e23f9640d85950634c706fe38ffebf42394e | 567,670 |
def _union_intervals(x, y):
"""Merge two sequences of intervals into a single tuple of intervals.
Any integer bounded by `x` or `y` is also bounded by the result.
>>> _union_intervals([(3, 10)], [(1, 2), (5, 17)])
((1, 17),)
"""
if not x:
return tuple((u, v) for u, v in y)
if not y... | e95820b2db55c8c1132d7fe5d650f47ecfa521ce | 567,676 |
def catplot_abscissa(x_order, hue_order=None, xtype='center'):
"""
Returns a dict that contains, for each possibly combination of x and hue
values, the abscissa of the corresponding bar in any Facet of a
seaborn 'bar' catplot called with x_order and hue_order as arguments.
Depending on the val... | c62dfe26027bc4d9be97c599df9dd374e2e551a2 | 567,681 |
import re
def split_titles(text):
"""
Splits text that is divided by slashes
"""
text = text.split('/')
text = [re.sub("\n","",t.strip()) for t in text]
return text | 4790d474a400ffd0d0183a510e0e60375adf1ac7 | 567,689 |
def subtract_numbers(num1, num2):
"""Returns the subtraction of two integers."""
return num1 - num2 | f1309604adc19ac0da2e66100b733d80cc6255f7 | 567,693 |
def color_rgbt(red, green, blue, transparency):
""" Given four intensities red, green, blue, transparency,
all from 0 to 255, returns the corresponding CSS
color string e.g. '#ff00ccff' """
return f"#{red*256**3 + green*256**2 + blue*256 + transparency:08x}" | bc7eed4cae1d3de8cc971ad5f5f7305d95f686ff | 567,696 |
def list2dict(L, value=None):
"""creates dict using elements of list, all assigned to same value"""
return dict([(k, value) for k in L]) | ffc5b67914046e49639210cc0d9e7a83850fb346 | 567,699 |
from pathlib import Path
def package_path(package: str) -> Path:
"""Join the current working path with the package name."""
return Path.cwd().joinpath(package.replace(".", "/")).parent | 6eac5cbee73b3fb8636059c1b020d250f1fc38d3 | 567,700 |
import re
def generate_aws_compatible_string(*items, max_length=63):
"""
Generate a AWS resource name that is composed from list of string items. This
function replaces all invalid characters in the given items into '-', and allow user
to specify the max_length for each part separately by passing the ... | b376800338c33e6f69f4567f2bc84c28c3238b11 | 567,701 |
from typing import AnyStr
import codecs
def auto_decode(string: AnyStr, encoding: str = "utf-8", errors: str = "strict") -> str:
"""Lookup a decoder and decode the bytestring if it is str, else return it
untouched if it's already in bytes (for utf). If its an int, etc, it'll try
to wrap it in str for you.
:param... | 05e6467bed694779a53bf964d46e418b68611f2a | 567,704 |
def reverse(text):
"""
Reverse text
"""
return text[::-1] | 8b95e7cf9d91e5e25117ecc87fb56a44f3f99760 | 567,706 |
import torch
def proba_to_label(probas):
"""
Converts predicted probabilities from extended binary format
to integer class labels
Parameters
----------
probas : torch.tensor, shape(n_examples, n_labels)
Torch tensor consisting of probabilities returned by CORAL model.
Examples
... | 21379762fabb5b03565be2d426182808b8fd7ddd | 567,708 |
def get_num_of_edges(edge_array):
"""
This method checks the shape of the edge array and returns an error if the number of neighbors is not equal to 2.
If there are no errors the number of edges is returned
"""
#check that edge_array dimensions makes sense
num_of_edges, num_Of_Neibs = edge_ar... | fea16c0402141c887c1dba05c471ee90fab2ea7f | 567,709 |
def within_range(val, vrange):
""" Check if a value is within a range.
**Parameters**\n
val: numeric
Value to check within range.
vrange: tuple/list
Range of values.
"""
if (val >= vrange[0] and val <= vrange[-1]) or (val <= vrange[0] and val >= vrange[-1]):
return ... | 44b4089b581b07c91c56f289ac46d357b2fc87cc | 567,711 |
def get_job_status(fw_conn, job_id):
"""Get Job ID Status
Args:
fw_conn (PanDevice): A panos object for device
job_id (str): The job ID number
Returns:
results (Element): XML output containing the job ID status details
"""
command = '<show><jobs><id>' + job_id + '</id></job... | 9e3e144e046c666c1ac833d487f61b0aa43b92d4 | 567,713 |
def really(question):
"""Ask a Yes/Mo question at the prompt.
:param question: The question that is asked.
:return: True if the response starts with a y.
"""
ask = ""
while not ask.startswith("y") and not ask.startswith("n"):
ask = input(question).lower()
return ask.startswith("... | 3d53ad178a06a0de968b52b3371c924cf107d45f | 567,714 |
def get_site_len_list(len_in):
"""
Read in site lengths (one length per row from file len_in).
Return list of lengths.
"""
site_len_list = []
with open(len_in) as f:
for line in f:
site_len = line.strip()
site_len_list.append(int(site_len))
f.closed
asse... | cca7f381b30b58de675c6d5ff2094f9c2b6c23d3 | 567,721 |
def persistent_real_state(real_state, spike):
"""Handles refractory state changes due to spike in last time bin.
Parameters
----------
real_state : torch tensor
real state in last time bin.
spike : torch tensor
spike state in last time bin.
Returns
-------
torch tensor
... | f2b581a964b2d2e95245140a00fb3414fdc10c9b | 567,722 |
import re
def contains_wp_shortcodes(body, *sc):
"""Search body for one or more shortcodes named sc"""
tagre = '|'.join(sc)
# terrible regex taken from Wordpress source
pattern = re.compile(
'\\[(\\[?)(' + tagre +
')\\b([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:... | d7e561f4129ab4250fcd3d5b5314739cce2eb770 | 567,724 |
def shouldDeleteAllMail(serverHostName, inboundServer, username):
"""
Given the hostname of the calendar server, the hostname of the pop/imap
server, and the username we're using to access inbound mail, determine
whether we should delete all messages in the inbox or whether to leave
all unprocessed ... | 1a844da1e18fe6b4bfc78f99e916f57bfc5323c6 | 567,725 |
def service_factory(prefix, base):
""" Test utility to create subclasses of the above ServiceHandler classes
based on a prefix and base. The prefix is set as the ``name`` attribute
on the resulting type.
e.g. ``service_factory("foo", ServicePoolHandler)`` returns a type
called ``FooServicePoolHandl... | 17c5766b0fda9ffa83d2bf3b39c6395a99b728e8 | 567,727 |
def parseAttributes(attrStr=None):
"""Parse the given attributes string (from CIX) into an attribute dict."""
attrs = {}
if attrStr is not None:
for token in attrStr.split():
if '=' in token:
key, value = token.split('=', 1)
else:
key, value = ... | 5b5fcb7c410f51c805971364af567cf7f99ab6c5 | 567,731 |
def initialize_skill_state(name, origin, beta, skill_gid) -> dict:
"""Create a new skill entry
Arguments:
name: skill name
origin: the source of the installation
beta: Boolean indicating wether the skill is in beta
skill_gid: skill global id
Returns:
populated skills... | fe453bd520f4464735194f44c093b7ae26ddb516 | 567,732 |
def _rename_time_index(dict_da):
"""Rename the dim time of each datarray to ensure proper merge.
Each time dim is associated to its probe.
Parameters
----------
dict_da : a dictionary of timeserie datarray
Return
------
new_dict : dict
A dictionary of renamed DataArray
"""
... | 1d7233840918035cfaddd444a804673f6fe2f486 | 567,737 |
import math
def isoperimetric_quotient(polygon):
"""Returns the isoperimetric quotient of the polygon, a measure of its compactness."""
return 4 * math.pi * polygon.area / polygon.length ** 2 | 73a8f2bc60a53ff63dde80001e31128cc1279d0e | 567,738 |
import torch
def MSE_criterion(x, y):
"""
Mean Square Error loss function.
Args:
x: output of autoencoder
y: input data
"""
return torch.mean((x-y)**2) | 35da5f3bf20e137b6bafceeebb4dbf5d12a4d437 | 567,740 |
def center_crop(data, shape):
"""
Apply a center crop to a batch of images.
Args:
data (torch.Tensor): The input tensor to be center cropped.
shape (list of ints): The output shape. If shape[dim] = -1, then no crop
will be applied in that dimension.
"""
for i in range(... | 908279c24e47a74a7c864936d21a7ff8d1ac0a2a | 567,745 |
def get_issue_info(obj):
"""Retrieve IssueTrackerIssue from obj.
Args:
obj: Instance of IssueTracked object.
"""
if hasattr(obj, "audit"):
issue_obj = obj.audit.issuetracker_issue
else:
issue_obj = obj.issuetracker_issue
return issue_obj.to_dict() if issue_obj else {} | e9d1a493a3e47cf871827a70354fb40f0b948908 | 567,748 |
from typing import Callable
def createPoly(a: float, b: float, c: float, d: float) -> "Callable":
"""Returns a function representing a polynomial that can be evaluated for an x."""
return lambda x: a * x ** 3 + b * x ** 2 + c * x + d | f9163e44ff79776618e9cc4f0a409537e09d84b9 | 567,749 |
from typing import Tuple
def process_url(url: str) -> Tuple[str, str]:
"""Extracts both the web address of the PrivateBin instance and the Paste ID from a URL.
:param url: The full URL of a paste, including passphrase.
:return: A tuple containing the server URL and the Paste ID.
"""
if '?' not in... | 9ede3ee3710a0d23fe87cb32a6dcfaab0a9731bf | 567,751 |
def _GetMaxValueForNumBits(num_bits):
"""Return max value for an unsigned integer of width num_bits."""
return 2**num_bits - 1 | f156aa478934fb534bc2c9cbfe8c2316bc51fd85 | 567,752 |
import pickle
def load_dict(path):
"""load an object from a path
Args:
path (str): the path where the pickle file locates
Returns:
object: loaded pickle file
"""
with open(path, 'rb') as f:
return pickle.load(f) | 0a2775385f46fd33a0d893a576b5b14372b748f1 | 567,754 |
import click
def _prompt(*args, allow_empty=False, **kwargs):
"""
Print a breakline before prompting for input and normalize values to accept
empty input when requested by caller.
Args:
args (any): arguments to click.prompt
allow_empty (boolean): whether to allow prompt to accept empt... | 2e007ea744fd993bc69971208fc70b34e9ebf63e | 567,755 |
def set_ordered(fuzzy_sets):
"""
Order a fuzzy set list by their centroids
:param fuzzy_sets: a dictionary where the key is the fuzzy set name and the value is the fuzzy set object.
:return: a list with the fuzzy sets names ordered by their centroids.
"""
if len(fuzzy_sets) > 0:
tmp1 = ... | eeb03e3400fa53755e17577eb7c40818a3cd3997 | 567,760 |
def getIter(object):
"""Return an iterator (if any) for object
"""
iterator = None
try:
iterator = iter(object)
except TypeError:
pass
return iterator | 9b1b39d53134a06baca4216b3b31e42c1d07c6e0 | 567,764 |
def read_file(path):
"""Read entire file content as string."""
with open(path) as file:
return file.read() | a81082fa9e010c10e6490f672d28e1009c568f5c | 567,765 |
def _element_identification_string(element):
"""
Gets a string that will hopefully help in identifing an element when there
is an error.
"""
info_string = "tag: {}".format(element.tag)
try:
elem_id = element.attrib["id"]
info_string += " id: {}".format(elem_id)
except KeyErro... | 2d320a71cbb0b053516fb8963c79f758203eb152 | 567,774 |
from typing import Iterable
from typing import Any
from typing import Optional
from typing import Callable
from typing import Dict
from typing import Mapping
def table(
headers: Iterable[str],
rows: Iterable[Iterable[Any]],
fill: str = "",
header_fmt: Optional[Callable[[str], str]] = None,
row_fmt... | a614ffd76627c2ad8c2c96267f443aa6ebc68915 | 567,778 |
def almost_equal(s1, s2, eps=1e-5):
"""
>>> a = (LatLon(55.77286, 37.8976), LatLon(55.77291, 37.89766))
>>> b = (LatLon(55.77286, 37.89761), LatLon(55.77291, 37.89767))
>>> almost_equal(a, b)
True
>>> a = (LatLon(55.89259, 37.72521), LatLon(55.89269, 37.72535))
>>> b = (LatLon(55.89259, 37.7... | d84f4a9eb1e3ea87a700f6a74499ce99de558d8a | 567,780 |
import re
def slot_name_from_member_name(member_name):
"""Translate member name to valid PostgreSQL slot name.
PostgreSQL replication slot names must be valid PostgreSQL names. This function maps the wider space of
member names to valid PostgreSQL names. Names are lowercased, dashes and periods common in... | aed9d999436095810e2348d29497718d6f73a787 | 567,788 |
def query_b(geoType,keyCol,**valConstraint):
"""
This function builds an SQL query from the values passed to the retrieve() function.
Arguments:
*geoType* : Type of geometry (osm layer) to search for.
*keyCol* : A list of keys/columns that should be selected from the layer.
***val... | e681a50f225adee84d0d368b83e5657551aed88b | 567,791 |
def get_prnt(node1, node2, parents):
"""Determine which of the nodes is child and which is parent.
Args:
node1 (str): first node of the edge
node2 (str): second node of the edge
parents (dict): dictionary mapping nodes to their parents
Returns:
str, str: id's of child and parent
... | f46248fb0d24cdefd92c8b00e76c9581711414cb | 567,793 |
def indice_maximum_liste(t):
"""
Renvoie l'int max d'une liste
Args:
t (list): Liste d'int
Returns:
int: Max
"""
assert len(t) > 0, "Le tableau est vide"
m = 0
for i in range(len(t)):
if t[i] > t[m]:
m = i
return m | ad03c862c7267d742e31caae9ad2f7f257d50d22 | 567,794 |
import math
def _Prefix(quantity, unit, precision, scale_callable, **args):
"""Formats an integer and a unit into a string.
Args:
quantity: A number.
unit: A string, the dimension for quantity, with no multipliers (e.g.
"bps"). If quantity is dimensionless, the empty string.
precision: An in... | 74ea1a7d075cab3519d5dbd875154d2bdd56fea5 | 567,805 |
def is_unique_column(df_column):
"""
:param df_column: Column of a pandas data frame
:return: Boolean encoding if the column has unique values
"""
return len(df_column.unique()) == len(df_column) | 27f2bb8649bb1a0fd7b5c626b5defc7613435e88 | 567,808 |
def remove_borders(keypoints, scores, border: int, height: int, width: int):
""" Removes keypoints too close to the border """
mask_h = (keypoints[:, 0] >= border) & (
keypoints[:, 0] < (height - border))
mask_w = (keypoints[:, 1] >= border) & (keypoints[:, 1] < (width - border))
mask = mask_h &... | cfac58f32ec840d66f883c2447b751180ccec9be | 567,809 |
from typing import Dict
from typing import Any
from typing import Tuple
def _as_ordered_key(
dictionary: Dict[str, Any]
) -> Tuple[Tuple[Any, ...], Tuple[Any, ...]]:
"""Turns a dictionary into a tuple. Used at _generate_key.
First entry is a tuple containing the key, second entry is tuple containing the
... | 65d602babe9f722f4b191d5b135d062f569390c1 | 567,812 |
def get_classes_of_type(module, class_type):
""" Within a module, there can be many class definitions. This filters all
classes within a module that inherit from class_type. Useful for getting
all blueprints from a views module, or orm objects from a models module.
"""
object_names = filter(
... | b0704051544dcd09ec385fd73846a1e3289068bb | 567,814 |
def nudge_min_max(min, max, num_bits, narrow_range):
"""
Calculate the maximum and minimum values of the quantization
Args:
min: scalar, input min
max: input max
num_bits: scalar
Defaults to 8. num_bits is the bitwidth of the quantization, range [2,16]
narrow_range: ... | ceb29f503164bcb5563621f27d8c135464c776be | 567,818 |
def list_contexts(flowlist):
"""Displays list of contexts along with 1 if the context is present for that flowclass.
Can send a preferred list or
:param flowlist: A FlowList in standard format
:return: pandas df with 'Context',plus columns for all flow classes
"""
contexts = flowlist[['Conte... | 2f845c69003b5e75b8413dd9578d0099cdc9a107 | 567,819 |
def eqcounter(cons, ndof_node=2):
"""Count active equations
Creates boundary conditions array bc_array
Parameters
----------
cons : ndarray.
Array with constraints for each node.
Returns
-------
neq : int
Number of equations in the system after removing the nodes
wit... | eea07a32261cfebd5ca239c7f0f0ef2b37669df7 | 567,825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.