content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def confidence(output):
"""Compute a confidence score for NN output"""
dim = output.shape[1]
if dim != 2:
raise NotImplementedError()
return [abs(x[1] - 0.5) + abs(x[0] - 0.5) for x in output] | 69879afa1c519c5ebc653640fdcdc4d9a1a9fa46 | 28,047 |
def cpu_roll_one():
"""Reset round score to zero."""
print("Computer rolled a 1")
print("round total set to 0. Other players turn!")
return 0 | 30ffdc0ac93ae104e87856ad5a6f0fda76cf51a3 | 28,048 |
import time
def calculate_time(func):
"""计算运行时间的装饰器"""
def decorator():
start_time = time.time() # 开始计时
func()
end_time = time.time() # 计时结束
print("Total Spend time:", str((end_time - start_time) / 60)[0:6] + "分钟")
return decorator() | 17d3adfd8c54dbe50232bb2568558e8a5648f23e | 28,050 |
def get_V_fan_d_t(t_fan_d_t, V_fan_P0):
"""1時間当たりの空気搬送ファンの風量 (m3/h) (13)
Args:
t_fan_d_t(ndarray): 1時間当たりの空気搬送ファンの稼働時間 (h/h)
V_fan_P0(float): 空気搬送ファンの送風機特性曲線において機外静圧をゼロとした時の空気搬送ファンの風量 (m3/h)
Returns:
ndarray: 1時間当たりの空気搬送ファンの風量 (m3/h)
"""
V_fan_d_t = V_fan_P0 * t_fan_d_t
retu... | 01d62dcdf4ca04ecd2fa6b70e3a3b7c9aec624dc | 28,051 |
def sqrt(pop):
"""
Returns square root of length of list
:param pop: List
:return: Square root of size of list
"""
return len(pop) ** 0.5 | 877ae17cbe2cdd3a5f5b2cb03fc8d0b7af48c916 | 28,052 |
def complete(ans):
"""
:param ans: string
:return: boolean
"""
for i in ans:
if i == '-':
return False
return True | 1cc423d2e532b25987f44c2dcd164192d548df07 | 28,053 |
def dict_subtract(d1, d2):
"""Subtract dictionary d1 from dictionary d2, to yield a new dictionary d."""
d = {}
for key, val in d1.iteritems():
if key not in d2:
d[key] = val
return d | baf8db2b5c0ff4be7d61effad388f6d9e8edd5c3 | 28,054 |
import requests
def __get_embedded_openload_url(url):
"""
url example:
https://openloads.co/c2/m2ZUtv0ylvY/filename.mp4
"""
url = url.replace(' ', '')
embed_url = "https://openload.co/embed/{0}"
try:
media_id = url.split('/')[4]
r = requests.get(embed_url.format(media_id... | 2baaa1d8b44722af81562cdb447951530c9fadc0 | 28,055 |
import numpy
def index_to_mask(x,n=100):
"""
Converts the list of indices x into a (nx1) boolean mask, true at those particular indices
"""
nrange=numpy.arange(n)
boole = numpy.zeros(nrange.shape, dtype=bool)
for xi in x: boole += nrange==xi
return boole | da460820c38ceede2d1495c6186ffd1e8a6a7e6b | 28,056 |
import re
def is_hex_color(color: str) -> bool:
"""
Checks if a given color string is a valid hex color
:param color:
:return:
"""
match = re.search(r"^#(?:[0-9a-fA-F]{3}){1,2}$", color)
if not match:
return False
return True | a86632883ccc05bc393b1b310c0fdf2eff559e55 | 28,057 |
import logging
def get_logger(name):
"""
Retrieves a logger.
:param name: The name of the logger
:returns: The requested logger
:rtype: logging.getLogger instance
"""
log = logging.getLogger(name)
log.setLevel(logging.ERROR)
return log | 45d36a78d1a076123a93b3460774056685befc1e | 28,058 |
def str2ascii_arr(name):
"""
0-255
"""
arr = [ord(c) for c in name]
return arr, len(arr) | fd3917a052bc60166aad6ca2a1a4b19154eda108 | 28,059 |
def find_ranges_index(ranges, item):
"""Find the index where an entry *may* be."""
lo = 0
hi = len(ranges)
while lo < hi:
mid = (lo + hi) // 2
test = ranges[mid]
try:
test = test[1]
except TypeError:
pass
if item > test:
lo = mi... | 55815410b96a3591f8389880a3606d9849e4ce9d | 28,060 |
def get_cls_db(db_name):
"""
Get benchmark dataset for classification
"""
if db_name.lower() == 'cls_davis':
return './dataset/classification/DAVIS'
elif db_name.lower() == 'cls_biosnap':
return './dataset/classification/BIOSNAP/full_data'
elif db_name.lower() == 'cls_bindingdb':... | 89cf36b94299e4a4e1b2a4880ae1e891e37e77ac | 28,061 |
import random
def random_mac():
"""Return a random Ethernet MAC address
@link https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml#ethernet-numbers-2
"""
head = "ca:fe:"
hex_digits = '0123456789abcdef'
tail = ':'.join([random.choice(hex_digits) + random.choice(hex_digits) f... | 0cace2b7928a9df1b0faea33e9df27b478c9eea7 | 28,063 |
import subprocess
def env_run(env_path, command, *args, **kwargs):
"""
Run a command on the context of the virtual environment at
the specified path.
"""
return subprocess.run([env_path/"bin"/command] + list(args), **kwargs).returncode == 0 | ff34f0ee37ad2c4f9c171d3a27ccaa74b1ed4b7b | 28,064 |
import pandas
def timestamp2period(ts):
"""Get 6-hour period around timestamp
Taking a timestamp, take the 6-hour period starting at the most recent
analysis, containing the requested timestamp. That will be the
period [ts.hour//6, ts.hour//6+6].
Args:
ts: pandas.Timestamp
"""
r... | 622cb45693c9a9261afbea0cddf432db0a14cb59 | 28,065 |
import sys
def getPythonContainers(meth):
"""Walk up the Python tree from method 'meth', finding its class, its module
and all containing packages."""
containers = []
containers.append(meth.im_class)
moduleName = meth.im_class.__module__
while moduleName is not None:
module = sys.modul... | ec5e5563ecf2905b7c037d966bde8f4f7239bcdf | 28,066 |
def remap_CIELab(image):
"""
INPUT:
image: the image to be remapped. The input colorspace should be CIELab
image.shape=(image_x, image_y, 3)
OUTPUT:
an image where the L a and b layers are scaled to be between 0 and 1 for most frequently used colors.
t... | 4ee5bed4763dce56f757e686b4416ce43f01afa4 | 28,067 |
import pathlib
def get_file_size(file_path):
""" Returns file size """
file = pathlib.Path(file_path)
return file.stat().st_size | aa90923cd117b2b96a76c8d29d6218e3a577d5df | 28,069 |
import os
def os_specific_env(env_var_name):
"""
Gets the operating system specific environment variable format string.
:param env_var_name: Environment variable name.
:type env_var_name: str
"""
current_os = os.environ["TEMPLATE_OS"]
if current_os.lower() == "linux":
return "${}... | fc32fcc2d2af81d9cd1f53330368ba7f58a5ee3b | 28,070 |
import pandas
def df_getitem_tuple_at_codegen(self, row, col):
"""
Example of generated implementation:
def _df_getitem_tuple_at_impl(self, idx):
row, _ = idx
data = self._dataframe._data[1][0]
res_data = pandas.Series(data, index=self._dataframe.index)
... | c785a9ce7a8879df43945dfb4224d7f897261cb4 | 28,072 |
import math
def deRuiter_radius(src1, src2):
"""Calculates the De Ruiter radius for two sources"""
# The errors are the square root of the quadratic sum of
# the systematic and fitted errors.
src1_ew_uncertainty = math.sqrt(src1.ew_sys_err**2 + src1.error_radius**2) / 3600.
src1_ns_uncertainty = ... | 55c7f174b61c249427f09cec3c885c049f1d38dc | 28,075 |
import logging
def get_job_source_code_hashes(self, job_info, provider, job_key, index, job_id=0, received_block_number=None):
"""Source_code_hashes of the completed job is obtained from its event."""
if received_block_number is None:
received_block_number = self.get_deployed_block_number()
to... | d38f02e328500853180f1d50d7629cd5e1be8328 | 28,076 |
from typing import Dict
def extract_method_arguments(line: str) -> Dict[str, str]:
"""Read method arguments from text"""
# Use the method call to break the string
arguments_str = line.split("(")[1].split(")")[0]
if not arguments_str:
return {}
args = {}
for entry in arguments_str.spl... | 9f3ca90775933b2b32549d7bf12f5c407181bd2d | 28,079 |
def twitterMatrix(db, query):
"""Run a Cypher query that returns pairs of Twitter screen_names lists of others to which they are linked."""
def matrix_query_as_list(tx):
return list(tx.run(query))
with db.session() as session:
result = session.read_transaction(matrix_query_as_list)
sc... | ceab8245b976a09362f97b7bcb0eb2ac1463e0d8 | 28,080 |
def flatten(list_of_lists):
"""List[List[X]] -> List[X]"""
return sum(list_of_lists, []) | 8f75134151897bcb58eb5524a40ad2dd515ee49a | 28,081 |
def regions_to_compound_region(regions):
"""Create compound region from list of regions, by creating the union.
Parameters
----------
regions : `~regions.Regions`
List of regions.
Returns
-------
compound : `~regions.CompoundSkyRegion` or `~regions.CompoundPixelRegion`
Comp... | 51c0844c30b0ec32f547e6922bf22508e8f066cf | 28,082 |
def fix_data(text):
"""Add BOS and EOS markers to sentence."""
if "<s>" in text and "</s>" in text:
# This hopes that the text has been correct pre-processed
return text
sentences = text.split("\n")
# Removing any blank sentences data
sentences = ["<s> " + s + " </s>" for s in senten... | b502784e9e8fa8875030730595dcaaae66e2f31b | 28,083 |
import base64
def b64_encode(value: bytes) -> bytes:
"""
URL safe base 64 encoding of a value
:param value: bytes
:return: bytes
"""
return base64.urlsafe_b64encode(value).strip(b"=") | 40a7dfbec7ec390a71cdacc5ab54ce8e2a092754 | 28,084 |
import subprocess
def safe_subprocess(command_array):
"""Executes shell command. Do not raise
Args:
command_array (list): ideally an array of string elements, but
may be a string. Will be converted to an array of strings
Returns:
bool, str: True/False (com... | fa7d6b0c1045f865bc3c888f8f751507120f86a9 | 28,087 |
def _get_tap(baseVal, powerVal):
"""Retrieve pre-defined list of tap sequences for a given base & power, or raise ValueError.
"""
if not baseVal in [2,3,5,9]:
raise ValueError('baseVal must be in [2,3,5,9], not %s' % str(baseVal))
tap = []
if baseVal == 2:
if powerVal == 2:
... | dc40edf1a09d5ad7fa76945a31b13570eacddb64 | 28,088 |
def comment_scalar(a_dict, key):
"""Comment out a scalar in a ConfigObj object.
Convert an entry into a comment, sticking it at the beginning of the section.
Returns: 0 if nothing was done.
1 if the ConfigObj object was changed.
"""
# If the key is not in the list of scalars there is... | f2121caa4e58ec88527ae128a0ac9669efa066d7 | 28,089 |
from datetime import datetime
def xml2date(s):
"""Convert XML time string to python datetime object"""
return datetime.strptime(s[:22]+s[23:], '%Y-%m-%dT%H:%M:%S%z') | 762480533d8e64544b4b4c4c67093098dcfebb56 | 28,091 |
import numpy
def _find_next_batch(
example_to_file_indices, num_examples_per_batch, next_example_index):
"""Determines which examples are in the next batch.
E = total number of examples
:param example_to_file_indices: length-E numpy array of indices. If
example_to_file_indices[i] = j, t... | 8a38521630cb701cb695a06aa8db697fd8307525 | 28,095 |
def rivers_with_stations(stations):
"""Returns a set with the names of any rivers with a monitoring station"""
counter = 0
valid_rivers = set()
while counter < len(stations):
valid_rivers.add(stations[counter].river)
counter += 1
if counter > 200000:
break
els... | 2003b12a875cd34b6faa85f564da56dff679dc99 | 28,096 |
def min(x, y):
"""Minimum"""
return min(x, y) | 8c6b242ae050cd1e80102677a043735fdf05be34 | 28,097 |
import os
def _absolute_template_path(fn):
"""
Return absolute path for filename from local ``xslt/`` directory.
Args:
fn (str): Filename. ``MARC21slim2MODS3-4-NDK.xsl`` for example.
Returns:
str: Absolute path to `fn` in ``xslt`` dicretory..
"""
return os.path.join(os.path.d... | ef9c46fe965cbf5e37ca66c186e4fcc44c004df8 | 28,098 |
def solution(ar):
"""
Return exactly once
:param ar:
:return:
"""
xor_sum = 0
# xor cancels the same elements ie. 2 xor 2 = 0
for item in ar:
xor_sum = xor_sum ^ item
return xor_sum | f0370136ba87fed1b8d40ece176e23257c7757b8 | 28,099 |
import re
def format_header ( parsed_args ):
"""
parse the RVDB formatted FASTA headers and re-writes in desired format
"""
accessions = []
with open (parsed_args.inputFASTA) as infile:
reader = infile.readlines()
try:
with open (parsed_args.output, 'w') as outfile:
... | cdc10767f36166f73e30e2c0b342db5ef8d524ec | 28,100 |
import os
def take_checkpoint(root):
"""
Calls the perforce server and takes a snapshot
"""
cmd = 'p4d -r %s -z -jc' % root
ret = os.system(cmd)
if ret == 0:
return True
return False | a7c022c9b240d60b800c1ec75b5741a6a11c12f1 | 28,102 |
def atom2dict(atom, dictionary=None):
"""Get a dictionary of one of a structure's
:class:`diffpy.structure.Structure.atoms` content.
Only values necessary to initialize an atom object are returned.
Parameters
----------
atom : diffpy.structure.Structure.atom
Atom in a structure.
di... | 6873c64bd39d211a43f302375d6a6c76e3bd0b7e | 28,103 |
def get_connectivity(input_nodes):
"""Create a description of the connections of each node in the graph.
Recurrent connections (i.e. connections of a node with itself) are excluded.
Args:
input_nodes (:obj:`list` of :obj:`Node`): the input operations of
the model.
Returns:
... | ea14ff70f4c821744079219a2ec3ee50acc0483b | 28,104 |
def get_message_with_context(msg: str, context: str) -> str:
"""
Concatenates an error message with a context. If context is empty
string, will only return the error message.
:param msg: the message
:param context: the context of the message
:return: the message with context
"""
if len(... | 8d625b297ba4510fdef3476138bafd1e210fcaa6 | 28,105 |
def get_default_keras_loss_names():
"""
Get the default available losses from Keras and return them as list of strings.
:return:
"""
return ['categorical_crossentropy'] | a26d5f8042d4728db36fa97fe838cd5437415bf8 | 28,106 |
def mean(array, axis=0):
"""Calculates standard error."""
return array.mean(axis=axis) if len(array) > 0 else 0.0 | 5ea0fe92b1a882a47d8418574978bf6adc592748 | 28,107 |
def unique(list1, list2):
"""Get the unique items that are in the first list but not in the second
list.
NOTE: unique(l1,l2) is not always equal to unique(l2,l1)
Args:
list1 (list): A list of elements.
list2 (list): A list of elements.
Returns:
list: A list with th... | 9e870319287ef7296cb5f54dc1089dc676ecc553 | 28,109 |
def all_belong(candidates,checklist):
"""Check whether a list of items ALL appear in a given list of options.
Returns a single 1 or 0 value."""
return 1-(0 in [x in checklist for x in candidates]) | 05aca77653dad3cd8221a66f45493aa53cb93654 | 28,110 |
from six import PY2
import sys
def write_bytes_to_stdout(b):
"""Write bytes (python 3) or string (python 2) to stdout."""
if PY2:
return sys.stdout.write(b)
else:
return sys.stdout.buffer.write(b) | 533d4c7f55adf890269334dd52bfc8e787d6aae4 | 28,111 |
def get_classes(module, superclass=None):
"""
Return a list of new-style classes defined in *module*, excluding
_private and __magic__ names, and optionally filtering only those
inheriting from *superclass*. Note that both arguments are actual
modules, not names.
This method only returns classe... | 9b31c7179a29b148e8e7503fa8bc06282e1248b4 | 28,112 |
from hashlib import md5 as _md5
def get_filesize_and_checksum(filename):
"""Opens the file with the passed filename and calculates
its size and md5 hash
Args:
filename (str): filename to calculate size and checksum for
Returns:
tuple (int,str): size of data and its ... | b8e1c0dc6bcb9785d2c6f47dbebe6ccedf18b1af | 28,113 |
def to_datetimepicker_format(python_format_string):
"""
Given a python datetime format string, attempts to convert it to
the nearest PHP datetime format string possible.
"""
python2PHP = {
"%a": "D",
"%A": "l",
"%b": "M",
"%B": "F",
"%c": "",
"%d": "d"... | 525563b4857e8cedb90c4180ee959b2c408ac92c | 28,115 |
import os
def _image_file_path(instance, filename):
"""Returns the subfolder in which to upload images for articles. This results in media/article/img/<filename>"""
return os.path.join(
'article', str(instance.article.pk), 'images', filename
) | f917666d7704f005e776ca75ecb296c5b1508be4 | 28,116 |
def getNameToIdDict(tree):
"""Get a mapping from name to id for an nxtree. Will be invalid if
changes are made to the tree.
"""
ret = {}
for id in tree.postOrderTraversal():
if tree.hasName(id):
ret[tree.getName(id)] = id
return ret | a94f6f9a90c1874c3f07f20e2e096929c923b60e | 28,117 |
def get_boundary():
"""
Before I used:
boundary = mimetools.choose_boundary()
But that returned some "private" information:
'127.0.0.1.1000.6267.1173556103.828.1'
Now I simply return a fixed string which I generated once and now re-use
all the time.
There is a reason for havin... | 82c70fe3b03de09f654aebe80691d235fadba4d0 | 28,118 |
def rebase(input_base, digits, output_base):
"""
Change digits of a number from input base to output base
"""
if input_base < 2:
raise ValueError("input base must be >= 2")
if any(map(lambda x: x < 0 or x >= input_base, digits)):
raise ValueError("all digits must satisfy 0 <= d <... | 8a242dae905559e8048cfb92e053bae5a8dde596 | 28,119 |
import json
def parse_json(s, **kwargs):
""" Wrapper to read JSON, stubbed for now """
return json.loads(s, **kwargs) | 1e22fcfbb8d2b6a61d74f5cf2f2ea4fb537bf21b | 28,120 |
import random
def generator_random_email():
"""生成随机的10位数邮箱
:return:
Examples:
| ${email} | Generator Random Email |
=>
| ${email} = 45tghmju79@email.com
"""
char_num = [a for a in range(0, 10)]
char_lower_case = list('abcdefghijklmnopqrstuvwxyz')
char_capital = list('abcdefgh... | 8d0ec38d614f67c06ce200afc88e6286d5ba82cd | 28,121 |
def rotate_convert(value) -> int:
"""
:param value:midi values: 1-63 plus
65-127 minus
:return: value to add
"""
if value & 64:
return -(value - 64)
else:
return value | 435048382ded63201da93654d4ab679534cd75f6 | 28,122 |
def convert_string(data_to_convert):
"""
Parse ASCII string from byte array
:param data_to_convert: Input byte array
:return: Parsed string
"""
return data_to_convert[2:].decode('hex') | 3bd234db7793d9d694e6c40f74f1acfcc09ca60f | 28,125 |
import os
import sqlite3
def get_properties(elt):
"""
Retrieve properties of an element such as its density, lattice constant, etc. as a dictionary
If no information is found in the database then at least Element, Z and mass will be returned
Examples
--------
> get_properties("C")
{'Elemen... | 8e820aa22f501437bd4a6fd8115ca4245ef70d76 | 28,128 |
def exception_str(exc):
"""Call this to get the exception string associated with the given exception
or tuple of the form (exc, traceback) or (exc_class, exc, traceback).
"""
if isinstance(exc, tuple) and len(exc) == 3:
return str(exc[1])
return str(exc) | eb3729cc49a5e346fbd9c064f2fe0fc4ef4bd2c2 | 28,129 |
def sanityCheck(url):
"""
Checks for a valid url pattern, and returns True if valid, False otherwise
url: string
valid: boolean
"""
splitted_url = url.split('/')
valid = False
try:
if splitted_url[0] == "https:" and splitted_url[1] == "" and splitted_url[2] == "github.com... | 21fc0fe52803ad010a0c5ca06aa3dfe750df4518 | 28,130 |
def xidz(numerator, denominator, value_if_denom_is_zero):
"""
Implements Vensim's XIDZ function.
This function executes a division, robust to denominator being zero.
In the case of zero denominator, the final argument is returned.
Parameters
----------
numerator: float
denominator: floa... | 45782f957c56a0f91528d6d945c5d7887fd68e95 | 28,131 |
def mock_exists(file_map, fn):
""" mock os.path.exists() """
return (fn in file_map) | f68741c4bd4da3e5f4d32dce1ef9c249495c8f5a | 28,132 |
def linear_function(x,m,b):
"""
Get the y value of a linear function given the x value.
Args:
m (float): the slope
b (float): the intercept
Returns:
The expected y value from a linear function at some specified x value.
"""
return m*x + b | 929882eb3f3e4b0767458c63ed17ca67fc6ab17f | 28,133 |
def pp_timestamp(t):
"""
Get a friendly timestamp represented as a string.
"""
if t is None:
return ''
h, m, s = int(t / 3600), int(t / 60 % 60), t % 60
return "%02d:%02d:%05.2f" % (h, m, s) | d1766cabcff9f09c145d98536900e9a82e734f63 | 28,139 |
import numpy
def pt2numpy(pt):
"""Translate WKT Raster pixel type to NumPy data type"""
numpytypes = {
'8BUI' : numpy.uint8,
'16BSI' : numpy.int16,
'16BUI' : numpy.uint16,
'32BSI' : numpy.int32,
'32BUI' : numpy.uint32,
'32BF' : numpy.float32,
'64BF' : nu... | ec5dad598da7ac2604dda7bf7e9cf2842006e493 | 28,140 |
def remove_hook_words(text, hook_words):
"""
removes hook words from text with one next word
for text = "a b c d e f"
and hook_words = ['b', 'e']
returns "a d" (without b, e and next words)
"""
words = text.split()
answer = []
k = 0
while k < len(words):
if words[k] in... | aaa1706fe7d9322d900ef346f3189824d06f8df2 | 28,142 |
def Farm_Loc(player):
"""farm location function"""
player.coins += 3
return (player) | 849e452774ea2446d4c6972044c1d6c2777b6554 | 28,144 |
def simdata2obsconditions(sim):
"""Pack simdata observation conditions into a dictionary.
Parameters
----------
simdata : Table
Simulation data table.
Returns
-------
obs : dict
Observation conditions dictionary.
"""
obs = dict(AIRMASS=sim.airmass,
EX... | 3a3d5ab351842d53e5c753b83f09ac68de1a9b55 | 28,145 |
import socket
def get_real_ip():
"""
Attempts to get the IP address that's used for interesting things.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 53))
except:
return False
ip_address = s.getsockname()[0]
first_octet = ip_addres... | 56de5f9fa00a083fc1682f70d500486c99147aad | 28,146 |
def is_u2f_enabled(user):
"""
Determine if a user has U2F enabled
"""
return user.u2f_keys.all().exists() | 39b3b93e03eee230fc978ad5ec64ba4965b2d809 | 28,149 |
def extend_feature_columns(feature_columns):
""" Use to define additional feature columns, such as bucketized_column and crossed_column
Default behaviour is to return the original feature_column list as is
Args:
feature_columns: [tf.feature_column] - list of base feature_columns to be extended
... | 11d0c77331745719d445f7926f041e2fe1c70903 | 28,150 |
import torch
def max_matching(scores):
""" Matching according to maximum similarity.
Input matrix shape: [D, T] (dim=0)
Return ids shape: [T]
"""
ids = scores.new_full((scores.size(1), ), -1).long()
# assume t2d
t2d_max, t2d_idxs = scores.max(dim=0)
match_t_idxs = torch.nonzero... | 63bf51639050371d55bcd3413738c26e82c878f2 | 28,151 |
def get_initial_user_settings(argv):
"""
Parses the given command line arguments to extract the user's desired
user_set_speed and safe_distance.
If a value is not given then None is returned in place of that value.
>>> get_initial_user_settings(["speed=20", "distance=150"])
(20, 150)
>>> ... | 058c5543688646a37e61a5e8f6e0b1f6abd5eacf | 28,152 |
def clean_data(players):
"""Sanitize the list of player data."""
cleaned_players = []
for player in players:
cleaned_player = {}
for key, value in player.items():
cleaned_value = value
if key == "height":
cleaned_value = int(value[0:2])
... | 88836eb154ff1a3cb32c567634adf813ac234de6 | 28,153 |
def _jupyter_server_extension_paths():
"""python module to load as extension"""
return [{"module": "ipydrawio_export"}] | a4a3cf100b8cfeb6acec9ff0d1482f2fe1587068 | 28,154 |
import argparse
import os
def parse_args():
""" Parse arguments for program
"""
parser = argparse.ArgumentParser(description="Program for renaming files")
parser.add_argument("find",help="Find pattern")
parser.add_argument("-i","--ignore_case", action="store_true", help = "Ignore case")
parser.add_argume... | 561ce79282688360f8122e7f89abbcf3f0d70f7d | 28,155 |
import shutil
def exe_exists(exe):
""" Returns the full path if executable exists and is the path. None otherwise """
return shutil.which(exe) | 38bed97a3d195e6adc8e0dba936d213828f15e2f | 28,156 |
def is_term_mod(label):
"""Check if `label` corresponds to a terminal modification.
Parameters
----------
label : str
Returns
-------
out : bool
"""
return label[0] == '-' or label[-1] == '-' | c7ed745be0ab0dac54c8846bb2865832e5aa4778 | 28,157 |
def confusion_stats(set_true, set_test):
"""
Count the true positives, false positives and false
negatives in a test set with respect to a "true" set.
True negatives are not counted.
"""
true_pos = len(set_true.intersection(set_test))
false_pos = len(set_test.difference(set_true))
false... | 401b216b1317f16a424830e71b48f1d21d603956 | 28,159 |
def verif_lettres_joueur(plateau, lettres_joueur, coup):
"""
Cette fonction renvoie True:
- Si le mot à placer appartient au lettres du joueur (lettres_joueurs)
ou
- Si une ou plusieurs lettres manquent mais sont déjà placées à la place
adéquate sur le plateau (plateau).
Sinon, la fonction r... | 8a05bbe54b281afec4bc31bb6577528aa6cf3816 | 28,160 |
def get_item_nodeid(item):
"""Build item node id."""
# note: pytest's item.nodeid could be modified by third party, so build a local one here
if item.location and len(item.location) > 2:
return item.location[0].replace("\\", "/") + "::" + item.location[2].replace(".", "::")
return item.fspath.re... | a25594640d96dd387a4fbecc11ef874b8000faf7 | 28,161 |
def category_parents(category):
"""
Get list parents of category
:param category: Object category, product. e.g <8c8fff64-8886-4688-9a90-24f0d2d918f9>
:return: Dict | List | List categories and sub-categories. e.g.
[
{
"id": "c0136516-ff72-441a-9835-1ecb37357c41",
... | 84616c76fb4179eb2f91600699e1f07d0de9b15f | 28,162 |
def missingNumber(nums: list) -> int:
"""
解法2:数学公式。
"""
n = len(nums)
expected_sum = n*(n+1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | ae6c0a7533e81c1c3d0e61a49298cdf551eda261 | 28,163 |
from typing import Iterable
from typing import Dict
from typing import Any
from typing import List
import collections
def _list_dict_to_dict_list(samples: Iterable[Dict[Any, Any]]) -> Dict[Any, List[Any]]:
"""Convert a list of dictionaries to a dictionary of lists.
Args:
samples: a list of dictionari... | a5bd1dea71306f5e8151f6dfcc94b96f328b6d76 | 28,165 |
def count_rule_conditions(rule_string: str) -> int:
"""
Counts the number of conditions in a rule string.
Parameters
----------
rule_string : str
The standard Iguanas string representation of the rule.
Returns
-------
int
Number of conditions in the rule.
"""
n_... | 4dc8bc3fdc7ee4d4302101a39b7849bcd7dff6e8 | 28,166 |
def check_length_of_shape_or_intercept_names(name_list,
num_alts,
constrained_param,
list_title):
"""
Ensures that the length of the parameter names matches the number of
pa... | d83ed7d6989c7e3ccdbbb256eaa72759a7f242d3 | 28,167 |
def compose_terms(terms):
"""
Compose a sequence of terms.
Composition is done with *time* ordered left-to-right. Thus composition
order is NOT the same as usual matrix order.
E.g. if there are three terms:
`terms[0]` = T0: rho -> A*rho*A
`terms[1]` = T1: rho -> B*rho*B
`terms[2]` = T2:... | dc6cdbe5f05e1a93335f0436136dfe4f0ec7a5d3 | 28,168 |
def get_token_object(auth):
"""
Retrieve the object or instance from a
token creation. Used for knox support.
:param auth: The instance or tuple returned by the token's .create()
:type auth tuple | rest_framework.authtoken.models.Token
:return: The instance or object of the token
:rtype: r... | 3651951e413f3fd44f159ed6070542d54f2923b2 | 28,169 |
def format_interconnector_loss_demand_coefficient(LOSSFACTORMODEL):
"""Re-formats the AEMO MSS table LOSSFACTORMODEL to be compatible with the Spot market class.
Examples
--------
>>> LOSSFACTORMODEL = pd.DataFrame({
... 'INTERCONNECTORID': ['X', 'X', 'X', 'Y', 'Y'],
... 'REGIONID': ['A', 'B',... | a7a87543eedb33248f6532ec234d47b7fe5455b3 | 28,170 |
import sys
def identify_column(query_column, header):
""" Identifies the query column of interest if entered as an integer
or a string and gives the index values of that column.
Parameters
----------
query_column: integer or string
The column to search for the query_value in.
... | 1dfbc16974dcfe971722636b99ffc22300d3ea28 | 28,171 |
from datetime import datetime
def to_time_string(value):
"""
gets the time string representation of input datetime with utc offset.
for example: `23:40:15`
:param datetime | time value: input object to be converted.
:rtype: str
"""
time = value
if isinstance(value, datetime):
... | b81ffff8b4ab626e0094bcfeb0bf6916de89d344 | 28,172 |
def u(string: str) -> bytes:
"""Shortcut to encode string to bytes."""
return string.encode('utf8') | 3310da2d9f24be94c0426128ac19db2481dd2c2d | 28,173 |
from pathlib import Path
import typing
import subprocess
def git_get_toplevel(repo_path: Path
) -> typing.Optional[Path]:
"""
Get top-level working tree path for @repo_path. Returns None
when not in repository.
"""
sp = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'... | ff047fed00839a27650e04cbc816b3a5d3ec9d28 | 28,176 |
import random
def random_selection(similarity_matrix, nb_items=None):
"""
Selects randomly an item from the given similarity_matrix
:param similarity_matrix: (pandas.DataFrame) an NxN dataframe; should be (a) symmetric and (b) values {i,j} to
represent the similarity betw... | dd54045f690dc63c3a5b8c21685c6d610b45fccb | 28,177 |
def try_guess(guess, current_game, game_word):
"""Test input letter"""
result = False
for i, value in enumerate(game_word):
if value == guess:
result = True
current_game[i] = guess
return current_game, result | 5f73dc0a4592ad3de7c880eb41f26660fee9ce68 | 28,178 |
def dictToTuple(heading, d):
"""Convert dict into an ordered tuple of values, ordered by the heading"""
return tuple([d[attr] for attr in heading]) | 1a76201da4e5348a4c4ba9607992ad41a1c87163 | 28,179 |
def nrl(tb37v, tb37h):
"""Lo/Naval Research Laboratory (NRL)
"""
A0 = 1.3 # values from Leif
A1 = 0.019
c = A0 - A1*(tb37v - tb37h)
return c | be3ffb39683126df089d1298a87f7d3ab351514a | 28,180 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.