content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import posixpath
def join_paths(a, *p):
"""
Joins multiple paths and ensures that the '/' is removed from the end.
Any path in *p that starts with / will be have the / removed.
"""
return posixpath.join(a, *(i.lstrip('/') for i in p)).rstrip('/') | 7e3fa0b56f6b3621643e2c47cf90faf16249369c | 645,311 |
def get(obj, field):
"""
Extracts field value from nested object
:type obj: ``dict``
:param obj: The object to extract the field from
:type field: ``str``
:param field: The field to extract from the object, given in dot notation
:return: The value of the extracted field
:rtype: ``str`... | 6b484d65d3aad84e944195db898afdd5d1986aca | 645,320 |
def pick_id(id, objects):
"""pick an object out of a list of objects using its id
"""
return list(filter(lambda o: o["id"] == id, objects)) | 3f3293cb35bd22446e8d3da4f45d007a858b0247 | 645,323 |
from typing import Optional
from pathlib import Path
from typing import List
def read_exclusion_file(path: Optional[Path] = None) -> List[str]:
"""Read a .exclusion file to determine which files should not be automatically re-generated
in .GitIgnore format
"""
if path is None:
path = Path("."... | 861f0352338426425385b0969fa13cc72e6259f0 | 645,328 |
def check_ascii(text: str) -> bool:
"""Check is a string is ASCII.
Args:
text (str): The string to check.
Returns:
bool: False means the text was not ASCII.
"""
if any(ord(c) >= 128 for c in text):
return False
return True | 8daff5b8875c1744137fe79e5937474d73cdf7de | 645,331 |
def create_fields(instance, **kwargs):
"""Return dict of fields to be used as create params."""
site = kwargs.pop("site", instance.site)
creation_user = kwargs.pop("creation_user", instance.creation_user)
effective_user = kwargs.pop("effective_user", instance.effective_user)
update_user = kwargs.pop... | fec2b6f9e6fd02ecf52bae8440e6bb2be68dbcbb | 645,334 |
def get_actual_source_freqs(messages_dets, expected_source_freqs):
"""
Check the message sources are as expected. Note - we don't have to know what
messages generated from helpers in other modules will do - just what we
expect from this module. So we don't specify what sources we expect - just
those... | 3bf2bc50e4983af378f734fb71a2a2494b174de4 | 645,337 |
from math import sqrt
def distance(x1, y1, z1, x2, y2, z2, round_out=0):
"""
distance between two points in space for orthogonal axes.
>>> distance(1, 1, 1, 2, 2, 2, 4)
1.7321
>>> distance(1, 0, 0, 2, 0, 0, 4)
1.0
"""
d = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2)
if ro... | 29a6b234f190acd40aa9850e2054ffc846215557 | 645,339 |
def get_models(config):
""" Get a list of the models in the source database
Args:
config (:obj:`dict`): configuration
Returns:
:obj:`list` of :obj:`dict`: models
"""
response = config['source_session'].get(config['source_api_endpoint'] + '/models')
response.raise_for_status()
... | ff722943deeda165d1fb5204abaed9a154dde007 | 645,340 |
import json
def from_json(value):
""" Decodes a JSON string into an object.
:param str value: String to decode
:returns: Decoded JSON object
"""
return json.loads(value) | 8ab44eb73063fce49dbcc5f1ad51768f27620a41 | 645,349 |
def scheming_field_required(field):
"""
Return field['required'] or guess based on validators if not present.
"""
if 'required' in field:
return field['required']
return 'not_empty' in field.get('validators', '').split() | 1c348ee62e50d1e4563bc0549390295d502dacca | 645,353 |
def replace_from_to(text, start_position, end_position, new_text):
""" Replaces the substring within the given range against another text."""
return "{}{}{}".format(text[:start_position], new_text, text[end_position:]) | a2182756656c4a5fe6069b5ebefb3a4e7b788df2 | 645,354 |
from typing import List
from typing import Dict
def get_flags(args: List[str]) -> Dict[str, List[str]]:
"""
Returns a dictionary containing the flags within the passed through command line arguments.
# Example
```py
# $ py ./src/main.py normal_argument -flag1 Hello, World ... | 2eba1fd243824b8e212b45e70c60b30ec225398d | 645,356 |
def len_selfies(selfies: str) -> int:
"""Returns the number of symbols in a given SELFIES string.
:param selfies: a SELFIES string.
:return: the symbol length of the SELFIES string.
:Example:
>>> import selfies as sf
>>> sf.len_selfies("[C][=C][F].[C]")
5
"""
return selfies.count... | 61f846c61bab517449fcc54717bd7836547bf026 | 645,360 |
def parse_log_level_names(str_log_level_names):
"""20:INFO,30:WARN,40:ERROR,50:FATAL"""
if not str_log_level_names:
return {}
log_levels = str_log_level_names.split(",")
log_levels = [item.split(":") for item in log_levels]
level_names = {int(level): name for level, name in log_levels}
... | 0c540d2ed8a12ffb841b055421c11d5cc2e827af | 645,364 |
def checkXML(XML, path):
"""Looks for path to XML tag and pulls out the text therein."""
if XML.find(path) is not None:
if XML.find(path).text is not None:
return XML.find(path).text
else:
return ""
else:
return "" | 5bd708cea712ce77760eb32fba61dfdd5db10d41 | 645,365 |
def compute_mean(sample):
"""Computes sample mean"""
return sum(sample) / float(len(sample) or 1) | 4ff4cf6659ed52607acd8323e182d16bbe809b24 | 645,368 |
def to_pascalcase(s: str) -> str:
"""convert a python identifier string to pascal case.
Examples:
>>> to_pascalcase('my_identifier')
myIdentifier
>>> to_pascalcase('my_long_identifier')
myLongIdentifier
>>> to_pascalcase('crab')
crab
"""
first, *other = s... | c1a5ee7d2fc7230bd2bbf8644d1a5b697e734904 | 645,370 |
def count_lines(input_file) -> int:
"""Count the lines of a given file
Args:
input_file (str): The file to open
Returns:
int: An integer that shows the line number
"""
with open(input_file) as f:
return sum(1 for line in f) | 4d6d03b5ff02ed78a65bfa426e2c484a247557b4 | 645,371 |
def getCanonicalSvnPath(path):
"""Returns the supplied svn repo path *without* the trailing / character.
Some pysvn methods raise exceptions if svn directory URLs end with a
trailing / ("non-canonical form") and some do not. Go figure...
"""
if path and path.endswith('/'):
path = path[:-1]
return path | 1d557a8ceddb3e7a987af25ec7dc549d7e337c96 | 645,378 |
def _paths_for_iter(diff, iter_type):
"""
Get the set for all the files in the given diff for the specified type.
:param diff: git diff to query.
:param iter_type: Iter type ['M', 'A', 'R', 'D'].
:return: set of changed files.
"""
a_path_changes = {change.a_path for change in diff.iter_chan... | fe828c21277c1051aebc4c125b53228ab9c7cc12 | 645,380 |
import json
def to_json(content: str) -> dict:
"""
deserialize the str to JSON object \n
:param content: the target json str
:return: the JSON object
:rtype dict
"""
return json.loads(content) | b9d8cb90ebb5409f9d38ae186721bf1a80107518 | 645,381 |
def remove_white_space(input):
"""Remove all types of spaces from input"""
input = input.replace(u"\xa0", u" ") # remove space
# remove white spaces, new lines and tabs
return " ".join(input.split()) | be8fb7f2b5409649e0bda614412037477354fb76 | 645,383 |
def safe_int(string):
""" Utility function to convert python objects to integer values without throwing an exception """
try:
return int(string)
except ValueError:
return None | 31f56458b833cef80a13ec097d5de696c11f0695 | 645,384 |
def directory_in_zip(zip_f, directory_name):
"""Determine if a directory exists in a ZIP"""
return any(x.startswith("%s/" % directory_name.rstrip("/"))
for x in zip_f.namelist()) | 94cb8f94661a4734c00a0227b104c738db1e2c48 | 645,389 |
import ast
from typing import Tuple
from typing import Type
def is_contained(node: ast.AST, to_check: Tuple[Type[ast.AST], ...]) -> bool:
"""Checks whether node does contain given subnode types."""
for child in ast.walk(node):
if isinstance(child, to_check):
return True
return False | e2d9ce47280a19180d7c2d10a1bf92f2c5227914 | 645,395 |
from datetime import datetime
def timestamp() -> str:
"""Timestamp that can be used in a file name."""
return datetime.now().isoformat().replace(":", "-") | 18f36c6f08333ff54b0eec19c205123a15875a22 | 645,399 |
import re
def split_string_on_punctuation(text):
"""Split on ?!.,; - e.g. "hi, how are you doing? blabla" ->
['hi', 'how are you doing', 'blabla']
(make sure you strip trailing spaces)"""
pattern = r'[?!.,;][\s]*'
return [i for i in re.sub(pattern, "|", text).split("|") if i != ""]
pass | c0334332d79c7dee9e98c7c215b0be657b7292c1 | 645,401 |
import json
def getResponseUrl(response):
"""
Get the return url from a hosted payment API call
:param response: Response object in JSON
:return: Transaction ID
"""
resp_dict = json.loads(response.text)
try:
url = resp_dict["url"]
except KeyError:
print('Retrieval uns... | 9abec3c44284e112d877efac02aa20d102254d54 | 645,402 |
def prefix_max(array: list, i: int) -> int:
"""Return index of maximum item in array[:i+1]"""
if i >= 1:
j = prefix_max(array, i-1)
if array[i] < array[j]:
return j
return i | 42d3b77e83e9783e30c6618b63e3cb060113f7e0 | 645,403 |
def formatDollars(d,noneValue='',zeroValue='$0'):
"""Formats a number as a whole dollar value with alternatives for None and 0."""
if d is None:
return noneValue
elif d==0:
return zeroValue
return '${:.0f}'.format(d) | 88972887ed4c8a894d74e4cbabb0a74e44d2c815 | 645,405 |
from typing import List
from typing import Any
def pad(sents: List[List[Any]], pad_token: Any):
""" Pad list of sentences according to the longest sentence in the batch.
@param sents: list of sentences, where each sentence
is represented as a list of words
@param pad_to... | 4e6d368701f7d9cee7498ab88cb7684487ffc2fd | 645,406 |
def parse_optionalString(value):
"""parse an optional string"""
if not value:
return None
return value | b3f45005b0cbffe7214f8d3240ecf79705fa9743 | 645,407 |
def get_base_req(req):
"""Get the name of the required package for the given requirement."""
if isinstance(req, tuple):
req = req[0]
return req.split(":", 1)[0] | 03642dedb41cda6841e6a63e3c9c50e2e8676234 | 645,411 |
def optimize(f, g, c, x0, n, count, prob):
"""
Args:
f (function): Function to be optimized
g (function): Gradient function for `f`
c (function): Function evaluating constraints
x0 (np.array): Initial position to start from
n (int): Number of evaluations allowed. Remember... | fad95de8d225fb158dff375b2a11059b229ea056 | 645,415 |
def addition(num1, num2=0):
"""
Adds two numbers
Args:
num1: The first number
num2: The second number, default 0
Returns:
The result of the addition process
"""
return (num1+num2) | 2a573575cbfbcf3b6165f8076a80c008c0b50b79 | 645,418 |
def build_n_sequence_dictionary(n : int, txt : str) -> dict:
"""
Returns a dict counting appearances of n-long progressions
Parameters
----------
n : int
The length of progressions to count
txt : str
A comma-separated string of roman numerals
Returns
-------
dict
... | 1b229dad484bef6d20b5bcc6c908a7b4240ca8ce | 645,426 |
from typing import Dict
def rb2coco_bbox(
rb_label: Dict,
label_id: int,
image_id: int,
category_id: int,
width: int,
height: int,
) -> Dict:
"""Convert rb bbox to coco bbox."""
assert rb_label["bbox2d"]
xnorm = rb_label["bbox2d"]["xnorm"]
ynorm = rb_label["bbox2d"]["ynorm"]
... | 4aa6d3b2c4c21d07e5b60df272f27de290169035 | 645,427 |
def find_key(value, dictionary, default=None):
"""
Find the given value in the given dictionary and returns its key.
If value is not found - return default value (None or given).
If many elements can be found - return one of them arbitrarily (the first one found)::
>>> find_key('d', {'a': 'b', ... | 5acef8b8cb35e0e3420ff4f9264b37d6ef8cec0f | 645,429 |
def caloria_function(is_male: bool, weight: float, height: float, age: float, sport_a_week: int) -> float:
"""
Calculates 24hour calory need.
Returns -1 in any error case.
:param is_male: True/False. Does human have MALE sex?
:param weight: float, kilograms
:param height: float, santimeters
... | 20ea77f846ad4455a119675b36f09a6995bfc23d | 645,434 |
from datetime import datetime
def get_datetime(date, time, *, microseconds=True):
"""
Combine date and time from dicom to isoformat.
Parameters
----------
date : str
Date in YYYYMMDD format.
time : str
Time in either HHMMSS.ffffff format or HHMMSS format.
microseconds: boo... | 641f91292da33de6d516bfa06749c98bee1dc028 | 645,437 |
def remove_dup(df_tweet):
""" Remove dupicated tweets (based on the 'tweet' text column)
For duplicated tweets, it will keep the first tweeet
Args:
df_tweet (pandas df): dataframe containing covid tweet
Returns:
df_tweet (pandas df): dataframe with duplicated tweets removed
"""
... | ced960eae68e0882ba0739cdb2734bfdc01192a5 | 645,438 |
import ipaddress
def ip_subtract(ip, val):
"""Subtract an integer to an IP address.
Args:
ip (str): An IP address in string format that is able to be converted by `ipaddress` library.
val (int): An integer of which the IP address should be subtracted by.
Returns:
str: IP address ... | 0372ba4f14f6a3722ea7843a8c36c5470890004d | 645,439 |
def within(min=None, max=None):
"""
Create a validation function to check whether an argument value is within
a specified range (inclusive).
`min` and `max` cannot both be None.
:param min: A lower bound for the value. Optional.
:param max: An upper bound for the value. Optional.
:return: A... | 03a6d4d7ac14f7c7845c9cdb5d9aa662af352ce6 | 645,440 |
import math
def _adamic_adar(set_one: list, set_two: list, graph) -> float:
"""
Calculate Adamic Adar score for input lists
:param set_one: A list of graph nodes -> part one
:param set_two: A list of graph nodes -> part two
:param graph: NetworkX bipartite graph
:return: Adamic Adar score
... | 65cf8c85c7fe888ad8f339622a6fb0b0b4949b35 | 645,443 |
def convert_hex_ascii_to_int(int_val):
"""
Use to convert from hex-ascii to int when encoding data particle values
"""
return int(int_val, 16) | 50774d5a2e9c2cfaed5e25f4031585cb496a7a1b | 645,459 |
def delta4(a, b, c, d):
"""Delta function (4 variables)
"""
if (a == b) & (b == c) & (c == d):
return 1
else:
return 0 | 060dd5491957e8d343f0a3a7ceae70ae2955e9b8 | 645,460 |
def _TestTypesMatch(types_to_run, this_tests_types):
"""types_to_run should be a set of test types to run. this_test_types should
be an iterable. Returns true if any type in the latter is also in the former,
i.e., if the two are not disjoint."""
return not types_to_run.isdisjoint(this_tests_types) | ebaa99b02039cd774f469414dd5a29844a27536e | 645,461 |
import itertools
def sorted_groupby(iterator, key, reverse=False):
"""
Similar to `itertools.groupby`, but sorts the iterator with the same
key first.
"""
return itertools.groupby(sorted(iterator, key=key, reverse=reverse), key) | e6f018f5828d070492a78d482b763ba864db0f10 | 645,469 |
def has_decorator(source_lines: list) -> bool:
"""
Checks if the source code for a function has a decorator or not
:param source_lines: Source code lines of a function
:return: True if there is a decorator else False
"""
return '@' in source_lines[0] | 84399e3eda2063f6f9bdbe474470c2cce362c5fc | 645,471 |
def get_phenotype_curie(phenotype_uri):
"""Extract Phenotypes CURIE from the URI
"""
if '/MEDDRA/' in phenotype_uri:
phenotype_id = phenotype_uri.split("/MEDDRA/", 1)[1]
return 'MEDDRA:' + phenotype_id
if '/HP:' in phenotype_uri:
phenotype_id = phenotype_uri.split("/HP:", 1)[1]
... | 708ee8da8a544f57189fb252452c4bf8c856dab7 | 645,472 |
def quick_stats(x, digits=3):
"""Quick wrapper to get mean and standard deviation of a tensor.
Parameters
----------
x: torch.Tensor
digits: int
Number of digits to round mean and standard deviation to.
Returns
-------
tuple[float]
"""
return round(x.mean().item(), digi... | 90a72d9499acb3cdd92515974f9f96f2aed123e8 | 645,473 |
def get_output_sdf_path(gold_conf_path):
"""
This function extracts the output sdf path for docking results from a gold conf-file.
Parameters
----------
gold_conf_path : str
Full path to gold conf-file.
Returns
-------
sdf_path : str
Full path to sdf-file.
"""
w... | 7d1cf606f62eae64ec91134b1e2520e2a0f1976f | 645,474 |
def getRequestsFileName(request):
"""Get the filename from a Requests context"""
content_disposition = request.headers.get("Content-Disposition")
if content_disposition is not None:
attributes = (x.strip() for x in content_disposition.split(";")
if x.startswith("filename="))
... | 4da0ef43d8fde804ee93f9de99208055a600a6fc | 645,475 |
def config_contains_tar(pipeline_config: dict, tags=None) -> bool:
"""
Check if the input file list contains a `.tar` archive.
"""
if tags is None:
tags = ["archive", "inside_archive"]
params = pipeline_config.get("params", {})
ffiles = params.get("fetch_files", [])
for ff in ffile... | 65c38a5f953f8236b2886abd6c46aeb8b6f14d65 | 645,476 |
def stats_variable_names(res):
"""Return the variable names for a stats object"""
def varname(s):
pos = s.find(':')
return s if pos==-1 else s[0:pos]
return set( [ varname(key) for key in res.keys()] ) | bcc97d16d3bf2bb2eb1e374e49a9268ac1ebeedf | 645,478 |
import socket
def _validate_as_ipv6(text: str) -> bool:
"""
A helper function for verifying that a string represents an IPv6 address.
:param text: the string to verify.
:return: `True` if the string looks like an IPv6 address or `False` if not.
"""
try:
socket.inet_pton(socket.AF_INET... | b6983533bddcf111ffcbce1a8b53f96d8c9f95d0 | 645,481 |
def fahrenheit(T_in_celsius):
""" returns the temperature in degrees Fahrenheit """
print ("FLAG --> my function call is here, accepting temp deg C and returning temp deg Fahrenheit ")
return (T_in_celsius * 9 / 5) + 32 | c4fa739923c5200267ab5eba6090143f5c479bc4 | 645,482 |
def pc_to_m(pc):
"""
Converts the input distance (or velocity) of the input from parsec to meters.
"""
return pc * 3.085677581 * 10**18 | 47b035a1e26f7e305f674687f5bfba2da791db3f | 645,485 |
import torch
def shiftdim(x, n=None):
"""Shift the dimensions of x by n.
Parameters
----------
x : torch.Tensor
Input tensor.
n : int, default=None
Shift.
* When N is positive, `shiftdim` shifts the dimensions to
the left and wraps the N l... | 972508bcd6d72fff37dcc690597884b8ee29d44f | 645,486 |
import json
def get_json(raw):
"""
Returns the given text expressed as JSON, or None if any error occurred.
"""
try:
return json.loads(raw)
except:
return None | 477b8d13c49188f62ebafc872201365a04a77853 | 645,487 |
def klass(obj) -> str:
"""
returns class name of the object. Might be useful when rendering widget class names
Args:
obj: any python class object
Returns:
str: name of the class
>>> from tests.test_app.models import Author
>>> klass(Author)
'ModelBase'
"""
retur... | 39eb3913e33b895889ec5a7f29fb37b9a634eb5b | 645,488 |
def hasannotation(string_list):
"""
Judge whether the string type parameter string_list contains annotation
"""
for c in string_list:
if c == "#":
return True
return False | fda92b66675c3333c9bf7ff99dbcefd12b7fb349 | 645,491 |
def _add_extension_asset(
client, customer_id, phone_number, phone_country, conversion_action_id
):
"""Creates a new asset for the call.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
phone_number: a phone number for your business, e.g. '(1... | 0065de950c3a8909489dbeea4dfbf02d5b76a820 | 645,492 |
def find_value(key, headers):
"""
Search *headers* for *key* and return the common value shared
across each element of *headers* and raise an exception if
multiple values are encountered.
"""
values = set([x[key] for x in headers])
if len(values) == 0:
raise KeyError('{} not found'.f... | e7632abdb07ce5630bd98bdde3e1af7154b392b6 | 645,494 |
def remove_even_integers(_array: list) -> list:
"""
Remove Even Integers from Array
"""
new_arrays = [number for number in _array if number % 2]
return new_arrays | a65d876d363a5f1c4eb18175870b67a3a8333c60 | 645,495 |
def exibeTokens(tokens):
"""
Apresenta sentença toquenizada no formato canônico, como string.
"""
tokens=[t.encode("utf-8") for t in tokens]
return " ".join(tokens) | 94f55e20a9671d3ee4af09dec966c32995ba5d61 | 645,496 |
def get_rp_health_summary(isamAppliance, check_mode=False, force=False):
"""
Retrieving a summary of Reverse Proxy health
"""
return isamAppliance.invoke_get("Retrieving a summary of Reverse Proxy health",
"/wga/widgets/health.json") | 9e4d7c5b5c29e20e178ee754c8496ede1149ce11 | 645,497 |
def input_validation(input):
"""
This function is used to test the stock ticker inputs and validate that they
pass the two key characteristics tests: being less than 5 characters in length
and having no digits.
@param: input is a string argument that represents the given input the c... | b89845fcdaa7f11781d24f500767645e51b97100 | 645,510 |
def get_currency_for_stripe(currency):
"""Convert Saleor's currency format to Stripe's currency format.
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.lower() | 733a12d69af02d6ed3c55d5a2328cf55cc58b75b | 645,511 |
def get_mask_file(img_file):
"""Takes an image file name and returns the corresponding mask file. The mask represents
pixels that belong to the object. Default implentation assumes mask file has same path
as image file with different extension only. Write custom code for getting mask file here
... | 9f0185817ae8dd6b0858eb9f336609e29226679e | 645,528 |
def exists_position(layout, row, column):
"""
Checks whether given row and column indices represent a valid position in
the layout.
Check whether row is inside the range od rows, check whether the column is
at or below the right edge of the keypad and finally check the left edge is
not a placeho... | 5cebd778a311992551c0bf74cd074b804cafdd99 | 645,535 |
import string
import random
def generate_random_string(length=8):
"""
Generate a random string
"""
char_set = string.ascii_uppercase + string.digits
return ''.join(random.sample(char_set * (length - 1), length)) | ff89304b3d695a6fcc22d2ee1b9e603eaf2b3a6d | 645,538 |
import configparser
def simulation_configuration(path):
"""
Reads an ASCII file with relevant parameters for simulation.
Parameters
----------
path : string
Path to ASCII file.
Returns
-------
can_params : dict
Parameters for cantilever properties. The dictionary contains:
amp_invols = float (in m/V)... | 650723c92ab53d93b1b6c036dd5bb5b2b59b46ee | 645,539 |
import re
def normalize_tainted_string(questionablestring):
"""
Trim, remove any non alphanumeric character and lower-case a questionable string
:param questionablestring: tainted string
:return: the normalized string
"""
return re.sub('\s+', ' ', re.sub('[\W_]+', ' ', questionablestring.lower... | bfc682d6447035e08a2de132e12c36863186a874 | 645,541 |
def mobius_inverse(a,b,c,d):
"""
Inverse of a Mobius transformation.
Parameters
----------
a : complex number
b : complex number
c : complex number
d : complex number
Returns
-------
function from C -> C
"""
return lambda z: (d*z - b)/(-c*z + a) | a628ed97b8ae42d79d3392e51afdd740212c3a60 | 645,542 |
from typing import Iterable
from typing import Tuple
from typing import Pattern
from typing import Optional
def pattern_match(string: str, patterns: Iterable[Tuple[Pattern[str], str]]) -> Optional[str]:
"""
Returns the replacement string when a pattern matches the string query
:param string: string to se... | f8b5c60fa02c53f5e644851ab23a7fcdea8abe59 | 645,546 |
def terminal_errors_except(*args):
"""
Returns a ``can_retry`` function for :py:func:retry` that only retries if
errors the ``Exception`` types specified.
:return: a function that accepts a :class:`Failure` and returns ``True``
only if the :class:`Failure` wraps an Exception passed in the args.... | f928574ca644bdf6556751e32e46fc12c55f007c | 645,549 |
def _del_temp(beta, rhat_dot_dgam, dgam0):
"""Returns the small correction in surface temperature
See Eqn (10) from Jackson+ (2012) ApJ.
Args:
beta (float): gravity-darkening exponent, probably 0.07 or 0.25
rhat_dot_dgam (numpy array): dot product between the unit location
vect... | 76cd0e33396b167653ad48b4aee1e24493c791a2 | 645,550 |
def capitalize(string):
""" helper function to create capitalized copy of string. """
return string[:1].upper() + string[1:] | 60f11ae2c60809b36e3ff2be7881ae7dfd606d08 | 645,554 |
def align_up(offset, align):
"""Align ``offset`` up to ``align`` boundary.
Args:
offset (int): value to be aligned.
align (int): alignment boundary.
Returns:
int: aligned offset.
>>> align_up(3, 2)
4
>>> align_up(3, 1)
3
"""
remain = offset % align
if ... | f74c2c3fba775d6bb15b7faf369e8706ecccc610 | 645,556 |
def much_consistency(df):
""" Helper function to handle known inconsistencies in raw data files
:param df: A pandas dataframe, BLS OEWS data set
:return df: A pandas dataframe
"""
# Force lower case column headers
df.columns = map(str.lower, df.columns)
print("...Forced column headers to ... | 009cf2972a6155296af7667b2c614c43c314683c | 645,558 |
def sanitize_webscrape_name(name):
""" Sanitizes webscrape powerplant names by removing unwanted
strings (listed in blacklist), applying lower case, and deleting
trailing whitespace.
Parameters
----------
name: str
webscrape plant name
Returns
-------
name: str
sani... | b4be5d8a25402e72011d20a4b652e6b5ca39650e | 645,560 |
import torch
def apply_gaussian_noise(img, amplifier=0.1):
"""
Applies gaussian noise to given image.
:param img: input image to add noise.
:param amplifier: noise amplifier to control noise.
:return: noisy image
"""
noise = torch.randn_like(img)
return (amplifier * noise) + img | bee094f6f305b97db0e61cbd9062de10b8a09ac9 | 645,562 |
def _check_not_in(obj, string):
"""
The 'i' substring of the list 'obj' must not be in 'string
:param obj: list of substring
:param string: element that needs to be checked
:return: False if a 'obj' substring is contained in 'string', True otherwise
"""
for i in obj:
if i in string:
... | 5e0958a63dc089abb7809044e3d68ecb5216e013 | 645,572 |
import math
def calc_eyebrow_coordinates(anchor_point, length, angle, width):
"""
Calculates points of eyebrow
:param anchor_point: a bottom right (bottom left) point
:param length: eyebrow length x
:param angle: brow angle
:param width: eyebrow thickness
:return: coordinates
"""
x... | 620ac9f52bbec246fe0704222b931bdbf1e46289 | 645,573 |
def normalise_bytes(buffer_object):
"""Cast the input into array of bytes."""
return memoryview(buffer_object).cast("B") | 87f5ff72d5d3e9ed796444c365e18d331103d0e4 | 645,575 |
def find_strongest_bot(bots):
"""Find bot with largest radius."""
return max(bots, key=lambda bot: bot.radius) | 3318e4a5ae94b5889426f5414697ab5098501dea | 645,576 |
def get_formatted_city_country(city, country, population=''):
"""Generate a neatly formatted city and country."""
city_country = city.title() + ', ' + country.title() + ': ' + population
return city_country | 830ba375b0cf7e2d0c14753e67b0b6d5fed21c44 | 645,581 |
from itertools import compress
def list_contains(list_of_strings, substring, return_true_false_array=False):
""" Get strings in list which contains substring.
"""
key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings]
if return_true_false_array:
return key_tf
keys_to_remove = ... | f901a88839b48f219c6758dd89e1bc65f6b4a6f0 | 645,583 |
import json
def agg_all(run_dir, solved, map_fct, agg_fct):
""" Calculate aggregates over all runs.
Args:
run_dir: directory containing benchmark results
solved: whether to consider only successful tries
map_fct: maps tries to values for aggregation
agg_fct: function used ... | 6cb1771c1aa322cee596f7bc3c3aba181c603a12 | 645,590 |
import json
def _record_message(record):
"""Return the message part of the given SNS record."""
source = record["EventSource"]
if source == "aws:sns":
return json.loads(record["Sns"]["Message"])
raise ValueError(f"Unsuported 'EventSource' {source}. Supported types: 'aws:sns'") | ab2c68bc464f32bbb02cf1848dbd79adefe46d15 | 645,594 |
def compress_secp256k1_public(point):
"""
Returns a 33-byte compressed key from an secp256k1 public key,
which is a point in the form (x,y) where both x and y are 32-byte ints
"""
if point.y % 2:
prefix = b'\x03'
else:
prefix = b'\x02'
return prefix + point.x.to_bytes(32, byt... | 39c914c85886f7987c51a9136a3e930cf42eaf38 | 645,598 |
def space_pad(number, length):
"""
Return a number as a string, padded with spaces to make it the given length
:param number: the number to pad with spaces (can be int or float)
:param length: the specified length
:returns: the number padded with spaces as a string
"""
number_length = len(... | 998a9de2644f69bc10feae0d4d3322ca5665f89f | 645,606 |
import re
def ecm_kw_regex_select(ecm_names_list, list_of_match_str):
"""Identify matching, non-matching ECM names using a list of search terms
This function searches a list of ECM names to find all of the ECM
names that have the words specified by the user as search terms.
This function is used to i... | dcc7dd512db184c7e09a91b0fed41151b0b420bd | 645,607 |
def tupleify_state(state):
"""
Returns the state as a tuple
"""
temp = []
for row in state:
temp.append(tuple(row))
return tuple(temp) | ae311fe1c9eba3c5d8aef3f8519b0d722089cb42 | 645,611 |
def lock_params(access_mode):
"""Returns parameters for Action Lock"""
return {'_action': 'LOCK', 'accessMode': access_mode} | 4918b5d4028389ce4325171d414ab9b7bb1225f5 | 645,612 |
def minus(set1, set2):
"""Given the two sets, returns set1 - set2."""
return set1 - set2 | 546a8d0b520ab217c95a97e2da74543efd9c592b | 645,613 |
def count_perturbations(perturbed_nodes_by_t):
"""
Count number of perturbations.
:param perturbed_nodes_by_t: dict (by time step) of dicts (by node) of node states
:return: number of perturbations
"""
return sum(len(current_perturbed_nodes)
for current_perturbed_nodes in perturb... | 6de029c0d9f05ff561566ea894a930fadc018233 | 645,615 |
def TimeToString(dt):
"""Convert a DateTime object to an ISO8601-encoded string."""
return dt.isoformat() + 'Z' | b374c750fedb8b17c1aee946639e2c2b21a5ffa6 | 645,616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.