content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def smalltalk(raw, context):
"""
An intent to answer to greetings and appreciations.
Answer the same with an exclamation mark (!).
"""
return raw + ' !', context | 869b799daad08df0f6f64466e0ca847f89ae40b3 | 592,005 |
def model_urlname(model, action):
"""Generates a canonical url for a certain action/view on a model"""
return f"{model._meta.label_lower}.{action}" | bc05269c546f79928d64a119b5aa016c6ec5884e | 592,012 |
def get_age(hh_head):
"""
Return the required category label for different ages.
"""
if 16 <= hh_head['DC1117EW_C_AGE'] <= 24:
return '16-24'
elif 25 <= hh_head['DC1117EW_C_AGE'] <= 34:
return '25-34'
elif 35 <= hh_head['DC1117EW_C_AGE'] <= 54:
return '35-54'
else:
... | e6b60542e7ca2481e2b514a9ad941af20e2184ff | 592,014 |
def check_same_parent(a, b, dataset, dict_parents):
"""
Check that the parents are the same
"""
return dict_parents[dataset][a] == dict_parents[dataset][b] | e9e8a06607274e0b9b5af93f949fd392a4f2eb39 | 592,015 |
def get_drop_down_xml(name, command, labels, help='', values=None):
"""Get the XML content for a drop down menu when making a ParaView plugin."""
def _enum(labels, values=None):
if values is None:
values = range(len(labels))
els = []
for i, lab in enumerate(labels):
... | 9ceb87c237032e3ba9ab2a6e3f724e5940f8afcf | 592,017 |
def _unsigned(i):
"""Translate a signed int into an unsigned int. Int type returned
is longer than the original since Python has no unsigned int."""
return i & 0xFFFFFFFF | 1588e435d4fdb12e7286e37de986acea66fd102f | 592,018 |
def get_field_from_model(model, fieldname):
"""Return Field object for Model.field."""
for f in model._meta.get_fields():
if f.name == fieldname:
return f | d9f82198e38b97cb993b74dcadb1628d72007952 | 592,019 |
import logging
def get_log_records(caplog):
"""Return api call log messages.
Format of record tuples is (logger_name, log_level, message).
"""
return [
log[2]
for log in caplog.record_tuples
if log[0] == "bookings.ticketing_system" and log[1] == logging.INFO
] | 04198c821aa4d67ecc6100190106082af3ae5ae0 | 592,022 |
def list_view_details(client, view=None, drawing=None):
"""List the views contained in a drawing, with more details.
Args:
client (obj):
creopyson Client
view (str, optional):
View name filter (wildcards allowed: True). Defaults: no filter.
drawing (str, optional... | e5727b4e08d1830d5285c4d006baeaa4987ecbab | 592,024 |
def punycode(domain):
"""Return the Punycode of the given domain if it's non-ASCII."""
return domain.encode('idna').decode('ascii') | 70f9867c4ec941fc853e242387b7d483480e6908 | 592,028 |
def crop_center_square(frame):
"""Crops a square from the center of a rectangular array."""
y, x = frame.shape[0:2]
min_dim = min(y, x)
start_x = (x // 2) - (min_dim // 2)
start_y = (y // 2) - (min_dim // 2)
return frame[start_y : start_y + min_dim, start_x : start_x + min_dim] | 7646025ce6d3e9c361be74babeae9d465cbda07e | 592,029 |
import functools
def wrap_after(after, condition=lambda *args, **kwargs: True):
"""
A helper for creating decorators.
Runs an "after" function after the decorated function. The condition
check is performed after the decorated function is called.
"""
def decorator(func):
@functools.wr... | a0569e0e456e51610b556b6c0ac32d961d8c0cdf | 592,031 |
def clean_url(url):
""" Tacks an s3:// onto the beginning of a URL if necessary.
url: an S3 URL, or what should be one
Return value: S3 URL
"""
if url[:6] == 's3n://':
return ('s3://' + url[6:])
elif url[:5] != 's3://':
return ('s3://' + url)
else:
return u... | ebb7d16df234254fd05a476e9ab66786ae3c8caa | 592,035 |
def unit(aClass, value):
""" Calls the 'unit' method of `aClass` with `value`. """
return aClass.unit(value) | 35189da86beb1fc584ff41a5ead63aec6351633f | 592,037 |
def init_wiki(args):
"""
Initialize a WikiFetcher object according to arguments
:param args: Argument object from command line
:return: A dictionary of all arguments for WikiFetcher
"""
return {"lang": args.lang[0], "limit": args.nb_resp[0]} | f522d13ddab6f0e4f527cb00d39ccefd5080a7fc | 592,044 |
def dict_prune_private(d):
"""Return a copy of a dict removing subtrees with keys starting with '_'."""
if isinstance(d, dict):
data = {}
for key, value in d.items():
if not key.startswith("_"):
data[key] = dict_prune_private(value)
return data
else:
... | 683c6fe31959ab2543f09e098b06ec5e86d24d8e | 592,045 |
import ipaddress
def get_ip_networks_from_file(filename, strict=True):
"""
Quickly generate a list of IPv4Networks from a file with built-in validation
:param str filename: The file to be parsed
:param bool strict: If true, raises errors when invalid networks are encountered.
:return: list
"""
with open(filen... | 8486a13a68d1b170e5510f695055be89664ecf19 | 592,047 |
import pkg_resources
def static_file_path(directory, file):
""" get path of the specified file from specified directory"""
resource_path = "/".join((directory, file)) # Do not use os.path.join()
try:
template = pkg_resources.resource_filename(__name__, resource_path)
except KeyError:
... | ad41dd7e7c77ab5ccf5d0bdd2a4d01e4fb95da12 | 592,050 |
def _has_ingress_white_list(ingress):
"""Check if the ingress has whitelisting applied"""
return bool(ingress.metadata.annotations.get("ingress.kubernetes.io/whitelist-source-range", False)) | 2dbcbfd2a8d11c55bdeb47783d52a89ac0ee1575 | 592,051 |
def partialr(func, *args, **kwargs):
"""partialr: Partially applies last arguments.
New keyworded arguments extend and override kwargs."""
return lambda *a, **kw: func(*(a + args), **dict(kwargs, **kw)) | bcb1433b1272bb0bb512602dd6647528882f11fc | 592,053 |
def callBeginningScenicTrace(func):
"""Call the given function, starting the Scenic backtrace at that point.
This function is just a convenience to make Scenic backtraces cleaner when
running Scenic programs from the command line.
"""
return func() | f63a0e73d959070f50ce6b389b87cc489c35563a | 592,054 |
def build_article_set(secao_list):
"""
Takes the value of 'secao' key in a 'config' dict ('secao_list') that
specifies which DOU sections to download and return a set of all possible
sections that might be downloaded: (sections 1, 2 and 3 from ordinary,
extra or sumplement editions).
"""
#... | 311624daa7c4f60af4e0a8d6407cc994222829f8 | 592,055 |
import pickle
def serialize(src):
"""
The default serialization method
In non-special cases, this method is used, protocol=2
Parameters
----------
src: object
data to serialize
Returns
-------
"""
return pickle.dumps(src, protocol=2) | 4837aa831b5afd62997aeab319c189f51d966860 | 592,061 |
def escape_lg(s):
"""Escape the > and < in the string, which are special in rst"""
return s.replace('>','\>').replace('<','\<') | 5ebee9ec50e5260e9fed929fbd5d17531d415062 | 592,062 |
def _get_entries_list(item, step, action):
"""Returns list of entries which need the action to be applied on step (runtest_call/teardown).
"""
entries_dict = {}
entries_list = []
if step in item.keywords.keys():
entries_dict = item.keywords[step]
if action in entries_dict:
... | 2520d8d6898f1a72f96602a192049d611e52228f | 592,063 |
from pathlib import Path
from typing import Optional
def secret(
name: str, secrets_dir: Path = Path("/run/secrets")
) -> Optional[str]:
"""Load the named secret from /run/secrets and return None otherwise."""
path = secrets_dir / name
if path.exists():
return path.read_text().strip()
... | 47ad7381157fa469b963c7fc769611c39713044d | 592,065 |
import re
def RemoveStackTraceDetails(output):
"""Removes all stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n',
'Stack trace: (omitted)\n\n', output) | dcffa3e0b90b381e2b0d3c1dfbcd61ff65a0deca | 592,066 |
def magNDx(v, limit=0):
"""Returns magnitude of an nD vector,
ignoring items if they are not numeric, with
an option to limit length of the tuple to a certain
length defined by the `limit` argument"""
if limit > 0:
return sum(vv**2 for i, vv in enumerate(v)
if (isinstance(vv, (int... | ff0abe4945edf4cfc9bc02fddc60116b09dbf74e | 592,067 |
def calculate_median(objects, field_name):
"""
Calculates the median where obj.total is the distribution count and
getattr(obj, field_name) is the distribution segment.
Note: this function assumes the objects are sorted.
"""
total = 0
for obj in objects:
total += obj.total
half =... | fef8cba7c84b772c9f47546c20067a79bb80d05c | 592,068 |
def gen_output(u1, u2):
"""
Inputs:
u1 : first column
u2 : second column
Outputs:
y : binary variable (1 or 0) ; 1 if x2 is preferred ; 0 if x1 is preferred
p: actual preference probability
"""
# utility function value generation
diff = u2 - u1
y = 1*(diff > 0.)
#p = prob... | c928ba29817a884f0dabf3a8cdfb7ae1ba0ed38b | 592,071 |
def fizz_buzz(number):
"""Returns 'Fizz' if a number is divisible by 3, 'Buzz' if a number is divisible by 5
'FizzBuzz' if a number is divisible by both 3 and 5
otherwise it returns the number itself
"""
if number % 3 == 0 and number % 5 == 0:
return "FizzBuzz";
elif number % 3 == 0:
return "Fizz"... | d6ec257c38dbb841d13be1917cec1da2a6bd627f | 592,078 |
def get_xy_from_waypoints(waypoints):
"""
Given a list of waypoints, returns a list of [x,y]
coordinates associated with those waypoints
"""
return list(map(lambda waypoint: [waypoint.pose.pose.position.x, waypoint.pose.pose.position.y], waypoints)) | f86fde822eae7be5ce8a7cd07ca40eab6db03285 | 592,080 |
def angle_Mr(Lr: float, w_: float) -> float:
"""
Mr = Lr - w_
:param Lr: mean longitude at t_r
:type Lr: float
:param w_: longitude of the preriapsis
:type w_: float
:return: mean anomaly at t_r
:rtype: float
"""
return Lr - w_ | 444ffece23070ff42057fe066409277bda3c0a5c | 592,081 |
def matrixvector_multiply(a, x):
"""takes a matrix and a vector represented as a list of list and multiplies them"""
if len(a[0]) == len(x):
product = []
for i in range(len(a)):
product.append(0)
for j in range(len(x)):
product[i] += a[i][j]*x[j]
return product
else:
return """ Matrix Vector Mul... | 96e3ef87d9a7ef4e8772b804c04ccfe809dfa081 | 592,083 |
def getMidpoint(p1, p2):
"""
p1 is a tuple of the first point
p2 is a tuple of the second point
returns the midpoint, in tuple form, of p1 and p2
"""
return (((p1[0] + p2[0]) / 2.), ((p1[1] + p2[1]) / 2.)) | c4c3953294465fb48c1b05e1b40c81eea1d32f4e | 592,087 |
from typing import Any
from typing import Dict
def error(data: Any = None, msg: str = '', code: int = -1) -> Dict[str, Any]:
"""
generate error response body with external status code 200
:param data: data
:param msg: message
:param code: user defined (not http) status code
:return: json resp ... | 1910578534731bf0dc1962d2c01e772ba914d9be | 592,088 |
def reverse_words(string):
"""
Reverses a space-delimited string of words using the string and list methods
"""
if type(string) is not str:
return None
str_list = string.split(" ")
str_list.reverse()
reversed_str = " ".join(str_list)
return reversed_str | b0b6adac59e0c627d2af8606f50d9f9ec57d5f98 | 592,091 |
async def fetch(url, session, charset='latin-1'):
"""Fetch a url, using specified ClientSession."""
try:
async with session.get(url) as response:
resp = await response.read()
print("Fetched: {0:30}".format(url))
return resp.decode(charset)
except Exception as e:
... | 647bdff579fdfbbf6e4662834afb8b9af7c30e42 | 592,092 |
def nodesets2affiliations(communities):
"""
Transform community format to "snapshot_affiliations"
Representation expected in input: dictionary, key= community ID, value= node set
Representation in output: dictionary, key=node, value=set of snapshot_affiliations ID
:param communities: dictionary, k... | 028ed5573e079f964452249fe4abc17e2654c546 | 592,094 |
def nii_to_json(nii_fname):
"""
Replace Nifti extension ('.nii.gz' or '.nii') with '.json'
:param nii_fname:
:return: json_fname
"""
if '.nii.gz' in nii_fname:
json_fname = nii_fname.replace('.nii.gz', '.json')
elif 'nii' in nii_fname:
json_fname = nii_fname.replace('.nii', ... | bcd5e6d6c24943fe1e32e05dc36e9011ce24ecfc | 592,095 |
def ingest_query(
staging_schema: str, csv_path: str, table_name: str, iam_role: str
) -> str:
"""Creates query which can be used to ingest tweets data into tweets table with found tweets processed csv file."""
ingest_tweets_query = f"COPY {staging_schema}.{table_name} FROM 's3://stwit-processed-bucket/{c... | 6b2a521c7a5d76b0a634e6f4c5d74c585f2d0c5e | 592,097 |
def first_device_in_session(user_events):
"""Get device id which initialize session."""
return user_events[0].transientId | a1ae48e43d72b06dc463f0df674740c483769118 | 592,099 |
def new_title(plot, append: str):
"""Append to the title of a Holoviews plot"""
return plot.opts.get().kwargs["title"] + f" {append}" | 22274e70f37b875407488fd83986863ee7f853b3 | 592,101 |
from typing import Dict
def generate_report(covered_files: Dict) -> str:
"""Generate the report
Args:
covered_files (dict): git coverage data
Returns:
str: report as a string
"""
report = (
'\ngit Coverage Report\n'
'-------------------\n'
)
if covered_fi... | e122a3531edc3043b58cd39876d496413172018f | 592,102 |
def returnNoImaging(file):
"""
Return a dummy fitsheader where imaging is set to false
Used for non-imaging instruments (FIES etc.)
"""
fitsheader={'imaging':0}
return fitsheader | 7ca8ac5d8713a2f2f3614762068c4038e258ff5a | 592,103 |
def extract_elementpara(parameter_dict, element):
"""
:param parameter_dict: python dict, parameter node for inpgen
:param element: string, i.e 'W'
:return: python dictionary, parameter node which contains only
the atom parameters for the given element
"""
elemen... | 03ce771b8e65c2b7d1e5bf93def8049fd909943c | 592,109 |
import copy
import random
def strategy_func_random(zmws):
"""
>>> random.seed(12345); strategy_func_random([])
[]
>>> random.seed(12345); strategy_func_random([('synthetic/1', 9)])
[('synthetic/1', 9)]
>>> random.seed(12345); strategy_func_random([('synthetic/1', 9), ('synthetic/2', 21), ('syn... | 8fe4bca9239d9da68db5c3bd8f40f1b42175d0cc | 592,111 |
def io_size(request):
"""
Fixture to parametrize over the io_sizes.
"""
return request.param | 6dd39c03cc238addd8a1748a18da848be5bda0d5 | 592,119 |
def get_player_move(marble_count):
"""Get a player's move."""
while True:
# get desired move
desired_move = input("How many marbles would you like to take? ")
try: # make sure the desired move is an integer
desired_move = int(desired_move)
except ValueError:
... | 3729c17942f6dc9e8d9faf152a15aa97c2420d2b | 592,122 |
def semeval_PRF(y_true, y_pred):
"""
Calculate "Micro P R F" of aspect detection task of SemEval-2014.
"""
s_all=0
g_all=0
s_g_all=0
for i in range(len(y_pred)//5):
s=set()
g=set()
for j in range(5):
if y_pred[i*5+j]!=4:
s.add(j)
... | 32ced6ddce7006f9cd9b262fa841818c7cb19d12 | 592,125 |
def iterable(x):
"""
iterable(x) -> bool
Returns whether an instance can be iterated. Strings are excluded.
Args:
x (any): the input variable.
Example::
>>> iterable(x for x in range(4))
True
>>> iterable({2, 3})
True
>>> iterable("12")
Fa... | 2b422baadcb5c6a8b35053863cff10cee1dec210 | 592,129 |
import torch
def generalized_distance_matrix_torch(X,Y):
"""
Returns the distances between all datapoints from X and Y,
considering each datapoint to be a row vector in each matrix individually.
Notes
-----
Let $X \in R^{n_x \times k}, Y \in R^{n_y \times k}$, the distance between all
poi... | 2fade3144d8482b76b1b5aaeac6c6f3df1507ae3 | 592,130 |
def cubicPointAtT(pt1, pt2, pt3, pt4, t):
"""Finds the point at time `t` on a cubic curve.
Args:
pt1, pt2, pt3, pt4: Coordinates of the curve as 2D tuples.
t: The time along the curve.
Returns:
A 2D tuple with the coordinates of the point.
"""
x = (
(1 - t) * (1 - t... | 47d0c4bff7f78e413abfe7724dcf2a9c120eb3d3 | 592,132 |
from typing import IO
import csv
def startfile_csv(ARG_filewriter: IO):
"""Writes the header for the .csv suncalc results file.
Parameters
----------
ARG_filewriter : IO
The file writing IO object.
Returns
-------
csvwriter : csv._writer
The IO object formatted specif... | f28eb1466b8945acc424635a5c1cd56d2a0d7cd3 | 592,140 |
def GetNameForCustom(custom_cpu, custom_memory_mib):
"""Creates a custom machine type name from the desired CPU and memory specs.
Args:
custom_cpu: the number of cpu desired for the custom machine type
custom_memory_mib: the amount of ram desired in MiB for the custom machine
type instance
Returns... | 6fab281eda65aff8daa812526310e24fb480d4d7 | 592,141 |
def decode_iter_request(data):
"""
Decode incoming response from an iteration request
Args:
data: Response data
Returns:
Next itervalue
"""
if "response_metadata" in data:
return data["response_metadata"].get("next_cursor")
elif "paging" in data:
current_pag... | 0202cff0a2ec44537958746c191db7cb47297754 | 592,143 |
import functools
def skip_if_no_pandas(func):
"""
Checks whether pandas is installed and skips the test if not
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except:
return self.skipTest(f"Test '{fun... | 9871cc8fa88f30d67d96ea6d7746aa9e4f438137 | 592,147 |
import math
def sigmoid_function(x):
"""
Calculate result of sigmoid function.
:param x: input value for sigmoid function
:return: result of sigmoid function.
"""
result = 1.0 / (1 + math.e**(-x))
return result | f2c4e710858829f452807a635b217fe2b3a8c673 | 592,153 |
from typing import Counter
def step2(input):
"""
>>> step2([ \
"eedadn", \
"drvtee", \
"eandsr", \
"raavrd", \
"atevrs", \
"tsrnev", \
"sdttsa", \
"rasrtv", \
"nssdts", \
"ntnada", \
"svetve", \
"tesnvt", \
... | 136e5f5baec1291c50309ece138e32eb21909671 | 592,155 |
def pixel(x, y, width_x, width_y):
"""Spatial representation of a pixel.
Parameters
----------
x : numpy.ndarray
x coordinates
y : numpy.ndarray
y coordinates
width_x : float
x diameter of the pixel, in microns
width_y : float
y diameter of the pixel, in micr... | c9d677323d6558655f733b927dad1cbc9f0be0c9 | 592,157 |
def binary_dominates(a, b):
"""Returns whether a binary dominates b"""
for ai, bi in zip(a, b):
if bi > ai:
return False
if a == b:
return False
return True | c48e0b4712d958b52cb3a4c53232a131ceefc986 | 592,160 |
def _read_grammar(filename):
"""
Reads file and converts to string.
:param filename: (str) ends in .txt, path to grammar
:return: (str) grammar string as in https://www.nltk.org/_modules/nltk/parse/generate.html
"""
with open(filename, 'r') as file:
data = file.read()
return data | daf20298a51568104568615ca9a950b4f8105b45 | 592,162 |
def interpolate_missing(y):
"""
Replaces NaN values in pd.Series `y` using linear interpolation
"""
if y.isna().any():
y = y.interpolate(method='linear', limit_direction='both')
return y | f97dca39e0552f5f0108c62b91e6d6bc34d8141d | 592,163 |
def get_description(stmt):
"""Retrieves the description of the statement if present.
"""
description_obj = stmt.search_one('description')
# Return description value if exists
return getattr(description_obj, 'arg', None) | f7a33ab942be98edb1db6909a9c4c9c666ba2650 | 592,164 |
def scale(components):
"""This scales rgb values in the range 0-255 to be in the range 0-1000.
"""
return (round(component / 255 * 1000) for component in components) | 640ccca8c88b09b3a6a4a94124dd9b6ad069c8d5 | 592,169 |
def iv_put(s: float, k: float) -> float:
"""Intrinsic value of a put"""
return max([0, k - s]) | d0ee2aac0b9b0e8ce4c44cb5c7fa5a1f107c6fd8 | 592,174 |
from typing import Dict
from typing import List
from typing import Tuple
def map_intermediate_to_input(
input_line_mapping: Dict[str, List], line_number: int
) -> Tuple[str, int]:
"""Map intermediate file lines to notebooke cell and line.
Maps the line at `line_number` to the corresponding code cell
... | 7ff8a642686df44ed3b182d43d6b3b7ea5e672a9 | 592,175 |
def get_default_data(**kwargs):
"""Returns a POST data dict using default values."""
limit = kwargs.get('limit', 20)
offset = kwargs.get('offset', 0)
direction = kwargs.get('direction', 'asc')
if not isinstance(limit, int):
raise TypeError("`limit` must be int")
if not isinstance(offset,... | 3c9ea441389ccb8af0d9e5935b5ab47c572d1a11 | 592,176 |
def merge_grad_list(all_grads, all_vars):
"""
Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs
"""
return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)] | ac6e609f464729f1efc6db4b9c8d4342db17b8a0 | 592,177 |
def is_same_file_contents(lhs: str, rhs: str) -> bool:
"""Compare file contents
Args:
lhs (str)
rhs (str)
Returns:
bool: returns True if two file contents is same, else False
"""
with open(lhs) as fd:
a = fd.readlines()
with open(rhs) as fd:
b = fd.read... | 1e540cbcd1b9b0b0c6cb9ff3937768ac1f22107f | 592,179 |
def _filter_for_numa_threads(possible, wantthreads):
"""Filter to topologies which closest match to NUMA threads
:param possible: list of nova.objects.VirtCPUTopology
:param wantthreads: ideal number of threads
Determine which topologies provide the closest match to
the number of threads desired by... | 391132b807885cdbe53fc56e866a1ab2000275f7 | 592,180 |
def flatten_column_names(columns, ordering):
"""
Takes a column MultiIndex and joins each entry into a single underscore
separated string based on the indices in the iterable `ordering`.
Spaces in the MultiIndex entry are replaced with underscores.
"""
values = [[x[y] for y in ordering] for x i... | b256a14cd9dcf97ee719e3d4f4eb895e6e810592 | 592,181 |
def forcedir(path):
"""Ensure the path ends with a trailing /
:param path: An FS path
>>> forcedir("foo/bar")
'foo/bar/'
>>> forcedir("foo/bar/")
'foo/bar/'
"""
if not path.endswith('/'):
return path + '/'
return path | 968db047d604eb63cdbd0955a7da20479c40fc6a | 592,183 |
def get_next_batch(inputs, labels, start, batch_size):
"""
Helper function for batching
Returns a slice of inputs and slice of corresponding labels
:param inputs: NumPy inputs array
:param labels: NumPy labels array
:param start: starting index for the slice
:param batch_size: number of exam... | ca7bb4c0f13d4604bb7efe49f7af6aacf4e89b3e | 592,184 |
def get_player_collided_flag(measurement,
prev_collision_vehicles,
prev_collision_pedestrians,
prev_collision_other):
"""Obtains collision flag from player. Check if any of the three collision
metrics (vehicles, pedestrians, ... | 8c9c6e7c9f74c3901c61b65b80aa3f907dd3574e | 592,186 |
def get_vm_name(name):
"""
Map node name to VM name by stripping DNS suffix
"""
return name.split('.', 1)[0] | ca65b7ad4aad9b210cb1cc98adee86480feb0067 | 592,191 |
def get_merge_targest(module):
"""Return a set of basic blocks that are targets of merge instructions."""
merge_targets = set()
for function in module.functions:
for basic_block in function.basic_blocks:
if (len(basic_block.insts) > 1 and
basic_block.insts[-2] in ['Op... | df6f9741e1f2de17ebca4e7653bc967919a258c7 | 592,192 |
import re
def is_valid_image(image):
"""True if string looks like a valid GCE image name."""
return re.match(r'^[a-z0-9\-_]+$', image) | 0b3d0598666462b45b80e616354f9ad3ee38fcb5 | 592,197 |
def get_group_list(fieldmodule):
"""
Get list of Zinc groups (FieldGroup) in fieldmodule.
"""
groups = []
field_iter = fieldmodule.createFielditerator()
field = field_iter.next()
while field.isValid():
group = field.castGroup()
if group.isValid():
groups.append(gr... | cad8aca65fbd69b15c506011741ba4faa2982cde | 592,198 |
def reduce_dataset(data, vars_to_keep, coords_to_keep):
""" Removes all variables and coordinates from input dataset that are not
listed in paramters.
Parameters
----------
data : xarray.Dataset
vars_to_keep : sequence of strings
dims_to_keep : sequence of strings
Returns
-------
... | 94b4f471733757aab05591710d84dfc685764532 | 592,199 |
def filterdict(origdict, keyset):
"""returns the subset of origdict containing only the keys in keyset and their corresponding values """
newdict = {}
# this cunningly works with cidict (case-insensitive dictionary class)
# since we just check if key in origdict, not the reverse...
# the keys are th... | 8f3c1fead05a5f2c6c46b71558c57acf9d1c6432 | 592,200 |
import functools
import click
def make_colour(**colour_kwargs):
"""
Create a colour shortcut
>>> make_colour(fg='red')('hey')
'\\x1b[31mhey\\x1b[0m'
>>> make_colour(fg='red')('hey', fg='green')
'\\x1b[32mhey\\x1b[0m'
>>> make_colour(fg='red')('hey', bg='green')
'\\x1b[31m\\x1b[42mhey\... | e357e563acc639e3996b5affcef849a641af8772 | 592,203 |
def temp_to_orig_section(temp_sec):
"""
Change a temp section into its original.
If it is its original it will return what was given.
:param temp_sec: temporary section created by 'create_temp_batch'
:return: orig section
"""
section = temp_sec
if temp_sec.startswith(('1', '2', '3', '4',... | 98592ddbec24a496c7225e0be8722d1df71f58f8 | 592,204 |
import importlib
def get_extractor_implementation(cls, pkg=None):
"""
Get the implementation of an Extractor.
:param cls: class name (str)
:param pkg: package where implementation is found (str)
:return: class implementation
"""
# known extractors
# others must be fully specified throu... | 33bfa823e4b5dd44a0a02483f2a51965855c1bf2 | 592,210 |
def _to_rio(xds, cc):
""" Apply CRS to Dataset through rioxarray functionality. """
return xds.rio.write_crs(cc.to_string(), inplace=True) | f4b0e23624087f991c52d3bf41fc9a1fdb016b98 | 592,211 |
from typing import OrderedDict
def unique(seq):
"""Return list of unique elements preserving original order."""
return list(OrderedDict.fromkeys(seq)) | cde7ccde5461682633fef039190634ba9aa59d23 | 592,213 |
import textwrap
def remove_returns(doc):
"""
Given a numpy-formatted docstring, remove the "Returns" block
and dedent the whole thing
Returns
-------
List of lines
"""
lines = textwrap.dedent(doc).split('\n')
outlines = []
rblock = False
for line in lines:
lstrip ... | f9c76a29b8a5bf49f889843973a2140a107c4574 | 592,221 |
def _WordScore(index, normalized_command_word,
canonical_command_word, canonical_command_length):
"""Returns the integer word match score for a command word.
Args:
index: The position of the word in the command.
normalized_command_word: The normalized command word.
canonical_command_word... | b4e37b491d27810634ba91386433f3f4e89eaa19 | 592,222 |
def demo_fields_docstring_arguments(m, b): # type: ignore
"""
Fields are used to describe specific properties of a documented object.
This function can be used in conjuction with L{demo_typing_arguments} to
find an arbitrary function's zeros.
:type m: number
:param m: The slope of the line.
... | 3d60575afa00f4811e675ea5badde08cfd496eb9 | 592,231 |
def wrap_star_digger(item, type_str, data_name='Value'):
"""
code used to extract data from Bing's wrap star
:param item: wrap star obj
:param type_str: target type string
:param data_name: target data label, might be "Entities", "Properties", 'Value'
:return: list of all matched target, arrange... | 37d96ae9643869175a1202a57c2137db8baa4bb6 | 592,234 |
def _formatobj(obj, *attrnames):
"""Format an object and some attributes for printing"""
attrs = ", ".join(f"{name}={getattr(obj, name, None)}" for name in attrnames)
return f"<{obj.__class__.__name__}({attrs}) at {hex(id(obj))}>" | 16bce586241a1f0410308e195a39a96cd05ed7a9 | 592,241 |
from pathlib import Path
def create_generic_file(tmpdir) -> Path:
"""
Create and store a generic file using Python built-in functions.
At the end of tests, this file is removed by the finalizer of the
'tmpdir' fixture.
Returns
-------
pathlib.Path
Path of the saved file
"""
... | d116149d013467b0f728f2232d11f22d6e2751bb | 592,242 |
import math
def dist_2d(x1, y1, x2, y2):
"""Returns the distance between (x1,y1) and (x2,y2)."""
return math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2)) | cea845bf7be56ad14fa5576a320685e260b0166e | 592,244 |
import requests
def get(endpoint='info', options='', ip='london.my-netdata.io', port='', api_version='v1/', return_type='json'):
"""Make REST API request to a netdata.
:param endpoint: Endpoint to call.
:param options: Optional params for api.
:param ip: What netdata to pull from.
:param port: Wh... | 079260d88927699709495f058cd2d8063d145074 | 592,245 |
import io
def String_to_CStringIo(string):
"""Converts a string to a StringIO.StringIO object.
Inverse of CStringIo_to_StringIo"""
return io.StringIO(string) | f92b7a279ae162434f14a033713fe36769b5d38f | 592,246 |
def get_objective(is_binary):
"""Gets classifier objective string which depends on if the problem is binary.
Args:
is_binary: boolean whether classification task is binary
Returns:
objective: string
"""
if is_binary:
return 'binary:logistic'
else:
return 'multi:softprob' | 18c353f287ac4cdc4818ca8ab35c605827c84cf0 | 592,249 |
def chan_a(device):
"""Channel A of the first device in the session fixture."""
return device.channels['A'] | e4cdfc8f6fe9e7c0c7f9877689072effa651f2bf | 592,252 |
def find_smallest_angle(angle1, angle2, absolute_value=False):
"""Find the smallest angle between two provided azimuth angles.
@param: - angle1 - first angle in degrees between 0 and 360 degrees
@param: - angle2 - first angle in degrees between 0 and 360 degrees
@param: - absolute_value - if true, retur... | c1f3581a7d43d344f81f204ba9f30df32601429e | 592,253 |
def _singleton(cls, *args, **kwargs):
"""Return the single instance of a class, creating it if it does not exist."""
if not hasattr(cls, 'instance') or cls.instance is None:
obj = cls(*args, **kwargs)
cls.instance = obj
return cls.instance | cc8b2a719af4ce5782c16d50ead96b49373b5fbb | 592,254 |
def shifted_list(l):
"""
Return the shifted (normalized) list of list l.
A shifted/normalized is a list which starts with 0 and ends with
last(l)-l[0]
"""
return [l[i] - l[0]+1 for i in range(len(l))] | 63d1bd34718130855ff27b69dfb10aadb0177219 | 592,257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.