content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_new_id(identifier, width):
""" Given an identifier, gets the next identifier.
:param identifier: the last identifier known.
:param width: the width of the identifier.
:return: the next identifier.
"""
if identifier.lstrip('0') == "":
identifier = str(1)
else:
identi... | 339eeb1032fe69e27428601e8f10df367276e5a0 | 35,532 |
def point_interval(ref_features, sec_features, disp):
"""
Computes the range of points over which the similarity measure will be applied
:param ref_features: reference features
:type ref_features: Tensor of shape (64, row, col)
:param sec_features: secondary features
:type sec_features: Tensor ... | 22f1477ec4ef86f343969f6316771f3ebb21d085 | 35,533 |
def quadratic_fit_search(f, a, b, tol=1e-6):
""" Impelements the Quadratic Fit Search method to find the minimum for
a single variable function.
Args:
f: Objective function
a: Lower bound of the search interval
b: Upper bound of the search interval
tol: Tolerance fo... | 691c76bdad0e0f2da14962180fd8ad568729903f | 35,534 |
def _remove_pageoutline(text: str):
"""
Remove any TracWiki PageOutline directives
"""
return text.replace('[[PageOutline]]', '') | 72642413d11b5251c4f981a48ce7eb582cc9baf7 | 35,535 |
from typing import Union
def factor_in_new_try(number: Union[int, float], try_count: int) -> Union[int, float]:
"""Increase the given number with 10% with each try."""
factor = float(f"1.{try_count}")
return int(number * factor) | 7cf66263b9e05be3ae51b55ef35a9a131433484f | 35,536 |
import tempfile
def get_temp_dir(prefix='tmp-cegr-', dir=None):
"""
Return a temporary directory.
"""
return tempfile.mkdtemp(prefix=prefix, dir=dir) | 3abd323f97e72edb66d6bc00c6d08459a37f962a | 35,537 |
def _cafec_coeff_ufunc(actual,
potential):
"""
Vectorized function for computing a CAFEC coefficient.
:param actual: average value for a month from water balance accounting
:param potential: average potential value from water balance accounting
:return CAFEC coefficient
... | 9e0b4201dff2acb6170b9719558da494f15ad6e7 | 35,538 |
from typing import List
import random
def sample_floats(low: float, high: float, k: int = 1) -> List[float]:
"""Return a k-length list of unique random floats in the range of low <= x <= high."""
seen = set()
for _ in range(k):
x = random.uniform(low, high)
while x in seen:
x =... | 9dcbef61809e1cfc3cc3748338137e4d48a95059 | 35,539 |
import os
def get_biocode_script_dict(base):
"""
Returns a dict where each key is a script category 'fasta', 'blast', etc.
and the values are the names of the scripts within that directory
"""
d = dict()
for directory in os.listdir(base):
if directory in ['build', '.git', 'sandbox', '... | d53bfe35bc0d9f489b30817cb787ba1892ffa333 | 35,540 |
def make_list(value):
"""
Takes a value and turns it into a list if it is not one
!!!!! This is important becouse list(value) if perfomed on an
dictionary will return the keys of the dictionary in a list and not
the dictionay as an element in the list. i.e.
x = {"first":1, "second":2}
... | 9616ef3c265c308ec667aaee43a68b70f5f4138f | 35,541 |
import collections
def _defaultdict_of_lists():
"""Returns a defaultdict of lists.
This is used to avoid issues with Windows (if this function is anonymous,
the Echo dataset cannot be used in a dataloader).
"""
return collections.defaultdict(list) | d1931c5a264a005202b744c42c90b22da9fbda8f | 35,542 |
import functools
import sys
import traceback
def system_exit(object):
"""
Handles proper system exit in case of critical exception.
Parameters
----------
object : object
Object to decorate.
Return
------
object
"""
@functools.wraps(object)
def system_exit_wrapper... | 1d2c4f907650cdb2f17590171c20ab0404efeeee | 35,544 |
def escape_invalid_characters(name, invalid_char_list, replace_with='_'):
"""
Remove invalid characters from a variable and replace it with given character.
Few chars are not allowed in asset displayname, during import/export
Escape those chars with `replace_with` and return clean name
Args:
... | 47359202f0cee82426d35ec5a85d315d96ece1d7 | 35,545 |
def _estimate_step_number(n_points: int, batch_size: int) -> int:
"""Estimates which step this is (or rather how many steps were collected previously, basing on the ratio
of number of points collected and the batch size).
Note that this method is provisional and may be replaced with a parameter in the conf... | c097140107c458f0517d9f616b20d88ef0268e15 | 35,547 |
def normalize_ordinal(ordinal):
"""
Given a string like "first" or "1st" or "1", return the canonical version ('1').
"""
return ordinal[0] if ordinal[0].isdigit() else str('ieho'.index(ordinal[1].lower()) + 1) | eceb5e26c54ce987eb65ce40c711000cc3164086 | 35,548 |
def chrange(start, end):
"""Generates a range of characters from start to end
:param start: a character, eg. 'b'
:type start: character (1 element string)
:param end: a character, eg. 'b'
:type end: character (1 element string)
:example:
>>> chrange('d','f')
... | 5cc18eec2aa33f6f27436a60eb01a04f2a974f04 | 35,549 |
import logging
def _makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
"""
A factory method which can be overridden in subclasses to create
specialized LogRecords.
"""
rv = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func)
if extra is not None:
... | dd12f3b8d7e0e342770f8e14cadfa5e1e8f47c64 | 35,551 |
def _is_valid_perm(perm):
"""Check string to be valid permission spec."""
for char in perm:
if char not in 'rwcda':
return False
return True | 357330ee32c2ed0c4ae537f5a9a8b7d08fb1918a | 35,552 |
import os
def file_path(filepath: str) -> str:
"""Special type for argparse, a filepath."""
if os.path.isfile(filepath):
return filepath
else:
raise FileNotFoundError(filepath) | 10936130f299252b56e68e6840503f332455ff28 | 35,553 |
def comp_height(self):
"""Compute the height of the Hole (Rmax-Rmin)
Parameters
----------
self : Hole
A Hole object
Returns
-------
H : float
Height of the hole
"""
(Rmin, Rmax) = self.comp_radius()
return Rmax - Rmin | 4dbab93edbe3d7f277480e96b4a5e885e6e9161e | 35,554 |
import random
def GenerateRandomChoice(choices, prev=None):
"""Generates a random choice from a sequence.
Args:
choices: sequence.
Returns:
A value.
"""
return random.choice(choices) | 1d38dd313b19f235d4ea367e841ce7e74ee8f69b | 35,555 |
def list2pairs(l):
"""
Turns any list with N items into a list of (N-1) pairs of consecutive items.
"""
res = []
for i in range(len(l)-1):
res.append((l[i], l[i+1]))
return res | b1c3770e66354862d2dd96eedd473582549aae96 | 35,556 |
def normalize_br_tags(s):
"""
I like 'em this way.
>>> normalize_br_tags('Hi there')
'Hi there'
>>> normalize_br_tags('Hi <br>there')
'Hi <br />there'
>>> normalize_br_tags('Hi there<br/>')
'Hi there<br />'
"""
return s.replace("<br>", "<br />").replace("<br/>", "<br />") | 21df28ca4a8bfc03375d2e07e8a1b3840d840557 | 35,557 |
def filter_none_values(kwargs: dict) -> dict:
"""Returns a new dictionary excluding items where value was None"""
return {k: v for k, v in kwargs.items() if v is not None} | f5a1f767291a72ebeac7b92c0bbe78b890330916 | 35,558 |
def radix_sort(array, base=10):
"""
Fuction to sort using radix sort algorithm
<https://en.wikipedia.org/wiki/Radix_sort>.
:param array: A list of elements to sort.
:param base: Integer number to represent base number
"""
maxLen = len(str(max(array)))
for i in range(maxLen):
... | 3d88977389a86360e48813d9c01ae00bf5a18a0b | 35,559 |
def mapContactsToLDAP(contact_list):
"""Create a payload for ldap_updater module calls.
Generate a list of dictionaries mapping Insightly properties to LDAP attributes.
Args:
contact_list (List): A list of contacts as JSON from Insightly to be converted into LDAP-like dictionaries.
Returns:
... | d05cb72fa6039929e8aa65b5fab91f1e865c1691 | 35,560 |
import os
def getConfig(ir, memconfig_file_path):
""" Gets the arrays to be partitioned from the memconfig file """
if not os.path.isfile(memconfig_file_path):
print("\tUser did not specify any arrays to partition")
return []
configFile = open(memconfig_file_path,'r')
partitions=[]
... | 3c5c85c8d1c337211a1d1070970555c293026070 | 35,562 |
from typing import List
import yaml
def get_training_class_names(training_config_file: str) -> List[str]:
"""get class names from training config file
Args:
training_config_file (str): path to training config file, NOT YOUR MINING OR INFER CONFIG FILE!
Raises:
ValueError: when class_name... | 4caba056481c653f97d5bb0b0f007cea20494412 | 35,563 |
def anticom(A,B):
"""
Compute the anticommutator between matrices A and B.
Arguments:
A,B -- square matrices
Return:
antcom -- square matrix of the anticommutator {A,B}
"""
antcom = A.dot(B) + B.dot(A)
return antcom | 734f435228fe3c69b52f3c5e8cc09e7f79bd01ce | 35,564 |
def html_attrs_tuple_to_string(attrs):
"""Converts a set of HTML attributes tuple to an HTML string.
Converts all HTML attributes returned by
:py:meth:`html.parser.HTMLParser.handle_starttag` ``attrs`` value into
their original HTML representation.
Args:
attrs (list): List of attributes, e... | 71d31439f1a18a90483097c70aa09c3f9448ac5d | 35,565 |
import json
def json_file_to_dict(file_path):
"""load a dict from file containing JSON
Args:
file_path (str): path to JSON file
Returns:
json_dict (dict): object representation of JSON contained in file
"""
return json.loads(open(file_path, "r").read()) | bf95cdf3ba049718caf2a5ca38ba3293c2eb308e | 35,568 |
import re
def restore_dash(arg: str) -> str:
"""Convert leading tildes back to dashes."""
return re.sub(r"^~", "-", arg) | 63313a006ed934eff1ca83486a3dde4f6ea9ef74 | 35,569 |
import hashlib
def __mysql_password_hash(passwd):
"""
Hash string twice with SHA1 and return uppercase hex digest,
prepended with an asterisk.
This function is identical to the MySQL PASSWORD() function.
"""
pass1 = hashlib.sha1(passwd.encode('utf-8')).digest()
pass2 = hashlib.sha1(pass1)... | f505025ea0459d42f118698c476fa83afb63f382 | 35,572 |
def extract_version_fields(version, at_least=0):
"""
For a specified version, return a list with major, minor, patch.. isolated
as integers.
:param version: A version to parse
:param at_least: The minimum number of fields to find (else raise an error)
"""
fields = [int(f) for f in version.st... | 04209b0029160b19bbdb80d45f560c696214f90a | 35,573 |
import argparse
import sys
def get_cmdline_args():
"""Parse cmdline and return Namespace."""
parser = argparse.ArgumentParser(
description="Multi QR code generator: reads data from file "
"(or stdin), writes HTML for printing to stdout.",
)
parser.add_argument('--title', help="title fo... | f41acdc9d3ccff3301224bef3e7cc41a40cadd2d | 35,574 |
def change_rate_extractor(change_rates, initial_currency, final_currency):
""" Function which tests directions of exchange factors and returns the
appropriate conversion factor.
Example
-------
>>> change_rate_extractor(
... change_rates = {'EUR/USD': .8771929824561404},
... ini... | 3ada3badcfa16c06c2a50ba943d67711e48b62a0 | 35,575 |
def get_codebook(ad_bits, codebook):
"""Returns the exhaustive codebooks for a given codeword length
:param ad_bits: codewor length
:type ad_bits: int
:return: Codebook
:rtype: list(str)
"""
return codebook[ad_bits-2] | 331c33e54abe5fd0d71edbc32d5f76d2ec6f03a9 | 35,576 |
def _shiftedWord(value, index, width=1):
"""
Slices a width-word from an integer
Parameters
----------
value: int
input word
index : int
start bit index in the output word
width: int
number of bits of the output word
Returns
-------
An integer with the sliced ... | d3c3ab1e1f34684607fb9f55f807053fd7052be0 | 35,577 |
import copy
def merge(dest, src):
"""Merge two config dicts.
Merging can't happen if the dictionaries are incompatible. This happens when the same path in `src` exists in `dest`
and one points to a `dict` while another points to a non-`dict`.
Returns: A new `dict` with the contents of `src` merged i... | e03bd548294ee8df71dc802672d22085ac85ee83 | 35,578 |
import random
def slow_reversible_propose(partition):
"""Proposes a random boundary flip from the partition in a reversible fasion
by selecting uniformly from the (node, flip) pairs.
Temporary version until we make an updater for this set.
:param partition: The current partition to propose a flip fr... | 8ccf4a1ba23815d9073ff7879380d095e9f0cf2c | 35,579 |
def list_to_number(column):
"""
Turns a columns of 0s and 1s to an integer
Args:
column: List of 0s and 1s to turn into a number
"""
# Cast column integers to strings
column = [str(cell) for cell in column]
# Turn to an integer with base2
return int(''.join(column), 2) | b6176726517133711d12e47ed47d55ef5bc8ab82 | 35,581 |
def update_url_pattern(pattern):
"""
Falls die URL, die für eine Request übergeben wird, schon eine Query enthält, wird diese aufgelöst,
damit die Paramter dem Request-Objekt als Dictionary übergeben werden können
:param pattern: URL mit Query (http...?...)
:type pattern: str
:return: Die Basis... | c5c12de221296ed0d029f83d496fddf90129743b | 35,583 |
def matrix_to_string(matrix, header=None):
"""
Returns a pretty and aligned string representation of a NxM matrix.
This representation can be used to print any tabular data, such as
database results. It works by scanning the lengths of each element
in each column and determining the format string d... | 7eb430356357de9d6a6b51c196df4aba29decada | 35,584 |
def SNR_kelly(spiketrain):
"""
returns the SNR of the waveforms of spiketrains, as computed in
Kelly et al (2007):
* compute the mean waveform
* define the signal as the peak-to-through of such mean waveform
* define the noise as double the std.dev. of the values of all waveforms,
each nor... | f827008138e9b02625db02ee6755da3451256d2d | 35,585 |
import math
def my_func(x):
"""
simple function that computes : sin(x) + 2x
Inputs:
1.x: input value (in radians)
Output:
returns y = sin(x) + 2x
"""
y = math.sin(x) + 2.0*x
return y | 15c14af682051d972d16ca3bf14a4f50f54cd79c | 35,586 |
import json
from datetime import datetime
import time
def iso_to_unix_secs(s):
""" convert an json str like {'time': '2022-02-05T15:20:09.429963Z'} to microsecs since unix epoch
as a json str {'usecs': 1644927167429963}
"""
dt_str = json.loads(s)["time"]
dt = datetime.strptime(dt_str, "%Y-%m-%... | 7421e6b1781b712ebc3b8bafd1d96f49c5f1d10c | 35,587 |
import time
import math
def time_str() -> str:
"""
Create a time string in format YYYYMMDD-HHMMSSsssTTTT
:return:
"""
time_s = time.strftime("%Y%m%d-%H%M%S{}%z")
ms = math.floor(math.modf(time.time())[0]*1000)
return time_s.format(ms) | dcdabd00015b53dc10c15d5f58eda8452d06e915 | 35,589 |
import os
def get_filename_not_ext(filename) -> str:
"""去除文件扩展名"""
return os.path.splitext(filename)[0] | e94dc20eaa26d45e93e907d31eddc0ba21a7cfae | 35,591 |
def add_view(func, **kw):
"""Method to store view arguments when defining a resource with
the add_resource class method
:param func:
The func to hook to
:param kw:
Keyword arguments configuring the view.
Example:
.. code-block:: python
class User(object):
... | 6e662b9544ca013dda2a18e372e28e00cd625718 | 35,592 |
def ned_enu_conversion(eta, nu):
"""Rotates from north-east-down to east-north-up
Args:
eta (array) : Drone position and rotation
nu (array) : Twitch of the drone - angular and linear velocities
Returns:
Array: Rotated eta and nu
"""
# yaw velocity is wrong -> ask aksel why!
retur... | 5660dead6909cc29df8775bf4d70569484d640d1 | 35,594 |
import requests
def check_time_response(domain):
"""Return the response time in seconds."""
try:
latency = requests.get(domain, headers={'Cache-Control': 'no-cache'}).elapsed.total_seconds()
return latency
except Exception:
return '?' | be208715ceae98122f7012a2982833e46b6979c7 | 35,595 |
def _safe_delay(delay):
"""Checks that `delay` is a positive float number else raises a
ValueError."""
try:
delay = float(delay)
except ValueError:
raise ValueError("{} is not a valid delay (not a number)".format(delay))
if delay < 0:
raise ValueError("{} is not a valid delay... | ff3014047c5f4bcd7d4054f8af11ccd722401546 | 35,598 |
def simple_solution(numbers, sum):
"""Complexity : O(N²)"""
for first in numbers:
for second in numbers:
if sum == first + second:
return True
return False | bebc90b9818dc8528dcaed2bbc8b1e9093e1f83c | 35,599 |
def attrChain(obj, *attrs):
"""if attrs is ["a1", "a2", ..., "an"], then this returns obj.a1.a2.a3...an.
If any .ak for k<n returns a scalar, stop and return None"""
r = obj
complete = False
started = False
for attr in attrs:
try:
r = getattr(r, attr)
started = True
... | e6df4cb2339da520a360da3fdee7ccadfab6d3f3 | 35,600 |
from typing import Dict
from typing import Any
def bundle_json_get_next_link(bundle_json: Dict[str, Any]) -> str:
"""get the 'next' link from a bundle, if it exists
Args:
bundle_json (Dict[str, Any]): the bundle to examine
Returns:
str: the url of the 'next' bundle or None
"""
fi... | db311eba00952b7d00bf5c9187cc52fb210c5560 | 35,601 |
import sys
def get_response_encoding():
"""Encoding to use to decode HTTP response from Google APIs."""
return None if sys.version_info[0] < 3 else 'utf8' | a6021f8f1769b530ccc10c360d63a0b5c64813e8 | 35,602 |
def strip_headers(post):
"""Find the first blank line and drop the headers to keep the body"""
if '\n\n' in post:
headers, body = post.split('\n\n', 1)
return body.lower()
else:
# Unexpected post inner-structure, be conservative
# and keep everything
return post.lower... | ac5b5a7b06f700a42698b3a65fd4c9017a001f30 | 35,603 |
def check_continuity(array):
"""
Check whether the array contains continous values or not like 1, 2, 3, 4, ..
"""
max_v = max(array)
min_v = min(array)
n = len(array)
# print(n, min_v, max_v)
if max_v - min_v + 1 == n:
# print("Given array has continous values")
retur... | 6b279cce3b332d5c593afe9590800fe3c8472710 | 35,604 |
import os
def in_console():
""" Return True if current environment is the flask console """
# See $UMBER_ROOT/bin/umber_console
return 'UMBER_CONSOLE' in os.environ | 88572e7ede96188dd84395bd1b2fdf28e55f53fc | 35,607 |
def get_node_type(conn, graph_node_pkey):
""" Returns the node type of a given graph node"""
c = conn.cursor()
c.execute(
"""
SELECT graph_node_type FROM graph_node WHERE pkey = ?""",
(graph_node_pkey, )
)
return c.fetchone()[0] | f68f29e45127854781c8fe5422ab754014df1d6b | 35,608 |
def _to_gin_params(parameters):
"""A helper function that convert key-value parameters to gin parameters"""
return ['--gin_param=%s' % e for e in parameters] | 8b8e0a9ee7fe162fa317d364da88e6bc02e99adb | 35,609 |
def getPixelFromLabel(label):
"""
Function to get the pizel from the class label. This reverse mapping is use to generate an image file fom available class labels.
:param label: class label
:type label: int
:return: (r,g,b) equivalent of class label color.
:rtype: tuple
"""
if label == ... | 746ae72f4adff1615f399ff5b591b7013ebdce46 | 35,611 |
def get_tadvs(words_li, pos_li, j):
"""
获取时间状语
"""
d = ''
while pos_li[j] != 'p' and j > 0:
d = words_li[j]+d
j -= 1
d = words_li[j]+d
return d | 04ab2a39eea784f3aa42cd5eca313ceaf8cf819d | 35,613 |
import argparse
def make_parser():
"""Create parser for grasp file and mesh file."""
parser = argparse.ArgumentParser(description='Visualize grasp file.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('input', type=str,
... | 69f3261df3befe03d82a5a43ed25b00e0cd3157c | 35,614 |
from typing import OrderedDict
def flatten(tree_dict):
"""Flatten tree_dict to a shallow OrderedDict with all unique exact pins."""
out = OrderedDict()
for key0, val0 in tree_dict.items():
out[key0[0]] = key0[1]
if not val0:
continue
for key1, subdict in val0.items():
... | d07271ac7c844fe8e56df20f1308aac777cb1acc | 35,615 |
import time
def ms_time_to_srt_time_format(d: int) -> str:
"""Convert decimal durations into proper srt format.
ms_time_to_srt_time_format(3890) -> '00:00:03,890'
"""
sec, ms = d // 1000, d % 1000
time_fmt = time.strftime("%H:%M:%S", time.gmtime(sec))
# if ms < 100 we get ...,00 or ...,0 whe... | 3ca2713615b7fb8ef1ea9e9712e0b26b23c5f7e1 | 35,616 |
def format_float(value: float, precision: int = 4) -> str:
"""
Formats a float value to a specific precision.
:param value: The float value to format.
:param precision: The number of decimal places to use.
:return: A string containing the formatted float.
"""
return f'{value:.{precision}f}' | 41ec3acf02f3400fd484c8e6f7a72509d3f20cd9 | 35,618 |
def get_settings(data):
""" Load needed settings from an issue report
Arguments:
data -- the parsed issue report dictionary
Output:
Dictionary of settings
"""
settings = {}
model = data.get("insulin_model")
if not model:
raise RuntimeError("No insulin model information fou... | 08f411a3256589f2fff3d5ec56c9756b23dbb7bd | 35,620 |
def calcula_probabilidade(numero_jogadas_restantes, distancia_atual):
"""
Recebe um número de jogadas restantes e a distância altual para
calcular a probalidade de se conseguir percorrer exatamente essa
distância com 'n' jogadas de dados
"""
if(distancia_atual == 0):
return ... | 77d85cab051b9b620388fb5a79af6413f5452c0a | 35,621 |
import logging
def TruncateStr(text, max_len=500):
"""Truncates strings to the specified maximum length or 500.
Args:
text: Text to truncate if longer than max_len.
max_len: Maximum length of the string returned by the function.
Returns:
A string with max_len or less letters on it.
"""
if len(... | 2401d6d56c6f99bd64cfd825aca0ab5badca1964 | 35,622 |
def timedelta_to_hour(delta):
"""
换算时间
:param delta:
"""
seconds = int(round(delta.total_seconds()))
hour = seconds / 3600
minute = (seconds % 3600) / 60
second = (seconds % 3600) % 60
return hour, minute, second | a99948e6b6cb9b39494568f6f2d78f7df39f35b4 | 35,623 |
def get_parameters(params, t, verbose=True):
"""
Convenience method for the numeric testing/validation system.
Params is a dictionary, each key being a parameter name,
and each value a list of values of length T (the number of trials).
The method returns a list of the argument values for test numb... | 70b624b465022efd9ef29e59b875881387f28935 | 35,625 |
def map_element(element):
"""Convert an XML element to a map"""
# if sys.version_info >= (2, 7):
# return {e.tag: e.text.strip() for e in list(element)}
# return dict((e.tag, e.text and e.text.strip() or "")
# for e in list(element))
return dict((e.tag, e.text) for e in list(element)... | b8a84be91f28757f28622a5909a569d35e38282f | 35,627 |
def _zone_group_topology_location_to_ip(location):
"""Takes a <ZoneGroupMember Location=> attribute and returns the IP of
the player."""
# Assume it is of the form http://ip:port/blah/, rather than supporting
# any type of URL and needing `urllib.parse`. (It is available for MicroPython
# but it req... | e3b038b92d4fcb24650dd6905847c9ca3f1fa13e | 35,628 |
from typing import Union
def transfrom_operand(operand: str) -> Union[str, int, bool]:
"""Transforms operand."""
result = operand.strip()
if result.isdigit():
result = int(result)
elif result in ['True', 'true', 'Yes', 'yes', 'T', 't', 'N', 'n']:
result = True
elif result in ['F... | 64bd30316d7176b01e66cd40d8852806b4da0e7b | 35,629 |
def get_or_create(session, model, **kwargs):
"""
Determines if a given record already exists in the database.
Args:
session: The database session.
model: The model for the record.
**kwargs: The properties to set on the model. The first
specified property will be used to ... | 74c77cfcbee09313b96284c34e59eb0ff1440f0c | 35,630 |
def get_state_salue(view, option):
"""Get selected values stored at the state element"""
element_value = ""
for element in view["state"]["values"]:
element_value = view["state"]["values"][element].get(option, None)
if element_value is not None:
if element_value.get("selected_opt... | f45b18ee16ad1b2885dbcd7465cf707d8dbfce8b | 35,631 |
import inspect
def resolve_msg_filter(filt):
"""If the filter provided is a message type, then create a filter which returns
any message of that type. Otherwise, assume the filter is a lambda method.
"""
if inspect.isclass(filt): # and issubclass(filt, PurpleDropMessage):
return lambda x: isin... | 5b97492c264cb8175b6de51f30ff952644312c5f | 35,632 |
def n_distinct(series):
"""
Returns the number of distinct values in a series.
Args:
series (pandas.Series): column to summarize.
"""
n_distinct_s = series.unique().size
return n_distinct_s | 5f262c376e844cff324b5e0376be91ead8e20c0d | 35,633 |
def get_index_offset_contents(result, source):
"""Return (line_index, column_offset, line_contents)."""
line_index = result['line'] - 1
return (line_index,
result['column'] - 1,
source[line_index]) | 5ee12a8c991ab50c71426cacf8db255f4f938de9 | 35,635 |
import argparse
def parse_options():
"""Parses command line options"""
parser = argparse.ArgumentParser(description='Process input files')
# parser.add_argument('-r', '--reference', type=str, nargs='?', default=None,
# help='reference genome input.')
parser.add_argument("-s","--seq... | 85a0aa14dd9f9b1706713eba61dc74d5fdd2351d | 35,636 |
def avg_eval_metrics(metrics):
"""Average evaluation metrics (divide values by sample count).
Args:
metrics: evaluation metrics
Returns:
averaged metrics as a dict
"""
n = metrics['sample_count']
metrics['loss'] = metrics['loss_sum'] / n
metrics['error_rate'] = metrics['error_count'] / n
if 't... | cfa3461c94b320a44438483f1d037c0b545cf02a | 35,637 |
def gather(m):
"""
Helper function to gather constraint Jacobians. Adapated from fenics.
"""
if isinstance(m, list):
return list(map(gather, m))
elif hasattr(m, "_ad_to_list"):
return m._ad_to_list(m)
else:
return m | 7821285d1dbce5e11b5452d906ad5333b0424b39 | 35,639 |
import os
def make_template_paths(template_file, paths=None):
"""
Make up a list of template search paths from given `template_file`
(absolute or relative path to the template file) and/or `paths` (a list of
template search paths given by user).
NOTE: User-given `paths` will take higher priority ... | 98f0a3e8aebec4e97a9ec91046e8bdf195f36c8f | 35,640 |
def epoch_s_to_ns(epoch_seconds):
"""
Converts epoch seconds to nanoseconds
"""
if type(epoch_seconds) is not str:
epoch_seconds = str(epoch_seconds)
return epoch_seconds + '000000000' | 7812fb76183caffdfc7851a06701d87a76d34c69 | 35,641 |
import copy
def dreplace(d, fv=None, rv='None', new=False):
"""replace dict value
Parameters
----------
d : dict
the dict
fv : any, optional
to be replaced, by default None
rv : any, optional
replaced with, by default 'None'
new : bool, optional
if true, de... | 86e29b6b3b8839ccf1de26483b71e8cd2e0fd6b8 | 35,642 |
from datetime import datetime
def now():
""" Simple function to return the current time formatted as used here in bfa logging.
:return: String containing the current time stamp.
note:: Author(s): Mitch """
return datetime.now().strftime("%Y-%m-%d %H:%M:%S") | da985e41032fccd07928602bd48fb7201f58132f | 35,643 |
def _snapshot_readable_date(specified_date):
"""
A function that transforms the specified date into a more human friendly string formatted date
:param specified_date: string formatted date
:return: Human readable string formatted date
"""
return specified_date.strftime('%B %d, %Y') | 84064e27e0e5ac289fe7e1f4c149bcd202c1cd3a | 35,646 |
import os
import argparse
def _validate_directory(path):
"""an argparse validator to confirm user input is a valid directory"""
if os.path.isdir(path):
return path
else:
raise argparse.ArgumentTypeError(f'cannot find directory {path}') | d6334a3285b79062a2558251a0d198aaf115eb40 | 35,648 |
from typing import List
from typing import Any
from typing import Callable
from typing import Optional
def extract_self_if_method_call(args: List[Any],
func: Callable) -> Optional[object]:
"""Check if this is a method rather than a function.
Does this by checking to see if `fu... | e93850cdad0bbe8fccfa1e508d14acd92f980b35 | 35,649 |
def encode_string(s, index):
"""
Transform a string in a list of integers.
The ints correspond to indices in an
embeddings matrix.
"""
return [index[symbol] for symbol in s] | bba25330f6d40b6211d11dda74fed8caa3dcfc16 | 35,650 |
def _is_instance(type_to_check, element, condition="any", deep=False):
"""
-----
Brief
-----
Function that verifies when "all" or "any" elements of the list "element" have the type
specified in "type_to_check" input.
-----------
Description
-----------
In some biosignalsnotebook... | 2b3f9e27e6a70fb9e665c237135eeb8c9d5e618b | 35,652 |
def as_linker_lib_path(p):
"""Return as an ld library path argument"""
if p:
return '-L' + p
return '' | 567509c01a4d24978b22834aeaded4f33762d6fe | 35,653 |
def remove_empty_arrays(movies_names_wl):
"""
This function takes movies_names_wl and removes empty arrays.
"""
for movie in movies_names_wl:
if(movie == []):
movies_names_wl.remove(movie)
return movies_names_wl | 6cac18c3f6c9fd23d05c9f1b969a027366d995a5 | 35,656 |
import random
def generate_project_name():
"""Generates a random project name."""
adjectives = [
'aged', 'ancient', 'autumn', 'billowing', 'bitter', 'black', 'blue', 'bold',
'broad', 'broken', 'calm', 'cold', 'cool', 'crimson', 'curly', 'damp',
'dark', 'dawn', 'delicate', 'divine', 'd... | 27ae42b20ab9d15add1cc162d3d4f2ab539447ff | 35,657 |
def split_backlink_section_from_markdown(string):
"""Split the backlinks section from the markdown file, which should be the last, but doesn't have to be :)
"""
# Find the section with Backlinks; if there are multiple for some reason, pick the last one
markdown_parts = string.rsplit("# Backlinks")
p... | 6ea6a070e0c6553ee01031b7175667d25c0236bd | 35,660 |
def get_frame(video_camera):
"""
Checks if the camera is open and takes a frame if so.
:param video_camera: A cv2.VideoCapture object representing the camera.
:return: Last frame taken by the camera.
"""
if video_camera.isOpened():
_, frame = video_camera.read()
else:
raise E... | 2c36b77b9f7e907276b397a1225cfa60f027d847 | 35,663 |
def detection_fruit(classe, prediction):
"""
This function analyses the list of prediction and return a
consolidation of the predictions done
Args:
-----
- classe : list of classes
- prediction : list of predictions
Returns:
--------
- fruit
"""
nb_predicted_images = le... | ea2202b5774401ae53b7faded82577237aa85800 | 35,664 |
def get_pwsh_script(path: str) -> str:
"""
Get the contents of a script stored in pypsrp/pwsh_scripts. Will also strip out any empty lines and comments to
reduce the data we send across as much as possible.
Source: https://github.com/jborean93/pypsrp
:param path: The filename of the script in pypsrp... | 43d1f0e526b9807ab729cb7b2b85ea1340699770 | 35,665 |
def is_numeric(obj):
"""Check whether object is a number or not, include numpy number, etc."""
try:
float(obj)
return True
except (TypeError, ValueError):
# TypeError: obj is not a string or a number
# ValueError: invalid literal
return False | 3cce07df54d6d83410cbd79580cdfdfd29f3edb1 | 35,666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.