content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def remove_full_rowspans(rows):
"""Remove rows in which all cells have the same text."""
return [row for row in rows if len(set(row)) > 1] | af1e4ccbd7e88e79e0f2bd01bf6dfaba4315bea3 | 103,416 |
from typing import Tuple
import getpass
def ask_creds() -> Tuple[str, str]:
"""manually ask for credentials
Returns:
Tuple[str, str]: username and password
"""
username = input("Enter your ProQuest username: ")
password = getpass.getpass("Enter your ProQuest password: ")
return (usern... | 951ff3ef88c3e6d52fe2b16dbce723bda5c9fea3 | 516,591 |
from datetime import datetime
def midnight(d): # noqa
"""Given a datetime.date, return a datetime.datetime of midnight."""
if d is None:
return None
return datetime(d.year, d.month, d.day) | 93c257d21722e8f31feec49fe2be193a833e75c2 | 263,909 |
def cwE(nc, w, adj, *args):
"""
Create column width _profile for cmds.rowColumnlayout command
:param nc: number of columns
:param w: total width of whole layout
:param adj: adjustment number to fit all columns to layout
:return:
column width
"""
width = (w - adj) / nc
cw = []
... | 6fa0ece3c7661a917c2f6595ab453be6852899b4 | 456,433 |
import re
def split_hname(hname):
"""split a hierarchical name (hname) into parts.
double '/' is used to escape the '/'.
and is transformed into a into single '/'
e.g.
hname = "network/network-fd02:://64"
=> ["network", "network-fd02::/64"]
:param str hname: hierarchical name
... | bb88dd2164a37c42a109332f6d62a85d2d009198 | 643,787 |
def plato_to_gravity(degrees_plato: float) -> float:
"""
Convert degrees plato to gravity.
"""
return 259.0 / (259.0 - degrees_plato) | 61edbccd590e9344ab69df7af3cc03895426c4c7 | 230,009 |
def catwalk(text):
"""
Replace multiple spaces in a string with a single space.
:type text: string
:param text: The text to fix.
>>> catwalk("this is a long sentence")
'this is a long sentence'
"""
# Return the fixed version
return ' '.join(text.split()) | 49f00d6e7d584ecaa31454e8cf2d214b937f5002 | 582,320 |
def bool_or_none(b):
"""Return bool(b), but preserve None."""
if b is None:
return None
else:
return bool(b) | 14627043e5fd67f11a72be916144269e658b26b1 | 477,732 |
def cropImage(image, crop_bottom, crop_top, crop_left, crop_right):
"""Crop an image.
Parameters
----------
image : numpy array
The image that is to be cropped
crop_bottom, crop_top, crop_left, crop : int
How many pixels to crop in each of these directions
Returns
-------
... | 8ecbeec91e213e8db192bb05e0f5032511608aa4 | 152,607 |
def abbr_status(value):
"""
Converts RFC Status to a short abbreviation
"""
d = {'Proposed Standard':'PS',
'Draft Standard':'DS',
'Standard':'S',
'Historic':'H',
'Informational':'I',
'Experimental':'E',
'Best Current Practice':'BCP',
'Intern... | 08025ed44e9c8ea725755f9a07b6a5a04834f896 | 32,490 |
def nodes_iter(topology):
"""Get an iterator for all nodes in the topology"""
return topology.nodes_iter() | 66613676ae76d1705c9a45eeb336862d99df2ebe | 635,902 |
def last_delta(x):
"""difference between 2 last elements"""
return x[-1]-x[-2] | e7a979b1b2a328b85e413e9c5817efa31d275d61 | 472,323 |
def c2f(t):
"""
Converts Celsius Temperature to Fahrenheit Temperature.
"""
return t * float(1.8000) + float(32.00) | c7c2fd30d257a0a09aaaa546445e80ef9553e93c | 522,546 |
def get_tri_from_course(course, courses):
"""
Given a courses dict, return the trimester of the :param course
"""
for tri in courses:
for _course in courses[tri]:
if course == _course:
return tri | 14970e0c7e72d9ef79a717d75a798f35a62aa09c | 367,106 |
import importlib
def find_dataset_using_name(dataset_name):
"""Import the module "data/[dataset_name]_dataset.py".
In the file, the class called DatasetNameDataset() will
be instantiated. It has to be a subclass of BaseDataset,
and it is case-insensitive.
"""
dataset_filename = "datasets." + ... | 961b38ac33b08b08d0be5d7c85c1c6c38ee0fe13 | 499,304 |
def _pseudo_alpha(rgb, opacity):
"""
Given an RGB value in [0, 1], return a new RGB value which blends in a
certain amount of white to create a fake alpha effect. This allosws us to
produce an alpha-like effect in EPS, which doesn't support transparency.
"""
return tuple((value * opacity - opa... | 0326d306c8846b46a7b9225ee5b969ff88e4e47d | 687,647 |
def image_scale(img):
"""Retrieves the image cell size (e.g., spatial resolution)
Args:
img (object): ee.Image
Returns:
float: The nominal scale in meters.
"""
# bands = img.bandNames()
# scales = bands.map(lambda b: img.select([b]).projection().nominalScale())
# scale = ee... | 038c14412c7a53dbc77915e99b162f2534361589 | 187,593 |
from typing import Union
from typing import Dict
from typing import List
import json
def dict_to_formatted_string(dictionary: Union[Dict, List]) -> str:
"""
Return dictionary as clean string for war room output.
Parameters
----------
dictionary : dict | list
The dictionary or list to form... | 2ecc473e68253c14260976cf77f459d67d5b6ef3 | 457,489 |
def get_title(soup):
"""
Get a topic title.
Examples
--------
>>> title_tag = '<title>title</title>'
>>> soup = make_soup(title_tag)
>>> get_title(soup)
'title'
"""
return soup.find('title').text.split('|')[0].strip() | d5ae3581338940f7ac7ddc4949fc294ed16d197e | 647,836 |
def convert_hours_to_days(hours):
"""
(int or float) -> float
Takes time in hours and returns time in days.
"""
return hours / 24.0 | 81e3e8a7060aa71b16a8eb4fdc0bac7af996febd | 164,914 |
import re
def truncate(text, words=25):
"""Remove tags and truncate text to the specified number of words."""
return ' '.join(re.sub('(?s)<.*?>', ' ', text).split()[:words]) | 42cc1f0520a92a6bcbc46501e37dcb6832d8f93f | 625,070 |
def Dictionary_to_XmlTupleString(python_dictionary):
"""transforms a python dictionary into a xml line in the form
<Tuple key1="value1" key2="value2"..keyN="valueN" />"""
prefix="<Tuple "
postfix=" />"
inner=""
xml_out=""
for key,value in python_dictionary.items():
inner=inner+'{0}="... | fe6a52b10dccc4e836bb12ec1c5b26017d075dcf | 671,285 |
import math
def calculate_entropy(positives, negatives):
"""
Given a column, calculate entropy for it
Parameters
----------
positives: int
Number of positive attributes
negatives: int
Number of negative attributes
Returns
-------
float
"""
# since the cal... | 424e2d0f9173eab0dd6d8ac9202057ea3f3bd61b | 465,444 |
def arg1(*args):
"""Returs args[0]. Helpful in making lambdas do more than one thing."""
return args[0] | c4254f3c16d001661088723e093ca4086d483e89 | 362,109 |
def background_subtract(meas_area, back_area, meas_time, back_time):
"""
Background_Subtract will subtract a measured Background peak net area from
a sample peak net area. The background peak is converted to the same time
scale as the measurement and the subtraction is performed. All inputs are
scal... | 36aa96743b396daccb571c6c59c0a0f592f25c29 | 391,443 |
def complete_matrix(X):
"""
input: X: sparse matrix
output: Y: same matrix with zeros completed
"""
Y={}
row=0
column=0
for k in X.keys():
row=max(row,k[0])
column=max(column,k[1])
for i in range(1,row+1):
for j in range(1,column+1):
if (i,j) in X.... | c3ceab63ba8282c7d67f562f27baa58481c5e3cd | 417,920 |
import collections
import math
def shannon_entropy(sequence, log_base=2):
"""
Calculates the shannon entropy over a sequence of values.
Args:
sequence: An iterable of values.
log_base: What base to use for the logarithm.
Common values are: 2 (bits), e (nats), and 10 (ban... | 5e1760ae666cda2faf477ccb218a3e1faf0b4da2 | 190,186 |
def distinct_powers(a, b):
"""
Finds and returns the number of distinct powers of a and b
Example:
>>> distinct_powers(5, 5)
15
:param a: Limit of a
:type a int
:param b: limit of b
:type b int
:return: number of distinct powers
:rtype: int
"""
# sanity checks
... | 4f77b03087bc0c0e0b0a8fc90bfc16941e2c1bd0 | 342,200 |
def mouse_coll_func(arbiter, space, data):
"""Simple callback that increases the radius of circles touching the mouse"""
s1, s2 = arbiter.shapes
s2.unsafe_set_radius(s2.radius + 0.15)
return False | 0127da96630136e2e058d7e46bb2a3099f673412 | 380,648 |
import random
def sim_detections(gt, tpr, fpr):
"""Simulates detection data for a set of ground truth cluster labels and an
annotator with a specified TPR and FPR.
Returns an array of with same length as input gt, where 1 indicates the
simulated annotator detected a cluster and 0 indicates an undetec... | ad8d0ac4423333c64ab1db8b838cba4ed7da4291 | 27,357 |
from typing import List
from typing import Any
def deduplicate(a_list: List[Any]) -> List[Any]:
"""
deduplicate a list
:param a_list: a list of possibly repeating items
:returns: a list of unique items
"""
new_list = []
for item in a_list:
if item not in new_list:
new_... | d3f9181bcb196a8f518eb208ec615fdbd4f0be04 | 165,990 |
def read_sym_table(sym_table_path: str) -> dict:
"""Read in a kaldi style symbol table.
Each line in the symbol table file is "sym index", separated by a
whitespace.
Args:
sym_table_path: Path to the symbol table file.
Returns:
sym_table: A dictionary whose keys are symbols and v... | 02b8811fe125358ec60ca98ba8eb15074b5be826 | 527,515 |
import math
def latlon2equirectangular(lat, lon, phi_er=0, lambda_er=0):
"""Naive equirectangular projection. This is the same as considering (lat,lon) == (y,x).
This is a lot faster but only works if you are far enough from the poles and the dateline.
:param lat:
:param lon:
:param phi_er: The ... | 84b423595df0c1036246d3ac0ee68627575ecfcc | 146,301 |
def money_with_currency(money):
"""A filter function that returns a number formatted with currency info."""
return f"$ {money / 100.0:.2f} USD" | b35569883abc855c6b633e7d91d93c87f86834bf | 529,215 |
def check_is_iterable(py_obj):
""" Check whether a python object is a built-in iterable.
Note: this treats unicode and string as NON ITERABLE
Args:
py_obj: python object to test
Returns:
iter_ok (bool): True if item is iterable, False is item is not
"""
# Check if py_obj is a... | 9d5c912a94237f71f6f85a479720dcbcc06144f8 | 415,898 |
def get_simple_split(branchfile):
"""Splits the branchfile argument and assuming branch is
the first path component in branchfile, will return
branch and file else None."""
index = branchfile.find('/')
if index == -1: return None, None
branch, file = branchfile.split('/', 1)
return b... | 2dc4dd86add1ee90937ee36d873c255b9ed1cd01 | 487,448 |
from collections.abc import Sequence
def is_list_like(obj):
"""
This function checks if the given `obj`
is a list-like (list, tuple, Series...)
type or not.
Parameters
----------
obj : object of any type which needs to be validated.
Returns
-------
Boolean: True or False depe... | 993ef0b572302ac24fe61e4a41fd2c845b35a7b6 | 553,915 |
from typing import Iterable
def const_col(dims: Iterable[int]) -> str:
"""
Name of an constant columns.
Parameters
----------
dims
Dimensions, that describe the column content.
Returns
-------
name: str
Column name.
Example
-------
>>> from rle_array.test... | 52aecf5872f6444bf0155f0556ce39b2250ce758 | 40,847 |
import attr
def struct(*args, **kw):
"""
Wrapper around ``attr.s``.
Sets ``slots=True`` and ``auto_attribs=True``. All other arguments are
forwared to ``attr.s``.
"""
return attr.s(*args, slots=True, auto_attribs=True, **kw) | 1eee1044ee340b2fe9387773304751d4efca209f | 31,222 |
import time
def _create_etag() -> str:
"""Generate the current timestamp to use as etag."""
return str(time.time()) | b96eaf2409aab3d5ecc33eb93f2facbefaf874fd | 236,522 |
def AA2n(s):
"""
>>> AA2n('AA')
27
>>> AA2n('A')
1
>>> AA2n('BC')
55
"""
v = 0
for i in s:
v *= 26
n = ord(i) - ord('A')
n += 1
v += n
return v | 48706143526bab792c043b4cb224a464fefb6208 | 508,899 |
def construct_return_tuple(original_ctypes_sequence):
"""Generate a return value for queryf(), scanf(), and sscanf() out of the
list of ctypes objects.
:param original_ctypes_sequence: a sequence of ctypes objects, i.e. c_long,
c_double, and ctypes strings.
:return... | 2183cb0266873184cdbc9dccbb1494e6999ee93c | 227,409 |
def checkanswer(possible, guess):
""" Case insensitive check of answer.
Assume inputs are in the correct format, since takeQuiz() accounts
for
Args:
possible (list): List of possible answers for question.
guess (string): User's guess for question.
Returns:
bool: True if guess... | efd7d81b83d23f62f85f65b6b000c1c4dd9ff98a | 455,113 |
def read_log_file(file_path):
"""
reads the values from a log_file
:param file_path: path to the log file
:return: indices, values => indices and values for them
"""
indices, values = [], [] # initialize these to empty lists
with open(file_path, "r") as filer:
for line in filer:
... | 546fa9c9ff39763bd045ad9c36898d3c62cdf8f3 | 481,104 |
from typing import Union
def num_format(num: Union[int,float], precision: int = 3) -> str:
"""Return a properly formated string for a number at some precision.
Formats a number to some precesion with trailing 0 and . removed.
Args:
num (Union[int,float]): Number to be formatted.
precisio... | 91ae5f2dadfed57a24a6f3e9a14a81e2e35f770d | 545,098 |
import time
def getMDY(t):
"""Return MMM DD, YYYY."""
tm = time.strptime(t, "%Y-%m-%d %H:%M:%S")
return time.strftime("%b %d, %Y", tm) | 631de3ca3eb1ca753c8e523c81d4d81f086a71f2 | 516,869 |
from typing import Tuple
import math
def calc_differential_steering_angle_x_y(b: int, dl: float, dr: float, o: float) -> Tuple[float, float, float]:
"""
Calculate the next orientation, x and y values of a two-wheel
propelled object based on the differential steering principle.
:param b: the distance ... | bd9c2bac7296e188930b51b7d5c1775f6af2ad9f | 593,958 |
def is_my_argument_a_string(maybe_string):
"""In this challenge you need check to see what type of object
the variable 'maybe_string' is. If it is a string type please return a true
if it is not a string object please return false.
"""
return isinstance(maybe_string, str) | 154e50b645c0c14e84940c3ebff0bd71bb10f598 | 225,767 |
def _get_mc_host(host=None):
"""Gets the host of the ModelCatalog"""
if host is None:
return "model-catalog" | 9e656f31d7c5949000347d3d1d8c06840d99539c | 535,484 |
def gethHfieldop(hx, hy, hz, l=2):
"""
Return magnetic field operator for one l-shell.
Returns
-------
hHfieldOperator : dict
Elements of the form:
((sorb1,'c'), (sorb2,'a') : h_value
where sorb1 is a superindex of (l, s, m).
"""
hHfieldOperator = {}
for m in ra... | 4d9f7e343de40fe68d8b4b2ee49ca894c5e063fb | 599,087 |
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
f0: derivative val... | 0884c0980dba3b819e62df1b36055d5b21670104 | 526,283 |
import math
def guessDistanceTrig(targetHeight, ownHeight, angleOffset, angle):
"""
Uses the difference between two heights and an angle to construct a
right triangle and tangent to determine the horizontal distance.
"""
return (targetHeight - ownHeight) / math.tan(math.radians(angle + angleOffset... | a7228673c84d0e37a69d3340ae0d2dfe6acf02dc | 237,628 |
import asyncio
async def wait_for_event(evt, timeout): # pylint: disable=invalid-name
"""Wait for an event with a timeout"""
try:
await asyncio.wait_for(evt.wait(), timeout)
except asyncio.TimeoutError:
pass
return evt.is_set() | b8b2616f36f12db092c8f12a402115df863dff6f | 663,043 |
import re
def try_include(line):
"""
Checks to see if the given line is an include. If so return the
included filename, otherwise None.
"""
match = re.match('^#include\s*[<"]?(.*)[>"]?$', line)
return match.group(1) if match else None | f30c885ffa783f78f5a71dc1906ac6e158226361 | 27,775 |
def triggered_telescopes(array, trigger_threshold):
"""
Return the list of telescopes that triggered in the array
Parameters
----------
array: list of telescope Class
trigger_threshold: float
Returns
-------
list of telescope Class
"""
trig_tel = [tel for tel in array if te... | 39f0ff7a1d042af3c4fbe09698ac6dc07df305e4 | 359,382 |
def clean_data(df):
"""
This function cleans data from the provided dataframe
Parameters: df is the dataframe with the messages and categories
Return: df is the dataframe already clean with no duplicates
"""
print("df shape=",df.shape)
duplicate = df[df.duplicated()]
print("df... | 7becbeb82c79ac0319b1dbacc65afcca0a1f7359 | 647,239 |
def underline(line, underline='~'):
"""Return an underline string for ``line``.
Intended for use with level 3 and lower headings.
Note that the default for ``underline`` assumes that the level
1 and 2 underlines are the standard ``=`` and ``-``. You can
pass a different underline character... | 27d898f92d15fbe50be133b61887c1211173979c | 179,604 |
def backslash_remove(text):
"""Return text without backslashes"""
return text.replace('\\', '') | 43771acac84fd57bfa0f21223b2f82735e42c7d8 | 256,637 |
def quick_sort(seq):
"""Quicksort method."""
if isinstance(seq, list):
if len(seq) <= 1:
return seq
piv, seq = seq[0], seq[1:]
low, high = [x for x in seq if x <= piv], [x for x in seq if x > piv]
return quick_sort(low) + [piv] + quick_sort(high)
else:
rai... | 47e5691b6808993d8e4387f1f10f03ab656be443 | 609,109 |
import random
import math
def randCoord(cLat=38.889484, cLong=-77.035278, radius=10000):
"""
Generate a random lat/long within a radius of a central location
:param cLat: central points latitude, in degrees
:param cLong: central points longitude, in degrees
:param radius: radius to generate points... | a86f1e13c56d66e898d557e73c5aa05b09e6455e | 452,403 |
import shlex
def get_flexbar_options_string(args):
""" Extract the flags and options specified for flexbar added with
add_flexbar_options.
Parameters
---------
args: argparse.Namespace
The parsed arguments
Returns
-------
flexbar_options: string
a string containing fl... | 72ba73bd51d037c3d6ad3f523913b1de93e5a729 | 401,601 |
import base64
def decode(b64):
"""
Decode given attribute encoded by using Base64 encoding.
The result is returned as regular Python string. Note that TypeError might
be thrown when the input data are not encoded properly.
"""
barray = base64.b64decode(b64)
return barray.decode('ascii') | 5c04c43247d1415ca8f1398c3b8206c50a7e0fa4 | 14,282 |
from typing import List
def _clean_names_refstate(names: List[str]) -> List[str]:
"""Uniformization of refstate profile names."""
to_clean = {
'Tref': 'T',
'rhoref': 'rho',
'tcond': 'Tcond',
}
return [to_clean.get(n, n) for n in names] | 29b3618bbe0b8f8e9922d91681d4761f769815c8 | 54,274 |
from typing import Callable
from typing import Any
import importlib
def get_function_by_name(func_str: str) -> Callable[..., Any]:
"""Get a function by its name.
Args:
func_str (str): Name of function including module,
like 'tensorflow.nn.softplus'.
Returns:
Callable[Any]: th... | f7a0fb35ab49b15b10668a16561609e6bd3f2355 | 355,683 |
def get_root_id(org_client):
"""
Query deployed AWS Organization for its Root ID.
"""
roots = org_client.list_roots()['Roots']
if len(roots) >1:
raise RuntimeError("org_client.list_roots returned multiple roots.")
return roots[0]['Id'] | 58c27ddf61e2a4d892eb90b3d64c7766fb1c0010 | 262,310 |
def _to_http_url(url: str) -> str:
"""Git over SSH -> GitHub https URL."""
if url.startswith("git@github.com:"):
_, repo_slug = url.split(':')
return f"https://github.com/{repo_slug}"
return url | 7bb6f5477dbf2e62cc480a78cf12cfee9ec7c1f6 | 512,009 |
from typing import Tuple
def _s2_face_uv_to_xyz( # pylint: disable=invalid-name
face: int, uv: Tuple[float, float]
) -> Tuple[float, float, float]:
"""
Convert face + UV to S2Point XYZ.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L348-L357
Args:
fa... | 2df5372e6bb3d304e386dcf2abdbd72dc75397aa | 556,517 |
import torch
def get_device(gpus: int) -> torch.device:
"""
Return the device type to use.
If the system has GPUs available and the user didn't explicitly specify 0
GPUs, the device type will be 'cuda'. Otherwise, the device type will be
'cpu' which will be significantly slower.
Parameters
... | 3fa7bbf5a39914428f215bce2b7dab9a06b6a4ba | 113,797 |
def _get_jira_label(gh_label):
""" Reformat a github API label item as something suitable for JIRA """
return gh_label["name"].replace(" ", "-") | 0e734c64198b6ccab6515317d60b6fa799ae8870 | 128,051 |
import requests
import json
def send_request( url, authKey ):
"""Send a request
Send a request using the provided url and authentication key.
Raise an exception if the request fails.
When successful, return the json data replied by the server
"""
try:
headers = {'Accep... | 6253aacef6addefe9f795252f91bc094d19d6fc7 | 524,569 |
def get_filename(disposition):
"""Parse Content-Disposition header to pull out the filename bit.
See: http://tools.ietf.org/html/rfc2616#section-19.5.1
"""
if disposition:
params = [param.strip() for param in disposition.split(';')[1:]]
for param in params:
if '=' in param:... | b24907fa6820d5d80f53cbd2e1c14a9578b959d6 | 558,169 |
import six
def _objectToDict(obj):
"""
Convert an object to a dictionary. Any non-private attribute that is an
integer, float, or string is returned in the dictionary.
:param obj: a python object or class.
:returns: a dictionary of values for the object.
"""
return {key: getattr(obj, key... | b65303a667b36ee0bab9110556392a85ec902c3c | 57,422 |
def theta_map(mat, z):
"""
Evaluates the conformal map "theta" defined by a matrix [a,b],[c,d]
theta = (a*z + b)/(c*z + d).
"""
[a, b], [c, d] = mat
return (a*z + b)/(c*z + d) | ab7fae009d93c8de0c4c8935600ce19588ed8a40 | 588,975 |
def pad(tokens, length, pad_value=0):
"""add padding 1s to a sequence to that it has the desired length"""
return tokens + [pad_value] * (length - len(tokens)) | 43ddf4229856d630f464aaaee21ebdeb8edc1980 | 562,406 |
def closestMatch(value, _set):
"""Returns an element of the set that is closest to the supplied value"""
a = 0
element = _set[0]
while(a<len(_set)):
if((_set[a]-value)*(_set[a]-value)<(element-value)*(element-value)):
element=_set[a]
a = a + 1
return element | 204709e6e1305a23fec39c64c851c2487d5bc753 | 251,063 |
def get_filter_name(filter_obj):
"""
Get filter name
Args:
filter_obj:
Returns:
str
"""
sql_expression = filter_obj.get("sqlExpression")
if sql_expression:
return sql_expression
clause = filter_obj.get("clause")
column = filter_obj.get("subject")
operat... | e3094eca8186e1edc957a1531bf5bd274e697ad5 | 476,562 |
def divide(dividend, divisor):
"""
:param dividend: a numerical value
:param divisor: a numerical
:return: a numerical value if division is possible. Otherwise, None
"""
quotient = None
if divisor is not None :
if divisor != 0:
quotient = dividend / divisor
return qu... | e5e6678f7de33524444b3bcd40fa45c21f42c77d | 38,811 |
import math
def circle(center_pt, radius):
"""
Creates a polygon with the given center point and radius
center_pt: center of circle, as tuple (x, y)
radius: radius of circle
return: list of tuples representing points on circle boundary.
first and last point should be the same.
"""... | d87c8cfa268fd3f7ae11540f96e220ee951ad20d | 232,056 |
def get_color_name(color_int):
"""Gets a human readable name for a traffic sign color.
Args:
color_int: ID of traffic light color (specified in styx_msgs/TrafficLight).
Returns:
A string corresponding to the color name.
"""
color_int_map = {
0: "RED",
1: "YELLOW",
2: "GREEN",
4: "UNKNOWN",
}
return... | 2f73c6f5e8a70110ded2ade1ce5d6f7320db2f4f | 553,491 |
def cat2axis(cat):
"""
Axis is the dimension to sum (the pythonic way). Cat is the dimension that
remains at the end (the Keops way).
:param cat: 0 or 1
:return: axis: 1 or 0
"""
if cat in [0, 1]:
return (cat + 1) % 2
else:
raise ValueError("Category should be Vi or Vj.") | ad33bf7a70d468c5eb9a98529b751ab8254ae24c | 53,536 |
def format_time(msec):
"""Converts msec to correct unit. Returns it as formatted string."""
if msec < 10**3: #ms
return str(msec)+"ms"
else:
return str(msec//1000)+"s" | fcf34cc6c5c7c74424b6d9ac7f0609a3ab515300 | 474,682 |
from typing import List
import re
def extract_jira_references(text: str) -> List[str]:
"""
Extract identifiers that point to Jira tickets
"""
return [result.group(0) for result in re.finditer(r"\w+-\d+", text)] | a9f428d9ed30119908a96c9bd8aac360ec177c46 | 222,836 |
def lagrange(x_data, y_data):
"""
Compute the interpolant polynomial corresponding to the
points given in (x_data, y_data)
Parameters
----------
x_data : list
List with x coordinates for the interpolation.
y_data : list
List with y coordinates for the interpolation.
Ret... | ae2ba231948d61327830ffe2cb255c0575b3a52e | 386,268 |
import collections
def find_consensus(sequences, threshold=0.7):
"""
Given aligned sequences, return a string where each position i is the
consensus value at position i if at least threshold fraction of strings
have the same character that position i, and "." otherwise.
"""
if len(sequences) ... | 3994f417977b2c89ea49b87452513481914e4697 | 404,434 |
import hmac
import hashlib
def gen_sign(key, data):
"""Compute RFC 2104-compliant HMAC signature."""
return hmac.new(key, data.encode('utf-8'), hashlib.sha256).digest() | d25ba278581e49f7197a0ac8524a00fef68ac36b | 325,748 |
def Moffat2D(x, y, amplitude=1.0, x_0=512.0, y_0=512.0, x_gamma=6.0, y_gamma=6.0,
alpha=1.0):
"""Two dimensional Moffat function with different scale parameters for both axes"""
rr_gg = (x - x_0) ** 2 / x_gamma**2 + (y - y_0) ** 2 / y_gamma ** 2
return amplitude * (1 + rr_gg) ** (-alpha) | 1451a83d8e9f6a1fc49132b1b4a244f92a5dcdfe | 561,090 |
def get_sequence_name_from(seq_name_and_family):
"""Get sequence name from concatenated sequence name and family string.
Args:
seq_name_and_family: string. Of the form `sequence_name`_`family_accession`,
like OLF1_CHICK/41-290_PF00001.20. Output would be OLF1_CHICK/41-290.
Returns:
string. Sequenc... | 25377994f92353efdae25deb42a315beb4c345a9 | 234,142 |
def color_to_hex(name):
"""Convert a named ReportLab color (Color class) to a hexadecimal string"""
_tuple = (int(name.red*255), int(name.green*255), int(name.blue*255))
_string = '#%02x%02x%02x' % _tuple
return _string.upper() | e1eba5f284ef90dfcb6bde8ef75739c58a62f89c | 345,556 |
def tokens_from_module(module):
"""
Helper method; takes a module and returns a list of all token classes
specified in module.__all__.
Useful when custom tokens are defined in single module.
"""
return [getattr(module, name) for name in module.__all__] | da1c53f9f1c56784c81000f98a3be9e675956e2a | 92,934 |
def xpath_lower_case(context, values):
"""Return lower cased values in XPath."""
return [v.lower() for v in values] | f9048bc16ea717ec6f0538ab8217a0e1e2223c0d | 96,059 |
def get_chunks(sequence, chunk_size):
"""Split sequence into chunks.
:param list sequence:
:param int chunk_size:
"""
return [
sequence[idx:idx + chunk_size]
for idx in range(0, len(sequence), chunk_size)
] | b7abdf160e6eacc635372d7fb07d09330cea292c | 510,256 |
from typing import Dict
from typing import List
def convert_spin_to_list(spins: Dict) -> List:
"""Convert the Spin dictionary from the ssoCard into a list.
Add the spin index as parameter to the Spin entries.
Parameters
----------
spin : dict
The dictionary located at parameters.physical.... | 0d06523abe118305bbef13d681cb1d811628edda | 43,947 |
def enact_interventions(background_inmate_turnover, background_release_number, time, infected_list, release_number,
social_distance, social_distance_tau, stop_inflow_at_intervention, tau):
"""Enacts specified interventions."""
# Print intervention info
print(f'Release intervention co... | 2816a9670d25c281642461256d2e464c9d4274c1 | 623,745 |
from typing import List
def generate_pairs(number: int) -> List[List[int]]:
"""Generate all pairs of number sequence.
Args:
number: <int> the number
Returns: <list> a sequence
Examples:
>>> assert generate_pairs(1) == [[0, 0], [0, 1], [1, 1]]
"""
return [
[top, inner... | 1f711fca8774ce06dc291d45aff1d4ac3b1388e1 | 636,538 |
def synchronous_events_intersection(sse1, sse2, intersection='linkwise'):
"""
Given two sequences of synchronous events (SSEs) `sse1` and `sse2`, each
consisting of a pool of positions `(iK, jK)` of matrix entries and
associated synchronous events `SK`, finds the intersection among them.
The inters... | 3335f84433f8a82c020689a185d04538fc9660b8 | 401,203 |
def rgb2mpl(rgb):
""" convert 8 bit RGB data to 0 to 1 range for mpl """
if len(rgb) == 3:
return [rgb[0]/255., rgb[1]/255., rgb[2]/255., 1.0]
elif len(rgb) == 4:
return [rgb[0]/255., rgb[1]/255., rgb[2]/255., rgb[3]/255.] | 02a74d00fe43763d69597960359bcc7912b2cf6c | 543,876 |
def get_signed_polygon_area(points):
"""
Get area 2d polygon
:param points: list[DB.UV]
:type points: list[DB.UV]
:return: Area
:rtype: float
"""
area = 0
j = points[len(points) - 1]
for i in points:
area += (j.U + i.U) * (j.V - i.V)
j = i
return area / 2 | 960d5a3e5bff125fb560580f81b5103fa8147789 | 20,174 |
def hash_employee_data(employee_data):
"""
Hashes employee data by email for quick lookup. This is
necessary for efficient comparison of remote and local data.
Returns
-------
Dictionary - employee email to employee_data
"""
email_to_employee = {}
for employee in employee_data:
... | a62e862e78171f5c98ad7d233fe944419e103b07 | 303,599 |
import re
def parse_id_name(one_string):
"""Parses b"500(guest)" (bytes) and returns (500, "guest") (str)"""
mtch = re.match(br"^([0-9]*)\(([^)]*)\)$", one_string)
if mtch:
return mtch.group(1), mtch.group(2).decode("utf-8")
return -1, "" | 2142c7196565b6166513be1b76273a0f3e6ab62b | 158,153 |
from typing import List
import torch
import collections
def get_balanced_sample_indices(target_classes: List, num_classes, n_per_digit=2) -> List[int]:
"""Given `target_classes` randomly sample `n_per_digit` for each of the `num_classes` classes."""
permed_indices = torch.randperm(len(target_classes))
if... | 90df01021555ec54a0f3ad5caf36494edd8ae200 | 204,059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.