content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _has_docker_file(repo, project_path):
"""Checks if project has a Dockerfile."""
return any(content_file.name == 'Dockerfile'
for content_file in repo.get_contents(project_path)) | adb9eba9ad908811f8f5b04098ec6be44ef824f9 | 653,092 |
from typing import Sequence
from typing import Tuple
import click
def print_table(rows: Sequence) -> None:
"""Print a formatted table."""
head, *rows = rows
col_lengths = list(map(len, head))
for row in rows:
col_lengths = list(map(max, zip(col_lengths, map(len, row)))) # type: ignore
d... | 21c38758f7607bd28204b8fc8dc0a2bbbe2c6eed | 653,094 |
def simHeatpump(T_cold, T_hot=50.0, efficiency=0.45, T_limit=-20.0, COP_limit=7.0):
"""
Creates a timedepent Coefficient of Performance (COP) based on the potential carnot
efficiency and a quality grade/efficiency of the system.
Parameters
-----------
T_cold: float, np.array or list, required
... | 573d061dd01c60812a988bcbe8e8aaf34173ebf3 | 653,095 |
def fetch_vest_scores(vest_dict,
ref_aa, somatic_aa, codon_pos,
default_vest=0.0):
"""Get VEST scores from pre-computed scores in dictionary.
Note: either all mutations should be missense or non-missense intended
to have value equal to default.
Parameters
... | 1bf3b98376ed22ccd58508daf658bc2be5070dee | 653,096 |
def xstr(s):
"""
Returns the given object as a string or if None then
returns the empty string
"""
return str(s) if s else "" | c1796e421dcafa98a0c6cdaa0ccd4aec63a0b641 | 653,098 |
def ma(df, ma_ranges=[10, 21, 50]):
"""
Simple Moving Average
Parameters
----------
df : pandas.DataFrame, must include columns ['Close']
Dataframe where the ma is extracted from
ma_ranges: list, default [10, 21, 50]
List of periods of Simple Moving Average to be extracted
Retur... | ddd88c75f17e0dcac6a9ce5991ee263ba92c6e83 | 653,105 |
def elchgeraeusch(wiederholungen):
"""Gibt einen String mit einer bestimmten Anzahl an Mööös aus."""
elchausspuch = ""
for i in range(wiederholungen): # das wird einfach wiederholungen-mal ausgeführt
elchausspuch += "Mööö " # a += b bedeutet a = a + b
return elchausspuch | f28861e3ff143f108dd5debd7e8635c6551eed2e | 653,109 |
def select_rows(match_value, col_index, all_rows, header=True):
"""Select only rows where the value in the search column matches
This allows the caller to process requests from one user or project at a
time if needed, for example when processing individual helpdesk tickets.
inputs:
match_value... | c320a184f965f13ae361c198b8c4098e530cc25c | 653,112 |
def is_no_cache_key_option(number):
"""Return ``True`` iff the option number identifies a NoCacheKey option.
A :coapsect:`NoCacheKey option<5.4.2>` is one for which the value
of the option does not contribute to the key that identifies a
matching value in a cache. This is encoded in bits 1 through 5 o... | aad8173794ae13fe885316f8048d66e547addc7b | 653,114 |
import torch
def to_sparse(tensor):
"""Given a one-hot encoding vector returns a list of the indexes with nonzero values"""
return torch.nonzero(tensor) | 52d336c060c23a139051997d97755da7babcc79f | 653,128 |
def _try_rsplit(text, delim):
"""Helper method for splitting Email Received headers.
Attempts to rsplit ``text`` with ``delim`` with at most one split.
returns a tuple of (remaining_text, last_component) if the split was
successful; otherwise, returns (text, None)
"""
if delim in text:
... | ecc57abd82c8a4c63100d2305af1cd21853fa86e | 653,134 |
from pathlib import Path
def chk_dir(src_dir):
"""To check if the directory exists. Returns boolean
"""
src_is_dir = Path(src_dir).is_dir()
if src_is_dir is False:
print(f"Test Directory '{src_dir}' does not exist.")
print("Add a directory containing the source images to run this test... | 50200b6de34af6ec50abf90b05e6a366502c78fe | 653,138 |
import zlib
import pickle
def _compress_obj(obj, level):
"""Compress object to bytes.
"""
return zlib.compress(pickle.dumps(obj, protocol=2), level) | 17c531c350103d27647bbd6c2baece4d2e46db3e | 653,140 |
def display_2Dlist(p):
"""Prints a piece, or each Piece in a list, to output.
Args:
p (Union[Piece, List[Piece]]): Piece, or list of Pieces, to print to output
"""
# helper function to display a piece
def dis(p):
for row in p:
print(row)
def is_piece(p):
ret... | e1bb93928825702f4b40620ca581797e1747bb62 | 653,141 |
from typing import Tuple
def parse_fasta_header(fasta_header: str) -> Tuple[str, str, str]:
"""Parse a fasta header with the following format: db|UniqueIdentifier|EntryName.
https://www.uniprot.org/help/fasta-headers
Parameters
----------
fasta_header : str
A fasta header in the format: d... | c2aac2e94288380646657a9d5c8303b8a5215d12 | 653,142 |
def rangify(value):
"""Return a range around a given number."""
span = 5
min_val = max(value - span, 1)
max_val = max(value + span, span * 2)
return range(min_val, max_val) | 39b4d93b49e90ad2e71723751bb9b49b7dc134ed | 653,143 |
def read(filename):
"""Read content of specified test file.
:param str filename: Name of file in 'testdata' folder.
:return: Content of file
:rtype: str
"""
with open('testdata/' + filename) as f:
return f.read() | 3d5485021d3a3578485f3b5f3ea59e0badc4a3c7 | 653,147 |
def num_to_emoji(n):
"""
Convert number to discord emoji
Parameters
----------
n : str
string number
Returns
-------
str discord emoji if valid, False otherwise
"""
num_emoji_map = {
"1": ":one:",
"2": ":two:",
"3": ":three:",
"4": ":four... | 1bacf8b2644d40c8ef38a87c0d171a551d1dcc0d | 653,152 |
def is_2numbers(astring):
"""
(str) -> Boolean
returns True if astring has at least two numbers.
else return False.
>>> is_2numbers('CIS122')
True
>>> is_2numbers('Ducks')
False
>>> is_2numbers('ABC-1')
False
"""
digits_ctr = 0
for c in astring:
if c.is... | b7ed49e2c0ec59e17d71fdbaf8a500a59b1ea35b | 653,153 |
from pathlib import Path
def run_prediction(predictor, inputs, cleanup_functions):
"""
Run the predictor on the inputs, and append resulting paths
to cleanup functions for removal.
"""
result = predictor.predict(**inputs)
if isinstance(result, Path):
cleanup_functions.append(result.unl... | 0284523f3a77477757b6236ef3956b451e5bce84 | 653,156 |
def num_words(text: str) -> int:
"""
Counts the number of words using whitespace as delimiter.
Args:
text: Sentence
Returns:
Number of words
"""
return len(text.split()) | 32b0b6d993772f8a15c3c9c9605c0ebe691fbb1e | 653,157 |
def DnsRequestsAndCost(trace):
"""Returns the number and cost of DNS requests for a trace."""
requests = trace.request_track.GetEvents()
requests_with_dns = [r for r in requests if r.timing.dns_start != -1]
dns_requests_count = len(requests_with_dns)
dns_cost = sum(r.timing.dns_end - r.timing.dns_start
... | a23ede3780b525562cc0abbcc3d9dc723aaaaa01 | 653,159 |
import shutil
def which(program):
"""Find the program executable
Args:
program (str): program name
Raises:
ValueError: Raise if the program isn't found
Returns:
obj: program executable path
"""
_executable = shutil.which(program)
if not _executable:
raise... | c0f920654321bbdfd074d999cb09dc8adeacd4b8 | 653,166 |
def delslash(value):
"""
Remove slash from start and end
>>> delslash('/foo/bar/')
'foo/bar'
:type str:
:rtype: str
"""
if value.startswith('/'):
value = value[1:]
if value.endswith('/'):
value = value[:-1]
return value | edde3a84a1715c5bb3a2f6aa1aca725348a91fa5 | 653,168 |
def int2hex(number: int, chars: int = 2) -> str:
"""
Converts integers to human-readable HEX
:param number: integer to convert
:param chars: minimal amount of chars(bytes) to show
:return: HEX string w/o prefix
"""
a = hex(number)[2:].upper()
chars = max(len(a) // 2, chars)
return ('... | 9595fb6a4ee3cab58aa99e2e7481ce6defe2f224 | 653,169 |
def tuple_incr(t1, idx, val=1):
"""Return a tuple with the index idx incremented by val"""
return t1[:idx] + (t1[idx]+val,) + t1[idx+1:] | bbf7c9d7b669fff5a42e224790b1af9135cce231 | 653,171 |
import json
def _output_object(name):
"""Format an object ID as JSON output, for returning from a narr. function.
"""
return json.dumps({'output': name}) | 38b3926452b8f3f6e3e2ee5b3204c4507a6b41de | 653,172 |
def script(script_file, **context):
"""
User-defined script to be loaded into administrative page.
:param script_file: location of javascript file (in the service's working directory).
Must be a javascript function.
:param context: context will be passed to the called script.
"""
with o... | bef659c1392b9331744759d04f88fc78fc6e339c | 653,174 |
def get_isa_field_name(field):
"""
Return the name of an ISA field. In case of an ontology reference, returns
field['name'].
:param field: Field of an ISA Django model
:return: String
"""
if type(field) == dict:
return field['name']
return field | 79480fb09a1f2a717d1c54472748207b8bf3f6f3 | 653,176 |
import torch
def nd_cross_entropy_with_logits(logits: torch.Tensor,
targets: torch.Tensor,
weights: torch.Tensor):
"""
Multidimensional version of `util.cross_entropy_with_logits`.
# Shape: (batch_size, d_1, ..., d_n, num_classes)
logi... | 4b619cd23d86a60d2a74ae437fc2191a69d2b3d8 | 653,177 |
def smooth_series(data, window, method="average"):
"""Apply a moving average or mean with window of size "window"
Arguments:
data {Dataframe} -- Pandas dataframe
window {int} -- size of window to apply
Keyword Arguments:
method {str} -- the method applied to smooth the data... | f09b956c0a899de8b8607e08b05bdbc917e473a7 | 653,179 |
def adjacent_enemy(inp, rowI, colI, enemy):
"""Check for enemy in adjacent square"""
if any(x[0]==enemy for x in [inp[rowI+1][colI], inp[rowI-1][colI], inp[rowI][colI+1], inp[rowI][colI-1]]):
return True
return False | 1fb36051402d3fef0c4c8b022676bdeb4f121b3a | 653,181 |
from typing import Dict
def validate_detail(detail: Dict[str, int]) -> bool:
"""Validates the given detail
Parameters
----------
detail : Dict[str, int]
The detail to be validated
Returns
-------
bool
True if the detail follows the schema, else False
"""
detail_ke... | db4e092f57b66fd0035e998c57044919f350205a | 653,184 |
import json
def read_json(input_file_path, verbose=False):
"""
Function reads json file from path and returns list of records
:param input_file_path: path to json input file
:param verbose: defines if verbose mode
:return: list of records
"""
with open(input_file_path) as json_file:
... | 5b1075cc0848c0954d9c5ede4870eddfe0320c81 | 653,185 |
def passthrough(result):
"""Simply return the result."""
return result | 3585ed7acf9a259bb497573eb14eca2c72f6e09e | 653,187 |
def score(data_row,
positives,
negatives,
strategy = "+"):
"""
-- DESCRIPTION --
Implementations of the scoring functions described in the thesis in /docs.
This function is designed to be applied row-wise to a pandas dataframe. For
example usage refer to the scoring wo... | a6abdb354276b60a6dd48a89d76c71f788834dee | 653,188 |
def confirm_action(message: str) -> bool:
"""Basic (Y/n)? wrapper for `input`"""
return input(message)[0:1] in "Yy" | 6418fa4cbcb78808a6428edd8be7812590e83c18 | 653,190 |
def split_df(df, columns_split):
"""Split a dataframe into two by column.
Args:
df (pandas dataframe): input dataframe to split.
columns_split (int): Column at which to split the dataframes.
Returns:
df1, df2 (pandas dataframes): Split df into two dataframe based on column.
The first has the fir... | 37aee5783680f6827891c737c9a4ffb9bba89b27 | 653,196 |
def _cli_bytes_from_str(text):
"""
Python 2/3 compatibility function to ensure that what is sent on the command line
is converted into bytes. In Python 2 this is a no-op.
"""
if isinstance(text, bytes):
return text
else:
return text.encode("utf-8", errors="surrogateescape") | e710819cb60ccfcdcd0a840c20c19882fec709ea | 653,198 |
import re
def getVarList(strLine):
"""this function takes a string in the format 'i{Am}AString{With}Variables'
and parse it for included var entries '{.+}'. The return of the function in
case of the example would be: ('Am','With')
"""
result = []
if strLine is None:
return result
... | e4fc66b2af3b5ab3f9ff0e540ed33c9ae0ce9f88 | 653,201 |
import itertools
def get_all_comb(array, r=None):
""" Get all combinations of items in the given array
Specifically used for generating variant combination
Parameters
----------
array: 1D array. input array
r: int. The number of items in a combination
Returns
-------
result: List... | 9c0ec4aeb76abf8339a7bcee5741ca39203f711a | 653,202 |
def format_url(category: str, year: int, month: str, day: str) -> str:
"""
It returns a URL from The Guardian website with links for the articles of the given date
and category
:param category: A String representing the category
:param year: An integer representing the year
:param month: A Str... | 5e385659b70efea2117c8b3e5a2534448c446b63 | 653,203 |
def patch_string_from_method(method: str) -> str:
"""Get the string that indicates the method to be patched for a calling method."""
switch_dict = {
"get": "tentaclio_gs.clients.GSClient._get",
"put": "tentaclio_gs.clients.GSClient._put",
"remove": "tentaclio_gs.clients.GSClient._remove"... | 2ed1ccda154ad7f6ae1dfbad514b2a49eb5ec6c2 | 653,206 |
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
result_list = []
for idx in range(len(list1)):
if idx == 0:
result_list.ap... | 5c2bcb13e0ee24df6711323d6d0d83f7bb2343b0 | 653,208 |
from datetime import datetime
def time_to_resolve(time_received, time_resolved):
"""Returns the time taken to resolve an issue.
Args:
time_received (datetime): Datetime showing when ticket was received.
time_resolved (datetime): Datetime showing when ticket was received.
Returns:
... | 8f0b17a2ca27b57dd7187fea5accd06452087035 | 653,209 |
def count_spaces(line):
"""
Counting the spaces at the start of a line
"""
return len(line)-len(line.lstrip(' ')) | 653fb273de0f89229d777d4baaa2a551908e97c4 | 653,212 |
def search_node_from_coord(x, y, nodes):
"""Get node's number from coordinates"""
return int(nodes.loc[(nodes['x'] == x) & (nodes['y'] == y)]['n']) | e61bb8351bbad871254a29fc0586da3a0fda0b24 | 653,213 |
def data_section(values):
"""
>>> data_section(range(0, 260))
'0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,... | f7449bbcffed64c24c394abcf60b2d7334524f25 | 653,214 |
def compare_dicts(dict_a, dict_b, excluded_keys=None):
"""Compare two dict with same keys, with optional keys to exclude from compare"""
if excluded_keys is None:
excluded_keys = []
return all(dict_a[k] == dict_b[k] for k in dict_a if k not in excluded_keys) | f376c1470cafe2943a0413aaa83aff8c47180f13 | 653,216 |
import torch
def boxes_to_cornels(box_xy, box_wh):
"""Convert boxes from x_center,y_center, width, height to x_min, y_min, x_max, ymax
Parameters
----------
box_xy : torch.Tensor
Predicted xy value
shape [batch_size, num_anchors, 2, conv_height, conv_width]
box_wh : torch.Tensor
... | cc866e198012555a45ff6686fe8f5b9c787a3304 | 653,217 |
def json_default_repr(obj):
"""Converts an object into a suitable representation for
JSON-ification.
If obj is an object, this returns a dict with all properties
not beginning in '_'. Otherwise, the original object is
returned.
"""
if isinstance(obj, object):
return {k: v for k, v in obj.__dict__.ite... | a9e57daa5fe2d6f4a0ece792b04b63eb10804915 | 653,218 |
def get_col_encryption_type(col_name, integrity_info):
"""
Returns type based on whether the column is encrypted as number (OPE) or symmetrically (Fernet) or asymmetrically (ABE)- this
is based on "type" attribute in TinyDB
:param integrity_info: {
'device_data': {
'added': {... | 3d5d03bcb46433b35fb170768ac8b2310e5437ad | 653,222 |
def _interpolate_crop(start: complex, stop: complex, loc: float, axis: int) -> complex:
"""Interpolate between two points at a given coordinates."""
start_dim, stop_dim = (start.real, stop.real) if axis == 0 else (start.imag, stop.imag)
diff = stop_dim - start_dim
if diff == 0:
raise ValueErro... | 3d26955948ce44b752957099b9b81b8f7c302d29 | 653,226 |
def make_fispact_material(mat):
"""
Returns a Fispact material card for the material. This contains the required
keywords (DENSITY and FUEL) and the number of atoms of each isotope in the
material for the given volume. The Material.volume_in_cm3 must be set to
use this method. See the Fispact FUEL k... | 013fc761743bef6564e9f5a23aa36474a4bd8246 | 653,227 |
from typing import Dict
def check_keystore_json(jsondata: Dict) -> bool:
""" Check if ``jsondata`` has the structure of a keystore file version 3.
Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters.
Copied from https://github.com/vbuterin/pybitcointools
Ar... | d4b0b57b55bcaad3f4fb42a53977df0d95973579 | 653,232 |
def check_codeblock(block, lang="python"):
"""
Cleans the found codeblock and checks if the proglang is correct.
Returns an empty string if the codeblock is deemed invalid.
Arguments:
block: the code block to analyse
lang: if not None, the language that is assigned to the codeblock
... | 3e65ed5864e96b1936bc17c3769d4c524ae7b188 | 653,233 |
def build_tree(items):
"""
This function takes a Python list of items and turns it into a binary tree
of the items, suitable for casting to an s-expression.
"""
size = len(items)
if size == 0:
return []
if size == 1:
return items[0]
half_size = size >> 1
left = build_... | ec38846804a942e25d92cb77cf9e42ed91e963d6 | 653,234 |
def get_depth_fn(depth_multipler, min_depth):
"""Builds a callable to compute depth (output channels) of conv filters.
Args:
depth_multiplier: a multiplier for the nominal depth.
min_depth: a lower bound on the depth of filters.
Returns:
A callable that takes in a nominal depth and... | 523b6db58096a64e93e4fa29ee989bff2a7bfda9 | 653,240 |
def acceleration(force, mass):
"""
Calculates the acceleration through force devided by mass.
@param force: force as a vector
@param mass: mass as a numeric value. This should be not 0.
@return: acc the acceleration
>>> acceleration(300, 30)
10.0
"""
#print "mass: ", mass
#p... | 6e093d9a8dc133701196b99d70a265ff6923542a | 653,241 |
def uniform_t_sequence(steps: int):
"""
Creates a sequence of t parameters whose values are equally
spaced and go from 0 to 1 using the given number of steps.
:param steps: number of steps
:return: sequence of t values
"""
return [t / steps for t in range(steps + 1)] | 0e94d2e2488271d5f67196fdf4eda9b2ae57974c | 653,242 |
def _validate_not_subset(of, allow_none=False):
"""
Create validator to check if an attribute is not a subset of ``of``.
Parameters
----------
of: str
Attribute name that the subject under validation should not be a subset of.
Returns
-------
validator: Callable
Validat... | 8b43d44e763f0d11b4a5b4f665d8b27f69291d3b | 653,243 |
import random
import string
def random_char_sequence(y: int) -> str:
"""Creates a random char sequence of length y for the job_id name randomization"""
return "".join(random.choice(string.ascii_letters) for x in range(y)) | 39c9bccbe0ab5787b2db557cbc6c3444620861ff | 653,244 |
import copy
def copy_miscellanious(misc):
"""
Returns a deepcopy of an object
"""
return copy.deepcopy(misc) | 745b13d271324c334db07bbfccd0be4059e29fca | 653,246 |
def join(*paths):
"""
Joins multiple paths into a single path.
Arguments:
*paths -- path components
"""
path = ""
for component in paths:
path += ("/" if path and not path.endswith("/") else "") + component.replace(
"\\", "/"
)
return path | 68b41d4efdf1979347e56b69dc7eb30fc77ae875 | 653,247 |
def parse_egg_dirname(dn):
"""
Extrahiere die folgenden Informationen aus dem Namen:
- den Paketnamen
- die Versionsangabe
- das Python-Versionstupel
>>> parse_egg_dirname('visaplan.tools-1.0-py2.7.egg')
('visaplan.tools', '1.0', (2, 7))
Sonstige Namen werden nicht erkannt:
>>> pa... | 26552089764c43144f7dd9e367e21aeced4c3681 | 653,250 |
def _serialize_time(val):
"""Create a JSON encodable value of a time object."""
return val.isoformat() | 648d71ab4d23dcba787751591160286223e34bda | 653,253 |
def signed_int_str(input_int: int):
"""
Converts an integer into a string that includes the integer's sign, + or -
:param int input_int: the input integer to convert to a signed integer string
:return str signed_int_str: the signed integer string
"""
if input_int >= 0:
return '+' + str(... | b6ea5e9ccdb8a30273d3bb790a4c9bc663daedcc | 653,256 |
def handle_object_placement(handle_to_self_field, potential_object, objectType, list=False):
"""
Helper function to checks to see if we can safely set a given field (handle_to_self_field)
to a potential_object by checking whether or not it is an instance of objectType.
:param handle_to_self_... | a509460a770df829ef2f3b962febae4fcbd2aa25 | 653,257 |
def extract_ratelimit(headers_dict):
"""Returns rate limit dict, extracted from full headers."""
return {
"used": int(headers_dict.get("X-RateLimit-Used", 0)),
"expire": float(headers_dict.get("X-RateLimit-Expire", 0)),
"limit": int(headers_dict.get("X-RateLimit-Limit", 0)),
"rem... | e299d8c56b6b83ff15af096ec8c5d467f82f5ddc | 653,262 |
import math
def distance(node1,node2):
"""
Calculates distance between nodes in pixels
Parameters
----------
node1 : Treelib Node
first node
node2 : Treelib Node
second node
Returns
-------
distance : float
distance between nodes in pixels
... | c0d94ba2fbc8c36e075eeb4589b1d4e6b8f17813 | 653,266 |
def format_weather_data(data_str):
""" Take weather data in weewx format and transform to param/value dict"""
## Data sample direct from weewx (shortened)
# "altimeter: 72.317316, ... maxSolarRad: None, ... windGustDir: 359.99994, windSpeed: 5.1645e-09"
# Replace "None" values with 0's
data_str =... | 2857bae006467dc74724397507172e951f175107 | 653,274 |
def primes(imax):
"""
Returns prime numbers up to imax.
Parameters
----------
imax: int
The number of primes to return. This should be less or equal to 10000.
Returns
-------
result: list
The list of prime numbers.
"""
p = list(range(10000))
result = []
... | 84b6d0ca986923a30e877d953e2fdec3452028ec | 653,276 |
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable) | f4e27bcc1719cab16abcd048dd0ad3ee46ea2f3b | 653,279 |
def entitydata_form_add_field(form_data_dict, field_name, dup_index, value):
"""
Add field value to form data; if duplicate then reformat appropriately.
Updates and returns supplied form data dictionary.
"""
if field_name in form_data_dict:
suffix = "__%d"%dup_index
else:
suffix... | 4fdf1f0c118f2b8d0230a7ddb73fc9a94558a4ea | 653,282 |
def generate_bio_entity_tags(mentions, sentence_length):
"""
Generate BIO/IOB2 tags for entity detection task.
"""
bio_tags = ['O'] * sentence_length
for mention in mentions:
start = mention['start']
end = mention['end']
bio_tags[start] = 'B-E'
for i in range(start + ... | 22c2500d8ffc9d22b751486c076508640522da64 | 653,284 |
def parseTime(t):
"""
Parses a time value, recognising suffices like 'm' for minutes,
's' for seconds, 'h' for hours, 'd' for days, 'w' for weeks,
'M' for months.
>>> endings = {'s':1, 'm':60, 'h':60*60, 'd':60*60*24, 'w':60*60*24*7, 'M':60*60*24*30}
>>> not False in [endings[i]*3 == parseT... | 219511b772aebb09a0e0ef3cfc5d4fbfc5d18cb5 | 653,288 |
def binary_search(array, target):
"""
array is assumed to be sorted in increasing values
Find the location i in the array such that array[i-1] <= target < array[i-1]
"""
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
... | 82a60dee9f4ab337860184b9409fc0ac768501d6 | 653,294 |
def f(N1, N2, Vg1, Vg2, Ec1, Ec2, Cg1, Cg2, Ecm, e):
"""
Parameters
----------
N1 : Int
Number of electrons on dot 1.
N2 : Int
Number of electrons on dot 1.
Vg1 : Float
Voltage on gate 1.
Vg2 : Float
Voltage on gate 2.
Ec1 : Float
Charging energy ... | 9143a13db0beb6c258060734bb3bbefbcabc0305 | 653,298 |
def findChIndex(c, str_in):
"""
Version 2: Using built-in methods.
Write a python function that returns the first index of a character 'c' in string
'str_in'.
If the character was not found it returns -1.
Ex:
findChIndex('a', 'dddabbb') will return 3
findChIndex('f', ... | 42d15a998721aa4b6420014088eed896ba5c971f | 653,302 |
import copy
def plugin_init(config, ingest_ref, callback):
""" Initialise the plugin
Args:
config: JSON configuration document for the Filter plugin configuration category
ingest_ref: filter ingest reference
callback: filter callback
Returns:
data: JSON object t... | 9798d8e755fa57143eb87f52c04be70e6c384983 | 653,305 |
def is_polygon_ccw(vertices):
"""
Check if a polygon's vertices are in counter-clockwise order.
Uses the Shoelace Formula:
https://bit.ly/2t78ytv
https://en.wikipedia.org/wiki/Shoelace_formula
"""
winding_number = 0
for i in range(vertices.shape[0]):
x2_m_x1 = vertices[(i + 1) %... | 000a463ec673d02170e5a86bd35c0961025b0748 | 653,308 |
def using_apt_get_on_parrotsec(line):
"""
Checks if your image uses parrotsec and uses apt-get.
This is discouraged - you should use apt instead.
"""
return "apt-get" in line | 9cf678423f1a83673fa19ea10bb1592278297c9d | 653,309 |
from typing import Dict
def apply_substitutions(command: str, substitutions: Dict[str, str]) -> str:
"""
Given a command string (with templates) and a substitution mapping, produce a
concrete command string that can be run in a shell.
Parameters
----------
command
A string to be execu... | 4a803a655ae8148afbe60fbc537eab7d1ee09881 | 653,311 |
import math
def pi(var_lambda: float, gamma=1.4) -> float:
""""
Returns gas dynamic function pi
Parameters
----------
var_lambda: float
superficial velocity of flow
gamma: float
isentropic exponent (default 1.4)
Returns
-------
pi: float
values of GD funct... | 260a631db7e6c2cb6adef233586ac6071665b209 | 653,319 |
def get_versions(existings):
"""
Given gathered path, get all existing versions.
"""
versions = set()
for k, v in existings.items():
versions = versions.union(v)
return versions | 5f8a1b58c7812a0c2db33e5663d0e82a6dc22011 | 653,321 |
import operator
def format_as_results(sim_vec, topic_uid, doc_collection,
run_name='default_run'):
"""Formats a similarity vector as the TREC output.
The format of the system results contains 5 tab-separated
columns:
1. qid
2. iter
3. docno
4. rank
5. sim
6.... | a4c6e042c183b3aaf6d95847c6f5b6747685de41 | 653,322 |
def entry_boundaries(entry):
"""
Get the start/end of an entry and order (start < end)
"""
start = entry.start
end = entry.stop
return start, end | d3ce521c071c6882d336e93ae26ed2a5f901de41 | 653,325 |
def linear_annealing(current_timestep, final_timestep, start_value, final_value):
"""
Linearly anneals a value from an initial value to a final value, given the current percentage.
"""
# Pô <3
percentage = min(1.0, current_timestep / final_timestep if final_timestep != 0 else 0)
current_eps = (f... | de53d88fe0cc0fe6ef30aa986321cf9e56a9c24c | 653,330 |
def remove_subject(subject, metric, dict_exclude_subj):
"""
Check if subject should be removed
:param subject:
:param metric:
:param dict_exclude_subj: dictionary with subjects to exclude from analysis (due to bad data quality, etc.)
:return: Bool
"""
if metric in dict_exclude_subj.keys(... | 5f50d21f2c0f8fcec95c93855f99464d52a77d8c | 653,332 |
def flatten_binary_logits(logits, labels, ignore_index=None):
"""Flattens predictions in the batch (binary case) Remove labels equal to
'ignore_index'."""
logits = logits.view(-1)
labels = labels.view(-1)
if ignore_index is None:
return logits, labels
valid = (labels != ignore_index)
... | c09752a5d1d18689f94edd940146125a44b06172 | 653,335 |
from typing import Union
def safe_get_dict(data: Union[None, dict], key, default: dict) -> dict:
"""
This method is a safe getter function that returns a dict entry in case that the dict is provided and it contains
the key (where the value itself is a dict). Otherwise it returns the provided default value... | 08bf91ffbb4153bb29a79c1badfda13b11312e90 | 653,341 |
def get_jid(log_name):
"""Strip path and file type from the log name to return the jid as int"""
return int(log_name.split('/')[-1].split('.')[0]) | 078294e445399220e56e42e4cfdfad2fba799a1a | 653,342 |
def get_bracket_depth(idx, left_bracket_indices, right_bracket_indices):
"""
Get the bracket depth of index idx.
Args:
idx (int): the index.
left_bracket_indices (list[int]): the left bracket index list.
right_bracket_indices (list[int]): the right bracket index list.
Returns:
... | 38c3a7440ebad745312e4adf8cacdf32c836bd64 | 653,344 |
def epsilon_to_kappa(r_k, epsilon, delta=0.16):
"""Convert frequency r_k and strain epsilon
to corresponding r_k and kappa as consumed by
functions in `latticegeneration`.
Returns
-------
r_k2 : float
kappa : float
See also
--------
latticegeneration.generate_ks
"""
ret... | ad8e6f65ed3352a6920f57fe0ad4cb86f886d1ee | 653,345 |
def versions_match(versions):
"""Check if the versions are the same"""
base = None
for name in versions:
if base is None:
base = versions[name]
elif base != versions[name]:
return False
return True | 6d02c9170302a18e14dfac393f1b573d491d3545 | 653,346 |
def mk_optional_string(data, jfield):
"""
Returns either the string represented in a json structure, or an empty string if it's not present
:param data: json that may contain the jfield
:param jfield: the name of the field
:return if the field exists then it's returned; otherwise an empty string i... | ecb58a820ff6a1ea1a2a82164a648b63e1f27ac7 | 653,349 |
import re
import inspect
def get_source(match: re.Match) -> str:
"""Extract source code lines of a matched object and prepare them
to being injected into .ipynb code cell."""
match_object = eval(match.group()[9:-1])
source_lines = inspect.getsourcelines(match_object)[0]
new_lines = [line.rstrip() ... | b6fd59308852658585c3be8783bc890a20d91830 | 653,353 |
def call_behavior_action_input_pin(self, pin_name: str):
"""Find an input pin on the action with the specified name
:param pin_name:
:return: Pin with specified name
"""
pin_set = {x for x in self.inputs if x.name == pin_name}
if len(pin_set) == 0:
raise ValueError(f'Could not find inpu... | e3031c27eef654a209e98fd6fd92cefc61c0e008 | 653,354 |
def is_ipv4_address(addr):
"""Return True if addr is a valid IPv4 address, False otherwise."""
if (not isinstance(addr, str)) or (not addr) or addr.isspace():
return False
octets = addr.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
... | 2f7127019bcc069462ef85e5d15e5fb3a44add8b | 653,356 |
def _sorted_data(lb_node_pairs):
"""
Return HTTP request body to be sent to RCv3 load_balancer_pools/nodes API
from list of (lb_id, node_id) tuples. The returned list is sorted to allow
easier testing with predictability.
:param list lb_node_pairs: List of (lb_id, node_id) tuples
:return: List ... | 5ced0c4d7044dde6e90dd7de65926b82e8336916 | 653,357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.