content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def round_down(num: int, interval: int) -> int:
""" Rounds down the given number to the nearest multiple of the given interval. """
return int(num - (num % interval)) | be5ec6bf32d2c4a33299b377676f109c09e61b93 | 601,260 |
def apply_transitions(n, transitions):
"""
Applies a list of transitions (permutations of two elements)
on the first *n* integers.
:param n: number of elements in the permutation
:param transitions: list of transitions
:return: permuted ensemble
"""
ens = list(range(n))
for a, b in ... | 2ee69d6b06c192d8a19b048510c2d5a398e24591 | 601,268 |
def Diff_20(Massl, Massh, A , B, mu_solv, nul, nuh):
"""
Calculates the diffusion coefficient at 20 degrees celcium.
Parameters
----------
Massl : float
The molar mass of low-boilling component, [g/mol]
Massh : float
The molar mass of high-boilling component, [g/mol]
A : floa... | 2ca84e7425b34c1a1e783d98b64d56f844c1aa5d | 601,271 |
from datetime import datetime
def in_date_set(date_set, check_date):
"""Checks whether check_date is within any of the bounds in date_set"""
check_month = datetime(year=check_date.year, month=check_date.month, day=1).date()
for pair in date_set:
p0 = datetime.strptime(pair[0], '%Y-%m-%d').date()
... | 9923980d221c9bd7c51c9315dc33010db869bbc0 | 601,272 |
def build_process_dic(lst):
"""
Simple method to build a dictionnary for process need and results
from a list such as ['cake', '8', 'dollar', '20'] wich will result in
{'cake' : 8, 'dollar' : 20}
"""
dico = {}
i = 0
for i, elem in enumerate(lst):
if elem[-1] =... | 856e338e13cf9952ee0aaac21886cb4aa1a16a28 | 601,274 |
from typing import List
from typing import Optional
def determine_root_gpu_device(gpus: List[int]) -> Optional[int]:
"""
Args:
gpus: non-empty list of ints representing which gpus to use
Returns:
designated root GPU device id
"""
if gpus is None:
return None
assert is... | c988e01573b242ab106ef4ef406f0ba88f7533c1 | 601,277 |
def has_deployments_ended(deployments):
"""Check if deployments has ended"""
for deployment in deployments:
if not deployment.has_ended:
return False
return True | bf79303165f2847bb1678b5b333c039a884e5ad4 | 601,278 |
def join_host_port(host, port):
"""Joins a host and port"""
if ":" in host or "%" in host:
host = "[" + host + "]"
return "%s:%d" % (host, port) | bc1b7d76cbc61910402f1187c9723d6d23d03b3a | 601,280 |
import itertools
def get_combinations(the_set):
"""
Get all combinations.
Get all combinations without redraw.
Parameters
----------
the_set : set
Set of labels.
Returns
-------
list_combinations : list
List of combinations.
"""
list_combinations = list... | fbed78a6fca1f358bf784c11efcf027b4aa2bac1 | 601,281 |
def parse_headers_values(headers):
"""Parses comma seperated headers
Headers with options and values using = seperator
are trimmed from spaces.
Returns list of header options and valuea.
"""
if headers is None:
return []
return [
"=".join([value.strip(' ') for value in hea... | b6f458042c2f9e99308b404496529d505b43c71c | 601,282 |
def check_value(val, reference):
"""Return whether value matches reference
Args:
val (scalar)
reference (scalar|list|tuple)
scalar check if val == reference
list check if check_value(val, ref) for ref in reference
tuple check if reference[0]... | 507b1594e9d1808e07d9f184b9cfdd9e89afe6ce | 601,286 |
def format_header(title):
"""Formats header for a title"""
message = "\n{w" + "-"*60 + "{n\n"
message += "{:^60}".format("{w" + title + "{n")
message += "\n{w" + "-"*60 + "{n"
return message | 2c60eba1a103c390a841956baed5f0dca6a5ce01 | 601,287 |
def emptyIndex(index):
"""
Determine whether an index is empty.
@param index: An index.
@type index: L{dict}
@return: true if C{index} is empty, otherwise false.
"""
if not index:
return True
for _ignore_fieldName, fieldIndex in index.iteritems():
for _ignore_fieldValu... | 1fb36a8caf6736f0579bbd5e73221c07751d7559 | 601,291 |
def boundaries_intersection(boundaries):
"""
compute the intersections inside a boundary
:param boundaries: list of list of vertex indices corresponding to the path
:return: list of common vertices between each tuple
"""
bound_conn = []
for bound_ind1 in range(len(boundaries) - 1):
f... | 7419d388f917650abd0717d67db39b1379f2f765 | 601,292 |
def _check_set(set_, value):
"""Return true if *value* is a member of the given set or if
the *value* is equal to the given set."""
return value in set_ or value == set_ | 9b5726166fcc50420523cbcfd4edbd4b07b9057e | 601,295 |
import socket
def getIpAddress(hostname=None):
"""returns the IP address for the current, or another, hostname"""
return socket.gethostbyname(hostname or socket.gethostname()) | b0724f3c58c31748cea406c7b4337500bd6e6083 | 601,296 |
def link(method):
"""
decorator to flag an admin method as rendering a link on client list view.
:param object method: method to be flagged.
:returns: method.
:rtype: type
"""
setattr(method, 'is_link', True)
return method | 78da478aaa7cade53d6f7a70c214eabd00715e2f | 601,297 |
def commute(A, B):
""" Return the commutator of two operators"""
return A*B - B*A | 3edba7e68fe372bb619990b0b830d5e9f96e1e77 | 601,298 |
def was_active(reference_date_value, asset):
"""
Whether or not `asset` was active at the time corresponding to
`reference_date_value`.
Parameters
----------
reference_date_value : int
Date, represented as nanoseconds since EPOCH, for which we want to know
if `asset` was alive. ... | a99a49acd3f1eb278739d99660705abaa62533dd | 601,303 |
def coords_to_float(coord):
"""Convert a latitude or longitude coordinate from a string to a float, taking into account N, E, S, W.
For example, '48.2S' to -48.2
Parameters
----------
coord : str
The string form of the coordinate
Returns
-------
float
The coordinate in... | 2eafa12802cd1932ce54419414287f0a8ed0dac0 | 601,307 |
def is_attr_protected(attrname: str) -> bool:
"""return True if attribute name is protected (start with _ and some other
details), False otherwise.
"""
return attrname[0] == '_' and attrname != '_' and not (
attrname.startswith('__') and attrname.endswith('__')) | 7011ff6f091379f56d3c1fb4ee5555165d8bf0a3 | 601,314 |
import shlex
import pipes
def shell_escape( cmd ):
"""
Returns a string with shell special characters escaped so they are not
interpreted by the shell.
The 'cmd' can be a string or a python list.
"""
if type(cmd) == type(''):
return ' '.join( [ pipes.quote(s) for s in shlex.split( cmd... | ee0a93e8463f665667c0c8f879ff87ec647a120c | 601,315 |
def make_sequence(elements):
"""
Ensure that elements is a type of sequence, otherwise
it converts it to a list with only one element.
"""
if isinstance(elements, (list, set, tuple)):
return elements
elif elements is None:
return []
else:
return [elements] | b1254c493fb1ce0dffb0e43ae2d25325557e234e | 601,318 |
def getfield(prop, field):
"""Attempt to fetch the text contents of an XML tag"""
return prop.find(field).next if prop.find(field) else None | d4a641da73d730f2fb8a0e10b6c504fcc178c8c6 | 601,319 |
def _entities_to_choices(entities, answer):
"""Generate a multichoice question template."""
if len(entities) > 26:
raise ValueError('Too many choices: {}'.format(len(entities)))
entity_dict = {}
choices_template = ''
answer_choice = None
for i, entity in enumerate(entities):
choices_template += ' ... | 4d1682782f2dc0235bd2471a945c2cb1fecd2c05 | 601,320 |
def buildTabs(substrate, partitionLines, tabAnnotations):
"""
Given substrate, partitionLines of the substrate and an iterable of tab
annotations, build tabs. Note that if the tab does not hit the partition
line, it is not included in the design.
Return a pair of lists: tabs and cuts.
"""
t... | efc0e2c668858afd73d2c9f90a838365057f6008 | 601,321 |
def get_mean_accuracy(n):
"""
Get the mean accuracy from a confusion matrix n.
Parameters
----------
n : dict
Confusion matrix which has integer keys 0, ..., nb_classes - 1;
an entry n[i][j] is the count how often class i was classified as
class j.
Returns
-------
... | 8c505f3cd660f3a5096c00bb04ee0d996aa974cb | 601,326 |
import time
def f_seen(self, origin, match, args):
""".seen <nick> - Reports when <nick> was last seen."""
if not match.group(2):
return self.msg(origin.sender, 'Please provide a nick.')
nick = match.group(2).lower()
if not hasattr(self, 'seen'):
return self.msg(origin.sender, '?')
... | a780a13b81e01128f3903bb2e3db2c8ab9f867c5 | 601,327 |
def _assert_compatible(image_1, image_2):
"""Raise an error if the shape of image_1 and image_2 do not match."""
if not image_1.shape == image_2.shape:
raise ValueError('Input images do not have the same dimensions.')
return None | 824b1f2806d29f38869216e0992a4a97893bf252 | 601,329 |
def repeat(phrase, num):
"""Return phrase, repeated num times.
>>> repeat('*', 3)
'***'
>>> repeat('abc', 2)
'abcabc'
>>> repeat('abc', 0)
''
Ignore illegal values of num and return None:
>>> repeat('abc', -1) is None
True
>>> repeat(... | c98f98bc3d3fa29068666066cca446f989ad3711 | 601,336 |
def propertyfrompropid(propid):
"""Convert int propid to R0* padded string."""
strid = str(propid)
idlen = len(strid)
prefix = 'R'
padding = 4 - idlen
if padding > 0:
prefix += '0' * padding
return prefix + strid | 7f12a85ae92146315c2a1570d4e6f1a9f0517cd7 | 601,337 |
def make_response(status, message):
"""
<Purpose>
Generates a http_response_dict with variable message and statuscode.
<Arguments>
status (int)
HTTP status message.
message (string)
HTTP payload
<Returns>
http_response_dict (dict)
"""
http_response_dict = {"version"... | d01359318bec1659af75ada77327c96594e6b92d | 601,338 |
import multiprocessing
async def get_num_processors():
"""Get the number of processors on this machine"""
return multiprocessing.cpu_count() | 72f5c3c9537bad19787a6750800d9655d9366c32 | 601,340 |
def page_authors_summary(page, config: dict):
"""
A summary of the authors' contributions on a page level
Args:
page (Page): Page class
config (dict): plugin's config dict
Returns:
str: HTML text with authors
"""
authors = page.get_authors()
authors_summary... | e65f7865f348a25183291f99378bb9b13ed3c9f1 | 601,342 |
def create_from_or(wlk, tree):
"""
For each subtree under the OR, create a new set of query params.
"""
params = []
for sub in tree.attrs:
sub_params = wlk.create(sub)
# Strip out one layer of nesting of lists
# This means that create always returns a list of dicts.
... | 7119b2c92efd35f2b875a83e7340327722730ee5 | 601,343 |
import random
def randfloat(lo, hi):
"""
Return random float between `lo` and `hi`
"""
return lo + random.random() * (hi - lo) | 0bbd28869ce01badf684f49e5ac97d29f7c2ec8e | 601,344 |
def cr_uid_id_context(method):
""" Decorate a traditional-style method that takes ``cr``, ``uid``, ``id``,
``context`` as parameters. Such a method::
@api.cr_uid_id
def method(self, cr, uid, id, args, context=None):
...
may be called in both record and tradi... | b19cb6d6ea09552998eee81b6fd4f150013e609b | 601,345 |
def is_integer(number: str) -> bool: #Shares name with the float method
"""Returns whether or not the given string is an integer."""
return number.replace('.', '', 1).isdecimal() and float(number).is_integer() | ffc1e3224977315a73a8c42055167087554af24a | 601,346 |
import time
def dateToTime(date):
"""
Takes as input a datetime object and outputs the seconds since epoch.
"""
return time.mktime(date.timetuple()) | 6cf7808948560d6add4550ee074e690f3f07258a | 601,351 |
def mult(num1, num2):
"""
Function to multiply two Numbers
"""
return num1 * num2 | 35c58758a22a9b39f68293c76e37650f14b042ab | 601,355 |
import itertools
def nQubit_Prep(n, overdetermined=False):
"""
Generate a list of preparation states corresponding to the
axes of the Bloch sphere. For QPT it is enough to take
all of the +ve eigenstates of the Bloch sphere
and a single -ve eigenstate. For this reason we take
[0, 1, +, +i] as ... | 052db5b753fd43d6fbfa48ccdc3314900cd777b4 | 601,358 |
def update_agent_properties(input_dict, original_string, secret_name):
"""
Replace any agent configuration SSH key settings in a provided dict.
"""
changed = False
for agent_config_key in ('agent_config', 'cloudify_agent'):
if agent_config_key in input_dict:
key = input_dict[... | 722c02e06743b570163149b686bbb06bdc72f111 | 601,360 |
def offset_from_utc(meta):
"""Check whether the metadata set has time zone offset metadata,
if exist, return its value, if not, return False.
:param meta: Metadata dictionary
:return:
"""
for key, val in meta.items():
if isinstance(val, dict):
if 'offsetfromutc' in val:
... | 8cd91c970bcdc3fcd637da3efecc3d874c4f292d | 601,363 |
def calc_percentage(dictionary: dict) -> dict:
"""
Calculates the percentage of each value for every key in the dictionary.
:param dictionary: The dictionary containing keys and the corresponding int or float values.
:return: A dictionary containing the keys of the given dictionary and their percentage... | 7aa7cd0b917c32896cec015a75c91c1206b06aed | 601,367 |
def different_voltage_levels_connected(net):
"""
Checks, if there are lines or switches that connect different voltage levels.
INPUT:
**net** (pandapowerNet) - pandapower network
OUTPUT:
**check_results** (dict) - dict that contains all lines and switches that connect
... | ddf2f6fd89d6a9549ad82a6688a2cdb7ad8df605 | 601,374 |
def add_n_delay(identifier, delay_input, delay_time, initial_value, order,
subs, subscript_dict):
"""
Creates code to instantiate a stateful 'Delay' object,
and provides reference to that object's output.
The name of the stateful object is based upon the passed in parameters,
so if ... | 64a77a22fad918a03861f303aecaf0461e939a81 | 601,377 |
def northPlaceCheck(shipSize, yIndexStart, xStart, yAxis):
"""Given a start position on the y index and a ship size will check if
if the y position is a valid location.
Args:
shipSize (INT): Ship size taken from Ship Class
yIndexStart (INT): Start index location
xStart (STR): The st... | 3ba98ab4892548f40e78ba45b9999c3878d4fda1 | 601,381 |
def invalid_resource(message, response_code=400):
"""
Returns the given message, and sets the response code to given response
code. Defaults response code to 400, if not provided.
"""
return {"message": message, "code": response_code} | c9e1d3f15f67e66bb1069b57b1764232acac7442 | 601,382 |
def _create_discrete_set_filter(discrete_set):
"""Returns a function that checks whether a value belongs to a set.
Args:
discrete_set: A list of objects representing the set.
Returns:
A function taking an object and returns True if its in the set. Membership
is tested using the Python 'in' operator (... | dd2d7320bbc52ba590491a2be680437d42555768 | 601,383 |
def diff_log_groups(log_group_options, old_log_group_options):
"""Upon a CloudFormation stack Create or Update event, logGroupOptions is passed in the
event parameter to Lambda. Upon a CloudFormation Update event the old logGroupOptions is also
provided. These two dicts are compared to return three sets of... | 603b72a0339090eef28fa47310e2f58ad42657fd | 601,386 |
import random
def random_connectivity_graph(n_s, min_neighbors=2, max_neighbors=3):
"""
:param n_s: total number of servers
:param min_neighbors: minimum nunmber of connections at least 2 to make a ring
:param max_neighbors: largest number of connections
:return: a random directed graph (possibly ... | 589d3724df7dbf46b10fa48c3ff9b55f16803e2f | 601,390 |
import csv
def read_csv_file(filename):
"""Reads a CSV file and return it as a list of rows."""
data = []
for row in csv.reader(open(filename),delimiter=','):
# transfer the string type to the float type
row=list((float(x) for x in row))
data.append(row)
return data | bd61f3a1de918476100551c77c6980b3b05015f3 | 601,391 |
from typing import Optional
from typing import Sequence
import difflib
def best_match(needle: Optional[str], haystack: Sequence[str]) -> Optional[str]:
"""Finds the closest match of a given string in a list of potential strings."""
if not needle or not haystack:
return None
matches = difflib.get_... | d5296fec16c6e570576eacd8a81f56093e5b15f7 | 601,392 |
def ping(*args):
"""Return the arguments passed to the function."""
return list(args) | 4bf1c8d52dffe2a302b5ebbdd1e22deb31e18c33 | 601,396 |
def cutsite_read(ligation_sites, seq, qual):
"""Find ligation sites in a given sequence and return list of the fragmented
sequence and quality.
Parameters:
-----------
ligation_sites : re.Pattern
Regex of all possible ligations according to the given enzymes.
seq : str
Sequence ... | e1b59c60697b21816b95f911c3f1399ffda28abc | 601,399 |
import json
def save_json(filename, data):
"""Write data to a file"""
with open(filename, encoding='utf-8', mode='w') as f:
json.dump(data, f, indent=4, sort_keys=False, separators=(',', ': '))
return data | 02ffb02d693aa48b11e62034df2faa1c488fc29c | 601,400 |
import shutil
def tempfiles(tmpdir, filespath):
"""Fixture for copying test files into a temporary directory"""
dest = tmpdir.join('testfiles')
shutil.copytree(filespath, str(dest))
return str(dest) | 88dafc571a6c4bc678ce18463122abe994cb6dd0 | 601,403 |
def getFirstPlist(textString):
"""Gets the next plist from a text string that may contain one or
more text-style plists.
Returns a tuple - the first plist (if any) and the remaining
string after the plist"""
plist_header = '<?xml version'
plist_footer = '</plist>'
plist_start_index = textStr... | 4cb6b2c3e46e6a9df922d9e01cd0e59bd5eba517 | 601,404 |
def nts(s, encoding, errors):
"""
Convert a null-terminated bytes object to a string.
Taken from tarfile.py.
"""
p = s.find(b"\0")
if p != -1:
s = s[:p]
return s.decode(encoding, errors) | 995e5fd90de242ccd9fdd443b99ea8aed74900b5 | 601,406 |
def translate_crops(crop_tuples, translate_tuple):
"""Translate crop tuples to be over the image are, i.e. left top at (0,0)."""
crop_tuples_translated = []
for crop_tuple in crop_tuples:
crop_tuples_translated.append(
(crop_tuple[0] - translate_tuple[0],
crop_tuple[1] - tra... | c0a4867cedc56a20cbc178e16a2f8395ccbdb65d | 601,410 |
def brutal_bounce(
new_config,
new_app_running,
happy_new_tasks,
old_app_live_tasks,
):
"""Pays no regard to safety. Starts the new app if necessary, and kills any
old ones. Mostly meant as an example of the simplest working bounce method,
but might be tolerable for some services.
:para... | a92207ff30dce978e3de3020d6be5e4101455354 | 601,412 |
def remove_topos(text, stops=["mataró", "mataro", "maresme", "catalunya"]):
""" Delete toponyms. """
text = text.lower().split(" ")
for i, word in enumerate(text):
if word in stops:
del text[i]
return " ".join(text) | 97cb15850b906d55f4d37bdae384224541df56c8 | 601,418 |
def get_header(filename):
"""
Returns each line of the input header as a list.
"""
header = []
f = open(filename, 'rb')
for l in f.readlines():
if l[0] == '#':
header.append(l)
else:
break
return header | 73add144d5fe4d5a0b7e450b46131635414e9e27 | 601,419 |
from datetime import datetime
def get_days_ago(datetime_obj):
"""
Converts a datetime object to "time ago" string
:param datetime_obj: Datetime
:return: "time ago" string
"""
days_ago = (datetime.now() - datetime_obj).days
datetime_str = "Today"
if days_ago == 1:
datetime_str =... | 3e8e3f19428198b29fb0ac407b542fb60cee99fc | 601,421 |
def volume_cube(d):
"""Returns volume of unit ball (wrt sup norm) in d-dim euclidian space."""
return 2 ** d | 11abdad3a27b0ebe0b17e3743387c677190f1abc | 601,423 |
def trade_duration_map_nb(record):
"""`map_func_nb` that returns trade duration."""
return record['exit_idx'] - record['entry_idx'] | 4f79d25df21bbad95dd4124ca8648dd6b90032ab | 601,424 |
import torch
def get_inverse_softplus_offset(offset):
"""Get inverse offsetted softplus."""
def inverse_softplus_offset(x):
return torch.log(x.exp() - 1) + offset
return inverse_softplus_offset | 0ddf8efd49a839a9ad09e3818c93473580ff7024 | 601,432 |
def get_tags_for_domain(domain):
"""Return relay domain custom tags."""
if domain.type != "relaydomain":
return []
return domain.relaydomain.tags | 8263141d7cda69772477eec7ce0fe3848c61488f | 601,436 |
def partition(items, low, high):
"""Return index `p` after in-place partitioning given items in range
`[low...high]` by choosing a pivot (The last item) from
that range, moving pivot into index `p`, items less than pivot into range
`[low...p-1]`, and items greater than pivot into range `[p+1...high]`.
... | 4feae4e599da71e3abd37021e35cdfc580378f8f | 601,438 |
def remove_dot_git(url_with_dot_git):
"""
Removes trailing .git in repo name or url
:param url_with_dot_git:
:return:
"""
url = url_with_dot_git.split('.git')[0]
return url | 4e9932d6268ba8dbd41afc42443c2a791ac396bd | 601,443 |
import string
from typing import Optional
from typing import List
def normalize_name(character_name: str, allowed_double_names: Optional[List[str]] = None) -> str:
"""
Ensures consistency for a character's name. For some scripts, "Jaime Lannister" is listed as "Jaime", "JAIME",
etc.
Parameters
-... | c8dc419d2cc58c8286835972928ec4394262a0b4 | 601,445 |
def _get_window_sizes(num_adaptation_steps):
"""Hardcoded way to get a reasonable scheme.
This assumes we do something proportional to
fast window: 75 steps
slow window: 25 steps
slow window: 50 steps
slow window: 100 steps
slow window: 200 steps
fast window: 50 steps
Which is a total of 500 steps.... | 5d528e41d45cc29ef0b9a9f563a07f1542c83c77 | 601,451 |
def read_header(fp, lines=300):
"""Read only the OpenITI header of a file without opening the entire file.
Args:
fp (str): path to the text file
lines (int): number of lines at the top of the file to be read
Returns:
(list): A list of all metadata lines in the header
"""
wi... | d6a718d21d23f376aa064d1bb5e44941454ffbf2 | 601,454 |
def get_folders_in_gcs_path_prefix(gcs_client,
bucket,
prefix_path,
recursive=True):
"""
This function lists all folders in a given GCS path using a more
efficient prefix filtering method so it only list... | 9d70d84872069fca05c87ff150b60d4e0c235b36 | 601,456 |
def toYelpScore(sentiment):
"""
Transforms a normalized sentiment analysis polarity rating to the Yelp 5 star format.
Arguments:
sentiment {Double} -- Polarity rating.
Returns:
Double -- Transformed polarity rating.
"""
return (sentiment*4)+1 | 82d9985ab6c314a159b15438a37e1f0f670aac86 | 601,461 |
def clamp(value: float, minimum: float, maximum: float) -> float:
"""Clamp a value between two numbers
Parameters
----------
value
The value to clamp
minimum
Minimum acceptable value
maximum
Maximum acceptable value
Returns
-------
float
The clamped ... | 5eab0017f779be59a6a597a47cca85437baf7af7 | 601,468 |
from typing import List
def find_common_prefix_len(prefix1: List, prefix2: List) -> int:
"""Returns common prefix size of the given two prefix sequences.
"""
result = 0
for index in range(min(len(prefix1), len(prefix2))):
if prefix1[index] == prefix2[index]:
result = index + 1
... | 95dfef4707e9d4129cba1d0eb5f9186d4d8e0ed0 | 601,472 |
def parseFloat(val):
"""Parse float from given string"""
return float('0' + str(val)) | 9bda9e796b5b2a27a5962dd7ac67d41bea8f417a | 601,473 |
def check_only_uk_data(nat_geo_series, geo_disag_series, uk_terms):
"""Checks if Both of these conditions need to met
1) value in the national_geographical_coverage is listed in uk_terms
2) value in geo_disag column is FALSE
and returns True if conditions are met, False otherwise.
Fu... | aa151c56f18934027dbfcdd1ffd740d026e9aeb6 | 601,474 |
def _calc_ilm_order(imshape):
"""
Calculates an ilm order based on the shape of an image. This is based on
something that works for our particular images. Your mileage will vary.
Parameters
----------
imshape : 3-element list-like
The shape of the image.
Returns
-------... | b52ebeb5247166ec084f5bd98332fcdfd7f1b830 | 601,476 |
def lower_case_underscore_to_camel_case(string):
"""Convert string or unicode from lower-case underscore to camel-case"""
splitted_string = string.split('_')
# use string's class to work on the string to keep its type
class_ = string.__class__
return class_.join('', map(class_.capitalize, splitted_s... | 5aa356e2d9be0b7ad0184643cb593b442aa3b77b | 601,477 |
from pathlib import Path
def get_template_paths(start_dir, extension_wildcard="*.conftpl"):
""" Returns a list of paths of identified templates. """
return Path(start_dir).rglob(extension_wildcard) | 10aa076a6c11389ce66589186beae5c0af91429d | 601,482 |
import pathlib
def sample_patch3(remote_sample) -> pathlib.Path:
"""Sample pytest fixture for sample patch 3.
Download sample patch 3 (PCam) for pytest.
"""
return remote_sample("sample-patch-3") | de54e802f486ba38d9e8875107f41d19028da934 | 601,483 |
import pickle
def readPickle(fileName):
"""
Reads a saved pickle.
"""
fileObj = open(fileName, 'rb')
outputObject = None
try:
outputObject = pickle.load(fileObj)
print('File Loaded at: ', fileName)
except:
print('Loading Failed.')
fileObj.close()... | 5e6d02722d531b01ca748b96f173ba6b3d0546af | 601,484 |
def prune_none(data):
"""removes keys where the value is `None`,
i.e. metrics which could not be computed"""
return {k: v for k, v in data.items() if v is not None} | c1ab821832d72bdca287a063a7411f6df4a7eb57 | 601,486 |
def remove_forbidden_characters(name):
"""
A function that will remove all the forbidden characters from the string. The forbidden characters are the ones
that are not allowed to be used in the names of windows files. Those are --> r'/*=:<>"|\'.
Parameters:
name : string
Returns
... | 15779459ea54bde04523afac60174f95ee2e4689 | 601,487 |
from datetime import datetime
def get_file_facts(database, ftp):
"""Get size and last modified date of a file in FTP directory.
Parameters:
database (str): Name of CDD database to check
ftp (str): FTP connection
Returns:
size (int): Size of file
date (str): Last modified d... | d72c2e068556e949ae208c76507437d0a86df1fa | 601,488 |
def is_oppo_clearance(event_list, team):
"""Returns whether an opponent cleared the ball"""
clearance = False
for e in event_list[:1]:
if e.type_id == 12 and e.team != team:
clearance = True
return clearance | e98751bebe29e2fd765e2dc2e33381080705f25a | 601,489 |
import re
def islongitude(value):
"""
Return whether or not given value is valid longitude.
If the value is valid longitude, this function returns ``True``, otherwise ``False``.
Examples::
>>> islongitude('+73.234')
True
>>> islongitude('180.1')
False
:param val... | 9f8c8b05423ff423a166a29948436770e365b36f | 601,491 |
def _TIME2STEPS(time):
"""Conversion from (float) time in seconds to milliseconds as int"""
return int(time * 1000) | 386e5a8857f4c03419ce2a4d96643ad638bea90f | 601,492 |
def real_number_batch_to_indexes(real_numbers, bins):
"""Converts a batch of real numbers to a batch of one hot vectors for the bins the real numbers fall in."""
_, indexes = (real_numbers.view(-1, 1) - bins.view(1, -1)).abs().min(dim=1)
return indexes | e7594fb8517d7cdfbe78c3899e68c253519379b5 | 601,496 |
def get_account_idx_for_deploy(accounts: int, deploy_idx: int) -> int:
"""Returns account index to use for a particular transfer.
:param accounts: Number of accounts within batch.
:param deploy_idx: Index of deploy within batch.
:returns: Ordinal index of account used to dispatch deploy.
"""
... | 1254e427b04c1b012b96f15640645fd556c1cd49 | 601,497 |
import re
def parse_fasta(entry):
"""parse_fasta(entry) -> dict. entry is a string.
Parse a string representation of a single FASTA entry into a dict.
The returned dict has values for 'name' and 'sequence'."""
if not entry.startswith('>'):
raise TypeError("entry does not start with '>'")
... | 9203981ebdf4e0e22d7c8b6cbd24f71257772588 | 601,502 |
def linebreak_removal(source_list):
"""
Remove line breaks from a block of text
"""
source_str = str(' '.join(source_list))
source_str = source_str.replace('\n', '')
single_str = source_str.replace('\r', '').replace('\n', '')
return(single_str) | 0316183f495cfd3367592684d615842a5fc2716f | 601,507 |
from pathlib import Path
import re
def get_version(package):
"""Get current version."""
version = (Path("src") / package / "__version__.py").read_text()
match = re.search("__version__ = ['\"]([^'\"]+)['\"]", version)
assert match is not None
return match.group(1) | d8a2dc3818a24aa144efefc9cc2bda4fd69906d5 | 601,514 |
def convert_rawdata(data_str):
"""Parse a C++ rawdata declaration into a list of values."""
start = data_str.find('{')
end = data_str.find('}')
if end == -1:
end = len(data_str)
if start > end:
raise ValueError("Raw Data not parsible due to parentheses placement.")
data_str = data_str[start + 1:end]... | 8d10553e64df07c7fb4b7e06058d0601fe3c5836 | 601,516 |
def maybe_localizer(label: str) -> bool:
"""Detect if label is maybe a localizer label"""
return '_' not in label and len(label) < 7 | a91ae2e9e4e977fc53498f62016f9235408bd1c1 | 601,518 |
def is_type_or_null_property(property_):
"""
Serpyco use "anyOf" (null, or defined type) key to define optional properties.
Example:
``` json
[...]
"properties":{
"id":{
"type":"integer"
},
"name":{
... | 4400bbc7fae9c84331db651322e757d755f2d792 | 601,524 |
def get_best(current, candidate):
""" Return the new bunnies saved if the given candidate did saved
more bunnies than the current
Args:
current (list[int]): sorted list of bunnies
candidate (set[int]): unordered collection of saved bunnies
Return:
list[int]: bunnies saved sorted ... | 4ea707c06289adcda3c3a2fade5909ebfb5e8c37 | 601,525 |
def fasta_to_sequence(fasta):
""" Convert a multiline fasta sequence to one line sequence"""
f = fasta.strip().split("\n")
if len(f) > 0:
return "".join(f[1:])
else:
return "" | 2e3195407bbb6fa83bbfbdc7fbab9eb5eff4709e | 601,532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.