content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def arg_name(name):
"""Convert snake case argument name to a command line name.
:param str name: The argument parameter name.
:returns: str
"""
return "--" + name.replace('_', '-') | e66284c3a99fe9a75799d4123ad23322089ec2ee | 8,376 |
def invert_node_predicate(node_predicate):
"""Build a node predicate that is the inverse of the given node predicate.
:param node_predicate: An edge predicate
:type node_predicate: (pybel.BELGraph, BaseEntity) -> bool
:rtype: (pybel.BELGraph, BaseEntity) -> bool
"""
def inverse_predicate(graph... | b6132728d17d520fd9ee22f228c45b364704d5ef | 8,377 |
import random
def get_number_by_pro(number_list, pro_list):
"""
:param number_list:数字列表
:param pro_list:数字对应的概率列表
:return:按概率从数字列表中抽取的数字
"""
# 用均匀分布中的样本值来模拟概率
x = random.uniform(0, 1)
# 累积概率
cum_pro = 0.0
# 将可迭代对象打包成元组列表
for number, number_pro in zip(number_list, pro_list):... | 34e367cb0e29df59ddf1e15deec1837d71a922f9 | 8,378 |
def gcd_fast(a: int, b: int) -> tuple:
"""
GCD using Euler's Extended Algorithm generalized for all integers of the
set Z. Including negative values.
:param a: The first number.
:param b: The second number.
:return: gcd,x,y. Where x and y are bezout's coeffecients.
"""
gcd=0
x=0
y=0
x=0
"""
if a < 0:
s... | d29cf59b310a7035555a04aaa358410319c3d1b3 | 8,379 |
def get_option_name(flags):
"""
Function to get option names from the user defined arguments.
Parameters
----------
flags : list
List of user defined arguments
Returns
-------
flags : list
List of option names
"""
for individualFla... | 359ab05c563aac217d8f275bb946fbafc37f3af2 | 8,380 |
def openthread_suppress_error_flags():
"""Suppress errors for openthread"""
return [
'-Wno-error=embedded-directive',
'-Wno-error=gnu-zero-variadic-macro-arguments',
'-Wno-error=overlength-strings', '-Wno-error=c++11-long-long',
'-Wno-error=c++11-extensions', '-Wno-error=variadic... | a6379b1b6133ca24226ca996d9275e4ada8dc3eb | 8,382 |
def split_loops_into_anchors(file_name):
"""
Split loops into anchors.
"""
left = []
right = []
run = file_name.split('.')[0]
i = -1
with open(file_name, 'r') as f:
for line in f:
if '#' in line:
# Skip header
continue
... | c5040b4c2a675d7250d0658a4e60fddd064d933a | 8,384 |
def first(*objects):
"""
Return the first non-None object in objects.
"""
for obj in objects:
if obj is not None:
return obj | 4d33225eb0348aa9b7fefa875070eb5527e67135 | 8,385 |
def init_list_with_values(list_length: int, init_value):
"""Return a pre-initialized list.
Returns a list of length list_length with each element equal to
init_value. init_value must be immutable (e.g. an int is okay; a
dictionary is not), or the resulting list will be a list of
references to same object (e.g. re... | 85d5aa5f575b6aec54658ca6d398ded5f48f7188 | 8,387 |
import re
def decode_sigma(ds,sigma_v):
"""
ds: Dataset
sigma_v: sigma coordinate variable.
return DataArray of z coordinate implied by sigma_v
"""
formula_terms=sigma_v.attrs['formula_terms']
terms={}
for hit in re.findall(r'\s*(\w+)\s*:\s*(\w+)', formula_terms):
terms[hit[0]]... | 3ea233f2b3acb0012166e8e002d6824845a7c043 | 8,390 |
def lowfirst(string):
"""
Make the first letter of a string lowercase (counterpart of :func:`~django.utils.text.capfirst`, see also
:templatefilter:`capfirst`).
:param string: The input text
:type string: str
:return: The lowercase text
:rtype: str
"""
return string and str(string)... | f877129f9225e84989fc70d096b01715a2287373 | 8,391 |
def priority(profile):
""" function : to set priority level based on certain age group
input : id, age, infection_status (0 means not infected , 1 means infected) , coordinates, residency
output : priority level : local_high(6), local_medium(5) , local_low (4), foreign(3), foreign(2) ,foreign(1)... | dae951efb11f8988cb32910e708bb4f69d8a3ed0 | 8,393 |
def seqlib_type(cfg):
"""
Get the type of :py:class:`~enrich2.seqlib.SeqLib` derived object
specified by the configuration object.
Args:
cfg (dict): decoded JSON object
Returns:
str: The class name of the :py:class:`~seqlib.seqlib.SeqLib` derived
object specified by `cfg`... | e48661f00eb6d0cb707fbb96d77b3a9ee3e798d6 | 8,394 |
import os
def parentdir(p, n=1):
"""Return the ancestor of p from n levels up."""
d = p
while n:
d = os.path.dirname(d)
if not d or d == '.':
d = os.getcwd()
n -= 1
return d | 826a52937c491404afaa254acb40827eec36f1b1 | 8,396 |
def rfactorial(n: int) -> int:
"""Recursive factorial function
:param n:
.. docstring::python
>>> from math import factorial
>>> rfactorial(1) == factorial(1)
True
>>> rfactorial(2) == factorial(2)
True
>>> rfactorial(3) == factorial(3)
True
... | c8455ce7d0e7e781c0c745287c2aef3c9a776a48 | 8,399 |
import os
import subprocess
import json
def construct_version_info():
"""Make version info using git.
Parameters
----------
None
Returns
-------
version_info : dict
Dictionary containing version information as key-value pairs.
"""
hera_opm_dir = os.path.dirname(os.path.r... | 9b56bb0e85555a6bb0989210d3d840d47cfecd42 | 8,400 |
def many2many_dicts(m2mlist):
"""
Maps objects from one list to the other list and vice versa.
Args:
m2mlist: list of 2lists [list1i, list2i] where list1i, list2i represent
a many to many mapping
Returns:
(one2two, two2one) : one2two, two2one
dictionaries from elements o... | edce4101213941dc08d2b32f4c4624ece02bf79c | 8,401 |
import codecs
import os
def _readfile(dirpath, filename):
"""
Read a complete file and return content as a unicode string, or
empty string if file not found
"""
try:
with codecs.open(os.path.join(dirpath, filename), "r", "utf-8") as f:
return f.read()
except IOError:
... | e4fb96aaccc4a3bc7837c182bf25796c724f3c5b | 8,402 |
import math
def calculate_inverse_log_density(cluster):
"""Calculate the log of inverse of Density of a cluster.
inverse of density-log = log-volume - ln(size)
Args:
cluster ():
Returns:
float: inverse of density-log
-inf if log-volume = -inf
"""
inverse_log_... | e6d6a77d078b080cd01d9fce47f9715562132864 | 8,403 |
def read_last_processed():
"""Read last processed build number."""
with open("last_processed", "r") as fin:
return int(fin.readline()) | 4362696222c0469c0150632650f07feb0f1a3273 | 8,406 |
def dirac(t, n, freq, pulse_delay):
"""
:param t: time sequence (s).
:type t: list of floats
:param n: time iteration index
:type n: int
:param freq: frequency of the sinusoid (Hz)
:type freq: float
:param pulse_delay: number of iteration for the delay of the signal defined
in the i... | 280234938eed8818666368d66b815ccb967b6dbb | 8,407 |
import torch
def DeterminePeople(tensor, classes):
""" Input: Tensor of all objects detected on screen
Output: Tensor of only 'people' detected on screen """
PersonIndexes = [] #Index of 'person' in tensor
CurrentIndex = 0
for t in tensor:
cls = int(t[-1])
ObjectDetected = "{0... | 37f0875fe4fbb5e636e5f63795b5634072fb80a7 | 8,409 |
def _l2t_section(label, include_section, include_marker):
"""Helper function converting section labels to text. Assumes
_l2t_subterp, _l2t_interp, and _l2t_appendix failed"""
if include_marker:
marker = u'§ '
else:
marker = ''
if include_section:
# Regulation Text with secti... | 01052effeba4f00fb1024d91c954aa6031153973 | 8,410 |
def extract_scores_from_outlist_file(outlist):
"""
:param outlist:
:return:
"""
scores = {'SEED': [], 'FULL': [], 'OTHER': []}
outlist_fp = open(outlist, 'r')
for line in outlist_fp:
if line[0] != '#':
line = [x for x in line.strip().split(' ') if x!='']
s... | cdaf7dca6784e6b7c5d9afd31b207d651824371e | 8,411 |
import os
def integration_url(scope="session"):
"""
returns an url
"""
test_url = os.getenv('TEST_URL_INTEGRATION', 'http://127.0.0.1')
port = os.getenv('TEST_PORT_INTEGRATION', 5000)
return f"{test_url}:{port}" | 7857f252ed82af027c93e991f0b079786ce0f6fc | 8,412 |
def is_aaai_url(url):
"""determines whether the server from url
@param url : parsed url
"""
return 'aaai.org' in url.netloc | 36a5a71de9c40ad287e44f064aa85053ed13eef9 | 8,414 |
import glob
import os
def read_batch_of_files(DIR):
"""Reads in an entire batch of text files as a list of strings"""
files = glob.glob(os.path.join(DIR,'*.txt'))
texts = []
for f in files:
with open(f,'r') as f:
texts.append(f.read())
return texts | 84068898e918cc6e4a073e6b6a11e7edc5b8cd75 | 8,415 |
def get_words_label(words_data: list) -> list:
"""
得到当前数据集下的词汇表
:param words_data: 读取到的词语数据
:return: 词汇表
"""
# 使用 set 去重
words_label = set({})
for words in words_data:
words_label.update(words[1])
res = list(words_label)
res.sort()
return res | d9ce0701c3c1baff1067d5c96a7730dc42b027f9 | 8,416 |
def hover_over(spell: str,
stopcast: bool = False,
dismount: bool = True,
) -> str:
""" Hover over target. """
macro = f'#showtooltip {spell}\n'
if stopcast:
macro += '/stopcast\n'
if dismount:
macro += '/dismount\n'
macro += f'/use [@mous... | 74586c97b971cbfab169c1777b6c82921015e8ba | 8,417 |
def read_story_file(filename):
"""read story file, return three lists, one of titles, one of keywords, one of stories"""
title_list, kw_list, story_list = [], [], []
with open(filename, 'r') as infile:
for line in infile:
title, rest = line.strip().split('<EOT>')
kw, story = ... | f354618f57eef3f8c842f2802044bc0fea0666f7 | 8,418 |
def rotate_points(points, width=600, height=300):
"""180 degree rotation of points of bbox
Parameters
----------
points: list or array
Coordinates of top-left, top-right, bottom-left and bottom-right points
width, height: int
Width/height of perspective transformed module image
Return... | ca15ebb21d9c34ba69049831395ce48de44c70a7 | 8,419 |
def inSkipTokens(start, end, skip_tokens: list) -> bool:
"""
Check if start and end index(python) is in one of skip tokens
"""
for token in skip_tokens:
if start >= token[0] and end <= token[1]:
return True
return False | a51124471eb9f1c3be84f132fc4cce3dad6ef336 | 8,420 |
def getBlock(lines, row):
"""
Parameters
----------
lines
row
Returns
-------
"""
block = []
for i in range(row, len(lines)):
if lines[i][0] == 'END':
return i, block
else:
if lines[i][0] != '#':
block.append(lines[i]) | 7c8f8e45084eb9ff92d7c68fc03bf285d98ab2d7 | 8,422 |
import os
def hasAWSEnviornmentalVariables():
"""Checks the presence of AWS Credentials in OS envoirnmental variables and returns a bool if True or False."""
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
if access_key and secret_key:
ret... | daaa2036d9cd50ea11e51217571d40cc37cb0e2f | 8,425 |
def shape(parameter):
"""
Get the shape of a ``Parameter``.
Parameters
----------
parameter: Parameter
``Parameter`` object to get the shape of
Returns
-------
tuple:
shape of the ``Parameter`` object
"""
return parameter.shape | ceb2b9a6199d980386b306ff329b797dc1815a29 | 8,427 |
def position_split(position_source, position_cible):
"""Prend les arguments positions_sources et position_cible et sépare la lettre et le chiffre. Les chiffres sont
transformé en entier dans l'objectif d'appliquer des opérations mathématiques. La lettre est transformé en
index dans l'objectif d'apli... | 51216b32614a6d9dd41216b445b9cc3036abf8f3 | 8,429 |
import os, subprocess
def get_mem_usage():
""" Get memory usage for current process """
pid = os.getpid()
process = subprocess.Popen("ps -orss= %s" % pid, shell=True, stdout=subprocess.PIPE)
out, _err = process.communicate()
return int(out) | 6b1897099c8038453eb705b76d0e63dc794dcbb7 | 8,430 |
import os
def get_last_modified(dirs):
"""Get the last modified time.
This method recursively goes through `dirs` and returns the most
recent modification time time found.
Parameters
----------
dirs : list[str]
list of directories to search
Returns
-------
int
mo... | 4ebc2679e8869097b8041bbe3ad893905fd94dca | 8,431 |
def get_maj_answer(votes_per_answer):
"""
:param votes_per_answer: dictionary with {'1': int, '2': int}, where the ints add up to NBR_ANNOTATORS
:return: the majority answers, i.e., number of votes at least half that of the number of annotators;
raises error if the answers are tied
"""
if (len(... | 87baeafd2ff39c4aa0ea970f501d1c195ffadecd | 8,432 |
import base64
def invoke_lambda_and_get_duration(lambda_client, payload, function_name):
"""
Invokes Lambda and return the duration.
:param lambda_client: Lambda client.
:param payload: payload to send.
:param function_name: function name.
:return: duration.
"""
response = lambda_clien... | c8d2b77e4f7bc338efcdfd21db4f7297a625b05c | 8,433 |
import re
def reglux_list(mydict,response):
"""
遍历正则抓取数据
:param mydict: 字典类型{key:正则表达式,}
:param response: request.text需要正则匹配的字符串
:return: 字典类型
"""
temp = {}
for m,n in mydict.items():
if '' != n:
pattern = re.compile(n)
matchs = pattern.findall(response)... | f75cad96991fedc6e1ab91a17abc1b8b91be6cdd | 8,434 |
import random
def read_stat():
"""
Mocks read_stat as this is a Linux-specific operation.
"""
return [
{
"times": {
"user": random.randint(0, 999999999),
"nice": random.randint(0, 999999999),
"sys": random.randint(0, 999999999),
... | 06889ca31c24aa890637ac63283091b096e48443 | 8,436 |
def bfs(graph):
"""Function that recreates the Breath First Search
algorithm, using a queue as its data structure.
In this algorithm, when a node is analyzed, it is
marked as visited and all of its children are
added to the queue (if they are not in it already).
The next node to be analyzed is g... | a14671a30d0c61389378ae44641901ec8dce8ac2 | 8,437 |
from pathlib import Path
def next_job_id(output_dir: Path) -> str:
"""Return the next job id."""
# The ids are of form "0001", "0002", ...
# Such ids are used for naming log files "0001.log" etc.
# We look for the first id that haven't been used in the output directory.
def make_job_id(n: int) ->... | 7fa35775e3bef8cf812b1173880c5be1ad3e6465 | 8,439 |
def POS(POSInt):
"""Returns 'F' if position indicator is present. The AllSportCG sends a * in a specific position to indicate which
team has posession, and this changes that character to an 'F'. Using font Mattbats, F is a football."""
POSText = ""
if POSInt == 42:
POSText = "F"
return(POSText) | 2f0dac3bfd0f803f1a60e740c104414bff29bf27 | 8,440 |
def is_visited(state, visited):
"""
Determines whether a State has already been visited.
Args:
state:
visited:
Returns:
"""
for visited_state in visited:
if state.shore == visited_state.shore and state.boat == visited_state.boat:
return True
return False | 567f85b63533188d58df4923e7e3a2a72da14943 | 8,441 |
def rgs_var(g, h, xoff, yoff):
"""Radiographs and variance with xoff and yoff offsets"""
gx0, hx0 = xoff, 0
if xoff < 0:
gx0, hx0 = 0, -xoff
nx = min(g.rg.shape[0]-gx0, h.rg.shape[0]-hx0)
gy0, hy0 = yoff, 0
if yoff < 0:
gy0, hy0 = 0, -yoff
ny = min(g.rg.shape[1]-gy0, h.rg.sha... | 17ebaecb34be1c67cb9454117097b574ce14998e | 8,442 |
def approx_match(stations, name):
"""
:param stations: dict เก็บข้อมูลพิกัดและอุณหภูมิของสถานีต่าง ๆ ในรูปแบบที่อธิบายมาก่อนนี้
:param name: เป็นสตริง
:return: คืนลิสต์ที่เก็บชื่อสถานีที่มีตัวอักษรใน name เป็นส่วนหนึ่งของชื่อสถานี โดยไม่สนใจว่าเป็นตัวพิมพ์เล็กหรือใหญ่
และไม่สนใจเว้นวรรคภายในด้วย (ชื... | 42338574242c7b866917e8480bc4accd4e569133 | 8,444 |
def get_xml_schema_type():
"""
Get xml schema type.
"""
return '{http://www.w3.org/2001/XMLSchema-instance}type' | 1704b7d6227cd88836f4a55488445192bf63c9aa | 8,445 |
def to_int(value):
"""Convert to integer"""
return value & 0xFF | 9045a7857dae407a196ccb29a142a8e243476b03 | 8,447 |
def get_P_fan_rtd_C(V_fan_rtd_C):
"""(12)
Args:
V_fan_rtd_C: 定格冷房能力運転時の送風機の風量(m3/h)
Returns:
定格冷房能力運転時の送風機の消費電力(W)
"""
return 8.0 * (V_fan_rtd_C / 60) + 20.7 | 52c3d887e2c1a9daaedaacfea28207cc31a14d81 | 8,448 |
def crop_2d(pts2d, Prect, bounds):
"""
Expects 2D coordinate points and a dict of bounds of traffic signs
"""
min_x = bounds['x'] - bounds['w']
max_x = bounds['x'] + bounds['w']
min_y = bounds['y'] - bounds['h']
max_y = bounds['y'] + bounds['h']
# print(min_x)
# print(max_x)
# print(min_y)
# print(max_y)
... | 2c218c518cd7a56bcb2c6ca87f9548d8ecc32c78 | 8,449 |
import pathlib
def get_tldname():
"""look in /etc/hosts or /etc/hostname to determine the top level domain to use
"""
basename = tldname = ''
with open('/etc/hosts') as hostsfile:
for line in hostsfile:
if not line.strip().startswith('127.0.0.1'):
continue
... | 5f1c4f7f63d0ffbd39a05d9529bffabaa2c5d216 | 8,451 |
import sys
def checkChangeLog(message):
""" Check debian changelog for given message to be present.
"""
for line in open("debian/changelog"):
if line.startswith(" --"):
return False
if message in line:
return True
sys.exit("Error, didn't find in debian/chang... | 7801a5207549a2ba48551c760f9d2781a79ed81e | 8,453 |
import numpy
def mean_average_error(ground_truth, regression, verbose=False):
""" Computes the mean average error (MAE).
Args:
ground_truth (list or 1-dim ndarray): ground truth labels.
regression (list or 1-dim ndarray): label estimations. Must have the same length as the ground tru... | 0bcc7fe67aa97dcf44595a6f2ef63ed242b29837 | 8,454 |
from typing import Union
from pathlib import Path
import base64
def read_as_base64(path: Union[str, Path]) -> str:
"""
Convert file contents into a base64 string
Args:
path: File path
Returns:
Base64 string
"""
content = Path(path).read_text()
return base64.b64encode(cont... | bf4071662fd335882f50e10b72e7623d5e84d855 | 8,457 |
def type_equals(e, t):
"""
Will always return true, assuming the types of
both are equal (which is checked in compare_object)
"""
return True | 7d394ab23369854476c91d85c4160cd177fa125f | 8,458 |
def set_active_design(oProject, designname):
"""
Set the active design.
Parameters
----------
oProject : pywin32 COMObject
The HFSS design upon which to operate.
designname : str
Name of the design to set as active.
Returns
-------
oDesign : pywin32 COMObjec... | 825108bbfe21baa73e256d527fb982919a6b08ea | 8,461 |
def write_tags(tag, content='', attrs=None, cls_attr=None, uid=None, new_lines=False, indent=0,
**kwargs):
"""
Write an HTML element enclosed in tags.
Parameters
----------
tag : str
Name of the tag.
content : str or list(str)
This goes into the body of the elemen... | ed0ade998b0232b8bca5cbb6083f8b60481b3ad9 | 8,462 |
def calc_BMI(w,h):
"""calculates the BMI
Arguments:
w {[float]} -- [weight]
h {[float]} -- [height]
Returns:
[float] -- [calculated BMI = w / (h*h)]
"""
return (w / (h*h)) | ee4d7b99a0bb1129d316c7031a65c465092358a3 | 8,464 |
def get_message_box_text():
"""Generates text for message boxes in HTML."""
html_begin = '<span style="font-size: 15px">'
html_end = '</span>'
shortcuts_table = "<table>" \
"<tr>" \
"<th>Shortcuts </th>" \
... | 29eb35e2b968fa125b77fde08669b75b5372de71 | 8,465 |
import os
import pickle
def load(filename: str) -> object:
"""
Load from pickle file
:param filename:
:return:
"""
if not os.path.exists(filename):
raise Exception(f"Unable to fine file {filename}")
with open(filename, 'rb') as fin:
obj = pickle.load(fin)
return obj | 3cda74b48c4e7d70d9b6462284e0bcafb8469f8e | 8,466 |
def get_file_content(filename):
""" Function reads the given file
@parameters
filename: Path to the file
@return
This function returns content of the file inputed"""
with open(filename, encoding='utf-8', errors='ignore') as file_data: # pragma: no mutate
return file_data... | 1396b6eae7addd329466e1e3ad597cf965360b60 | 8,467 |
def mb_to_human(num):
"""Translates float number of bytes into human readable strings."""
suffixes = ['M', 'G', 'T', 'P']
if num == 0:
return '0 B'
i = 0
while num >= 1024 and i < len(suffixes) - 1:
num /= 1024
i += 1
return "{:.2f} {}".format(num, suffixes[i]) | 95f6ae29c8031347e32f51f349afc986abe31473 | 8,470 |
def success(message, data=None, code=200):
"""Return custom success message
Args:
message(string): message to return to the user
data(dict): response data
code(number): status code of the response
Returns:
tuple: custom success REST response
"""
response = {'status':... | 721542f71ad3a641efbe0a0d62723a2df23960a5 | 8,471 |
def past_days(next_day_to_be_planned):
"""
Return the past day indices.
"""
return range(1, next_day_to_be_planned) | d4b0e7387303f48bc3668f5d71b374dace6e7f44 | 8,473 |
import argparse
def parse_args(args):
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description='Run opsdroid.')
parser.add_argument('--gen-config', action="store_true",
help='prints out an example configuration file')
return parser.parse_args(args) | e4bf8f3117c5064f6dc76f257eb63233e69da3cb | 8,475 |
def import_obj(obj_path, hard=False):
"""
import_obj imports an object by uri, example::
>>> import_obj("module:main")
<function main at x>
:param obj_path: a string represents the object uri.
;param hard: a boolean value indicates whether to raise an exception on
impor... | cceed0d6162d4ab281472c1f2c9bb58a0b9195d1 | 8,476 |
from datetime import datetime
def generate_date_now():
"""Get current timestamp date."""
return "{0}".format(datetime.utcnow().strftime('%s')) | 84489bee5b01537c273c4dc64e96586434c405e4 | 8,477 |
import random
def create_contig_and_fragments(contig, overlap_size, fragment_size):
"""
Creates a contig and overlapping fragments
:param str contig: original sequence to create test data from
:param int overlap_size: number of bases fragments should overlap
:param int fragment_size: length of ba... | cb6394004f1500aefb55354cadd9788ab29749f7 | 8,479 |
def assign_road_name(x):
"""Assign road conditions as paved or unpaved to Province roads
Parameters
x - Pandas DataFrame of values
- code - Numeric code for type of asset
- level - Numeric code for level of asset
Returns
String value as paved or unpaved
"""
... | 01bf8bccca43aa833e3d9edfcbfe0213e30d9ac0 | 8,480 |
def GetGap ( classes, gap_list ):
"""
Input
classes: {课号:{教师姓名:[完成课时,完成课时比例,完成业绩]}} (dict)
Output
availableT: available teacher list,在职教师名及其完成业绩(tuple)
unavailableT: unavailable teacher list,离职 & 管理岗教师名及其完成业绩(tuple)
gap:由离职 & 管理岗教师产生的业绩缺口(float)
"""
gap = 0
availableT = []
... | 4c9bba825d4763e8c98c3f01f623b331d97a5cd4 | 8,481 |
def generateMessage(estopState, enable, right_vel, left_vel):
"""
Accepts an input of two bools for estop and enable.
Then two velocities for right and left wheels between -100 and 100
"""
# Empty list to fill with our message
messageToSend = []
# Check the directions of the motors, False =... | 3c0d2f912ee1fca4e819b0b5813de48b7f1bb338 | 8,482 |
def cost_deriv(a, y):
"""Mean squared error derivative"""
return a - y | 15d02e49af734f9ad95e63214055f4dda58d41f4 | 8,483 |
from pathlib import Path
def read_cd_files(prefix: Path, fname: str) -> dict:
"""
result[name] = path-to-the-file
name: e.g., 08-1413.jpg
pato-to-the-file: e.g., /cifs/toor/work/2011/cyclid data/./CD9/2008-06-19/08-1413.jpg
"""
result = {}
with open(fname) as f:
for line in f:
... | c8b16b01819d00be0efb2f12cc25eeb7730facf9 | 8,486 |
def _generate_spaxel_list(spectrum):
"""
Generates a list wuth tuples, each one addressing the (x,y)
coordinates of a spaxel in a 3-D spectrum cube.
Parameters
----------
spectrum : :class:`specutils.spectrum.Spectrum1D`
The spectrum that stores the cube in its 'flux' attribute.
Re... | 9d4b5339f18022607f349c326dc83e319a690a26 | 8,488 |
import logging
import argparse
import sys
import os
def get_args():
"""
Read arguments from the command line and check they are valid.
"""
logger = logging.getLogger("stats.args")
parser = argparse.ArgumentParser(
description="Extract alignment statistics from a SAM/BAM file")
parser... | c6747dea5b9579243ef538ab1fc5fb07e0ab7e70 | 8,489 |
import re
def get_frame_rate_list(fmt):
"""Get the list of supported frame rates for a video format.
This function works arround an issue with older versions of GI that does not
support the GstValueList type"""
try:
rates = fmt.get_value("framerate")
except TypeError:
# Workaround ... | d3db15553a9bd28dc7be0754c7c8202e20aab8d2 | 8,490 |
def convert_null_to_zero(event, field_or_field_list):
""" Converts the value in a field or field list from None to 0
:param event: a dict with the event
:param field_or_field_list: A single field or list of fields to convert to 0 if null
:return: the updated event
Examples:
.. code-block:: py... | c81bf5909d13b9cb2ce759c3ab0643e03b95c203 | 8,491 |
def setBit(int_type, offset, value):
"""following 2 functions derived from https://wiki.python.org/moin/BitManipulation, this one sets a specific bit"""
if value == 1:
mask = 1 << offset
return(int_type | mask)
if value == 0:
mask = ~(1 << offset)
return(int_type & mask) | 642e8ffb41aaf3c5514038e525275c053a4cd8b1 | 8,492 |
from typing import Dict
from typing import Any
def get_xml_config_gui_settings(xml_dict: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Get the tool configuration from the config XML.
Parameters
----------
xml_dict: OrderedDictionary
Parsed XML Tool configuration
Returns
-------
Orde... | a13168d8441093f8fb6ce341fd07c5e51d4169a7 | 8,493 |
def deduplicate_list(list_with_dups):
"""
Removes duplicate entries from a list.
:param list_with_dups: list to be purged
:type lost_with_dups: list
:returns: a list without duplicates
:rtype: list
"""
return list(set(list_with_dups)) | 7034f1d8533613f9478916ce7f4b18fd9f94bfe4 | 8,494 |
def adjust_factor(x, x_lims, b_lims=None):
"""
:param float x: current x value
:param float x_lims: box of x values to adjust
:param float b_lims: bathy adj at x_lims
:rtype: float
:returns: b = bathy adjustment
"""
if b_lims is None:
return 0
if x < x_lims[0] or x > x_lims[... | b0f92eef6098894fa54a3a3ed55fc01b7f6dae95 | 8,496 |
def is_empty_element_tag(tag):
"""
Determines if an element is an empty HTML element, will not have closing tag
:param tag: HTML tag
:return: True if empty element, false if not
"""
empty_elements = ['area', 'base', 'br', 'col', 'colgroup', 'command', 'embed', 'hr',
... | 429129246c7458f0928f22f8b99db03763c2b699 | 8,497 |
def get_outlier_definition(biomarker):
"""
Centralised definitions of biomarker outliers for filtering
"""
if biomarker == "APHalfWidth":
outlier_definition = 100.0 # ms
else:
raise ValueError(f"Biomarker {biomarker} not found.")
return outlier_definition | 27876fd83c644d7c4f751b99ab2703044e54f41d | 8,498 |
def get_incident_message_ids(client, incident_id):
"""
Returns the message ids for all the events for the input incident.
"""
detail_response = client.get_incident_details(incident_id)
message_ids = []
# loop through all the events of this incident and collect the message ids
if 'events' in... | 3067eb438effb2977fd3a724a284bd58f485b743 | 8,499 |
def _Dirname(path):
"""Returns the parent directory of path."""
i = path.rfind("/") + 1
head = path[:i]
if head and head != "/" * len(head):
head = head.rstrip("/")
return head | 075063a6dd29456f4adb969621d9727aa187d53b | 8,500 |
def IsLoopExit(op):
"""Return true if `op` is an Exit."""
return op.type == "Exit" or op.type == "RefExit" | dbc24fa0efa69447416963a9911c7fae3fd1f244 | 8,503 |
import os
def fasta_file_to_lists(path, marker_kw=None):
"""Reads a FASTA formatted text file to a list.
Parameters
----------
path : str
Location of FASTA file.
marker_kw : str
Keyword indicating the sample is a marker.
Returns
-------
dict
Contains list of i... | b8a70b6ee697fdd52d117e4a1bdfed8fe79d84d5 | 8,504 |
def islazy(f):
"""Internal. Return whether the function f is marked as lazy.
When a function is marked as lazy, its arguments won't be forced by
``lazycall``. This is the only effect the mark has.
"""
# special-case "_let" for lazify/curry combo when let[] expressions are present
return hasattr... | 7dd0a09f6a0e60b252ece344d62a937393598167 | 8,505 |
def _sample_ncols(col_limits, random_state):
""" Sample a valid number of columns from the column limits. """
integer_limits = []
for lim in col_limits:
try:
integer_lim = sum(lim)
except TypeError:
integer_lim = lim
integer_limits.append(integer_lim)
re... | e31f2e290910b9e7376750b18a6ca6436a82a0cb | 8,506 |
import string
def is_printable(s: str) -> bool:
"""
does the given string look like a very simple string?
this is just a heuristic to detect invalid strings.
it won't work perfectly, but is probably good enough for rendering here.
"""
return all(map(lambda b: b in string.printable, s)) | 78941ba7daca94274fc1b238b6f411f73fc875f6 | 8,507 |
import re
def get_index_of_tone_vowel(syllable):
"""
Returns the index of the vowel that should be marked with a tone accent in a given syllable.
The tone marks are assigned with the following priority:
- A and E first
- O is accented in OU
- otherwise, the *final* vowel
Returns -1 if n... | 97d4f724f56ce3270e317b4d885b3ac5730e59f5 | 8,508 |
def statement_block(evaluator, ast, state):
"""Evaluates statement block "{ ... }"."""
state.new_local_scope()
for decl in ast["decls"]:
evaluator.eval_ast(decl, state)
for stmt in ast["stmts"]:
res, do_return = evaluator.eval_ast(stmt, state)
if do_return:
state.remo... | e38575e5e2119cd9794ea5f0b1629cecf411a0e9 | 8,509 |
def _create_query_dict(query_text):
"""
Create a dictionary with query key:value definitions
query_text is a comma delimited key:value sequence
"""
query_dict = dict()
if query_text:
for arg_value_str in query_text.split(','):
if ':' in arg_value_str:
arg_valu... | 2e4478bdf110911d4ca9fcc6c409aab3504a0b8a | 8,510 |
def _getVersionString(value):
"""Encodes string for version information string tables.
Arguments:
value - string to encode
Returns:
bytes - value encoded as utf-16le
"""
return value.encode("utf-16le") | 36646a686c17f2c69d71a0cdeede56f0a1e514e2 | 8,511 |
from typing import List
from typing import Optional
def get_shift_of_one_to_one_match(matches: List[List[bool]]) -> Optional[int]:
"""
Matches is an n x n matrix representing a directed bipartite graph.
Item i is connected to item j if matches[i][j] = True
We try to find a shift k such that each item ... | f8168e72dab64acc26841a49122dcf08d473ea1f | 8,512 |
def plurality(l):
"""
Take the most common label from all labels with the same rev_id.
"""
s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0])
s.name = 'y'
return s | 4e363648e79b5e9049aca2de56fd343c1efe1b93 | 8,513 |
def _handle_text_outputs(snippet: dict, results: str) -> dict:
"""
Parse the results string as a text blob into a single variable.
- name: system_info
path: /api/?type=op&cmd=<show><system><info></info></system></show>&key={{ api_key }}
output_type: text
outputs:
- name: system_in... | 693a3e5cba6d72d09b2adb3745abb4fcf07f92d3 | 8,515 |
from datetime import datetime
def parse_timestamp(datetime_repr: str) -> datetime:
"""Construct a datetime object from a string."""
return datetime.strptime(datetime_repr, '%b %d %Y %I:%M%p') | ddacf877c55466354559f751eac633b5bcd7313c | 8,516 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.