content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import math
def get_overall_score(r1_score, bond_score, missing_elements_score, stoich_score, anisotropy_penalty, score_weighting):
"""
Get the overall score for an optimizer result
:param r1_score:
:param bond_score:
:param missing_elements_score:
:param stoich_score:
:param anisotropy_pe... | 2f8174ed7e08644156d5a5287dcbabba759f3e9a | 601,741 |
def bslice(high, low=None):
"""
Represents: the bits range [high : low] of some value. If low is not given,
represents just [high] (only 1 bit), which is the same as [high : high].
"""
if low is None:
low = high
return slice(low, high + 1) | d3a3085f8da638ef63c7d0f65605543f6f3605b7 | 20,046 |
def firesim_tags_to_description(buildtriplet, deploytriplet, commit):
""" Serialize the tags we want to set for storage in the AGFI description """
return """firesim-buildtriplet:{},firesim-deploytriplet:{},firesim-commit:{}""".format(buildtriplet,deploytriplet,commit) | 20c17da1c8620f14cd7849f4687e759645462809 | 399,174 |
def update_text(s,**kws):
"""
Replace arbitrary placeholders in string
Placeholder names should be supplied as keywords
with the corresponding values being the text to
replace them with in the supplied string.
When placeholders appear in the string they
should be contained within '<...>'.
... | b4ef41689b21093ee3823d341e162d5526110d74 | 283,686 |
def as_scalar(val):
"""
If val is iterable, this function returns the first entry
else returns val. Handles strings as scalars
:param val: A scalar or iterable
:return:
"""
# Check string
if val == str(val):
return val
try: # Check iterable
it = iter(val)
# ... | b43a730180f85c4fb227aebaad98ca0ec5f7314f | 465,276 |
def vf_stokes(r,g,eta,drho,Nkn=0.):
"""terminal velocity of Stokes flow (Reynolds number < 2, Davies number < 42)
Args:
r: particle size (cm)
g: gravity (cm/s2)
eta: dynamic viscosity (g/s/cm)
drho: density difference between condensates and atmosphere (g/cm3)
Nkn: K... | c8234fa729b08696d2db22b7d2a69ae4ae23c1ed | 505,190 |
import aiohttp
async def text_callback(resp: aiohttp.ClientResponse) -> str:
"""Returns the response result as text.
Mostly useful for endpoints that returns just text on its output. Some
examples::
$ curl ifconfig.me/ip
123.123.123.123
$ curl 'wttr.in/?format=%t'
+31°C
... | 2cf7e0d88654f62e3ab33ed8a8dde9495fbe453b | 620,473 |
from io import StringIO
def readFromFile(fileName: str) -> str:
"""Returns the complete content of the given file."""
sio = StringIO()
with open(fileName) as f:
return f.read() | 568893f751fc401165e3c6e81e56c44441975820 | 396,700 |
def getNumberFromId(obj_id):
"""Returns the long decimal number (as a string) from the end of a wsadmin object id string.
For example, returns 1157676511879 from the following id:
PAP_1(cells/ding6Cell01|coregroupbridge.xml#PeerAccessPoint_1157676511879)
Returns the original id string if the ID string... | bcefc9a82ade614600db38e603607f76019016f0 | 529,498 |
def register_global_step(mr):
"""
Add global step to ModelRegistry.
Parameters
----------
mr : ModelRegistry
"""
def callback(**kwargs):
mr.global_step_ = kwargs["global_step"]
return callback | a362aa51e9e6aba68aad908982d6e683587a8c10 | 264,291 |
def _get_name(dist):
"""Attempts to get a distribution's short name, excluding the name scope."""
return getattr(dist, 'parameters', {}).get('name', dist.name) | fd57e523c1a84a36f9ed56236e4b8db1e887575c | 709,709 |
def split_files(files, split_train, split_val, use_test):
"""Splits the files along the provided indices
"""
files_train = files[:split_train]
files_val = files[split_train:split_val] if use_test else files[split_train:]
li = [(files_train, 'train'), (files_val, 'val')]
# optional test folder
... | 908cf517abe1201a62678af9ba8323f78d3769ad | 435,421 |
def isiterable(x):
"""Determines if an object is iterable and not a string."""
return hasattr(x, "__iter__") and not hasattr(x, "upper") | 7f82e3e3c21235b7270f6f1106e5ba49d698e353 | 454,951 |
def python_sum(num_list):
"""Calculate the sum using standart 'sum' function of python."""
return sum(num_list) | 07d6b35ff5dae23b017e568e4cd91ca65df15b96 | 522,596 |
def set_device_orientation_override(alpha: float, beta: float, gamma: float) -> dict:
"""Overrides the Device Orientation.
Parameters
----------
alpha: float
Mock alpha
beta: float
Mock beta
gamma: float
Mock gamma
**Experimental**
"""
return {
... | 2113001cc29327fbadcb053c3270e32a6384ea82 | 652,060 |
def bfs_shortest_path_distance(graph: dict, start, target) -> int:
"""Find shortest path distance between `start` and `target` nodes.
Args:
graph: node/list of neighboring nodes key/value pairs.
start: node to start search from.
target: node to search for.
Returns:
Number o... | 9eb28d7c854bdc8adc49b208169d68fb9ad15901 | 249,372 |
def cut_string(string, limit=30):
"""Shorten the length of longer strings."""
if len(string) <= limit:
return string
else:
return string[:limit-3] + '...' | 842cfefcff84c4f146cc85a4e86dff1486e9a434 | 702,116 |
import torch
def gradient_detailed_overlap(grad, V, num_classes):
"""Similar to `gradient_overlap`, but here, we compute the overlap of the gradient
with the individual eigenvectors. The gradiejt overlap can be written as
overlap(grad, S_V) = ||P_V grad||^2 / ||grad||^2
= (sum_{c=1... | cd3889ccb1fac23bb4888901b3b87dff0dbd26c2 | 412,475 |
def string_to_list(line, sep=','):
"""convert a comma (or sep) separated string to list.
If line is None (or any falsy value), return [].
"""
return line.split(sep) if line else [] | 179e9f5c67dfa6b9a3b3902bed44f5ce497dd4b7 | 458,607 |
def inc(x):
"""
Increments the value of x
>>> inc(4)
5
"""
return x + 1 | 79159342dd7ab241e7f513192fc29d14b5bcd314 | 600,617 |
def find_boolean_function(lib_json_data, port_name):
"""
Search for a boolean function for a certain port in a .lib.json file.
:param lib_json_data: json data of a .lib.json file
:param port_name: The port name
:returns: The boolean function as a string. Empty string if no boolean function was foun... | fac223dcc68bba04858018d190ea82e91ae79f66 | 605,176 |
def get_display_name_from_arn(record):
"""Get the display name for a version from its ARN.
Args:
record
A record returned by AWS.
Returns:
A display name for the task definition version.
"""
arn_parts = record.split(":")
name = arn_parts[5]
version = arn_parts... | be00a08c88b07a9134a3625a83912422bb29a05a | 479,586 |
def weekday_name(day_of_week):
"""Return name of weekday.
>>> weekday_name(1)
'Sunday'
>>> weekday_name(7)
'Saturday'
For days not between 1 and 7, return None
>>> weekday_name(9)
>>> weekday_name(0)
"""
days = ['Sunday', 'Monda... | 7a7e80f3afcf20d66c4b2a595d3756c871414c33 | 565,562 |
def _choice_evaluator(choice_array, choice_condition):
"""
Determines which rows in `choice_array` meet the given `choice_condition`,
where `choice_condition` is in the set `{0.0, 1.0}`.
Parameters
----------
choice_array : 1D ndarray of ints that are either 0 or 1.
choice_condition : int i... | 82e1ae37884b486342c375e630c567387766d5fd | 573,150 |
import operator
def sortedby2(item_list, *args, **kwargs):
"""sorts ``item_list`` using key_list
Args:
item_list (list): list to sort
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
Returns:
list : ``... | e0e721734b0d3b9c6c63b3ee7f8f8f2285163a4a | 190,536 |
def generate_seeds(rng, size):
"""
Generate list of random seeds
:param rng: random number generator
:param size: length of the returned list
"""
seeds = [rng.randint(0, 2**32 - 1) for _ in range(size)]
return seeds | f264ccaac3f59d33261f35b2eb0c04a43eed3fc6 | 452,089 |
def min(self, parameter_min):
"""
It returns the minimum value of a parameter and the value's indexes.
Parameters
----------
parameter_min: str
Name of the parameter.
Returns
-------
min_dict: dict
Dictionary with the following format:
{
... | 5f71e69bc1525ce94a626b742c2df7ef45b5e85a | 639,846 |
def log_gaussian_kernel(dist, h):
"""log of the gaussian kernel for bandwidth h (unnormalized)"""
return -0.5 * (dist * dist) / (h * h) | d897d671d12c0bb273c05f9d000614668173336b | 540,117 |
import re
def get_words(text):
"""
A method to separate the words in a string.
Args:
text (str): input text string.
Return:
words (list): a list of words in the string.
"""
return re.compile('\w+').findall(text) | 0fc217640c2e7d1ee6ac8dcd836c6cdfdc8ef269 | 251,599 |
def yices_logic(pysmt_logic):
"""Return a Yices String representing the given pySMT logic."""
ylogic = str(pysmt_logic)
if ylogic == "QF_BOOL":
ylogic = "NONE"
return ylogic | cdbec0f413d58e8de8eaefd1f2e62998fb02fda6 | 413,830 |
def get_params_string(param_values: dict) -> str:
"""Generate the string from the dict with parameters
Args:
param_values (dict): dict of "param_name" -> "param_value"
"""
params_string = ", ".join(
[k + "=" + str(param_values[k]) for k in param_values.keys()]
)
return params_str... | 3f4a8019da68a67b5da90917524eaf6ee1f5c69e | 354,877 |
def monomer_from_anisotropy(a, Am, Ad, b):
"""
Calculate monomer fraction from anisotropy, monomer and dimer anisotropy
and brightness relation.
"""
return (b * a - Ad*b) / ((Am - b * Ad) - (1-b) * a) | a106af8efed1be5aa3377a04c74e8d704d8eaa19 | 487,392 |
def _corners(d):
"""Return corner coordinates.
@param d: `dict` with keys
`'x', 'y', 'w', 'h'`
@return: quadruple
@rtype: `tuple`
"""
x = d['x']
y = d['y']
w = d['w']
h = d['h']
xmax = x + w
ymax = y + h
return x, xmax, y, ymax | c466f3c09c1cdb828bf6570b0200cf757edfe13a | 402,540 |
def square(x):
"""
Return the square of the single parameter.
:param x: A numeric value
:return: The squre of x
"""
return x*x | dae9cd5e6bf610a71c7bdde08c7365b9363fb0a8 | 563,747 |
def triangular(n):
"""Gives the n-th triangle number."""
return n*(n+1)/2 | 17b5cbd0f690dbf0043ea84da3fef56c82812599 | 689,599 |
def selection_sort(list_: list) -> list:
"""Returns a sorted list, by selection sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by selection sort method
"""
def find_smallest_index(list_: list) -> int:
"""Returns the index of the... | 54158ca1346fcfc67602282a5458d0d0f8bc77c5 | 322,698 |
import yaml
def compare_markdown_content(file1, file2, compare='both'):
"""Compare Markdown file metadata
Args:
file1 (str): first file contents
file2 (str): second file contents
compare (str): compare 'meta', 'body' or 'both'
Returns:
True if metadata are logically the s... | 7e17416bddc820df56f94caa3d601a6b2a9c0fda | 546,409 |
import calendar
def toUnixSeconds(timestruct):
"""Convert a datetime struct to a Unix timestamp in seconds.
:param timestruct: A ``datetime.datetime`` object to convert into a
timestamp in Unix Era seconds.
:rtype: int
"""
return calendar.timegm(timestruct) | 6df27af852cc388beb98489072bbd69d37ca1c18 | 288,715 |
def get_atom_order_from_xyz(xyz):
"""
Get the order in which atoms should be added to the zmat from the 3D geometry.
Args:
xyz (dict): The 3D coordinates.
Returns:
list: The atom order, 0-indexed.
Returns:
None: Not used, but important for returning the same number of param... | 8687531bfbec590970f31831f10169e38a87e122 | 151,723 |
def split_overlapping(signal, freq=257, time=2, shift=0.5):
"""
Splits the signal data into segments. Expects signal with dim-0 samples, dim-1 leads (12)
:param signal: the signal
:param freq: frequency rate of the signal
:param time: time length of the segments
:param shift: time shift in takin... | ba72e6315f1bf9dec12655f459bcd3d6e4b42a7e | 574,606 |
def _toArchitectureDir(architecture):
"""Re-map 'x64' to 'amd64' to match MSVC directory names.
"""
return {'x64':'amd64'}.get(architecture, architecture) | 53f630829ea4c91c032401ba16f28d900c16e98a | 122,452 |
import csv
def readcsv(filename, delimiter=',', quotechar='"'):
"""Read CSV file data into a list.
Args:
filename (str): Full path of file.
delimiter (str, optional): Delimiter
quotechar (str, optional): Quote character
Returns:
list: List of lines from CSV file
"""
... | e80b09d27339561b4d3bdb12979ece8fd2bd83dc | 585,223 |
def sparseFeature(feat, feat_num, embed_dim=4):
"""
create dictionary for sparse feature
:param feat: feature name
:param feat_num: the total number of sparse features that do not repeat
:param embed_dim: embedding dimension
:return:
"""
return {'feat': feat, 'feat_num': feat_num, 'embed... | ffe53e988e20a2f23db1c63f3a471ff04650f592 | 600,552 |
def lennard_jones(r, sig, eps):
"""
Calculate Lennard Jones potential for given distance, sigma, and epsilon values.
Energy unit: (kB)
"""
return 4 * eps * ((sig / r)**12 - (sig / r)**6) | 643ee902f5f5845dcca62fa315886f6a438f48dd | 342,868 |
from typing import Optional
def normalize_string(s: str, *, suffix: Optional[str] = None) -> str:
"""Normalize a string for lookup."""
s = s.lower().replace('-', '').replace('_', '').replace(' ', '')
if suffix is not None and s.endswith(suffix.lower()):
return s[:-len(suffix)]
return s | b8104ef22b1ecda3bcddc092bfbdf02956780e79 | 152,779 |
def generate_timestamp_format(date_mapper: dict) -> str:
"""
Description
-----------
Generates a the time format for day,month,year dates based on each's
specified time_format.
Parameters
----------
date_mapper: dict
a dictionary for the schema mapping (JSON) for the dataframe f... | cd535a4fb35917517711cf149430c128e2c46b6d | 16,085 |
def fib_n(n):
"""Efficient way to compute Fibonacci's numbers. Complexity = O(n)"""
fibs = [0, 1] # we don't need to store all along the way, but the memory is still as good as in the naive alg
for i in range(2, n + 1):
fibs.append(fibs[-2] + fibs[-1])
print(fibs[-1])
return fibs[-1] | 684fecfd5d65bc91cea45f1767c4ae4bae4a73a9 | 531,312 |
def points_bounds(points):
"""Return bounding rect of 2D point list (as 4-tuple of min X, min Y,
max X, max Y)."""
min_x, min_y, max_x, max_y = (
points[0][0],
points[0][1],
points[0][0],
points[0][1],
)
for point in points[1:]:
min_x = min(min_x, point[0])
... | 4c0cbd47bef32fe5d3c1787789d806016d0db4ff | 78,291 |
def getPrecedence(operator):
"""
Returns the precedence for operators for use in toReversePolish(), where high numbers represent greater precedence
:param operator: operator token data
:return: number representing the precedence of the given operator
"""
if operator == "^":
return 3
... | 44532c6bec002aea1596219b78ec029955db0694 | 47,367 |
def ppo_learn(agent, env, env_state, history, args):
"""Learning loop for PPOAgent."""
eval_next = False
# Act
rollout = agent.gather_rollout(env, env_state, history, args)
# Learn
history = agent.learn(*rollout, history, args)
# Sync old and current policy
agent.sync()
# Check fo... | b327352eca31e8247cb1278be769cdc934d344e1 | 520,974 |
def _get_field_ix(line, field):
"""Get position of field ('GT' or 'DS') in FORMAT"""
fmt = line[8].split(':')
if field not in fmt:
raise ValueError('FORMAT field does not contain {}'.format(field))
return fmt.index(field) | 3eaae31d7a8cb2113b7b2b5423376e92c644f7b5 | 485,157 |
import string
def is_printable(s):
"""
Return True if the string is ASCII (with punctuation) and printable
:param s:
:return:
"""
for c in s:
if c not in string.printable:
return False
return True | 83303b689d6885c94aad129f195c80460a771ea5 | 382,232 |
def selected_data(accu, selector):
"""
Returns the selected data.
If the selector function is not None, returns the results of
applying the selector function to accu.
Otherwise returns accu.
:param accu: The data accumulator
:param selector: Optional iterable returning function that has the ... | 0904f5a4db41aff4d8e6a5c9c6a9185a8ca9e393 | 163,428 |
def _get_unique(node_list, key, mode=None):
"""
Returns number or names of unique nodes in a list.
:param node_list: List of dictionaries returned by Neo4j transactions.
:param key: Key accessing specific node in dictionary.
:param mode: If 'num', the number of unique nodes is returned.
:return... | 26e99c75e30692936781833bf3cd2addf1efd391 | 542,226 |
def isfile(line):
"""
Files are wrapped in FHS / FTS
FHS = file header segment
FTS = file trailer segment
"""
return line and (line.strip()[:3] in ["FHS"]) or False | 2e33c98f18e44913d18dbbbbed7ec6bd7887f8ba | 82,462 |
from typing import Union
from typing import Dict
import torch
def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int:
"""
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise.
"""
if isinstance(batch, torch.Tensor):
return batch.size(0) # type: ign... | bfdf7c141a6791648a342e0a253cfaaa75b6a61a | 522,146 |
def relative_to(path, target):
"""Return the relative path of the input to the target path.
For example:
path = /a/b/d/c/Y
target = /a/b/c/X
Then this function will return:
'../../c/X'
Args:
path (pathlib.Path):
target (pathlib.Path):
Returns:
str: ... | b6b6a71b0372e6b6bf6bf4d7acfbafe0ad73f77d | 515,925 |
from typing import Tuple
def fixture_image_shape() -> Tuple[int, int, int]:
"""
Image shape used for the tests.
:returns: Image shape.
"""
return (64, 128, 3) | f67c44028acd880b2cabe64ef3496c28183d3799 | 370,812 |
def clean_kwargs(kwargs, keys=None):
"""Removes each key from kwargs dict if found
Parameters
----------
kwargs : dict
* dict of keyword args
keys : list of str, optional
* default: ['obj', 'pytan_help', 'objtype']
* list of strs of keys to remove from kwargs
Returns
... | fad1c665666f49c6b01cc6f1a442c2ae207e7b21 | 291,239 |
def purelin(n):
"""
Linear Transfer Function
:param int n:Net Input of Neuron
:return: Compute purelin(n)=n
:rtype: int
"""
return n | 79115d62260775d8be3aef5bbffd33b9e3526848 | 537,182 |
def flatten_list(nest_list):
"""
嵌套列表压扁成一个列表
:param nest_list: 嵌套列表
:return: list
"""
result = []
for item in nest_list:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result | 00d6eed3772f6bfc43bc4f3915a3351dfebe65b6 | 303,775 |
def is_functioncall(reg):
"""Returns whether a Pozyx register is a Pozyx function."""
if (0xB0 <= reg <= 0xBC) or (0xC0 <= reg < 0xC9):
return True
return False | 0361199ad60446224741948c2af25e24a53ac362 | 346,910 |
def nodes(G):
"""Returns an iterator over the graph nodes."""
return G.nodes() | 3a1a543f1af4d43c79fd0083eb77fedd696547ec | 2,821 |
from typing import Iterable
from typing import List
def indent(level: int, lines: Iterable[str]) -> List[str]:
"""
Indent the lines by the specified level.
"""
return [' ' * level + line for line in lines] | 9fea8a60c3dfa9f91b49c39167cd3dadf1b21604 | 646,305 |
import re
def regex_capture(pattern, list_of_strings, take_index=0):
"""Apply regex `pattern` to each string and return a captured group.
pattern : string, regex pattern
list_of_strings : list of strings to apply the pattern to
Strings that do not match the pattern are ignored.
take_index... | ec5f08ec9885ad2f6bca54f34923716c2e04c0a5 | 404,339 |
def format_datetime(value, format='short'):
"""Filtro que transforma un datetime en str con formato.
El filtro es para ser usado en plantillas JINJA2.
Los formatos posibles son los siguientes:
* short: dd/mm/aaaa
* full: dd de mm de aaaa
:param datetime value: Fecha a ser transformada.
:pa... | 61708656a69ca928443d38e59d37935e3e29e4e3 | 348,217 |
def _GetPermissionErrorDetails(error_info):
"""Looks for permission denied details in error message.
Args:
error_info: json containing error information.
Returns:
string containing details on permission issue and suggestions to correct.
"""
try:
if 'details' in error_info:
details = error_i... | 0401e6a9fbc1de0a3ed3515de569b7cd21d70fcc | 292,785 |
def find_child(parent, child_tag, id=None):
"""
Find an element with *child_tag* in *parent* and return ``(child, index)``
or ``(None, None)`` if not found. If *id* is provided, it will be searched
for, otherwise the first child will be returned.
"""
for i, child in enumerate(list(parent)):
... | ebc9b9bb6ba7ed78efc7a094478b22de1769ccb9 | 48,712 |
def split_datetime(a_datetime):
"""Given a datetime.datetime, return a 2-tuple of (datetime.date, datetime.time)."""
return (a_datetime.date(), a_datetime.time()) | 1647fc742e14e8e880b0f2be0e946a4446071b6c | 61,628 |
def format_option_for_gamess(opt, val, lop_off=True):
"""Reformat `val` for option `opt` from python into GAMESS-speak."""
text = ''
# Transform booleans into Fortran booleans
if str(val) == 'True':
text += '.true.'
elif str(val) == 'False':
text += '.false.'
# No Transform
... | c295735cae19ef7e687e3d0f2e9770fd6807a694 | 362,155 |
import requests
def is_valid(email, password):
""" Method to Validate SUSI Login Details
:param email: SUSI Sign-in email
:param password: SUSI Sign-in password
:return: boolean to indicate if details are valid
"""
print('Checking the validity of login details ....')
params = {
'lo... | 90cd3ba23d70e61d7af376603391cdc84b8aced8 | 484,802 |
def deep_encode(e, encoding='ascii'):
"""
Encodes all strings using encoding, default ascii.
"""
if isinstance(e, dict):
return dict((i, deep_encode(j, encoding)) for (i, j) in e.items())
elif isinstance(e, list):
return [deep_encode(i, encoding) for i in e]
elif isinstance(e, str):
e = e.encode... | 6541695e741cb2f47d7d2fe87a45f1d8d8ca67fe | 48,742 |
import re
def is_correct_vector_v3(vector):
"""
Checks whether CVSSv3 base vector is valid.
:param vector: base vector of CVSSv3 (string)
:return: True if valid
"""
return vector is not None \
and re.match(r'(CVSS:3\.0/)?AV:[NALP]/AC:[LH]/PR:[NLH]/UI:[NR]/S:[UC]/C:[NLH]/I:[NLH]'
... | b091826c5f99ca7f41888f950086f983ddbd1f8b | 582,378 |
import logging
def _getFormatter(verbose=False):
"""Get log formatter.
Args:
verbose: True if a more verbose log format is desired.
Returns:
logging.Formatter object.
"""
base_formatting = '[%(levelname)s] %(message)s'
if verbose:
formatter = logging.Formatter('[%(pr... | 79e629938d208c06c996b804b779f9cf6c1928cb | 308,746 |
def get_rendered(font, text, color, cache):
"""Simple font renderer that caches render."""
if text in cache:
image = cache[text]
else:
image = font.render(text, 0, color)
cache[text] = image
return image | 13557f705882da5865812a0be86cf8b46b95e202 | 29,849 |
def parser(response):
"""Parses the json response from CourtListener /opinions endpoint."""
results = response.get("results")
if not results:
return []
ids = []
for result in results:
_id = result.get("id", None)
if _id is not None:
ids.append(_id)
return ... | 9632ba800b5de4978aa1c85615dfdeb389bfe5ca | 650,076 |
def parseMovie(line):
"""
Parses a movie record in MovieLens format movieId::movieTitle .
"""
fields = line.split("::")
return int(fields[0]), fields[1] | adb5d04b59eced65b2ca5e477624401d199499d4 | 621,037 |
def str_ellipsis(string: str, max_length: int = 40) -> str:
"""
Reduces the length of a given string, if it is over a certain length, by inserting str_ellipsis.
Args:
string: The string to be reduced.
max_length: The maximum length of the string.
Returns:
A string with a maximu... | dd3db6981703277dcb5a04a2839a638ebba18209 | 343,942 |
import csv
def detect(stream):
"""Returns True if given stream is valid CSV."""
try:
csv.Sniffer().sniff(stream, delimiters=',')
return True
except (csv.Error, TypeError):
return False | 92dfeb58c4505fd9843ec1463ba6ae88349dd8d9 | 681,834 |
def default_get_new_authority_record_details(model, authority):
"""Return a tuple of id and URL for a new authority record. This
function provides a default implementation.
Arguments:
model -- AuthorityRecord model class
authority -- Authority object
"""
prefix = 'entity-'
try:
... | 33386ca9b14621faaad6982ecab781b834ce905b | 307,795 |
def with_vars(carry_vars):
"""Generate WITH statement using the input variables to carry."""
return "WITH {} ".format(", ".join(carry_vars)) | fb98749d74fffad6d9b5218cec7db5ecd8a6da6b | 379,563 |
import json
def read_json(param, filename='../secret.json'):
"""Return result of a given parameter from a JSON file
param - dictionary key within specified file
filename - path to JSON file
"""
with open(filename, 'r') as json_file:
json_string = json_file.read()
datastore = js... | 5d0a5b10f77109f584c9f788ce3551ed5965bb20 | 165,445 |
def cli(ctx, files):
"""Show file information
Output:
List of files containing info
"""
return ctx.gi.file.describe(files) | 7e1842289d59d02d8f219ca57990065c3d7d5134 | 542,375 |
import math
def clip_text(text, max_len):
"""
Clip text to max length, adding ellipses.
"""
if len(text) > max_len:
begin_text = ' '.join(text[: math.floor(0.8 * max_len)].split(' ')[:-1])
end_text = ' '.join(
text[(len(text) - math.floor(0.2 * max_len)) :].split(' ')[1:]
... | 5f543b9de53f9069320ac42fb13a9fc53a17037d | 467,401 |
def get_features_and_target(df):
"""
Takes a full dataset as argument and returns the corresponding X (features)
and y (target) dataframes.
"""
X = df.iloc[:, df.columns != 'hotel_cluster']
# Deals with the case where the dataframe is the test one
y = df['hotel_cluster'] if 'hotel_cluster' ... | e4d2cb66a0dedfbaa6d8e9174aad622ae7b775c2 | 471,170 |
def generate_ordered_sequences(waypoint_lists):
"""
Given an ordered list of lists of possible choices, generate all possible
ordered sequences.
"""
sequences = []
if len(waypoint_lists) == 0:
return []
if len(waypoint_lists) > 1:
for node in waypoint_lists[0]:
for child in generate_ordered_sequences(wayp... | 8bb0fe184b1c98bbfc769b90473b77719e59eec0 | 90,199 |
def calculate_checksum(message: bytes) -> bytes:
"""Calculates the checksum for a message.
The message should not have a checksum appended to it.
Returns:
The checksum, as a byte sequence of length 2.
"""
return sum(message).to_bytes(2, byteorder='big') | 5816446fc06bb573282fcf53aa01656b183a4ace | 358,284 |
def attach_ordinal(num):
"""Convert an integer to an ordinal string, e.g. 2 -> '2nd'."""
suffixes = {str(i): v
for i, v in enumerate(['th', 'st', 'nd', 'rd', 'th',
'th', 'th', 'th', 'th', 'th'])}
v = str(num)
# special case early teens
if v in {... | dc54c9919af1b64e217ca552ffacd01becec989b | 609,526 |
def splitwords(line, sep=','):
"""Split a line into words using `sep`. Instances of `sep` within
quotes are ignored as separators.
>>> splitwords('ID=GQ,Number=1,Type=Float,Description="Genotype Quality"')
['ID=GQ', 'Number=1', 'Type=Float', 'Description=Genotype Quality']
>>> splitwords('ID=GQ,Num... | 6fc82d26eccdd10842e3b647597ae74fdbb25e4f | 313,662 |
def patch_response(response):
"""
returns Http response in the format of
{
'status code': 200,
'body': body,
'headers': {}
}
"""
return {
'statusCode': response.status_code,
'headers': dict(response.headers),
'body': response.content.decode(),
'isBa... | 4a4f073e8fa242803b83508c4e581e0be2020fff | 652,846 |
def set_size(width, fraction=1, subplots=(1, 1)):
"""
Set figure dimensions to avoid scaling in LaTeX.
"""
golden_ratio = 1.618
height = (width / golden_ratio) * (subplots[0] / subplots[1])
return width, height | 109f185ba76081532b2be9c9945625f13da99fc8 | 113,791 |
def _container_exists(blob_service_client, container):
"""Check if container exists"""
return next(blob_service_client.list_containers(container), None) is not None | d59f7e517876f093bbba8a580dd3fe31895075e2 | 689,664 |
def isfloat(n):
"""Checks if number is a float."""
num = str(n)
if "." in num:
return True
return False | 95947e63a7eb0a44b8c5b7a99999267884d8fe1a | 294,245 |
def get_grid(context, grid_id):
"""
Returns the sprytile_grid with the given id
:param context: Blender tool context
:param grid_id: grid id
:return: sprytile_grid or None
"""
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
for grid in mat_data.grids:
... | c29223b2a972dad49446d257ce1b0b619a344d7f | 133,299 |
def list_users_with_grants(mydb):
"""
Get an array of tuples containing database users and their databases.
Args:
mydb - A connected MySQL connection
Return:
An array of tuples ( user, host, database )
"""
databases = []
cursor = mydb.cursor()
cursor.execute('SELECT Use... | 8ddaad5d4942af8b952f17330e3d0f11861c3206 | 414,181 |
def int_to_bytes(i):
"""Convert int to bytes
"""
return i.to_bytes(8, "big") | 3f10c96663bab191dd5f8ccf24a83878985016e7 | 102,988 |
def uppercase(value):
"""
Returns the string with all alpha characters in uppercase
"""
return value.upper() | bf2de90f329ae57e6a11c9d64bd178814c316623 | 265,403 |
def hostname(fqdn):
"""Return hostname part of FQDN."""
return fqdn.partition('.')[0] | 2def763bcc2dc9112314414a9f43621235f100ff | 693,334 |
import json
def load_json_file(filepath):
"""Load content of json-file from `filepath`"""
with open(filepath, 'r') as json_file:
return json.load(json_file) | 578575a6398c3e803613b8b4277043bcab08191c | 101,348 |
def status_button_class(x):
"""A little helper function that takes a status value and returns a
bootstrap button class so that report follow up are displayed
consistently across the site.
Options here reflect status choices in tfat.models:
STATUS_CHOICES = [
# (0, "Not Requested"),
... | 937f171c828e2a5339e6f0c974290190e2c49a1a | 403,173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.