content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def upload_bytes(interface: str, scale="bytes", precision=2):
"""Returns total bytes uploaded in the given interface
:Params:
:interface (str): Interface name
:scale (str): Chosen scale (bytes, KiB, MiB, GiB, TiB, kB, MB, GB, TB or auto)
:precision (int): Number of r... | 63,200 |
def ref_validator(
validator, # type: Draft4Validator
ref, # type: typing.Any
instance, # type: typing.Any
schema, # type: JSONDict
):
# type: (...) -> typing.Generator[ValidationError, None, None]
"""When validating a request or response that contain $refs, jsonschema's
RefResolver onl... | 63,201 |
def fidelity(state1: np.ndarray, state2: np.ndarray) -> float:
"""Fidelity of two quantum states.
The fidelity of two density matrices ρ and σ is defined as
trace(sqrt(sqrt(ρ) σ sqrt(ρ)))^2.
The given states can be state vectors or density matrices.
Args:
state1: The first state.
... | 63,202 |
async def test_all_users_answered():
"""
when all users answer
the game should end
"""
user1_id = 1
user2_id = 2
send_message_mock = AsyncMock()
mock_message = AsyncMock()
team_data = TeamData(2)
trivia_bot = TriviaBot(team_data=team_data,
quest... | 63,203 |
def preprocess_img(img_path, height, width, channel):
""" pre-process images located in img_path parameter
by resizing them to desired shape then horizontally flip them to double the data size
:param list of str img_path: locations of all images in the list
:param int height: desired height
:pa... | 63,204 |
def main():
"""
Parse command-line arguments, compute and print answers.
"""
parser = argparse.ArgumentParser(description=\
'Bayesian Audit Process For'
'A Single Contest '
'Across One or More... | 63,205 |
def _iter_extension_names_and_paths(name):
"""
Fetches the names
This function is a generator.
Parameters
----------
name : `str` or `iterable` of `str`
The name to fetch to single strings.
Yields
------
name : `str`
Extension names.
path : `str`
... | 63,206 |
def compute_headings(traces):
"""
Given a list of traces, compute the heading of each point and append.
"""
headings = []
for trace in traces:
trace_headings = []
dir_vector = direction(trace[0], trace[1])
angle = atan2(dir_vector[1], dir_vector[0])
if angle < 0:
angle += 2*pi
tr... | 63,207 |
def _describe_marketplace_bp(name, out, version, source, app_state):
"""Describe a marketplace manager blueprint"""
describe_marketplace_bp(
name=name, out=out, version=version, app_source=source, app_state=app_state
) | 63,208 |
def venn(data, names=None, fill="number", show_names=True, show_plot=True, outputDir=False, **kwds):
"""
data: a list
names: names of groups in data
fill = ["number"|"logic"|"both"], fill with number, logic label, or both
show_names = [True|False]
show_plot = [True|False]
"""
if data is None:
raise Exc... | 63,209 |
def createobslogfits(headerDict):
"""Create the fits table for the observation log"""
# define generic columns of output table
col=[]
for k, f in zip(headerList, formatList):
print k,f, headerDict[k]
col.append(fits.Column(name=k, format=f, array=headerDict[k]))
for k, f in zip(scamheaderLi... | 63,210 |
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... | 63,211 |
def ExecuteBlueprint():
"""
Execute a blueprint on the ZeroRobot
It is handler for POST /blueprints
"""
return handlers.ExecuteBlueprintHandler() | 63,212 |
def getFatherPath(path):
"""
获取指定路径下面文件夹的父路径
:param path: 文件路径
:return:
"""
print(os.path.dirname(path)) | 63,213 |
def vgg8(**kwargs):
"""VGG 8-layer model (configuration "S")
"""
model = VGG(config['S'], **kwargs)
return model | 63,214 |
def pn_cli(module):
"""
This method is to generate the cli portion to launch the Netvisor cli.
It parses the username, password, switch parameters from module.
:param module: The Ansible module to fetch username, password and switch.
:return: The cli string for further processing.
"""
userna... | 63,215 |
def get_botnet_pcap_db():
"""
Reads a botnet resource pcap, calculates statistics for it and returns the DB path.
:return: the database path for the botnet resource pcap statistics DB
"""
import Core.Statistics
import Lib.PcapFile as PcapFile
bot_pcap = PcapFile.PcapFile(BOTNET_PCAP)
b... | 63,216 |
def colorize(msg, color):
"""Given a string add necessary codes to format the string."""
if DONT_COLORIZE:
return msg
else:
return '{0}{1}{2}'.format(COLORS[color], msg, COLORS['endc']) | 63,217 |
def setplot(plotdata):
#--------------------------
"""
Specify what is to be plotted at each frame.
Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
Output: a modified version of plotdata.
"""
from clawpack.visclaw import colormaps
plotdata.clearfigures() # clear an... | 63,218 |
def generateCircles(n):
"""
生成圆圈数据
"""
data, _ = make_circles(n_samples=n, factor=0.5, noise=0.06)
return data | 63,219 |
async def test_setup_camera_bad_data(hass: HomeAssistant) -> None:
"""Test bad camera data."""
client = create_mock_motioneye_client()
cameras = copy.deepcopy(TEST_CAMERAS)
del cameras[KEY_CAMERAS][0][KEY_NAME]
client.async_get_cameras = AsyncMock(return_value=cameras)
await setup_mock_motioney... | 63,220 |
def CopyFile(src, dst):
"""Copy a file from src to dst."""
shutil.copy(src, dst)
print "Copying %s to %s" % (src, dst) | 63,221 |
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)) | 63,222 |
async def wait_for(fut: Union[Future, Task, Coroutine], timeout: Union[int, float], loop: base_loop.BaseLoop=None) -> Coroutine[Any, None, None]:
"""
wait for a Future to be completed in `timeout` seconds if the Future isn`t done until then, this function
raises RuntimeError(for now) indicating its been wa... | 63,223 |
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>" \
... | 63,224 |
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 | 63,225 |
def find_serial_port(ports_list=None):
""" Return the port path once the device is identified, otherwise raise an exception. """
device_info_request = bytearray([0x01, 0x2b, 0x0e, 0x01, 0x00, 0x70, 0x77]) # Raw device information request
if not ports_list:
# This pythonic line of code creates a l... | 63,226 |
def _formal_post_request(hub, endpoint, **data):
"""
Required Parameters:
hub.callback Subscribers Endpoint
hub.mode subscribe / unsubscribe
hub.topic Content of Subcription
Optional Parameters:
hub.lease_seconds Duration of the subscription in ... | 63,227 |
def config_cursor(db_params):
"""
Construct module name from server type, and import module.
The DbCursor class consists of a number of methods and attributes.
Some of these need to be customised for use according to the actual
RDBMS in use. The customised versions are stored in their own modules
... | 63,228 |
def _copy_test_requires_to(egg_info_dir):
"""Copy the requirements file to egg-info/test-requires.txt."""
with open(os.path.join(egg_info_dir, 'test-requires.txt'), 'w') as dest:
for source in _any_existing(TEST_REQUIREMENTS_FILES):
dest.write(open(source, 'r').read().rstrip('\n') + '\n') | 63,229 |
def CalculateBurdenVDW(mol):
"""
#################################################################
Calculate Burden descriptors based on atomic vloumes
res-->dict type with 16 descriptors
#################################################################
"""
temp = _GetBurdenMatrix(mol, prop... | 63,230 |
def getUploadedMd5(req, courseId, assignmentId):
""" Returns the md5 file for the current user"""
websutil.sanityCheckAssignmentId(assignmentId)
websutil.sanityCheckCourseId(courseId)
# Check permission
req.content_type = 'text/html'
s = Session.Session(req)
if s.is_new():
s.invali... | 63,231 |
def PolicyIteration(gamma=0.95, th=0.01):
"""
policy iterationで状態の価値評価する.
->return:状態価値テーブルV
"""
actions = list(range(4))
states = all_solvable_boards()
policy = {}
for state in states:
policy[tuple(state)] = [random() for _ in actions]
def estimate_by_policy(gamma,th,policy... | 63,232 |
def create_dataset_group(name=None, roleArn=None, kmsKeyArn=None):
"""
Creates an empty dataset group. A dataset group contains related datasets that supply data for training a model. A dataset group can contain at most three datasets, one for each type of dataset:
To train a model (create a solution), a da... | 63,233 |
def test_require_title_and_author(title, author, mock_jstor):
"""
Skip records that don't have a query-able title and author.
"""
mock_jstor.add_article(article_title=title, author=author)
Text.ingest_jstor()
assert Text.select().count() == 0 | 63,234 |
def scale_destructive(im, fac):
"""Degrades image by reducing scale then rescaling to original size
"""
amt = np.interp(fac, [0.0, 1.0], (1.0, 0.25))
w,h = im.shape[:2][::-1]
nw,nh = (int(amt * w), int(amt * h))
im_dst = resize(im, width=nw, height=nh, interp=cv.INTER_CUBIC)
im_dst = resize(im_dst, width=... | 63,235 |
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... | 63,236 |
def _files(*p_args, **p_kwargs):
"""
:param p_args:
:param p_kwargs:
:return:
"""
def paramed_decorator(func):
@functools.wraps(func)
def decorated(*args, **kwargs):
request = args[0]
for file_name in p_args:
fp = request.FILES.get(file_n... | 63,237 |
def query_candidates(conn, road_table_name, sequence, search_radius):
"""
サーチ円内に存在するシーケンスデータの各々の計測データの候補をクエリーする
Query candidates of each measurement in a sequence within
search_radius.
"""
stmt = '''
WITH
--- WITH sequence AS (subquery here),
seq AS (SELECT *,
... | 63,238 |
def _process_parallel(tasks, data, reduce_method=combine_result_with_and):
"""Process a list of tasks in parallel
This method processes a list of tasks and then
combines the results using the reduce_method
Args:
tasks (list): List of bound tasks
data (Result): 'Boxed' data input for ta... | 63,239 |
def read_corpus(corpus_dir):
"""
Read de corpus html files from the received directory.
:param corpus_dir: corpus directory
:return: {doc_name:[doc_terms]}
"""
LOGGER.info('Reading corpus')
corpus = {}
for _, _, files in os.walk(corpus_dir):
for file in files:
content... | 63,240 |
def math_sinh(x):
"""Implement the SQLite3 math built-in 'sinh' via Python.
"""
try:
return math.sinh(x)
except:
pass | 63,241 |
def rand_string(n):
"""
Return a random string.
"""
return ''.join(
random.SystemRandom().choice(
string.ascii_lowercase + string.digits) for _ in range(n)) | 63,242 |
def authenticate(email: str, pw: str) -> Return:
"""Checks the user's email and password to authenticate them.
Args:
email: The user's email address.
pw: The user's password
Returns:
An object describing the status of the user's attempt.
"""
user = db.session.query(User).fi... | 63,243 |
def inverted_indexing():
"""
TODO: Missing documentation
"""
path = sys.argv[1]
start_time = time.time()
result = DDS().load_files_from_dir(path).flat_map(_invert_files)\
.reduce_by_key(lambda a, b: a + b).collect()
print(result[-1:])
print("Elapsed Time {} (s)".format(time.time(... | 63,244 |
def is_thursday(date_str):
"""
>>> is_thursday('2019-07-03')
False
>>> is_thursday('2019-07-04')
True
>>> is_thursday('1999-11-04')
True
"""
d = date.fromisoformat(date_str)
return d.weekday() == 3 | 63,245 |
def dump_json_list_to_ndjson(log, json_, local_file_path: str, bq_fix: bool = True, bq_c_fix: dict = None,
already_flat: bool = False, **kwargs):
"""
Dump List of Dicts to NDJSON (Newline Delimited JSON)
:param log: logger obj
:param json_: List of Dicts
:param local_fi... | 63,246 |
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]) | 63,247 |
def inrad(v1, v2, r):
"""Are two points winthin r?"""
if (abs(v1[0]-v2[0])) > r:
return False
elif (abs(v1[1]-v2[1])) > r:
return False
elif (abs(v1[2]-v2[2])) > r:
return False
elif dvv(v1,v2) > r:
return False
else:
return True | 63,248 |
def check_n_cycles(n_cycles, len_cycles=None):
"""Check an input as a number of cycles definition, and make it iterable.
Parameters
----------
n_cycles : float or list
Definition of number of cycles.
If a single value, the same number of cycles is used for each frequency value.
... | 63,249 |
def get_neuroh5_cell_data(f):
"""
Parameters
----------
f: h5py.File
Yields
-------
dict
"""
labs = f['H5Types']['Population labels']
population_table = f['H5Types']['Populations']
cell_types_order = {labs.id.get_member_value(i): labs.id.get_member_name(i)
... | 63,250 |
def get_test_triplegs_with_modes():
"""get modal split for randomly generated data"""
n = 200
day_1_h1 = pd.Timestamp('1970-01-01 00:00:00', tz='utc')
one_day = datetime.timedelta(days=1)
mode_list = ['car', 'walk', 'train', 'bus', 'bike', 'walk', 'bike']
df = pd.DataFrame(index=np.arange(n))
... | 63,251 |
def sample_batch(scramble_buffer, net, device, batch_size, value_targets):
"""
Sample batch of given size from scramble buffer produced by make_scramble_buffer
:param scramble_buffer: scramble buffer
:param net: network to use to calculate targets
:param device: device to move values
:param batc... | 63,252 |
def solve_nonlinear(info_dict, eps_fn, b, iterative=False, method=DEFAULT_SOLVER, verbose=False, atol=1e-10, max_iters=10):
""" Solve Ax=b for x where A is a function of x using direct substitution """
def relative_residual(eps, x, b):
""" computes relative residual: ||Ax - b|| / ||b|| """
A = ... | 63,253 |
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':... | 63,254 |
def test_try_body_correct_default(
assert_errors,
parse_ast_tree,
default_options,
code,
statements,
):
"""Testing that default settings raise a warning."""
tree = parse_ast_tree(code.format(statements))
visitor = TryExceptVisitor(default_options, tree=tree)
visitor.run()
asser... | 63,255 |
def confidenceInterval(x, p):
"""
returns the smallest interval (start, end) and its size
that covers at least a fraction of 'p' of the data-points
given by x.
"""
import math
x = sort(array(x))
## set n to the next integer that is greater or equal
## to #data-points * p.
n =... | 63,256 |
def test_update_comment_ignore_reports(
staff_client, private_channel_and_contributor, reddit_factories
):
"""Update a comment to ignore reports as a moderator"""
channel, user = private_channel_and_contributor
post = reddit_factories.text_post("post", user, channel=channel)
comment = reddit_factori... | 63,257 |
def tokenize(s):
"""
Ковертирует строку в питон список токенов
"""
return s.replace('(', ' ( ').replace(')', ' ) ').replace('>', ' > ').replace('-', ' - ').split() | 63,258 |
def refresh_report(filename, data_sources, variables_filters):
"""execute the flow necessary to refresh de desired report"""
# initiate workbook
SapReport = SapRefresh()
# configure path
data_directory = pathlib.Path(global_configs_df.query('description=="path-data_directory"')['value'].values[0])
... | 63,259 |
def acoustics2D(iplot=False,kernel_language='Fortran',htmlplot=False,use_petsc=False,outdir='./_output',solver_type='classic'):
"""
Example python script for solving the 2d acoustics equations.
"""
if use_petsc:
from clawpack import petclaw as pyclaw
else:
from clawpack import pycla... | 63,260 |
def show_size_of_family_accuracy_comparisons(all_family_predictions):
"""Compare, using charts and measurements, effect of size on accuracy.
Args:
all_family_predictions: pandas DataFrame with 3 columns,
classification_util.PREDICTION_FILE_COLUMN_NAMES.
"""
cxn = pfam_utils.connection_with_tmp_table(... | 63,261 |
def run_tests_with_coverage(test_labels, verbosity=1, interactive=True, extra_tests=[], xml_out=False):
"""
Run the unit tests for all the test labels in the provided list.
Labels must be of the form:
- app.TestClass.test_method
Run a single specific test method
- app.TestClass
Run... | 63,262 |
def clean_tests(c):
"""Clean up files from testing"""
_delete_file(COVERAGE_FILE)
shutil.rmtree(TOX_DIR, ignore_errors=True)
shutil.rmtree(COVERAGE_DIR, ignore_errors=True) | 63,263 |
def snmp_enable(handle, community=None,
privilege="disabled", trap_community=None,
sys_contact=None, sys_location=None, port="161", **kwargs):
"""
Enables SNMP.
Args:
handle (ImcHandle)
community (string): community
privilege (string): "disabled", "li... | 63,264 |
def reset_model(n_clicks):
"""
Creates the model at loading, then upon click, resets the model, and probably solve all human problems
inputs:
reset_model n_clicks (int): clicks on the button
outputs:
reset_model_status children (string): the status update
"""
global vae_model, o... | 63,265 |
def clean_ufo(path):
"""Make sure old UFO data is removed, as it may contain deleted glyphs."""
if path.endswith('.ufo') and os.path.exists(path):
shutil.rmtree(path) | 63,266 |
def main(
sonos_device_name: str,
backlight_directory: str,
window_width: int,
window_height: int,
playback_information_refresh_interval: int
) -> None:
"""Control your Sonos device with your keyboard"""
with SonosDevice(sonos_device_name) as sonos_device:
with Ba... | 63,267 |
def test_when_condition_in_target_string_or_array(if_statement_validator):
"""When condition is `in` target must be `string` or `array`."""
test = {
'condition': 'in',
'target': 123,
'then': 'bob',
}
validate_result = if_statement_validator(test)
assert not is_successful(val... | 63,268 |
def GetKey():
"""Fetches rcpkey from metadata of the instance.
Returns:
RPC key in string.
"""
try:
response = urllib.urlopen(
'http://metadata/computeMetadata/v1beta1/instance/attributes/rpckey')
return response.read()
except IOError:
return '' | 63,269 |
def past_days(next_day_to_be_planned):
"""
Return the past day indices.
"""
return range(1, next_day_to_be_planned) | 63,270 |
def get_client():
"""Return instance of _Mongo with set up connection.
If connection exists and is new, reuse it. If it is old, check if it is
working and reuse it, or create new one.
"""
global _GLOBAL_MONGO_CHECKUP
global _GLOBAL_MONGO
last_success = _GLOBAL_MONGO_CHECKUP or 1
if last... | 63,271 |
def test_paragraph_series_m_ib_ol_ol_nl_i4_t_ib():
"""
Test case: Ordered list x2 newline indent of 4 text (indented block)
"""
# Arrange
source_markdown = """1. 1.
foo
"""
expected_tokens = [
"[olist(1,1):.:1:3:: ]",
"[olist(1,4):.:1:6: ]",
"[BLANK(1,6):]",
... | 63,272 |
def test_server_process_noop(loop):
"""Make sure the server exits after the with statement."""
with (yield from Server([], loop=loop)) as server:
assert server.is_running
yield from asyncio.sleep(0.05)
assert not server.is_running | 63,273 |
def range_window(preceding=None, following=None, group_by=None, order_by=None):
"""Create a range-based window clause for use with window functions.
This RANGE window clause aggregates rows based upon differences in the
value of the order-by expression.
All window frames / ranges are inclusive.
P... | 63,274 |
def wrapto360(angle):
"""
Wrap a value on -180, 180 to 360.
:param degrees: float
:return: float
"""
if angle >= 0:
return angle
else:
return 360 + angle | 63,275 |
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) | 63,276 |
def test_multiple_subscriptions(message_maker, run_services, tracker):
"""
Test multiple subscriptions
The tested service has one channel handled by multiple entrypoints
and also multiple channels handled by one entrypoint.
Simulates successful handshake, subscription to three channels
and a f... | 63,277 |
def get_collection_member(
query_info: Dict[str, str], session: scoped_session
) -> Dict[str, str]:
"""
Get member from a collection
:param query_info: Dict containing the ids and @type of object that has to retrieved
:param session: sqlalchemy session
:return: dict of object with its properties... | 63,278 |
def deci2sexa(deci, pre=3, trunc=False, lower=None, upper=None,
b=False, upper_trim=False):
"""Returns the sexagesimal representation of a decimal number.
Parameters
----------
deci : float
Decimal number to be converted into sexagesimal. If `lower` and
`upper` are given t... | 63,279 |
def get_bprop_get_tensor_slice_operator(self):
"""Backpropagator for _GetTensorSlice"""
def bprop(x, dev_mat, tensor_map, out, dout):
return (zeros_like(x),)
return bprop | 63,280 |
def simple_email(
subject='',
message='',
sender=None,
to=None,
fail_silently=False
):
"""Sends a simple email
"""
sender = sender or htk_setting('HTK_DEFAULT_EMAIL_SENDER', HTK_DEFAULT_EMAIL_SENDER)
to = to or htk_setting('HTK_DEFAULT_EMAIL_RECIPIENTS', HTK_DEFAULT_EMAIL_RECIPIENTS)... | 63,281 |
def test_is_list_exist(mocker, list_name, get_list_res, expected):
"""
Given:
- Case A: List named list1 and getList response which include the list
- Case A: List named list2 and getList response which contains an error that list was not found
When:
- Running IsListExist
Then:... | 63,282 |
def download(outformat, path, identifier, namespace='cid', domain='compound', operation=None, searchtype=None,
overwrite=False, **kwargs):
"""Format can be XML, ASNT/B, JSON, SDF, CSV, PNG, TXT."""
response = get(identifier, namespace, domain, operation, outformat, searchtype, **kwargs)
if not... | 63,283 |
def compute_o_value_legacy(owner_pwd, user_pwd, rev, keylen):
"""
Implementation of algorithm 3.3 of the PDF standard security handler,
section 3.5.2 of the PDF 1.6 reference.
"""
# steps 1 - 4
key = compute_o_value_legacy_prep(owner_pwd, rev, keylen)
# 5. Pad or truncate the user password ... | 63,284 |
def webex_buffer_input_cb(data, buffer, input_data):
""" Callback called for input data on a buffer. """
chat = get_chat_from_buffer(buffer)
if chat:
chat.send_message(input_data)
return weechat.WEECHAT_RC_OK | 63,285 |
def base_corner(baseparams, base, newbase, tri, sobol=1.0, outbasename=""):
"""
Plots the new vs. old base of across interpolation, as long as dim(base) > 1,
and produces a corner plot for dim(base) > 2.
Parameters
----------
baseparams : dict
Parameters forming the base of the grid, an... | 63,286 |
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... | 63,287 |
def train_lanenet(dataset_dir, weights_path=None, net_flag='vgg'):
"""
:param dataset_dir:
:param net_flag: choose which base network to use
:param weights_path:
:return:
"""
train_dataset = lanenet_data_feed_pipline.LaneNetDataFeeder(
dataset_dir=dataset_dir, flags='train'
)
... | 63,288 |
def refine_field(field_class,values,*,name=None):
"""Factory function that returns a field sub-class with restricted values.
A helper factory function to define a sub-class of a BaseField (or sub-class)
that restricts the allowable values. For example, if you have a constant in
a predicate that is rest... | 63,289 |
def run_diagnostics_from_filetables( opts, filetable1, filetable2=None ):
"""Runs the diagnostics. The data is specified by the filetables.
Most other choices, such as the plot sets, variables, and seasons, are specified in opts,
an instance of Options."""
outdir = opts['outputdir']
if outdir is N... | 63,290 |
def plug_level_connections(node):
"""
Given the name of a node find all of the connections to and from it.
The return value is a pair of arrays, connections coming in and
connections going out of this node, each consisting of pairs with
the names of the source and destination plug names.
Th... | 63,291 |
def mlregress(x, y, intercept=True):
"""
Parameters
----------
x
y
intercept
Returns
-------
"""
"""Return the coefficients from a multiple linear regression, along with R, the coefficient of determination.
x: The independent variables (pxn or nxp).
y: The dependent v... | 63,292 |
def get_dropq_compute_from_module(module_import_path, attr='dropq_compute',
MockComputeObj=MockCompute, **mc_args):
"""
mocks dropq compute object from specified module
returns: mocked dropq compute object
"""
module_views = sys.modules[module_import_path]
seta... | 63,293 |
def test_portmap_portstat_route(cl_operator, service):
"""portmap portstat route test"""
response = cl_operator.get(url_for('visuals.portmap_portstat_route', port=service.port, filter=f'Service.state=="{service.state}"'))
assert response.status_code == HTTPStatus.OK
assert response.lxml.xpath(f'//td/a[... | 63,294 |
def format_numbers(
data, headers, column_types=(), integer_format=None, float_format=None, **_
):
"""Format numbers according to a format specification.
This uses Python's format specification to format numbers of the following
types: :class:`int`, :class:`py2:long` (Python 2), :class:`float`, and
... | 63,295 |
def quoted_native_concat(nodes):
"""This is almost native_concat from the NativeTemplate, except in the
special case of a single argument that is a quoted string and returns a
string, the quotes are re-inserted.
"""
head = list(islice(nodes, 2))
if not head:
return ''
if len(head) ... | 63,296 |
def load(tree_file: t.IO[str]) -> Program:
"""Load the input data, parse it and construct the tree."""
lines = tree_file.readlines()
programs_by_name: t.Dict[str: Program] = {}
# Start by just finding out whom everyone is
programs = {p.name: p for p in map(Program.from_line, lines)}
def is_ho... | 63,297 |
def trace(
record,
sl,
kwargs_data={},
fit_modekwargs_legend={},
kwargs_subplots={},
title=None,
kwargs_plot={},
errorbar_kwargs=None,
xlim=None,
ylim=None,
xlabel='Time in fs',
ylabel='Relative Bleach',
legend=True,... | 63,298 |
def generate_date_now():
"""Get current timestamp date."""
return "{0}".format(datetime.utcnow().strftime('%s')) | 63,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.