content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
def get_residue_info(name, num_scheme=None, verbose=False):
"""
Gets residue info from the GPCRdb
Parameters
----------
name : str
Name of the protein to download (as in its GPCRdb URL).
num_scheme : str
Alternative numbering scheme to use.... | 0b458cc63da8e0df521727a253a54d06d8548522 | 672,396 |
def sample_builder(samples):
"""
Given a dictionary with value: count pairs, build a list.
"""
data = []
for key in samples:
data.extend([key] * samples[key])
data.sort()
return data | 5a33bb4d6b0b363aa99161cc63f195efecfde964 | 672,400 |
import logging
from typing import Any
def _value(record: logging.LogRecord, field_name_or_value: Any) -> Any:
"""
Retrieve value from record if possible. Otherwise use value.
:param record: The record to extract a field named as in field_name_or_value.
:param field_name_or_value: The field name to ext... | 994c306ad15e972817128f70ac61c8de7071e719 | 672,404 |
def replace_tags(string, from_tag="i", to_tag="italic"):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace("<" + from_tag + ">", "<" + to_tag + ">")
string = string.replace("</" + from... | dccb4f34d0c26575a9a0c74fdb02c9a3dc4b2cd2 | 672,406 |
def fourcc_to_string(fourcc):
"""
Convert fourcc integer code into codec string.
Parameters
----------
fourcc : int
Fourcc integer code.
Returns
-------
codec : str
Codec string corresponding to fourcc code.
"""
char1 = str(chr(fourcc & 255))
char2 = str(ch... | 987330ec455e6ff043b4e045af9aa68425597471 | 672,410 |
def shape_of_horizontal_links(shape):
"""Shape of horizontal link grid.
Number of rows and columns of *horizontal* links that connect nodes in a
structured grid of quadrilaterals.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
tuple of i... | 4926b9ed439dec11aff75d4a9554d1b19d3eb20c | 672,412 |
def most_common(hist):
"""Makes a list of word-freq pairs in descending order of frequency.
hist: map from word to frequency
returns: list of (frequency, word) pairs
"""
t = []
for key, value in hist.items():
t.append((value, key))
t.sort()
t.reverse()
return t | aa8b757d30d103738c6acc924f1363449d6802cd | 672,418 |
from typing import Any
from typing import Optional
def arg_to_int(arg: Any, arg_name: str, required: bool = False) -> Optional[int]:
"""Converts an XSOAR argument to a Python int
This function is used to quickly validate an argument provided to XSOAR
via ``demisto.args()`` into an ``int`` type. It will t... | 2e753b01cf290c90ee4f1607042ef4a6ae3e2c2d | 672,420 |
import random
def populate(num_rats, min_wt, max_wt, mode_wt):
"""Initialize a population with a triangular distribution of weights."""
return [int(random.triangular(min_wt, max_wt, mode_wt))\
for i in range(num_rats)] | e69809b25ea63fba0487794e6d0f4982897461c2 | 672,421 |
def calc_freq_from_interval(interval, unit='msec'):
"""
given an interval in the provided unit, returns the frequency
:param interval:
:param unit: unit of time interval given, valid values include ('msec', 'sec')
:return: frequency in hertz
"""
if interval <= 0:
print('Invalid inter... | cb1862f86128b0b51363d309cf844df5bc02ba85 | 672,425 |
def unganged_me1a_geometry(process):
"""Customise digi/reco geometry to use unganged ME1/a channels
"""
if hasattr(process,"CSCGeometryESModule"):
process.CSCGeometryESModule.useGangedStripsInME1a = False
if hasattr(process,"idealForDigiCSCGeometry"):
process.idealForDigiCSCGeometry.useG... | a22ec5e1c93be2f5f3300f08c211b343b9a7f980 | 672,427 |
import random
import string
def random_string(n):
"""γ©γ³γγ ζεεηζ random string generator
Args:
n (int): ζεζ° length
Returns:
str: γ©γ³γγ ζεε random string
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=n)) | 9e6c26df098c3cef3b01e2c68409b33ad87d12f0 | 672,428 |
def convert_timestamp_to_seconds(timestamp):
"""Convert timestamp (hh:mm:ss) to seconds
Args:
timestamp (str): timestamp text in `hh:mm:ss` format
Returns:
float: timestamp converted to seconds
"""
timestamp_split = timestamp.split(":")
hour = int(timestamp_split[0])
minute... | 75c8f6cb6d0e8fd9646c686e8feb3871e1175457 | 672,430 |
import torch
def kpts_2_img_coordinates(kpt_coordinates: torch.Tensor,
img_shape: tuple) -> torch.Tensor:
""" Converts the (h, w) key-point coordinates from video structure format [-1,1]x[-1,1]
to image coordinates in [0,W]x[0,H].
:param kpt_coordinates: Torch tensor in (N,... | 93932bc54402fc105afad2e6b34570d3c83ac0b7 | 672,431 |
def combine(*dep_lists):
"""Combines multiple lists into a single sorted list of distinct items."""
return list(sorted(set(
dep
for dep_list in dep_lists
for dep in dep_list))) | 8eef7e25c93038c008b272dc17e913a61fe0e535 | 672,432 |
def _get_fn_name_key(fn):
"""
Get the name (str) used to hash the function `fn`
Parameters
----------
fn : function
The function to get the hash key for.
Returns
-------
str
"""
name = fn.__name__
if hasattr(fn, '__self__'):
name = fn.__self__.__class__.__na... | 8acdfe38c7f497244d2bf01f343ac241e3af6f6d | 672,433 |
def getPep (site, pos_in_pep, ref_seq):
"""
get the pep seq arount the given site from the reference sequence
Parameters
----------
site : int
pos in protein seq
pos_in_pep : int
position in the peptide (defines the number of aa will get around the site)
ref_seq : str
... | af1760a32f2260f74cac430076f578a0ddf33531 | 672,434 |
def parse_lines_to_dict(lines):
"""
Parse a list of message into a dictionnary.
Used for command like status and stats.
:param lines: an array of string where each item has the following format
'name: value'
:return: a dictionary with the names (as keys) and values found in the
lines.
"... | ec2246795fccfef79847be76ee013c1ca471b1a6 | 672,436 |
import string
import re
import hashlib
def get_hash(text):
"""Generate a hashkey of text using the MD5 algorithm."""
punctuation = string.punctuation
punctuation = punctuation + "β" + "β" + "?" + "β"
text = [c if c not in punctuation else ' ' for c in text]
text = ''.join(text)
text = re.sub(... | a20f34cda28c4a5d48799e1e61634da3d67b3da3 | 672,437 |
def fletcher_reeves(algo):
"""
Fletcher-Reeves descent direction update method.
"""
return algo.current_gradient_norm / algo.last_gradient_norm | 4a4d320f403436f73c92bfeb888eba262b4cae05 | 672,448 |
from typing import Union
def calculate_digital_sum(number: Union[int, str]) -> int:
"""Calculate the digital sum of the number `number`."""
return sum([int(digit) for digit in str(number)]) | b4d8b216473c81e80e1ff5553e7518b0f0a1d760 | 672,450 |
def tile_type(tile_ref, level, ground_default, sky_default):
"""Returns the tile type at the given column and row in the level.
tile_ref is the column and row of a tile as a 2-item sequence
level is the nested list of tile types representing the level map.
ground_default is the tile type to r... | 25260f8b199b689db1dd74958c15ff3964585678 | 672,460 |
from typing import Optional
def validate_state_of_charge_min(state_of_charge_min: Optional[float]) -> Optional[float]:
"""
Validates the state of charge min of an object.
State of charge min is always optional.
:param state_of_charge_min: The state of charge min of the object.
:return: The valida... | e1d811c7b6636743639e65d58be9c998c54023eb | 672,470 |
def int_to_name(n,hyphen=False,use_and=False,long_scale=False):
"""
Convert an integer to its English name, defaults to short scale (1,000,000 = 'one billion'), returns a string
Args:
n -- int to be named
hyphen --bool, use hyphens for numbers like forty-eight
use_and -- bool, u... | 9eb18f3c2ceabf4e0411ab5591245006e21c930a | 672,472 |
def get_token_types(input, enc):
"""
This method generates toke_type_ids that correspond to the given input_ids.
:param input: Input_ids (tokenised input)
:param enc: Model tokenizer object
:return: A list of toke_type_ids corresponding to the input_ids
"""
meta_dict = {
"genre": {
... | 1b47cb6854388b756e89ff09b962c4dafe2fa649 | 672,473 |
def string_permutation(s1,s2):
"""
Edge case: If the strings are not the same length, they are not permutations of each other.
Count the occurence of each individual character in each string.
If the counts are the same, the strings are permutations of each other.
Counts are stored in array of 128 s... | 45e5fb7e1a4cebc15314e75a48cfd889f4a364b8 | 672,474 |
def get_cdk_context_value(scope, key):
"""
get_cdk_context_value gets the cdk context value for a provided key
:scope: CDK Construct scope
:returns: context value
:Raises: Exception: The context key: {key} is undefined.
"""
value = scope.node.try_get_context(key)
if value is None:
... | 96f0fc440679a3245f517af0bf0aae54a9ca2028 | 672,475 |
def missing_to_default(field, default):
"""
Function to convert missing values into default values.
:param field: the original, missing, value.
:param default: the new, default, value.
:return: field; the new value if field is an empty string, the old value
otherwise.
:rtype: any
... | 3af701c966b95711869def642a1c2f571bc40bfb | 672,476 |
def format_setting_name(token):
"""Returns string in style in upper case
with underscores to separate words"""
token = token.replace(' ', '_')
token = token.replace('-', '_')
bits = token.split('_')
return '_'.join(bits).upper() | 7dd6829ca430ea020bee2e75e21d3f41d9dd2d70 | 672,477 |
def simple_request_messages_to_str(messages):
"""
Returns a readable string from a simple request response message
Arguments
messages -- The simple request response message to parse
"""
entries = []
for message in messages:
entries.append(message.get('text'))
return ','.join(ent... | 06a3c564df0405726e0e8b13d7d4d5173fb07530 | 672,479 |
def get_angle_errors(errors):
"""
Takes error vectors computed over full state predictions and picks the
dimensions corresponding to angle predictions. Notice that it is assumed
that the first three dimenions contain angle errors.
"""
return errors[:,:, :3] | b253e1e3b6b98a0d47eb789b3fe01c5fcb782cb2 | 672,480 |
def apply_filter_list(func, obj):
"""Apply `func` to list or tuple `obj` element-wise and directly otherwise."""
if isinstance(obj, (list, tuple)):
return [func(item) for item in obj]
return func(obj) | ef028323b6161eda45e84e3f95ea55246c32a3aa | 672,484 |
def intensity2color(scale):
"""Interpolate from pale grey to deep red-orange.
Boundaries:
min, 0.0: #cccccc = (204, 204, 204)
max, 1.0: #ff2000 = (255, 32, 0)
"""
assert 0.0 <= scale <= 1.0
baseline = 204
max_rgb = (255, 32, 0)
new_rbg = tuple(baseline + int(round(scale * (... | 338f1266fe4c1be791a026276da7096c7a7b4eb7 | 672,485 |
def calc_gamma_components(Data_ref, Data):
"""
Calculates the components of Gamma (Gamma0 and delta_Gamma),
assuming that the Data_ref is uncooled data (ideally at 3mbar
for best fitting). It uses the fact that A_prime=A/Gamma0 should
be constant for a particular particle under changes in pressure
... | 873e9ff8fed0f4c8d257b9848bee5c3dbac1efa3 | 672,488 |
import json
def get_ikhints_json() -> str:
"""Return a test document-config/ikhints.json."""
ikhints = {
"hints":
("[\r\n [\r\n 1.33904457092285,\r\n -1.30520141124725,\r\n"
" 1.83943212032318,\r\n -2.18432211875916,\r\n"
" 4.76191997528076,\r\n -0.29564744... | 8c01d822141a8b662195adfb3695950965e95e63 | 672,495 |
def _backup_path(target):
"""Return a path from the directory this is in to the Bazel root.
Args:
target: File
Returns:
A path of the form "../../.."
"""
n = len(target.dirname.split("/"))
return "/".join([".."] * n) | 9a0826bfbaeae2f22d9885e6bb4d6ef6feef2a78 | 672,496 |
import math
def RE(bigramprob, token2p, token1p):
"""Returns the Relative Entropy.
Relative entropy is P1*log2(P1/P2) where here P1 is P(rightword)
and P2 is P(right word | left word)."""
return token1p * math.log(token1p/(bigramprob/token2p), 2) | 3b2e4a897139b6defe012e928e896d44100e9d32 | 672,497 |
def spread(spread_factor: int, N: int, n: int) -> float:
"""Spread the numbers
For example, when we have N = 8, n = 0, 1, ..., 7, N,
we can have fractions of form n / N with equal distances between them:
0/8, 1/8, 2/8, ..., 7/8, 8/8
Sometimes it's desirable to transform such sequence with finer st... | 4252d123a223a30acbcf41f9c8eb00e6a3f08a4f | 672,511 |
def count_inversion(sequence):
"""
Count inversions in a sequence of numbers
"""
s = list(sequence)
a = 0
b = True
while b:
b = False
for i in range(1, len(s)):
if s[i-1] > s[i]:
s[i], s[i-1] = s[i-1], s[i]
a += 1
... | 5637b8ed51b38b30d5975c8fb11cf177d5c0c47d | 672,518 |
def _ParsePlusMinusList(value):
"""Parse a string containing a series of plus/minuse values.
Strings are seprated by whitespace, comma and/or semi-colon.
Example:
value = "one +two -three"
plus = ['one', 'two']
minus = ['three']
Args:
value: string containing unparsed plus minus values.
Re... | 43847aeedc61fd49a76475ee97ff534f55d80044 | 672,520 |
def load_id01_monitor(logfile, scan_number):
"""
Load the default monitor for a dataset measured at ID01.
:param logfile: Silx SpecFile object containing the information about the scan and
image numbers
:param scan_number: the scan number to load
:return: the default monitor values
"""
... | be5d9ea24b328c07a471fe3d8327298d900111a2 | 672,522 |
from datetime import datetime
def time_delta(t1, t2):
"""
Takes two datetime strings in the
following format :
Sun 10 May 2015 13:54:36 -0700
and returns the time difference in
seconds between them.
Parameters
----------
t1, t2 : string
Input two timestamps to compute
... | b53bd6bb372b74aa025429c2721f75ff006eabb0 | 672,523 |
import json
import base64
def get_key(path):
"""
This is to retrieve a stored key and username combination to access the EPC API.
These values are stored in a JSON file in a local directory and hidden by the .gitignore to avoid
making these public. The key is then encoded as per the EPC documentation.... | 1ae39887c1e12bbc2919600b1f1b531b3ec6ad03 | 672,524 |
def _get_edge_length_in_direction(curr_i: int, curr_j: int, dir_i: int, dir_j: int, i_rows: int, i_cols: int,
edge_pixels: set) -> int:
"""
find the maximum length of a move in the given direction along the perimeter of the image
:param curr_i: current row index
:param ... | 7dcf08f91c80b351d27fe2b497b24f6368ee32d8 | 672,526 |
def __model_forward_pass__(args, model, obs_traj_seq, pred_traj_len, seq_start_end, metadata, curr_sample, model_fun):
"""
Wrapper call to the model forward pass, which depending on the exact model, may require different kinds of input
:param args: command line arguments that contain several parameters to c... | 69c7f761631248931d70e8f46da8a0068695c21b | 672,528 |
def check_database(con, dbname):
"""Check a database exists in a given connection"""
cur = con.cursor()
sql = """SELECT 0 FROM pg_database WHERE datname = '%s'"""
cur.execute(sql % dbname)
result = cur.fetchall()
if result:
return(True)
else:
return(False) | 1349e46fdf99e5180e4c889c4e510ba4c71d1f2f | 672,529 |
import math
def _circle_loss(labels,
scores,
rank_discount_form=None,
gamma=64.,
margin=0.25):
"""Returns the circle loss given the loss form.
Args:
labels: A list of graded relevance.
scores: A list of item ranking scores.
rank_disc... | 0ad130145d2c7c206c075f5614676048245a2555 | 672,531 |
def get_filename_with_dead_code_stats(hist_repo, repo_to_measure):
"""Get the filename that contains dead code statistic."""
return "repositories/{repo}/dashboard/{repo_to_measure}.dead_code.txt".format(
repo=hist_repo, repo_to_measure=repo_to_measure) | de4048e756d3300a3ec3c2e69b8d0e0660bb8c31 | 672,536 |
def sort_work(params, priority):
"""
Returns a dictionary as params but ordered by score
Input:
params = dictionary of the form {input_name : value}
priority = the list of input_name ordered by score calculated by score_function
Output:
sorted_dict = the same dictionary as params b... | 6ecfca8245cccd539893c23366490a9b9e00e92d | 672,540 |
import re
def camelize(string, uppercase_first_letter=True):
"""
Convert strings to CamelCase.
From inflection package: https://github.com/jpvanhal/inflection
Examples::
>>> camelize("device_type")
'DeviceType'
>>> camelize("device_type", False)
'deviceType'
"""
if not strin... | 8f355a1ce2648250a6bf5b7b37614fd53e7706b6 | 672,545 |
import time
def time_to_call_it_a_day(settings, start_time):
"""Have we exceeded our timeout?"""
if settings.timeout <= 0:
return False
return time.time() >= start_time + settings.timeout | a0c5c3e28da369522093760a3977af89dba5a5a8 | 672,547 |
def _convert_change_list_to_new_query_json(inp_json, change_list):
"""
As the json for the new query would be very similar to the json of the
requested query, the oversights only return a list of changes to
be made in the current json.
This function takes as input the current json, applies the list ... | efc61c291b01d2743b38e0a3327f06fa1d046bbd | 672,549 |
def input_file(tmpdir_factory):
"""Generate a temporary file used for testing the parse_file method."""
rows = [('81 : (1,53.38,β¬45) (2,88.62,β¬98) (3,78.48,β¬3) (4,72.30,β¬76) '
'(5,30.18,β¬9) (6,46.34,β¬48)'), '8 : (1,15.3,β¬34)',
('75 : (1,85.31,β¬29) (2,14.55,β¬74) (3,3.98,β¬16) (4,26.24,β¬55... | 7e4e10c8096a44da6b9e8caac7f84a1e9ea224e7 | 672,550 |
from datetime import datetime
def datetime_from_qdatedit(qdatedit):
"""
Return the Python datetime object corresponding to the value of
the provided Qt date edit widget.
"""
return datetime(
qdatedit.date().year(),
qdatedit.date().month(),
qdatedit.date().day()) | 725f6a65ba8cb4012eb2955a7a672989a5d2c722 | 672,551 |
def clean_url(url):
""" Strips the ending / from a URL if it exists.
Parameters
----------
url : string
HTTP URL
Returns
-------
url : string
URL that is stripped of an ending / if it existed
"""
if url[-1] == '/':
return url[:-1]
return url | e5d5015adf4e06064a0d4d5638284bf1341f1a28 | 672,553 |
import requests
import json
def call_rest_api(endpoint, query):
"""
Call REST API endpoint
:param endpoint:e.g. 'http://127.0.0.1:9500/wind_deg_to_wind_rose'
:param query: e.g. query = {'wind_deg': wind_deg}
:return:
"""
response = requests.get(endpoint, params=query)
if response.sta... | 9a0e061dca1d3fa76803dcc70c883d5f80e460a0 | 672,558 |
def display_rows(content, message, is_ratio=True):
"""Return content formatted for display to terminal.
keyword args:
content list -- A list of tuples obtained from a SQL query
message string -- A string used as the title of the formatted output
is_ratio boolean -- A boolean used to determine if '%... | 2eda7c52e34d14503dad36f4281b93879b7051e4 | 672,565 |
def _read_file(fname):
"""
Args:
fname (str): Name of the grammar file to be parsed
Return:
list: The grammar rules
"""
with open(fname) as input_file:
re_grammar = [x.strip('\n') for x in input_file.readlines()]
return re_grammar | 9e6fba0bf76f3170a3d26a73ba6bac3c9c8c34be | 672,566 |
def _clean_col_name(column):
"""Removes special characters from column names
"""
column = str(column).replace(" ", "_").replace("(","").replace(")","").replace("[","").replace("]","")
column = f"[{column}]"
return column | 4f8bd6ae210629394e3b50702fc7134e4c4cc5bf | 672,569 |
def italics(text: str) -> str:
"""Make text to italics."""
return f'_{text}_' | ea5a4474e3d7490c746fffd8edd74a7b8349a010 | 672,570 |
import torch
def prepare_batch(batch):
"""This is the collate function
The mass spectra must be padded so that they fit nicely as a tensor.
However, the padded elements are ignored during the subsequent steps.
Parameters
----------
batch : tuple of tuple of torch.Tensor
A batch of da... | 8d762d7d5cf812ab8612854eb692b1ffd827713d | 672,573 |
def reversed_list (seq) :
"""Returns a reversed copy of `seq`.
>>> reversed_list ([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]
>>> reversed_list ([1])
[1]
>>> reversed_list ([])
[]
"""
result = list (seq)
result.reverse ()
return result | effb925f734def5720364f14b97814279d79d161 | 672,577 |
def grouper(some_list, count=2):
"""
splits a list into sublists
given: [1, 2, 3, 4]
returns: [[1, 2], [3, 4]]
"""
return [some_list[i:i+count] for i in range(0, len(some_list), count)] | 9cd9f79a077b0cd64fd51dc0c6b4ea7ede2188fa | 672,580 |
def _recur_flatten(key, x, out, sep='.'):
"""Helper function to flatten_dict
Recursively flatten all nested values within a dict
Args:
key (str): parent key
x (object): object to flatten or add to out dict
out (dict): 1D output dict
sep (str): flattened key separato... | 344e1f5c89997fe188ca5857a72a4ad071eda941 | 672,586 |
import hashlib
def calculate_digest(body):
"""Calculate the sha256 sum for some body (bytes)"""
hasher = hashlib.sha256()
hasher.update(body)
return hasher.hexdigest() | 11d6c4e9d331bc7ffb97118e707143bdee59bb04 | 672,589 |
import signal
import errno
def _settable_signal(sig) -> bool:
"""Check whether provided signal may be set.
"""
try:
old = signal.signal(sig, lambda _num, _frame: ...)
except OSError as e:
# POSIX response
assert e.errno == errno.EINVAL
return False
except ValueError... | a5efd821befd8dbde2a65757f713542f1be1f225 | 672,590 |
def u2t(x):
"""
Convert uint-8 encoding to 'tanh' encoding (aka range [-1, 1])
"""
return x.astype('float32') / 255 * 2 - 1 | f278fc1b8c6b408744766af28d78b2625dae890d | 672,591 |
def first_non_empty(data_or_instance, field_or_fields, default=None):
"""
Return the first non-empty attribute of `instance` or `default`
:type data_or_instance: object or dict
:param data_or_instance: the instance or the resource
:type field_or_fields: str or tuple or list
:param field_or_fiel... | 9be9d7fddcfc3b71b92ca12fb8949d85ad4cb342 | 672,593 |
def get_tile_size(model_height, model_width, padding, batch_height, batch_width):
"""
Calculate the super tile dimension given model height, padding, the number of tiles vertically and horizontally
:param model_height: the model's height
:param model_width: the model's width
:param padding: padding
... | 6ad9781ebd4a6ca1326de9b7123b3d717e4bf615 | 672,595 |
import torch
def ndc_to_screen_points_naive(points, imsize):
"""
Transforms points from PyTorch3D's NDC space to screen space
Args:
points: (N, V, 3) representing padded points
imsize: (N, 2) image size = (height, width)
Returns:
(N, V, 3) tensor of transformed points
"""
... | d8b361b8dca2c89aef6988efcae67e9554f1dae8 | 672,599 |
def normalize(qualName):
"""
Turn a fully-qualified Python name into a string usable as part of a
table name.
"""
return qualName.lower().replace('.', '_') | 3f87366a595451dc43e8c0392cac4eae03b10e64 | 672,602 |
def load_language_modeling(from_path: str) -> list:
"""Load language modeling dataset.
"""
dataset = []
with open(from_path, 'r', encoding='utf-8') as reader:
for line in reader.readlines():
dataset.append(line.strip())
return dataset | 528466c259757bea4e1893e3b0fc3a684b75a3eb | 672,604 |
def num_to_str(num):
# type: (None) -> str
"""Number to string without trailing zeros"""
s = str(num)
return '0' if s == '0' else s.rstrip('0').rstrip('.') | 1d326ad885797bb69ca961994d93d1ec7f730208 | 672,606 |
def _get_last_cell(nb):
"""
Get last cell, ignores cells with empty source (unless the notebook only
has one cell and it's empty)
"""
# iterate in reverse order
for idx in range(-1, -len(nb.cells) - 1, -1):
cell = nb.cells[idx]
# only return it if it has some code
if cel... | e99ab592a480c015f028e622dad587bd1bf5fdcb | 672,609 |
def data_for_ray_slice(radar, ray_sl, fieldnames=None):
""" Given a slice object ray_sl, return r,az,el,t,data
corresponding to the fieldnames. If fieldname is None,
no data will be returned. Fieldnames should be a sequence of field
names. A data dictionary is returned with a key for each of... | d1c21d4964394df0494cff106d6ab857d9704132 | 672,611 |
def should_sync(data, last_sync):
"""
Determine if a data collection needs to be synced.
"""
# definitely sync if we haven't synced before
if not last_sync or not last_sync.date:
return True
# check if any items have been modified since last sync
for data_item in data:
# >=... | 1a289af57af8119ee78586a32032227c7fa7c40d | 672,615 |
def get_accuracy(y_bar, y_pred):
"""
Computes what percent of the total testing data the model classified correctly.
:param y_bar: List of ground truth classes for each example.
:param y_pred: List of model predicted class for each example.
:return: Returns a real number between 0 and 1 for the model accura... | e5c9f54c214aa87fff9d5b98d6b60b73850b8ad6 | 672,616 |
def shell_sort(arr):
"""
Fuction to sort using Shell Sort
<https://en.wikipedia.org/wiki/Shellsort>.
:param arr: A list of element to sort
"""
gap = int((len(arr)/2))
while gap > 0:
for i in range(gap, len(arr)):
temp = arr[i]
j = i
while j >=... | 5a559b25f092c73371537cfc79123cf49498f0bc | 672,618 |
def not_equals(x):
"""A functional !=.
>>> not_equals(2)(2)
False
>>> not_equals("David")("Michael")
True
"""
def not_equals(y):
return x != y
return not_equals | 27ae5dda655e854abbaf126643d26eb1577449d9 | 672,619 |
from typing import List
def wrap_text(string: str, max_chars: int) -> List[str]:
"""A helper that will return a list of lines with word-break wrapping.
:param str string: The text to be wrapped.
:param int max_chars: The maximum number of characters on a line before wrapping.
:return: A list of strin... | a0e990ef50f0c54ff40a5962f4a052f3d9916563 | 672,622 |
import math
def get_sqrt_shape(area):
"""
Returns a square shape, assuming the area provided can be square.
"""
height = int(math.sqrt(float(area)))
width = height
return width, height | 89e3ae2d36bcbd501021a8a65b019d71741dfd53 | 672,624 |
def interpret_origin(geom, origin, ndim):
"""Returns interpreted coordinate tuple for origin parameter.
This is a helper function for other transform functions.
The point of origin can be a keyword 'center' for the 2D bounding box
center, 'centroid' for the geometry's 2D centroid, a Point object or a
... | f88fdc42bbe0fa319acefadb8be80b34dfa047e1 | 672,626 |
import torch
def _clip_barycentric_coordinates(bary) -> torch.Tensor:
"""
Args:
bary: barycentric coordinates of shape (...., 3) where `...` represents
an arbitrary number of dimensions
Returns:
bary: Barycentric coordinates clipped (i.e any values < 0 are set to 0)
an... | 880f2c8ae3d6c07ac6f02d75e8d2c1e58f42586f | 672,627 |
def normal_row_count(model_cls, db):
""" Uses a normal .count() to retrieve the row count for a model. """
return model_cls.select().count() | 0fc5840fbe8212e0d1a43f4b64b34ac01d08045c | 672,629 |
def longestString(listOfStrings):
"""
return longest string from a non-empty list of strings, False otherwise
By "longest", we mean a value that is no shorter than any other value in the list
There may be more than one string that would qualify,
For example in the list ["dog","bear","wolf","cat"... | 14244a76c65fcffc255f203eb7d1f8aa098b9cd2 | 672,637 |
import re
def make_scanner(regex):
"""
Make log scanner for scanning potential attack using regex rule.
:param regex: regex rule for detecting attack in the log line
:return: function that scan for the attack in log file using the regex
"""
def scanner(line):
return True if re.search(... | f99264bb57febeb27999469107bd2ec92a7d5c84 | 672,641 |
def has_duplicates(t):
"""Checks whether any element appears more than once in a sequence.
Simple version using a for loop.
t: sequence
"""
d = {}
for x in t:
if x in d:
return True
d[x] = True
return False | cc84a39d88ef7b92e173c96e5f68813b71609297 | 672,648 |
import collections
def _get_output_map_from_op(varmap, op):
"""Returns a dict from op output name to the vars in varmap."""
iomap = collections.OrderedDict()
for key in op.output_names:
vars = []
for varname in op.output(key):
vars.append(varmap[varname])
if len(vars) =... | 33d32952c9077bf78c6e4c5672880786ed28075d | 672,651 |
def wrap_text_begin_end(title, body):
"""Wrap a block of text with BEGIN and END for PEM formatting."""
return (
"-----BEGIN %s-----\n" % (title,)
+ body
+ "\n-----END %s-----\n" % (title,)
) | 380ff08610cce2503d6a4dd04bfc35b5fe384175 | 672,658 |
import re
def extract_integers(string):
"""Extract all integers from the string into a list (used to parse the CMI gateway's cgi output)."""
return [int(t) for t in re.findall(r'\d+', string)] | 3313d79756f97d316dfb99c3b176d94f4e5d1df3 | 672,660 |
def full_name(family, style):
"""Build the full name of the font from ``family`` and ``style`` names.
Names are separated by a space. If the ``style`` is Regular, use only the ``family`` name.
"""
if style == 'Regular':
full_name = family
else:
full_name = family + ' ' + style
... | cdff8d6ae15170c5e9474874c9385dfd9b4999df | 672,661 |
import hashlib
def get_signature(item):
"""
Returns the sha256 hash of a string
"""
hash_object = hashlib.sha256(item.encode())
return hash_object.hexdigest() | bbb35a9d5b06f42c76bea4f00c1763199f2bf609 | 672,664 |
def safe_pandas_length(o):
""" Return the length of a pandas Series and DataFrame as expected for WL serialization.
- The length of a Series is the only value of the tuple `shape`.
- The length of a dataframe is the number of columns. It's the second value of `shape`.
This function is safe, when the s... | ae2a27b2708350cfb7de210ecce265d91f54748b | 672,665 |
from typing import Any
def is_int(value: Any) -> bool:
"""Checks if a value is an integer.
The type of the value is not important, it might be an int or a float."""
# noinspection PyBroadException
try:
return value == int(value)
except Exception:
return False | f9b1c28f6c954376373a1d8ea8de533d2b4c8974 | 672,668 |
def _res_heur(data, *args, **kwargs):
"""
Returns, for the given data, the heuristic determining the
resolution of the voxel grid and correspondingly, how many
points get hashed to the same value.
"""
return 3 * len(data) ** 0.33333333 | a14ed6ae638d65c9571a750478c9f8b7c7cd2909 | 672,675 |
def state_to_int(p, statelist):
"""
Converts array of fermion-configuration into integer
Args:
p - dictionary that contains the relevant system parameters
statelist - fermion configuration
Returns:
out - integer corresponding to state
"""
# construct unique integer for th... | c07cba94e669e12fd82e6f6f46163661405f99ca | 672,677 |
import re
def is_latlong(instr):
"""check whether a string is a valid lat-long."""
return (re.match(r'^\s*[0-9.+-]+\s*,\s*[0-9.+-]+\s*$', instr) != None) | 611181fa0f6b95b735a5df7629c01985b54b5f21 | 672,680 |
def member_joined_organization_message(payload):
"""
Build a Slack message informing about a new member.
"""
member_name = payload['user']['name']
member_url = payload['user']['url']
org_name = payload['organization']['name']
org_url = payload['organization']['url']
message = 'Say hi! ... | f57dfdbf1cf1e305be9c67366093849493e63c6d | 672,682 |
import yaml
def parse_file(path):
"""Super simple utility to parse a yaml file given a path"""
with open(path, 'r') as cfile:
text = cfile.read()
conf = yaml.load(text, Loader=yaml.CLoader)
return conf | 899ab670a69d4faa4c008848c4cfb979e3f29c51 | 672,685 |
def load_dataset(filepath):
"""Loads a file on the CoNLL dataset.
:param filepath: Path to a text file on the CoNLL format.
:return (X, Y) lists of sentences and labels.
"""
X = list()
x = list()
Y = list()
y = list()
for line in open(filepath):
# blank lines sepa... | b06d853abb5a616b64ae765875ef3954522fcdfe | 672,687 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.