content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def parse_matches_regex(regex, value, error_message='Unmatched value [{0}]'):
"""Raises ValueError(error_message.format(value)) if value does not match
regex.
"""
res = regex.match(value)
if not res:
raise ValueError(error_message.format(value))
else:
return value | 3df1abe4e415e61813f4b4d48dc0463cdb5751eb | 599,662 |
from operator import itemgetter
def find_primer(bed, pos, direction):
"""Given a reference position and a direction of travel, walk out and find the nearest primer site.
Parameters
----------
bed : list
A list of dictionaries, where each dictionary contains a row of bedfile data
pos : int... | ee89f69e46cf5e5116c06bd20d2910c3f1df2f62 | 599,667 |
def aspectratio(image):
"""The aspect ratio of the image"""
return image.shape[1] / image.shape[0] | e35491430229dbbfd6487b11dfa931bc7dee0fa6 | 599,668 |
def _bbox_class(class_index):
"""Create a function to determine if a bounding box label matches a given class"""
def bc(x):
"""Determine if a bounding box label matches a given class"""
return x[4] == class_index
return bc | 55b66e0235206c7d769d685f22ffce2dc595bb29 | 599,669 |
def argsort(seq):
""" Argsort a list of string
Parameters:
-----------
seq: list of words
list of words to sort
Returns:
--------
sorted_seq: list of int (indices)
list of indices (same size as input seq) sorted
(eg. seq=['foo', 'bar','foo','toto'] => out=[1,0,2,3])
"""
... | 69dc07786bd4ebfe00ab573c2148eb52c9e7b442 | 599,672 |
from typing import List
from pathlib import Path
import json
def RAW_STRUCTURES() -> List[dict]:
"""Read and return raw_structures.json"""
with open(
Path(__file__).parent.joinpath("raw_test_structures.json"), "r"
) as raw_data:
return json.load(raw_data) | 254888555c6c0b5102e839f3a9531e04407082b0 | 599,674 |
def _select_eval_with_lowest_and_highest_step(df_evals, sign, dim_x, dim_f):
"""Select step and eval from data with highest and lowest step.
Args:
df_evals (pd.DataFrame): Frame containing func evaluations (long-format).
sign (int): Direction of step.
dim_x (int): Dimension of x to sele... | ecbb98381c90d3abc89621cf89c4590ea2f00e69 | 599,678 |
from typing import Dict
from typing import Any
def handle_set_translation_row_insertion(
language: str,
translation: str,
set_name: str
) -> Dict[str, Any]:
"""
This method will take the set translation data and convert it, preparing
for SQLite insertion
:param language: The language of th... | cd8231c7f8b4907567b67de8641616cb9da48347 | 599,685 |
import json
def mocked_request_bad_response(*args, **kwargs):
"""
Mocks a bad response from a request.
"""
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
if json_data:
... | 882dc161d633086a09853547f124768ccb163498 | 599,689 |
import torch
def maybe_cuda(what, use_cuda=True, **kw):
""" Moves `what` to CUDA and returns it, if `use_cuda` and it's available.
"""
if use_cuda is not False and torch.cuda.is_available():
what = what.cuda()
return what | e54aa5745ca6ba2af14078c41821ad1a38fd8a33 | 599,693 |
def get_role_name(session, role_arn):
"""
Get function role name based on role_arn
Parameters
----------
session : :class:`Session`
AWS Boto3 Session. See :class:`Session` for creation.
role_arn : str
Role arn
Returns
-------
str
Role name.
Returns N... | 9b6d014dfcc9bfa2d82d35a12c86894e4a94ebca | 599,696 |
def get_command(ps_output):
"""Returns the command string extracted from the output of a ps command."""
valid_line = ps_output[1]
data = valid_line.split()
return data[0].strip(':') | f54515e947265542b9407f8a2f2e64e7800d7a51 | 599,699 |
import ipaddress
def get_usable_range(ip_network):
"""Given a network, return the string of usable IP addresses.
Args:
ip_network (str): An IP network in string format that is able to be converted by `ipaddress` library.
Returns:
str: String of usable IP Addresses within network.
Ex... | 2921d3de6e9eeaefb5e7237b0719f49c8dc7c033 | 599,703 |
def has_no_empty_params(rule):
"""
Check whether a flask rule has no empty paramaters.
Args:
rule: The rule to check.
Returns:
True or False.
"""
defaults = rule.defaults if rule.defaults is not None else ()
arguments = rule.arguments if rule.arguments is not None else ()
... | 1dd5c6286499b792e6d73cd5299c8531a746f7c3 | 599,704 |
import multiprocessing
def is_spawning_platform() -> bool:
"""
Returns ``True`` if running on a platform which defaults multiprocessing to spawn.
"""
return multiprocessing.get_start_method(allow_none=False) == "spawn" | b3b3f233c66487bc331b829bc0545c9d5da24d03 | 599,707 |
def sdiv(n):
"""
Safe division clamp, ensure n is not less than 1.
"""
return max(1, n) | 8ccccef8e095501a519501847d2cb58d9523b8b1 | 599,709 |
def get_kubecluster_pods(cluster):
"""Get series of worker pods name / namespace dict from current cluster"""
worker_pods = cluster.workers
pods_dict = {}
# following code from dask source
for number, pod in worker_pods.items():
podname = pod._pod.metadata.name
namespace = pod.namesp... | a685c9ff96eebaa6f6f17b93851c58eddcd8e5fb | 599,710 |
def comparePlugin(x,y):
"""
Customized comparison function for sorting based on
priority and then name in alphabetical order.
Usage: ListOfPluginInstances.sort(comparePlugin)
"""
if x.priority != y.priority:
return x.priority-y.priority
if x.name > y.name:
retu... | 37a19ffc561d0384c54f8b21922fac7dde2e81ad | 599,712 |
def checkerboard_basis(c: complex) -> str:
"""Classifies a coordinate as X type or Z type according to a checkerboard pattern."""
return 'X' if int(c.real + c.imag) & 1 == 0 else 'Z' | 49a1a2296b45328a2ffcd04186800fd9379a1946 | 599,715 |
def joint_membership(a, b):
"""Calculate the joint membership of arrays.
Parameters
----------
a : array-like of shape (n_samples,)
The first array of membership.
b : array-like of shape (n_samples,)
The second array of membership.
Returns
-------
joint_membership_ : ar... | 8865748eae74354e3325a697ff5fccc8a94272ec | 599,720 |
import torch
def generate_square_subsequent_mask(sz):
"""Generates an upper-triangular matrix of -inf, with zeros on diag."""
return torch.triu(torch.ones(sz, sz) * float('-inf'), diagonal=1) | 718eaec36ca9df491a27bdac439930035b41704d | 599,722 |
def theta_to_T(theta,p,p0=1000.):
"""Calculate (virtual) temperature [K], from (virtual) potential
temperature, theta, [K] and pressure p [mbar] using Poisson's equation.
Standard pressure p0 at sea level is 1000 mbar or hPa.
Typical assumptions for dry air give:
R/cp = (287 J/kg-K) / (1004 J... | 9497fc9199b024495fb3399d11441751fbce1d5b | 599,730 |
def calc_scoring_rate(
shots_per_poss,
three_make_rate,
two_make_rate,
three_attempt_rate,
ft_attempt_rate,
ft_make_rate,
):
"""Calculates points per possession from underlying rate statistics"""
points_per_attempt = (
3 * three_attempt_rate * three_make_rate
+ 2 * (1 - t... | 4245a9df33f5f2e9dd2f3ace3c260476110f84da | 599,736 |
def get_lidar_in_image_fov(
pc_velo, calib, xmin, ymin, xmax, ymax, return_more=False, clip_distance=2.0
):
""" Filter lidar points, keep those in image FOV """
pts_2d = calib.project_velo_to_image(pc_velo)
fov_inds = (
(pts_2d[:, 0] < xmax)
& (pts_2d[:, 0] >= xmin)
& (pts_2d[:, ... | aed91a255c5338d9c728d469a6fa897112ac4984 | 599,737 |
def scale(x: float, original: float, new: float) -> float:
"""
Scale a value "x" from the "original" to the "new" frame of reference.
"""
return (x * new) / original | eae1479b21812109ea6e106c7c7a425b0d8eaa09 | 599,739 |
from typing import Counter
def count_attributes(attribute_dict):
"""Count the number of times attributes are found in study metadata.
Parameters
----------
attribute_dict : dict
Dictionary of study attributes, where keys are study identifiers
and attributes are values found in the stu... | 40e23d1d71fcbecb4452909f7b6e5d89d89a66de | 599,745 |
def ad_group_ids_are_unique(df):
"""
This function returns True iff ad_group_ids are unique (only show up once in the rows of df)
"""
return len(df[['ad_group_id']].drop_duplicates()) == len(df) | 468834e05f7bb15282078fa0bb73ed82227fc18d | 599,750 |
from typing import Mapping
def any_value_is_none(d: Mapping):
"""Returns True if any value of the mapping is None"""
return any(d[k] is None for k in d) | 608fd6f5bc5048ccbd58a228e9e315a4f61c22fb | 599,754 |
def kelvtoreau(kelvin):
""" This function converts kelvin to Reaumur, with kelvin as parameter."""
Reaumur = (kelvin - 273.15) * 0.8
return Reaumur | c597284305628a4b159f29e6e825df0e2fae9882 | 599,757 |
import re
def _cleanup_type(type_str):
"""Cleanup string representing a C++ type
Cleanup simply consists in removing spaces before a ``*`` character and
preventing multiple successive spaces in the string.
Parameters
----------
type_str : str
A string representing a C++ type definiti... | 2e1f9d2680e984d3ff334e4d483838277b68ce4d | 599,758 |
def defineVariable( signal, make_a_reference = False ):
"""
create a sting containing e.g.
'double signalName'
"""
return signal.getDatatype().cpp_define_variable( signal.name, make_a_reference ) | 58632fa3b7db2238af06dced9f40974499e05035 | 599,759 |
def get_target_start_date_col(forecast_id):
"""Returns the name of the target start date col for dataframes
associated with the given forecast identifier
Args:
forecast_id: string identifying forecast (see get_forecast)
"""
if forecast_id.startswith("nmme"):
return "target_start"
... | 4eab8d822c8d4b632fb61a0ac19f8936830a9940 | 599,762 |
def _filter_tuples(services_states, state):
"""Return a simple list from a list of tuples according to the condition
@param services_states: LIST of (string, boolean): service and running
state.
@param state: Boolean to match the tuple against.
@returns [LIST of strings] that matched the tup... | a61ccfbbc3a7efe37ebb9b0808b947f33ece6c62 | 599,764 |
import math
def _remove_edge_blobs(blobs, image_shape):
"""Remove blobs detected around the edge of the image.
:param blobs: list of blobs detected from the image
:param image_shape: shape of the image. Provides the bounds to check.
:returns: list of filtered blobs
"""
img_height, img_width =... | 15bb099c13102a138bb43def8fb00c8c944cdb90 | 599,766 |
import gzip
def openfile(infile, method, compresslevel=1):
"""
Open file handling if compressed or not
"""
fhd = None
if infile.endswith('.gz'):
fhd = gzip.open(infile, method, compresslevel)
else:
fhd = open(infile, method + '+b')
return fhd | d6f5fcfde01c38335a15511a35ba618bdb8d8493 | 599,772 |
from typing import Iterable
from typing import Container
from typing import Set
def merge_sets(*set_args:Iterable[Container]) -> Set:
""" Given any number of sets, merge them into a single set
N.B. This function only performs a "shallow" merge. It does not handle
nested containers within the "outer" sets... | ea08cc50466a2c5e46f7e41ea9cd43782077dcb1 | 599,773 |
import base64
def frontend_proc_info(processor_type: str, processor_process_endpoint: str) -> str:
"""Return processor info (opaque string) for exchanges with frontend."""
proc_info = f"{processor_type}|{processor_process_endpoint}"
return base64.b64encode(proc_info.encode()).decode() | 7d23b46711a9c48356c511a82b1c9e8f6da6c40d | 599,776 |
def lmemoFib(n, memoize):
""" Fibonacci numbers solved with memoization using list"""
if n < 3:
return n
if memoize[n] >= 0:
return memoize[n]
else:
memoize[n] = lmemoFib(n-1, memoize) + lmemoFib(n-2, memoize)
return memoize[n] | 242f0593a5790cef0e74480c8b13b7a3b4ce95ec | 599,781 |
def name_it(id, start, stop):
"""
Automatically name a sound file with respect to (start, stop) slice audio
:param id:
:param start:
:param stop:
:return string:
"""
return "{}_{}_{}_{}".format(id,
int(start * pow(10, 6)),
... | f74bb8246ccef3f97cc1c6fab43cf492bbaa060f | 599,782 |
def qnn_dense_legalize(attrs, inputs, types):
"""Default legalization is None."""
return None | 7ef41d7ef028e368ce7b7457864e6cdc5f606339 | 599,783 |
def add_outputs_from_dict(
api_current_dict: dict,
fields_to_keep: list
) -> dict:
"""
Filters a dict and keeps only the keys that appears in the given list
:param api_current_dict: the origin dict
:param fields_to_keep: the list which contains the wanted keys
:return: a dict based o... | bfe251de9a8f2634b7777b1e2a89e6071b213ce1 | 599,786 |
def addTeamBranchUsage(err=''):
""" Prints the Usage() statement for this method """
m = ''
if len(err):
m += '%s\n\n' %err
m += 'Link a Task Branch (TB) with a Team Branch (TmB) on Salesforce.\n'
m += '\n'
m += 'Usage:\n'
m += ' teamlnbr [OPTIONS] -s <stream> -n <team n... | 99fe9839336d589cb19a25a18b5245d561f65d7a | 599,788 |
def trim_empty_blpairs(uvp, bl_grp, spw=0, pol='pI'):
"""
Remove any baseline-pairs with zero data from a list of blpairs.
Parameters
----------
uvp : UVPSpec
Contains power spectra.
bl_grp : list of lists of tuples
List of redundant groups of baseline pairs, e.g. outpu... | 1d8e3563f09553c73bf6d0f4d38ac209944a38ca | 599,789 |
def _apply_jump(board, move):
"""Apply a jump move to a given board.
Args:
board: board string
move: move tuple
Returns:
Board string of new position.
"""
assert (board[move[0]].lower() == 'b')
board_list = list(board)
board_list[move[-1]] = board_list[move[0]]
if mov... | 2bcf732f88809a6942b53777e465dec9404cf4ee | 599,791 |
import math
def isprime(n):
"""Returns True if n is prime and False otherwise"""
if not isinstance(n, int):
raise TypeError("argument passed to is_prime is not of 'int' type")
if n < 2:
return False
if n == 2:
return True
max = int(math.ceil(math.sqrt(n)))
i = 2
whi... | 5f35de4a637b50f8846ece039369d80953e2b495 | 599,792 |
import time
def rt_parse_comment_time(t):
"""
Given a string representing the RT ticket's comment timestamp, this
returns a parsed time struct version of this timestamp.
:param t: the string of the RT ticket's comment timestamp
"""
return time.strptime(t, "%Y-%m-%d %H:%M:%S") | f98afbcc9d8fbc503bfcbe5f627a06c4a2eb1255 | 599,793 |
def percent_bias(series1, series2):
"""Percent bias (PBIAS) measures the average tendency
of the simulated values to be larger or smaller than their observed ones.
https://rdrr.io/cran/hydroGOF/man/pbias.html#:~:text=Percent%20bias%20(PBIAS)%20measures%20the,values%20indicating%20accurate%20model%20simula... | e271e0d2753bc7396fe5d959eaab422d2963e802 | 599,794 |
def newline(text, number=1):
"""adds number newlines to the end of text"""
return text.strip() + ("\n" * number) | af43d6e329f4769be1e4641879218cd208059fe0 | 599,796 |
def json_encode_date(d):
"""Encoder for dates (from module datetime)."""
return {"date" : str(d)} | 0f9a334df097e75bbca039ff58c969623925a29f | 599,797 |
import array
import math
def _fold_sizes(num_rows, num_folds):
"""Generates fold sizes to partition specified number of rows into number of folds.
:param num_rows: number of rows (instances)
:type num_rows: integer
:param num_folds: number of folds
:type num_folds: integer
:returns: an array.... | f621bd5564b7e6c0614af6f4dd6757a026b4e313 | 599,798 |
def piecewise(functions, conditions, fallback=lambda x : 0):
"""
Return a piecewise function such that if condition ``i`` in the given list
of conditions is true, then the function at index ``i`` is executed.
If none of the conditions are satisfied, then the given fallback function
is used (default is lambda x :... | c35dcf774082c454ab63d6e94ede6b7483baa92b | 599,799 |
def pie_pct_format(value):
""" Determine the appropriate format string for the pie chart percentage label
Args:
value: value of the pie slice
Returns:
str: formated string label; if the slice is too small to fit, returns an empty string for label
"""
return '' if value < 7 else '%.0f... | ac5e7f15fb12b383cfe99e3579dff9d1e2b84843 | 599,801 |
def get_key(url):
"""
Given a URL path convert it to an S3 Key by replacing some parts of the path
with empty strings
"""
return url.replace("/v0/submission/", "").replace("/files", "") | 6eba37db2a4a31c81c4c02f61fd4d0133d0b8e20 | 599,806 |
def split_layers_str(layers_str):
""" Splits a comma seperated list into its components.
Strips leading and trailing blanks from each entry.
Args:
layers_str: String in the form: "layer_1,layer_2,..."
Returns:
List of strings in the form [layer_1, layer_2, ...]
"""
if layers_str ... | 8e94e1d6ba8245db1acf0df75b02b1ca595728cb | 599,807 |
def value_of_card(card: str) -> int:
"""Determine the scoring value of a card.
:param card: str - given card.
:return: int - value of a given card. 'J', 'Q', 'K' = 10; 'A' = 1; numerical value otherwise.
"""
if card in ("J", "Q", "K"):
return 10
if card == "A":
return 1
re... | 7f47ccda286a621a20624fc8c0b868fbbc734473 | 599,811 |
def truncate(text, max_size, ellipsis='...'):
"""Truncate text if it's too long."""
if len(text) > max_size:
text = text[:max_size] + ellipsis
return text | 6a86e113748b6031dd61b7e6f1defdae1a06e06a | 599,812 |
import re
def check_host(hostname, black_list, white_list):
"""Check hostname to see if it valid
Checks if the hostname is in the white and black list and return back
according to the regex filtering.
"""
for host_regex in black_list:
if len(host_regex) > 1 and re.search(host_regex, host... | 83c5b31b0fe12c3d7992e1e91f5e2cd7412ef2d5 | 599,813 |
from typing import Any
def shape_safe(x: Any):
"""
Exception-safe getter for ``shape`` attribute
Args:
x: any object
Returns:
``x.shape`` if attribute exists, empty tuple otherwise
"""
return x.shape if hasattr(x, "shape") else () | 59093723d9f757c9f9616ae44d608b7c24b47072 | 599,815 |
def isSafe(i, j, visited, graph):
"""
This function to check whether a given cell (row, col) can be included in DFS or not
:param i: current row number
:param j: current column number
:param visited: 2-d grid of visited nodes
:param graph: given 2-d grid
:return: bool
"""
return (
... | 9bcf672e71d09f474bb4251ac9bf9cd0edd9214f | 599,816 |
def second_arg (x, y, * args, ** kw) :
"""Returns the second argument unchanged"""
return y | ed06a4ee018f0de029c6a0be32d54a4ebaa0d50c | 599,821 |
def default_version_splitter(instring):
"""Split the version string out of version output."""
return instring.split()[-1] | b9939fa5e0d01ce798b8184bc49a1a627f7034f0 | 599,822 |
def common(string1, string2):
""" Return common words across strings1 1 & 2 """
s1 = set(string1.lower().split())
s2 = set(string2.lower().split())
return s1.intersection(s2) | 92cd759e7fc79b72efc29cac85c8e22cf2acb78d | 599,832 |
def dilate(geom, mask):
"""
Add one row of neighbors to the True values of a pixel mask and return
the new mask.
This can be used to include extra rows of pixels in a mask that was
pre-computed, e.g. via `tailcuts_clean`.
Parameters
----------
geom: `~ctapipe.instrument.CameraGeometry`
... | 5bc642ab3568c1ba3a55682d2ba2ac78d0f816e5 | 599,833 |
from typing import Mapping
def validate_schema(assert_,
data,
schema,
optional=None,
on_unexpected_cols='raise'):
"""Check if a data frame complies with a schema
Parameters
----------
data : pandas.DataFrame
Data ... | 068c5784a8ea4721fbd1fcdc4fd4328b6bfbd099 | 599,834 |
def _is_on_line(x, y, ax, ay, bx, by):
"""
Check if point `x`/`y` is on the line segment from `ax`/`ay` to `bx`/`by`
or the degenerate case that all 3 points are coincident.
>>> _is_on_line(0.5, 0.5, 0.0, 0.0, 1.0, 1.0)
True
>>> _is_on_line(0.0, 0.0, 0.0, 0.0, 1.0, 1.0)
Tru... | 0d2c1cf9381b2136235826bd422a84ecf7447bea | 599,838 |
def find_choice_index(choice, choices):
"""
Finds the index of an item in a choice list.
"""
for choice_tuple in choices:
if choice == choice_tuple[1]:
return choice_tuple[0] - 1 | 98af0147ddf78aec44fab5d564b455fd1394a27b | 599,841 |
def get_rpkm_score(hit, function_fraction, total_readcount, length_cutoff):
"""Calculates RPKM score of a single hit (number of reads per million
reads per kilobase of reference gene)
Args:
hit (:obj:DiamondHit): DIAMOND hit
function_fraction (float): fraction of the score assigned to a... | df4c18f00919b1e6bdafec1077f1240f3f02a7f1 | 599,844 |
def _parse_options_list(options):
"""
Args:
options: list of the BeautifulSoup objects
Returns:
list[dict]: list of parsed info about faculties
"""
faculties_list = []
for option in options:
faculties_list.append({
'name': option.text,
'code': int... | 19fbe248422728ace7133d23104025ddf1a90f96 | 599,845 |
def get_user(trans, user_id):
"""Get a User from the database by id."""
user = trans.sa_session.query(trans.model.User).get(trans.security.decode_id(user_id))
if not user:
return trans.show_error_message("User not found for id (%s)" % str(user_id))
return user | 93610353947874159ad961038e73ffc1dc588ea2 | 599,846 |
def equal_object_refs(d1, d2):
"""
Checks whether two references point to the same object.
:type d1: dict
:type d2: dict
:return: True if passed references point to the same object, otherwise False
"""
have_equal_ids = d1['id'] == d2['id']
have_equal_types = d1['type'] == d2['type']
... | d48bea0d0a4956dd629cb8d112f9b095cdd6bd51 | 599,847 |
def linear_search(list, target):
"""
Returns the index position of the target if found, else returns None
"""
for i in range(0, len(list)):
if list[i] == target:
return i
return None | df7cd5084a2bb2a57cc561a8e3c87b613e27773b | 599,851 |
def get_team_instance(employee):
"""Get employee team"""
return employee.organisationdetail.team | ae499167f2224d025c54e56ccc27b26cb1d40e74 | 599,852 |
import click
def verify_operation(txt, msg=None):
"""
Issue click confirm request and return result. If msg is none and
confirm response is n, output msg.
Parameters:
txt (:term:`string`):
String that is prefixed to the prompt text and defines the
verification request.
... | 70554e86b852e939fd40caf654a707ecfd55ec4e | 599,854 |
def lineups_data(goals_a, goals_b):
"""
lineups_data(goals_a, goals_b) -> dict
Convert to goals team data as: won, lost, matched, goals_made etc, i.e.:
lineups_data(3, 2) -> {'hw': 1, 'vw': 0, 'hl': 0, ...}
hw: home_won vw: visit_won
hm: home_matched vm: visit_matched
... | 9e1e67997ebd627a2ea2bd056ed85ba113ee9dcf | 599,857 |
def _parse_outputs(outputs_data):
"""
Parses outputs from .tfstate file
:param outputs_data: dict
"output": {
"value": string,
"type": string
}
:return: dict, with the following structure:
{
"{name}": string,
}
"""
res_outputs = {}
for name, value... | 5a732a9d23e6e2d2480ce623e30e6cdecaad80bb | 599,859 |
def loop_bodies(k: int, url_path: str, lines: list) -> dict:
"""
We loop lines here to extract :
- query params
- command to execute
- response to return
"""
extracted_params = {
"command": [],
"body_params": [],
"query_params": [],
"res": "request sent.",
... | 5fcd018ba12bd1ba7ac7f07ea3aba8491b5743d8 | 599,860 |
def hour2str (hr, delimiter=":") :
""" Transfer hours to hh:mm format string
args:
hr: hours, 0.0 to 36.0, will error for negative
delimiter: char separate deg, min and sec, default is ":"
returns:
string hours and minutes, in hh:mm format
"""
mi = int(round(hr * 60))
hh ... | f762502bd36939d60dcd5ac8a83e895c1e5e0b53 | 599,861 |
def p_dict_has_key( dct, key ):
""" If `dct` is a dictionary AND has the `key`, then return True, Otherwise return False """
return ( isinstance( dct, dict ) and (key in dct) ) | 9dda0bd79e4899f5ed2a86af84be3126f7598ad5 | 599,863 |
def get_telecom_model_queryset(request, model):
"""
The queryset of models `Isp`, `IspGroup`, `PrefixListUpdateTask` with
filter depending on user's role/identity/group. The views below will use
this as a basic queryset. This ensures that users won't accidentally see
or touch those they shouldn't.
... | 1b7e5201b66548af6792f30c0ff267ee3487251c | 599,864 |
def reily_name(name):
"""Maps our simplified names to full Reily names"""
names = dict(svol='Sv\\"{o}l', leiptr='Leiptr', gjoll='Gj\\"{o}ll', fjorm='Fj\\"{o}rm', fimbulthul='Fimbulthul', ylgr='Ylgr', sylgr='Sylgr', slidr='Slidr', phlegethon='Phlegethon', aliqa_uma='Aliqa Uma', atlas='ATLAS', elqui='Elqui',... | 2547479477448d29189f6352355db800e1de2271 | 599,866 |
def _find_nonascii(s):
"""
Return a list of (line#, [col#, col#, col#]) tuples, one per line, that identify the positions of non-ascii characters.
Lines without non-ascii characters are skipped.
Returns an empty list if none found.
Number values are zero-indexed.
"""
outvals = []
lines ... | a18fac2fa2be16b0fa697a5f8ae97fb97b02380f | 599,867 |
def _convert_display_size(size):
"""
Convert filesize into human-readable size using unit suffixes
"""
unit_gigabyte = 1024 * 1024 * 1024.0
unit_megabyte = 1024 * 1024.0
unit_kilobyte = 1024.0
if size > unit_gigabyte:
return "{:.2f} GB".format(
size / unit_gigabyte)
... | 6723b67c03ca205342e21ef4a637a1faacb69d18 | 599,871 |
def avg_item_count_character(db):
"""Returns the average number of items per character from MongoDB
database.
Args:
db (pymongo.database.Database): MongoDB database
Returns:
(float) Average number of items per character
"""
agg_dict = [
{
"$lookup":
... | 112b03d8b3bb69556c04e79fc5bd5262665b5df9 | 599,874 |
def get_text_from_object(object_array):
""" Receives a soup4 object array and returns a string array with the text of each object"""
return [current_tag.text.strip() for current_tag in object_array] | a340d3855f7e7d38271a9de98dd650a00f6fda34 | 599,875 |
import io
def read_description(filename):
"""Reads filename and returns its contents."""
with io.open(filename, encoding="utf-8") as opendescription:
return opendescription.read() | 3144bed42593f5db40bdfcbd5a7468fa44fe95cd | 599,878 |
import random
import string
def generate_typeable_handle(length=8):
"""Generate a random typeable (a-z, 1-9) string for consent URL."""
return "".join([random.choice(string.digits +
string.ascii_lowercase) for _ in range(length)]) | 51e8d573c1307f275ff092c8bd750b75b6503f66 | 599,879 |
def get_number_of_pieces_and_kings(spots, player_id=None):
"""
Gets the number of pieces and the number of kings that each player has on the current
board configuration represented in the given spots. The format of the function with defaults is:
[P1_pieces, P2_pieces, P1_kings, P2_kings]
and if giv... | bdf0b12e7eac46247146b5c5112c817900933223 | 599,881 |
def hasCapitalLetters(passW):
"""
checks if password has Capital Letters
"""
count = 0
for i in passW:
if(i.isupper()):
count+=1
return count | 315984fa3c51e8ecdc185c162607e1bd773c9221 | 599,882 |
def draw_polygon_segment(start, to):
"""Draws a line between to points - start and to"""
def func(ctx):
ctx.move_to(*start)
ctx.line_to(*to)
return func | cd8f6d5b40b3d59fee2cb9948a241aa2ee1a3cdd | 599,883 |
def pop_or_raise(args, missing_error, extra_error):
"""Pop a single argument from *args* and return it. If there are
zero or extra elements in *args*, raise a `ValueError` with message
*missing_error* or *extra_error*, respectively."""
try:
arg = args.pop(0)
except IndexError:
raise... | 371562bb5eaa37d59fcec904c99ad71670978d24 | 599,893 |
def create_power_of_two(number: int) -> int:
"""Creates the smallest power of two which is at least number."""
power = 1
while power < number:
power = power * 2
return power | bc961fcc2ba597d45367f81d426b57a83fc8a97d | 599,894 |
import re
def br_to_p(value):
"""
Converts text where paragraphs are separated by two <br> tags to text
where the paragraphs are wrapped by <p> tags.
"""
value = re.sub(r'<br\s*/*>\s*<br\s*/*>', u'\n\n', value)
paras = re.split('\n{2,}', value)
paras = [u'<p>%s</p>' % p.strip() for p in pa... | 1635b1aebd37e1b686330bbbd0e6b7810627f1fc | 599,896 |
def batch(items, size):
"""Batches a list into a list of lists, with sub-lists sized by a specified
batch size."""
return [items[x:x + size] for x in range(0, len(items), size)] | f655d5ca4e7bbe7fc6ed60d8fc9bbdf1bbfd972d | 599,897 |
import json
def loadJSON(filepath):
""" Loading json file
"""
with open(filepath, 'r') as f:
return json.load(f) | e577f95426d1051013ce33151be406b0c679fcb3 | 599,899 |
def get_api_auth_names(bosslet_config):
"""
gets the api and auth hostnames from the domain
Args:
bosslet_config (BossConfiguration): Configuration for the target Bosslet
Returns:
tuple(str) of api hostname and auth hostname
"""
api = bosslet_config.names.public_dns('api') + '.'... | 064307ffa9d3f52e1ed3273287d3bb1c1ada2ccf | 599,906 |
def _GetPathFromUrlString(url_str):
"""Returns path component of a URL string."""
end_scheme_idx = url_str.find('://')
if end_scheme_idx == -1:
return url_str
else:
return url_str[end_scheme_idx + 3:] | c45c6b4d17036e2239a27fb6cb5701194c01a84c | 599,908 |
import yaml
def load_config(path="config/default.ymal") -> dict:
"""
Load and parses a YAML configuration file
:param path: path to YAML configuration file
:return: configuration dictionary
"""
with open(path, 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile)
return cfg | 59417b3e6f727244cee51558f064d371dd86d911 | 599,910 |
def int_to_abbrev_str(n: int):
"""Given an integer returns an abbreviated string representing the integer, e.g., '100K' given 100000"""
if n > 0 and n % 10**6 == 0:
return f'{n // 10**6}M'
elif n > 0 and n % 10**3 == 0:
return f'{n // 10**3}K'
else:
return f'{n}' | 862a5932954426fc0f2f923a721e53834f5067ab | 599,911 |
def calc_Distance_from_Magnitudes(M,m):
"""
m: apparent magnitude
M: absolute magnitude
"""
return 10**(m+5-M)/5 | a280306883d9b5a6e3dc56cf19cd77e160ef98db | 599,915 |
def _separate_bitstring(bitstring, creg_sizes):
"""Separate a bitstring according to the registers defined in the result header."""
substrings = []
running_index = 0
for _, size in reversed(creg_sizes):
substrings.append(bitstring[running_index: running_index + size])
running_index += si... | b1b1f412c5766ed2e676078c4bfbe9574737ff94 | 599,927 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.