content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_email_domain(email):
"""
Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_emai... | 941717a8a614235dd17b1573fc8a962c5f869cb9 | 650,641 |
def factR(n):
"""Assumes n an int > 0
Returns n!"""
if n == 1:
return n
else:
return n*factR(n - 1) | a53dd510438592bfd64799812da3e5a21b524d13 | 650,642 |
from typing import Callable
def get_values_by_keys(k: list, default=None)->Callable[[dict], list]:
"""
Filter dictionary by list of keys.
Parameters
----------
k: list
default: any, optional
Set as default value for key not in dict.
Default value is None
"""
return lam... | 2306493ef30753cac90d16529a4f128c45877fba | 650,643 |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... | 76a0a2e5148327f4ca311be74d974492129d4a3f | 650,647 |
def find_version_attribute(obj):
"""Depending on the object, modified, created or _date_added is used to store the
object version"""
if "modified" in obj:
return "modified"
elif "created" in obj:
return "created"
elif "_date_added" in obj:
return "_date_added" | 3b1068e65dd9341e4887a0c65904d41b6c9bea22 | 650,648 |
def returnTrue(layer):
"""Returns True for any object passed to it."""
return True | 4a4fac0cb57e4f092571e395ae435c4069d26496 | 650,652 |
def all_debates(debates):
"""Debate filter returning all debates.
"""
return debates | 2b4144cc640018198b6c85cb71fe1e5af5c6b1b6 | 650,654 |
def get_shell_from_file(shellname):
"""
Returns the shell from a .shell file in the shell directory as a string. It
can then be formatted to place ip and port in the file.
"""
filecontents = None
with open('shells/{}.shell'.format(shellname), 'r') as f:
filecontents = f.read()
return... | c82951afeef53d571a3fc453279df51b820970b3 | 650,660 |
def setKeyPath(parent, keyPath, value):
"""
Allows the setting of arbitrary nested dictionary keys via a single
dot-separated string. For example, setKeyPath(parent, "foo.bar.baz",
"xyzzy") would create any intermediate missing directories (or whatever
class parent is, such as ConfigDict) so that t... | c92b1312b54e4a71be81c6577024def06a0b85f8 | 650,662 |
def temp_coeff_cold(lower, upper):
"""
Calculates and returns the m and b coefficients for y = m*x + b
for a line intersecting (lower, 0) and (upper, 255).
"""
m = 255/(upper-lower)
b = 255 - m * upper
return m, b | 0391f2d918627f43577555056d09e9c9efe1d15d | 650,663 |
import torch
def become_constant_trick(x, lengths):
"""
Input:
x: a tensor of shape (batch, stream, channel)
lengths: a tensor of shape (batch,)
Returns:
A tensor y of shape (batch, stream, channel), such that
y[i, j, k] = x[i, j, k] if j < lengths[i] else x[i, lengths[i],... | be8a0938f58b5274de1e030f75b4c4976e2a4bf8 | 650,664 |
def df_last_column(df, column_name):
"""Move a dataframe column to the right-most position.
Parameters
----------
df: :class:`pandas.DataFrame`
Dataframe to rearrange
column_name: :obj:`str`
Column to move.
Returns
----------
:class:`pandas.DataFrame`
... | 4ec7bfac2ed2099ff940456d78482ef0b368fcf8 | 650,665 |
from typing import Optional
def get_colour(label: str) -> Optional[str]:
"""Given the label of the thing to plot, determine the colour."""
if "given investment" in label:
return "orange"
if "all-in day one" in label:
return "blue"
if "cash" in label:
return "red"
if "nomina... | 7c9788ff22e5deaf83ad0272a487a69e67c91c3b | 650,666 |
def domain(url):
"""
Extracts the domain of an url
>>> domain('https://gitlab.laas.fr/pipo')
'gitlab.laas.fr'
>>> domain('gitlab.laas.fr/pipo')
'gitlab.laas.fr'
"""
if '://' in url or url.startswith('//'):
url = url.split('//')[1]
return url.split('/')[0] | eebef75ec3a418bb6afe830a6a3a98f31d54e7a8 | 650,667 |
import copy
def get_shared_data(component):
"""
Returns the actual list of component data based on how data is
stored in component, either from the `data` attribute or from the
`data['content']` attribute.
Returns:
list: List of component data.
"""
if component:
return (co... | 59fb8fd717973f7c0767497f7b28cc7dab94f27a | 650,671 |
from pathlib import Path
def read_df(t, tfmt, store, path):
"""
Read a matrix present in a `store` at a certain `path` with
the appropriate formatting of the date `t`.
"""
key = Path(path) / t.strftime(tfmt)
df = store[str(key)]
return df | d164135f83f9bc427a0c839d53a729df68d85047 | 650,672 |
import re
def filename_filter(filename: str, repl: str = '') -> str:
"""
将文件名替换成合法的文件名
:param filename: 原文件名
:param repl: 替换字符
:return: 合法文件名
"""
return re.sub('[/:*?"<>|]', repl, filename) | dfbd37d389da23e2837b122713b02284ad3cef38 | 650,673 |
def get_frac_moffat(r, alpha, beta):
"""
Calculate the fraction of light within radius r of a Moffat profile.
"""
frac = 1 - alpha**(2*(beta-1))*(alpha**2 + r**2)**(1-beta)
return(frac) | 9cdcdeb348cf47dde7eb81228f04603cb83872b3 | 650,675 |
def get_text_box(text, margin=0):
"""Return the coordinates of a Matplotlib Text.
`text` is a Matplotlib text obtained with ax.text().
This returns `(x1,y1, x2, y2)` where (x1,y1) is the lower left corner
and (x2, y2) is the upper right corner of the text, in data coordinates.
If a margin m is supp... | 88b986eb422f39c968db39dc401b9cd49eeb7aa3 | 650,676 |
import random
def create_neg_relations(entities, rels_between_entities, rel_type_count, neg_rel_count):
""" Creates negative relation samples, i.e. pairs of entities that are unrelated according to ground truth """
neg_unrelated = []
# search unrelated entity pairs
for i1, _ in enumerate(entities):
... | 4a8897b3055cf74106852b64944bb76c67674f71 | 650,678 |
def confirmation_reader(msg: str) -> bool:
"""Prints a message and asks for user confirmation.
Asks the user with a [Y/n] option for confirmation.
Args:
msg: The message to be printed before the confirmation choice.
Returns:
The users answer in form of a boolean value.
"""
ans... | e8c8822633e01ab9755516a2858128bb08db118d | 650,679 |
def get_unused_options(cfg_dict, options):
"""
Returns the unused keys in a configuration dictionary. An unused key
is a key that is not seen in *options*.
Parameters
----------
cfg_dict : dict
options : :py:class:`~enrich2.plugins.options.Options`
Returns
-------
`set`
... | 8f9a43f6b761fdd81450e8cad63ace47194233fe | 650,683 |
def calculate_correlation_lengths(semimajor, semiminor):
"""Calculate the Condon correlation length
In order to derive the error bars from Gauss fitting from the
Condon (1997, PASP 109, 116C) formulae, one needs the so called
correlation length. The Condon formulae assumes a circular area
with diam... | 8f6c0d424541e83b1fc8ee896b6252001072d4eb | 650,687 |
def split_and_fill(s, fill = 4, delim = ':'):
"""
Takes a string, a fill amount, and a delimiter and outputs an iterable,
where each index is the substring up to or after `delim`, zero-filled to `fill`.
e.g. split_and_fill("de:ad:be:ef") returns "00de", "00ad", "00be", "00ef"
"""
return (a.... | d0df948a0e5a0cd444354e7735a349886906a3da | 650,689 |
import json
def convert_to_json(value):
"""Converts the inputted object to JSON format.
Args:
value (obj): The object to be converted
Returns:
string : The JSON representation of the inputted object
"""
return json.dumps(value) | 7d73f3dfcf18dd08c5769ed00589734088f58541 | 650,691 |
def build_creative_name(order_name, creative_num):
"""
Returns a name for a creative.
Args:
order_name (int): the name of the order in DFP
creative_num (int): the num_creatives distinguising this creative from any
duplicates
Returns:
a string
"""
return 'HB {order_name... | a2ff9031601b09d504557dea48d021e931281b06 | 650,696 |
def simple_method_io(method, cdt, indataname, outdataname):
"""
Helper function to create inputs and outputs for a simple
Method with one input, one output, and the same CompoundDatatype
for both incoming and outgoing data.
"""
minput = method.create_input(compounddatatype=cdt,
... | 29890ecd0b582823a9e6f86021efd21abd410b60 | 650,697 |
def format_user(user_id):
"""
Formats a user id so it appears as @user in the slack
"""
return "<@" + user_id + ">" | 9fed6c29ca4a1b687c63f947a3d3b6bb5d8948d8 | 650,698 |
def scala_T(input_T):
"""
Helper function for building Inception layers. Transforms a list of numbers to a dictionary with ascending keys
and 0 appended to the front. Ignores dictionary inputs.
:param input_T: either list or dict
:return: dictionary with ascending keys and 0 appended to front... | 7ed86eb0485faa981ebbad921af676ca145a8c20 | 650,700 |
def is_material_collidable(material):
"""Check whether a material has meta suggesting we need collision meshes"""
collision_filter = material.meta('collisionFilter')
return (not collision_filter) or (len(collision_filter) > 0) | 32914177162bae9753e8c2ecb3bd7d41fa5f8529 | 650,702 |
def getClass(obj):
"""Return the class or type of object 'obj'.
Returns sensible result for oldstyle and newstyle instances and types."""
if hasattr(obj, '__class__'):
return obj.__class__
else:
return type(obj) | 0b2f7b11b946ea92a7453a232c8d43f575544fdf | 650,704 |
import zipfile
import io
def _make_zip_file() -> zipfile.ZipFile:
"""Returns an in-memory zip file."""
data = io.BytesIO()
zf = zipfile.ZipFile(data, 'w')
zf.writestr('a.txt', b'content of a')
zf.writestr('b/c.txt', b'content of c')
zf.writestr('b/d/e.txt', b'content of e')
zf.writestr('b/f.txt', b'cont... | 5e7a71ec589c88248d9de89f83a3d72152748e20 | 650,711 |
def container_name_for(image, application_id):
"""
Get a name for a service container based on image and application ID
Parameters:
image - image that the container is for
application_id - application id that the container is for
Return value:
A string
"""
return image.... | 651ad10fe0b1578f8ba79affc249199ca20b932d | 650,713 |
from datetime import datetime
def date_cleanup(date):
"""Transforms date of form YYYYMMDD to datetime object.
Args:
date (Union[str, NoneType]): Date of the form YYYYMMDD to be transformed.
Returns:
``datetime.datetime`` object if given string.
Returns None if None is given.
... | 729b085aba90d11e2105a5fc55d0a5b1a9845dc6 | 650,714 |
def comma_to_dot(comma_number: str) -> float:
"""Transform the decimal separator from comma to dot.
Args:
comma_number: number as a string with comma as a decimal separator
Return:
The dot-separated number corresponding to the given one.
"""
return float(comma_number.replace(',', '.')) | 150d5f6b3f16d68cb885e9a12116f4e4534fc4e4 | 650,718 |
def fits_file(name, ra, my_dir):
"""Get the FITS file for a given source.
Parameters
----------
name : string
Source name.
ra : float
Right ascension.
my_dir : string
Working directory.
Returns
-------
string
Name of the FITS file of the field the so... | 633214d8fec9e5ae448b67b638d2661c3e83f0a2 | 650,720 |
def get_bytes(s):
"""Returns the byte representation of a hex- or byte-string."""
if isinstance(s, bytes):
b = s
elif isinstance(s, str):
b = bytes.fromhex(s)
else:
raise TypeError("s must be either 'bytes' or 'str'!")
return b | 99485b4beb67296bde391669d6a8c8db524f7094 | 650,721 |
import torch
def cRM_tanh_recover(O, K=10, C=0.1):
"""CRM tanh recover.
Args:
O (torch.Tensor): predicted compressed crm.
K (torch.Tensor): parameter to control the compression.
C (torch.Tensor): parameter to control the compression.
Returns:
M (torch.Tensor): uncompresse... | 59b1005eec4e0f13e3012ef40e0266a718a35d14 | 650,723 |
def _get_item_from_doc(doc, key):
"""
Get an item from the document given a key which might use dot notation.
e.g.
doc = {'deep': {'nested': {'list': ['a', 'b', 'c']}}}
key = 'deep.nested.list.1'
-> 'b'
:param doc dict:
:param key str:
:rtype: value
"""
if '.' in key:
... | 82a12365ff933cc88d769779c929a7f6a6b0cd66 | 650,724 |
def cmp_individual_scaled(a, b):
""" Compares two individual fitness scores, used for sorting population
Example:
>>> GPopulation.cmp_individual_scaled(a, b)
:param a: the A individual instance
:param b: the B individual instance
:rtype: 0 if the two individuals fitness score are the same,
... | 07fcbaf73621948ec8fe2c48e2e6a4f573203475 | 650,725 |
def prot_comp_composite(row):
"""Creates a composite column from the protein and compound IDs"""
composi = row["DeepAffinity Compound ID"] + "," + row["DeepAffinity Protein ID"]
return composi | c69f92a700133f03346998070d09ab0eeed349b6 | 650,726 |
import math
def num2si(x, format='%.15g', si=True, space=' '):
"""
Returns x formatted using an exponent that is a multiple of 3.
Parameters
----------
x : scalar
The number to format.
format : str
Printf-style format specification used to format the mantissa.
si : bool
... | 79fe73668736e13fe38915bbf55a1ff848b85824 | 650,727 |
from typing import List
from typing import Tuple
def process_data(data: str) -> List[Tuple[int, int, int]]:
"""Parse the raw data.
Convert raw triangle data:
1 2 3
4 5 6
Into list of tuples, where each item is a triangle with a, b, c sides
"""
triangles = []
for triangle in ... | dd82c6e8a603f185315283c48d9b571c155f2d3c | 650,728 |
def check_enemy_ub(time_count):
"""check enemy ub
Args
time_count (int): count up after ub
Returns
is_enemy_ub (boolean): enemy ub existence
"""
if time_count > 9:
return True
else:
return False | d0f8873e9cd5819b4e87bb7eb5851542ffb80eb3 | 650,732 |
import json
def get_json(content):
"""Decode the JSON records from the response.
:param content: the content returned by the eBird API.
:type content: http.client.HTTPResponse:
:return: the records decoded from the JSON payload.
:rtype: list
"""
return json.loads(content.decode("utf-8")... | 3e2e88063ddc730170212e635e11e64aca474a47 | 650,737 |
def data_is_encrypted(tasks_backup_job):
""" Returns True if the tasks data has been encrypted.
This assumes that the worker stores the encrypted AES key in
tasks_backup_job.encrypted_aes_key_b64
when the tasks are encrypted.
This will return False for any backup ol... | 4d8727f97be709aafd21d09be54e5090faad5e73 | 650,738 |
def get_first_label(x):
"""Returns the label of the first element.
:param x: Series or DataFrame
"""
return x.index[0] | 9c2c98cca3f163a01b9ce06fa75b516e9b84a49b | 650,740 |
def max_lens(X):
"""
max_lens
Return: a tuple of which each element is the max length of the elements in
the corresponding dimension of the input X.
Example: max_lens([[1,2,3], [4,5]]) --> [2,3]
"""
if not isinstance(X[0], list):
return tuple([len(X)])
elif not isinstance... | 763e9b31bd09e539fc36fe5f8a7dcb816e17ec0b | 650,744 |
def linearsearch(A, elem):
"""
Linear Search Algorithm that searches for an element in an array with O(n) time complexity.
inputs: Array A and element e, that has to be searched
output: True/False
"""
for a in A:
if a==elem:
return True
return False | 5372e23eba64cacb59532a126b5aac6fdc9efe8f | 650,745 |
def efficientdet_params(model_name):
""" Map EfficientDet model name to parameter coefficients. """
params_dict = {
'efficientdet-d0': {
'compound_coef': 0,
'backbone': 'efficientnet-b0',
'R_input': 512,
'W_bifpn': 64,
'D_bifpn': 3,
... | 53e434752b2dee6fb63d6ed733babe17a0c8dcd8 | 650,748 |
def subset_data_for_overhang(dataframe, overhang, horizontal=True, filter=True):
"""Subset Tatapov dataframe for given overhang.
**Parameters**
**dataframe**
> Tatapov dataset, for example `tatapov.annealing_data["25C"]["01h"]`
**overhang**
> Overhang class instance (`Overhang`)
**horiz... | 760b809429c5bbc62a024759a1cb5aa57709559b | 650,755 |
def maybe_name_or_idx(idx, model):
"""
Give a name or an integer and return the name and integer location of the
column in a design matrix.
"""
if idx is None:
idx = range(model.exog.shape[1])
if isinstance(idx, int):
exog_name = model.exog_names[idx]
exog_idx = idx
#... | ebdbbe3440a14353c910fc0b55639b5acf83b240 | 650,759 |
def is_code_token(text):
"""
True for non-comment, non-whitespace token text.
"""
char0 = text[0]
return char0 != '#' and char0 > ' ' and char0 != '\\' | 31697b7eea1e926c3c594c3de87b07b4db834511 | 650,760 |
def range_check(df, maximum, minimum):
"""
range_check adds a column to data frame with label if data are out of range.
Arguments:
df: data frame with a column 'raw' of raw data.
maximum: maximum acceptable value - above this value, data are anomalous
minimum: minimum acceptable valu... | d58bcc332e61b252ee3dac9fe500d29fe546cb35 | 650,762 |
def PyDict_Keys(space, w_obj):
"""Return a PyListObject containing all the keys from the dictionary,
as in the dictionary method dict.keys()."""
return space.call_method(space.w_dict, "keys", w_obj) | 369ddad264ecad32dd4a47709f07dc033d57560b | 650,764 |
def get_attr_resolver(obj_type, model_attr):
"""
In order to support field renaming via `ORMField.model_attr`,
we need to define resolver functions for each field.
:param SQLAlchemyObjectType obj_type:
:param str model_attr: the name of the SQLAlchemy attribute
:rtype: Callable
"""
retu... | 23376addb0b5a3ab600e251e512f9174a27a66b6 | 650,766 |
def openFile(file_path):
"""Open file in read mode, return file contents"""
md_file = open(file_path, 'r')
file_contents = md_file.read()
md_file.close()
return file_contents | 3f637474910ff6b3549f22cc7384b6d1a419b5b7 | 650,767 |
def textarea_to_list(textarea):
"""
Takes a string and returns list of lines, skipping blank lines
"""
list_ = textarea.splitlines()
return [x.strip() for x in list_ if x.strip() != ''] | f7d08a939f38c8e12924acfe727fe9d31831e83a | 650,771 |
def _get_tensors_from_graph(graph, tensors):
"""Gets the Tensors in `graph` with the name of the tensors in `tensors`.
Args:
graph: TensorFlow Graph.
tensors: List of Tensors.
Returns:
List of Tensors.
"""
new_tensors = []
for orig_tensor in tensors:
new_tensor = graph.get_tensor_by_name(o... | 4bb4066e95c712c262f2b096d5523664d65dd54d | 650,774 |
def ratioTest(kps1, kps2, matches):
"""
Take in two sets of keypoints and the set of matches between them
Perform ratio test to get best matches (60% threshold)
Return surviving matches
"""
ratioMatches = list()
for match in matches:
m1, m2 = match
if m1.distance < 0.60*m2.di... | ddce0908bb1c3999ff6c67e2ff012f3383cdd37b | 650,775 |
def cel2kel(t):
"""Converts from Celsius to Kelvin"""
return t + 274.2 | 04d6d474e9de56a8200a0fc147611906d4e58a16 | 650,776 |
import itertools
def combinate(listoffiles, combnum):
"""
Makes a list of tuples with the N choose combnum options
Parameters
----------
listoffiles: list
list of file names
combnum: int
combination number (N choose combnum)
Returns
-------
combinedlist: list
... | dacd66a4355ae2686d1db960bb3dba3daf935ae4 | 650,778 |
def search(seq, val):
"""Search location of key in a sorted list.
The method searches the location of a value in a list using
binary searching algorithm. If it does not find the value, it return -1.
Args:
seq: A sorted list where to search the value.
val: A value to search for.
Re... | c56ab329059bcb026e5608d9da06cf348ef7663c | 650,779 |
def generate_command_argument(hlwm, command, argument_prefix, steps):
"""
generate the next argument of the command which has the given
argument_prefix.
This function makes at most 'step' many recursive calls.
It returns a list of full arguments starting with the argument_prefix.
"""
if st... | 966a921a760f56b571e875c46a555a945363af53 | 650,780 |
def preprocess_prediction_data(text, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
text (obj:`str`): The input text.
tokenizer(obj: `paddlenlp.data.JiebaTokenizer`): It use jieba to cut the chinese string.
Returns:
input_ids (obj: `list[in... | b5eba0f2db3e68426339156ec3ef75f965f0cba9 | 650,784 |
def df_to_records(df):
""" Convert pandas DataFrame to table compatible data aka records. If DataFrame is empty keep the columns.
:type df: pandas.DataFrame
:rtype: list[dict]
"""
if df.empty:
# Return column names in 'records' style.
return [{c: None for c in df.columns}]
r... | 11492828676a820fdcb221707fc10d189f19074b | 650,786 |
from datetime import datetime
def is_datetime(value):
"""Checks, if given value is a datetime.
:param value: The value to check.
:type value: object
:returns: True, if value is a datetime (and not a date), false otherwise.
:rtype: Boolean
>>> from plone.event.utils import is_datetime
>>>... | 47be1dec1585bf6ccfb506fe800a71de03954e4d | 650,788 |
def find_furthest_room(distances):
"""Find furthest room from the distances grid."""
return max(max(row) for row in distances) | 9a8690e50c3f7099070e69e94453dc66ae9fda2c | 650,789 |
import json
def pretty_json(data):
"""Return a pretty formatted json
"""
data = json.loads(data.decode('utf-8'))
return json.dumps(data, indent=4, sort_keys=True) | 941eaa5bcd6ec91596812595b80726ec63b7181d | 650,790 |
import random
import string
def _generate_password(length=16):
"""
Generate password of specified length with at least one digit,
uppercase letter, and lowercase letter. This is used as the
IKEv2 PSK on both sides of the tunnel.
"""
# Need 1 each: uppercase, lowercase, digit
pw_minimum = ... | 962a886ebc17d83544908357579b20b5d7fbaff5 | 650,791 |
def mipmap_size(base_width, base_height, mip_level):
"""Return mipmap width and height
Args:
base_width (int): Width of the base image (mip level 0)
base_height (int): Height of the base image (mip level 0)
mip_level (int): Level of mip to get
Returns:
tuple(mip_width, mip_... | c24775f80dc74ed73b53f388b061d5c5cecb7810 | 650,792 |
def get_examples(section_div, examples_class):
"""Parse and return the examples of the documentation topic.
Parameters
----------
section_div : bs4.BeautifulSoup
The BeautifulSoup object corresponding to the div with the "class"
attribute equal to "section" in the html doc file.
ex... | 93da0bfc7fec2b2f7668fd24825068a91c672398 | 650,794 |
def is_hla(chrom):
"""
check if a chromosome is an HLA
"""
return chrom.startswith("HLA") | 2af4c8169910cd445c32bb49e0e118a237f9ffbc | 650,800 |
def _QuoteCpuidField(data):
"""Add quotes around the CPUID field only if necessary.
Xen CPUID fields come in two shapes: LIBXL strings, which need quotes around
them, and lists of XEND strings, which don't.
@param data: Either type of parameter.
@return: The quoted version thereof.
"""
return "'%s'" % ... | 3f3aa420d77605b0954b0381c3698d39242d7cde | 650,804 |
def swap(x, i, j):
"""
swap bits i and j of x.
"""
mask = (1<<i) | (1<<j)
m = x&mask
if m == 0 or m == mask:
return x
return x^mask | a6a885bad2f2ed20d050a500bc45d640e948b598 | 650,805 |
def has_shebang_or_is_elf(full_path):
"""Returns if the file starts with #!/ or is an ELF binary.
full_path is the absolute path to the file.
"""
with open(full_path, 'rb') as f:
data = f.read(4)
return (data[:3] == '#!/' or data == '#! /', data == '\x7fELF') | 4dd67c8bd9a5d5afd00fed3d564cf32e7551adb0 | 650,807 |
def orientation(a, b, c):
"""Compute the orientation of c relative to the line AB."""
M = [[a[0] - c[0], a[1] - c[1]], [b[0] - c[0], b[1] - c[1]]]
# Return det(M)
return M[0][0] * M[1][1] - M[0][1] * M[1][0] | af107633562bc713e29b55ca686e0f8aab640557 | 650,812 |
def F(agents, images_in):
"""The stacked agent map.
Takes a list of agents and a list of images and applies each agent
to the corresponding image.
Args:
agents: List of agents
images_in: List of input images
Returns:
List of output images after applying the agents
"""
... | 7c78d6277000968aada8eb2060993c3ca6c08306 | 650,816 |
def to_unicode(obj):
"""
Converts any string values into unicode equivalents.
This is necessary to allow comparisons between local non-unicode strings and the unicode values returned by the api.
:param obj: a string to be converted to unicode, or otherwise a dict, list,
set which will be recursi... | 8751443e87014ca9e5a9ae71be9f41f2d26eadb3 | 650,818 |
from pathlib import Path
def check_paths(vtk_src_dir, application_srcs):
"""
Check that the paths are valid.
:param vtk_src_dir: The path to the VTK source.
:param application_srcs: The user source files to be scanned for modules.
:return: True if paths, files exist.
"""
ok = True
if ... | 213df92072459a55721d386308dc5fe74b0420c7 | 650,820 |
import time
import asyncio
async def wait_host_port(host, port, duration=10, delay=2):
"""Repeatedly try if a port on a host is open until duration seconds passed
from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499
:param str host: host ip address or hostname
:param int p... | 8d8f71662929b8d917bec27f9dcc1ddb6bb52e13 | 650,821 |
def haspropriety(obj, name):
"""Check if propriety `name` was defined in obj."""
attr = getattr(obj, name, None)
return attr and not callable(attr) | fc83254933dba169b9725182d15006cc85d1ef45 | 650,823 |
def match_factory(variable, factories):
"""Match variable to VariableFactory using rank, name, and units.
Args:
variable (Variable): Variable to match.
factories (VariableFactory or tuple of VariableFactory): VariableFactory to
check against.
Returns:
bool: True if a ma... | d83f8ab86fb6aab37eefddb3e5f64115c6079891 | 650,824 |
def insertion_sort(array):
"""
Sort array in ascending order by insertion sort
Insertion sort iterates, consuming one input element
each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element
from the input data, finds the location it belongs within
... | 4445bae0f5dc8c572f83a4eda2958119c23558b4 | 650,825 |
import torch
def validation_loop(model, testloader, criterion):
"""
Returns test loss and accuracy score of a given torch model.
NOTE: divide outputs with the total number of epochs to get
the final values.
Parameters:
model (nn.Module): A torch model
... | 7d7b54d60d20dee68baafd26d29db338c98af517 | 650,826 |
def join_sentences_by_label(grouped_sentences_df, label_col="topic_name", sentence_col="sentence"):
"""
Function used to join sentences into texts. Sentences are grouped by topics
---
**Arguments**\n
`grouped_sentences_df` (DataFrame): DataFrame with sentences groped by topics and which contains
... | c30c21d5478b4bdbbd321444e85b8c44fcb61ea6 | 650,829 |
def rotate_image(image):
""" Rotate an image according to it's EXIF info. """
try:
orientation_tag = 274 # 0x0112
exif=dict(image._getexif().items())
if exif[orientation_tag] == 3:
image = image.rotate(180, expand=True)
elif exif[orientation_tag] == 6:
im... | 6843c9e86572d968b3666e348e162b68ef153a6a | 650,830 |
def replace_token(token, token_replacement, value):
"""
Replace `token` with `token_replacement` in `value`
:param: token: string e.g. : | .
:param: token_replacement: string e.g. _ -
:param: value: dictionary, list, or str
"""
if isinstance(value, str):
return value.replace(token, ... | f8e80d2e95afda7d661e3ed94588a4270c23e1fc | 650,833 |
def svm_model(r3d_kpc, n0, r_c, beta, r_s=1.0, gamma=3.0, epsilon=0.0, alpha=0.0):
"""
Compute a Simplified Vikhlinin model
Parameters
----------
- r3d_kpc: array of radius in kpc
- r_c : core radius parameter
- n_0 : normalization
- beta : slope of the profile
- r_s : characteris... | 02e532ca1e0af574b4d3c07ffe47e87b9223ca95 | 650,836 |
def is_ea(email: str) -> bool:
"""
Email domain name is "empacad.org"
"""
eml_domain = email.split('@')[1]
if eml_domain == 'empacad.org':
return True
return False | ae024b4d74fb453a1f5b95163a3f0bfe60d57340 | 650,839 |
def test_acc_formatter(test_acc: float) -> str:
"""Wrap given test accuracy in a nice text message."""
return f"Test Accuracy: {test_acc}" | 1c5ff2480037350a393995d20e1dd354b5b0499a | 650,841 |
import requests
def post_input_form(input_text):
"""Posts a string as a form field (application/x-www-form-urlencoded)
named 'input' to the REST API and returns the response.
"""
url = 'http://localhost:5000/parse'
return requests.post(url, data={'input': input_text}) | d2e7c9aa97ca7ef0d5f7100a74e83f2cdc6d882b | 650,842 |
def exercise2(n):
"""
Write a recursive Python function that returns the sum of the first n integers.
"""
if n > 0:
return n + exercise2(n - 1)
else:
return 0 | befd299860098d018063218c89d443dc5bc38fb6 | 650,843 |
def date_parser(dates):
"""Return list strings in truncated DateTime format ('yyyy-mm-dd').
Args:
dates (list): A list containing string values,
each value in the (DateTime) format 'yyyy-mm-dd hh:mm:ss'.
Return:
Example:
Input: date_parser(['2019-11-29 12:50:54',... | 6f53f5aa13978330333baf941b7696c86045ed6b | 650,846 |
def fallback(*candidates):
"""
:param candidates:
:return: First argument which is not None
"""
for i in candidates:
if i is not None:
return i | 67d78e3c6ed5064cc75501f576ec9a1427598959 | 650,852 |
def _module_dir(lock_filename):
"""Returns module dir from a full 'lock_filename' path.
Args:
lock_filename: Name of the lock file, ends with .lock.
Raises:
ValueError: if lock_filename is ill specified.
"""
if not lock_filename.endswith(".lock"):
raise ValueError(
"Lock file name (%s) h... | a6f38371cee760211732b182546466047de44499 | 650,855 |
def construct_link_dossierbehandelaar_query(graph_uri, bericht):
"""
Construct a SPARQL query for linking a dossierbehandelaar to a bericht.
:param graph_uri: string
:param bericht: dict containing properties for bericht
:returns: string containing SPARQL query
"""
q = """
PREFIX e... | a4616b80efb74bca4dc7647c9ed3929e58035cf6 | 650,859 |
def summer_clearsky(summer_times, albuquerque):
"""Clearsky irradiance for `sumer_times` in Albuquerque, NM."""
return albuquerque.get_clearsky(summer_times, model='simplified_solis') | ac4a349d3dcba7043afcca041279b35c7ea9aa18 | 650,863 |
from typing import Dict
from typing import Any
def build_validation(validator) -> Dict[str, Any]:
"""Builds and returns a fake validator response object."""
if validator == "lookml":
return {
"validator": "lookml",
"status": "failed",
"errors": [
{
... | 5c7cc5a9fc4f486162d1a94775eee4e4e992adc7 | 650,865 |
def quoteStr(s, addQuotes=False, quoteDouble=False, quoteSingle=True):
"""
s (str) -- Source string parameter.
Options:
- addQuotes (bool|str) -- Add quotes around result string (default: False, don't quote).
- quoteSingle (bool) -- Quote single quotes ('), default is True.
- quoteDouble (bool) ... | 399ef818107e5409211348aa64386bbc2a24113c | 650,868 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.