content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _parse_class(s):
"""
Parse a key, value pair, separated by '='
On the command line (argparse) a declaration will typically look like:
foo=hello
or
foo="hello world"
"""
items = s.split('=')
key = items[0].strip() # we remove blanks around keys, as is logical
if len(... | 5,340,600 |
def data_base():
"""mock the database"""
my_db = database.Database(":memory:")
yield my_db
my_db.database.close() | 5,340,601 |
def getStringSimilarity(string1:str,string2:str):
"""
This function will return a similarity of two strings.
"""
import difflib
return difflib.SequenceMatcher(None,string1,string2).quick_ratio() | 5,340,602 |
def test_hover_parameter_bool():
"""Test that hovering over parameters shows their values LOGICAL"""
string = write_rpc_request(1, "initialize", {"rootPath": str(test_dir)})
file_path = test_dir / "hover" / "parameters.f90"
string += hover_req(file_path, 8, 38)
errcode, results = run_request(string,... | 5,340,603 |
def release(ctx):
"""Release the packages to Pypi!"""
dist_dir = os.path.join(ROOT_DIR, "dist")
if not os.path.isdir(dist_dir):
sys.exit("Dist directory does not exist. Build first?")
print("This is what you are about to upload:")
for fname in sorted(os.listdir(dist_dir)):
s = os.st... | 5,340,604 |
def model_downloader(
handler_type: HandlerType,
bucket_name: str,
model_name: str,
model_version: str,
model_path: str,
temp_dir: str,
model_dir: str,
) -> Optional[datetime.datetime]:
"""
Downloads model to disk. Validates the s3 model path and the downloaded model.
Args:
... | 5,340,605 |
def calc_simcoef_distr(patfeats, labels, id_dict, simcoef):
"""
Calculates the score distributions
Inputs:
- simcoef: simcoef the values are calculated with (string)
- labels: list of strings with the scores to be calculated (e.g.: ['cited', 'random'])
- id_dict: dictionary containing the pa... | 5,340,606 |
def test_nodes_of_empty_weight_weight_graph_is_empty(empty_weight_graph):
"""Test that the list of nodes for an empty graph is empty."""
assert empty_weight_graph.nodes() == [] | 5,340,607 |
def fft(signal, sampling_rate, plot=False, show_grid=True, fig_size=(10, 5)):
"""
Perform FFT on signal.
Compute 1D Discrete Fourier Transform using Fast Fourier Transform.
Optionally, plot the power spectrum of the frequency domain.
Parameters
----------
signal : ndarray
Input arr... | 5,340,608 |
def pattern_count(data, **params):
"""
Count occurrences of a given pattern.
Args:
data (list): values.
params (kwargs):
pattern (str or list): the pattern to be sought in data (obligatory)
metric (str): 'identity' counts identical positions,
... | 5,340,609 |
def pathify(path):
"""\
Generator that returns values suitable for path store navigation:
- No values, if path is None.
- One value, if path is a string or isn't iterable.
- Each value, otherwise.
"""
if path is not None:
if isinstance(path, str):
yield path
... | 5,340,610 |
def read_directory(directory):
"""
Read file names from directory recursively
Parameters
----------
directory : string
directory/folder name where to read the file names from
Returns
---------
files : list of strings
list of file names
"""
try:
... | 5,340,611 |
def do(hostname):
"""
Performs a GET request.
Parameters
----------
hostname : str
Target request
Return
------
The request results
"""
try:
return requests.get(hostname, timeout=10)
except TimeoutException:
print("\033[1;31mRequest timeout: test a... | 5,340,612 |
def getAssignmentReport(assignment):
"""
Produces an ABET assignment report (as a markdown-formatted string)
for the given assignment (which is expected to be a codepost API
object) by pulling all relevant data as well as source
code files (and grader comments) for randomly selected A, B and C samples
"""
... | 5,340,613 |
def start_game():
"""
Method to start
:return: Choice selection for new game or load game
"""
maximize_console()
print_title()
print('Do you want to start a new game (enter 1) or resume an ongoing game (enter 2)?')
choice = input('||> ')
print()
return choice | 5,340,614 |
def manage(cmd):
"""Update a testing database"""
_local('django-admin.py {}'.format(cmd)) | 5,340,615 |
def reply_to_mention(mention, payload):
""" Replies to a mention with the emojify'd text """
try:
request_response = requests.post('http://emojifythis.org/emojifi', data=json.dumps(payload))
json_response = request_response.json()
mention.reply(json_response['text'] + '\n\n =============... | 5,340,616 |
def copy_dir(src_fs, src_path, dst_fs, dst_path,
walker=None, on_copy=None):
"""Copy a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or s... | 5,340,617 |
def p_data_page_after(p):
"""datasort : datasort '@' AFTER '(' pagelist ')' """
p[0] = p[1].with_after(p[5]) | 5,340,618 |
def modified_files():
"""
Gets a list of modified files in the repo.
:return: A list of absolute paths to all changed files in the repo
"""
repo_root_dir = repo_root()
return [os.path.join(repo_root_dir, d.b_path) for d in get().head.commit.diff() if not (d.new_file or d.deleted_file)] | 5,340,619 |
def test_subtraction(
lcs_lhs, lcs_rhs, orientation_exp, coordinates_exp, time_exp, time_ref_exp
):
"""Test the subtraction of 2 coordinate systems.
Parameters
----------
lcs_lhs:
Left hand side coordinate system
lcs_rhs:
Right hand side coordinate system
orientation_exp:
... | 5,340,620 |
def encode_data(dataset_path=DATASET_PATH):
"""Encodes the symbloc music in the dataset folder.
:param dataset_path (str): Path to the dataset
:return data, filenames (list): Encoded songs and their file names
"""
# encoded songs and their file names
data = []
filenames = []
... | 5,340,621 |
def test_extract_params_no_arguments(all_param_type_transmute_func):
""" if no arguments are passed, use the defaults """
extractor = ParamExtractorMock()
extractor._query_argument = lambda *args: NoArgument
extractor._header_argument = lambda *args: NoArgument
extractor._path_argument = lambda *ar... | 5,340,622 |
def get_inception_score(images, batch_size, splits=10):
"""
the function is to calculate the inception score of the generated images
image is a numpy array with values should be in the range[0, 255]
images 299x299x3
"""
assert(type(images) == np.ndarray)
inception_model = inception_v3
... | 5,340,623 |
def generate_audio_testing(raw_gain, raw_freq, raw_dampings, modal_fir, reverb, impulse_profile,
gains, frequencies, dampings, modal_response,
noise, acceleration_scale, revc, audio_sample_rate, example_secs, scratch='controls'):
"""Generate DiffImpact's estimat... | 5,340,624 |
def dice_coef_multilabel(y_true, y_pred, numLabels=4, channel='channel_first'):
"""
calculate channel-wise dice similarity coefficient
:param y_true: the ground truth
:param y_pred: the prediction
:param numLabels: the number of classes
:param channel: 'channel_first' or 'channel_last'
:retu... | 5,340,625 |
def gaussian(sigma, fs, t=None):
""" return a gaussian smoothing filter
Args:
sigma: standard deviation of a Gaussian envelope
fs: sampling frequency of input signals
t: time scale
Return:
a Gaussian filter and corresponding time scale
"""
if... | 5,340,626 |
def score_sent(sent):
"""Returns a score btw -1 and 1"""
sent = [e.lower() for e in sent if e.isalnum()]
total = len(sent)
pos = len([e for e in sent if e in positive_wds_with_negation])
neg = len([e for e in sent if e in negative_wds_with_negation])
if total > 0:
return (pos - neg) / to... | 5,340,627 |
def flipud(tensor):
"""
Flips a given tensor along the first dimension (up to down)
Parameters
----------
tensor
a tensor at least two-dimensional
Returns
-------
Tensor
the flipped tensor
"""
return torch.flip(tensor, dims=[0]) | 5,340,628 |
def connect():
"""Function to connect to database on Amazon Web Services"""
try:
engine = create_engine('mysql+mysqlconnector://dublinbikesadmin:dublinbikes2018@dublinbikes.cglcinwmtg3w.eu-west-1.rds.amazonaws.com/dublinbikes')
port=3306
connection = engine.connect()
Sessio... | 5,340,629 |
def get_file_type(filepath):
"""Returns the extension of a given filepath or url."""
return filepath.split(".")[-1] | 5,340,630 |
def set_viewport_height(height: int):
"""Sets the viewport's height.
Returns:
None
"""
internal_dpg.configure_viewport(0, height=height) | 5,340,631 |
def calcB1grad(B2grad,W2,A2):
"""
Calculates the gradient of the cost with respect to B1 using the chain rule
INPUT: B2grad, [layer3Len,1] ; W2, [layer2Len, layer3Len] ;
A2, [layer2len, 1]
OUTPUT: B1grad, [layer2Len, 1]
"""
temp1 = np.dot(W2,B2grad) #layer2Len * 1 vector
... | 5,340,632 |
def main():
"""The main function."""
import argparse
parser = argparse.ArgumentParser(
description='Train DB-CNN for BIQA.')
parser.add_argument('--base_lr', dest='base_lr', type=float, default=1e-1,
help='Base learning rate for training.')
parser.add_argument('--batc... | 5,340,633 |
def after(*args, **kwargs):
"""After advice"""
print "After true" | 5,340,634 |
def plot_3d(x, y, z, title, labels):
"""
Returns a matplotlib figure containing the 3D T-SNE plot.
Args:
x, y, z: arrays
title: string with name of the plot
labels: list of strings with label names: [x, y, z]
"""
plt.rcParams.update({'font.size': 30, 'legend.fontsize': 2... | 5,340,635 |
def crossvalidate(splitter, axis, *arg):
"""split each input in arg into train and test splits by indexing along the axis
using the indices returned by splitter. Both returns are lists."""
for trainind, testind in splitter:
# from list of arg where each entry is [train, test] to [trainarg, testarg]
... | 5,340,636 |
def test_against_pytpm_doc_example():
"""
Check that Astropy's Ecliptic systems give answers consistent with pyTPM
Currently this is only testing against the example given in the pytpm docs
"""
fk5_in = SkyCoord('12h22m54.899s', '15d49m20.57s', frame=FK5(equinox='J2000'))
pytpm_out = Barycentri... | 5,340,637 |
def is_rating_col_name(col:str)->bool:
"""
Checks to see if the name matches the naming convention for a rating
column of data, i.e. A wrt B
:param col: The name of the column
:return: T/F
"""
if col is None:
return False
elif isinstance(col, (float, int)) and np.isnan(col):
... | 5,340,638 |
def _make_buildifier_command():
"""Returns a list starting with the buildifier executable, followed by any
required default arguments."""
return [
find_data(_BUILDIFIER),
"-add_tables={}".format(find_data(_TABLES))] | 5,340,639 |
def infer_path_type(path: str) -> Union[XPath, JSONPath]:
"""
Infers the type of a path (XPath or JSONPath) based on its syntax.
It performs some basic sanity checks to differentiate a JSONPath from an XPath.
:param path: A valid XPath or JSONPath string.
:return: An instance of JSONPath or XPath
... | 5,340,640 |
def ensure_dir_exists(dirname):
"""Ensure a directory exists, creating if necessary."""
try:
os.makedirs(dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise | 5,340,641 |
def get_proximity_angles():
"""Get the angles used for the proximity sensors."""
angles = []
# Left-side of the agent
angles.append(3 * pi / 4) # 135° (counter-clockwise)
for i in range(5): # 90° until 10° with hops of 20° (total of 5 sensors)
angles.append(pi / 2 - i * pi / 9)
... | 5,340,642 |
def delete(request, scenario_id):
"""
Delete the scenario
"""
# Retrieve the scenario
session = SessionMaker()
scenario = session.query(ManagementScenario).filter(ManagementScenario.id == scenario_id).one()
# Delete the current scenario
session.delete(scenario)
session.commit()
... | 5,340,643 |
def main():
"""main"""
#Initialize acl
acl_resource = AclResource()
acl_resource.init()
#Create a detection network instance, currently using the vgg_ssd network.
# When the detection network is replaced, instantiate a new network here
detect = VggSsd(acl_resource, MODEL_WIDTH, MODEL_HEIGHT... | 5,340,644 |
def get_python_list(file_path):
"""
Find all the .py files in the directory and append them to a raw_files list.
:params:
file_path = the path to the folder where the to-be read folders are.
:returns:
raw_files : list of all files ending with '.py' in the read folder.
"""
python_files =... | 5,340,645 |
def angle(p1, p2, p3):
"""Returns an angle from a series of 3 points (point #2 is centroid).
Angle is returned in degrees.
Parameters
----------
p1,p2,p3 : numpy arrays, shape = [n_points, n_dimensions]
Triplets of points in n-dimensional space, aligned in rows.
Returns
-------
... | 5,340,646 |
def transformer_parsing_base():
"""HParams for parsing on WSJ only."""
hparams = transformer_base()
hparams.attention_dropout = 0.2
hparams.layer_prepostprocess_dropout = 0.2
hparams.max_length = 512
hparams.learning_rate_warmup_steps = 16000
hparams.hidden_size = 1024
hparams.learning_rate = 0.05
hpa... | 5,340,647 |
def split_protocol(urlpath):
"""Return protocol, path pair"""
urlpath = stringify_path(urlpath)
if "://" in urlpath:
protocol, path = urlpath.split("://", 1)
if len(protocol) > 1:
# excludes Windows paths
return protocol, path
return None, urlpath | 5,340,648 |
def createParPythonMapJob(info):
"""
Create map job json for IGRA matchup.
Example:
job = {
'type': 'test_map_parpython',
'params': {
'year': 2010,
'month': 7
},
'localize_urls': [
]
}
"""
pr... | 5,340,649 |
def calc_lampam_from_delta_lp_matrix(stack, constraints, delta_lampams):
"""
returns the lamination parameters of a laminate
INPUTS
- ss: laminate stacking sequences
- constraints: design and manufacturing guidelines
- delta_lampams: ply partial lamination parameters
"""
lampam = np.ze... | 5,340,650 |
def _save_plugin_metadata(order_model, plugin_meta):
"""Add plugin metadata to an order."""
if not isinstance(plugin_meta, dict):
plugin_meta = {}
order_plugin_meta_repo = repos.get_order_plugin_meta_repository()
order_plugin_meta_repo.save(plugin_meta, order_model) | 5,340,651 |
def perp(i):
"""Calculates the perpetuity to present worth factor.
:param i: The interest rate.
:return: The calculated factor.
"""
return 1 / i | 5,340,652 |
def apply_aircraft_layout(flight_id, aircraft_layout_id):
"""
Apply an aircraft layout to a flight, copying across seat allocations
:param flight_id: ID of the flight to apply the layout to
:param aircraft_layout_id: ID of the aircraft layout to apply
"""
# TODO : This needs refactoring but wo... | 5,340,653 |
def chebyshev(x, y):
"""chebyshev distance.
Args:
x: pd.Series, sample feature value.
y: pd.Series, sample feature value.
Returns:
chebyshev distance value.
"""
return np.max(x-y) | 5,340,654 |
def soda_url_helper(*, build_url, config, year, **_):
"""
This helper function uses the "build_url" input from flowbyactivity.py,
which is a base url for data imports that requires parts of the url text
string to be replaced with info specific to the data year. This function
does not parse the data,... | 5,340,655 |
def generate_base_provider_parser():
"""Function that generates the base provider to be used by all dns providers."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('action', help='specify the action to take', default='list',
choices=['create', 'list', 'update',... | 5,340,656 |
def search(
submitted_before: Optional[datetime] = None,
submitted_after: Optional[datetime] = None,
awaiting_service: Optional[str] = None,
url:Optional[str] = None,
token:Optional[str] = None,
quiet:bool = False
) -> List[dict]:
"""Query metadatasets accordi... | 5,340,657 |
def _target_js_variable_is_used(
*, var_name: str, exp_lines: List[str]) -> bool:
"""
Get a boolean value whether target variable is used in
js expression or not.
Parameters
----------
var_name : str
Target variable name.
exp_lines : list of str
js express... | 5,340,658 |
def rnn_temporal(x, h0, Wx, Wh, b):
"""
Run a vanilla RNN forward on an entire sequence of data. We assume an input
sequence composed of T vectors, each of dimension D. The RNN uses a hidden
size of H, and we work over a minibatch containing N sequences. After running
the RNN forward, we return the ... | 5,340,659 |
def rejection_fixed_lag_stitch(fixed_particle: np.ndarray,
last_edge_fixed: np.ndarray,
last_edge_fixed_length: float,
new_particles: MMParticles,
adjusted_weights: np.ndarray,
... | 5,340,660 |
def zip_equalize_lists(a, b):
"""
A zip implementation which will not stop when reaching the end of the
smallest list, but will append None's to the smaller list to fill the gap
"""
a = list(a)
b = list(b)
a_len = len(a)
b_len = len(b)
diff = abs(a_len - b_len)
if a_len < b_len:... | 5,340,661 |
def test_encounter_detail(client, project, species):
"""Verify that we can navigate to the encounter detail page (status
code=200) and that the template is the one we think it is.
"""
encounter = EncounterFactory(project=project, species=species)
response = client.get(
reverse("tfat:encount... | 5,340,662 |
def cover_line(line):
"""
This function takes a string containing a line that should
potentially have an execution count and returns a version
of that line that does have an execution count if deemed
appropriate by the rules in validate_line().
Basically, if there is currently no number where t... | 5,340,663 |
def find_period(samples_second):
""" # Find Period
Args:
samples_second (int): number of samples per second
Returns:
float: samples per period divided by samples per second
"""
samples_period = 4
return samples_period / samples_second | 5,340,664 |
def sqrt(x: int) -> int:
"""
Babylonian Square root implementation
"""
z = (x + 1) // 2
y = x
while z < y:
y = z
z = ( (x // z) + z) // 2
return y | 5,340,665 |
def is_consecutive_list(list_of_integers):
"""
# ========================================================================
IS CONSECUTIVE LIST
PURPOSE
-------
Reports if elments in a list increase in a consecutive order.
INPUT
-----
[[List]] [list_of_integers]
- A list ... | 5,340,666 |
def deploy_wazzap(l_dir=env.local_directory):
"""Deploys wazzap to our remote location
Can set local location by using l_dir='<local path>'
"""
env.local_directory = l_dir
deploy_app(host_=env.myhost) | 5,340,667 |
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
"""
See https://gist.github.com/syrte/592a062c562cd2a98a83
Make a scatter plot of circles.
Similar to plt.scatter, but the size of circles are in data scale.
Parameters
----------
x, y : scalar or array_like, shape (n, )
... | 5,340,668 |
def test_read_mzxml():
"""Test reading peak data from an mzXML metabolomics file.
GIVEN an mzXML file
WHEN that mzXML file is parsed into a list of Peak objects
THEN make sure those Peak objects are correct
"""
mzxml_path = DATA_DIR / "test_metabolomics/test.mzXML"
with open(mzxml_path, "r")... | 5,340,669 |
def generate_agency_tracking_id():
""" Generate an agency tracking ID for the transaction that has some random
component. I include the date in here too, in case that's useful. (The
current non-random tracking id has the date in it.)
@todo - make this more random"""
random = str(uuid4()).replace('-... | 5,340,670 |
def get_enabled_gems(cmake_file: pathlib.Path) -> set:
"""
Gets a list of enabled gems from the cmake file
:param cmake_file: path to the cmake file
:return: set of gem targets found
"""
cmake_file = pathlib.Path(cmake_file).resolve()
if not cmake_file.is_file():
logger.error(f'Fail... | 5,340,671 |
def celeryAdd3(a,b):
"""This is for a specific Celery workflow
f = (a+b) * (a+b)
We'll use chord, group and chain"""
if request.method == 'GET':
# When a worker receives an expired task it will mark the task as REVOKED
res = (group(add.s(a,b), add.s(a,b)) | mul.s()).apply_async(expires=6... | 5,340,672 |
def print_success(text):
"""
Print a success message.
Parameters
----------
text : str
The message to display.
"""
print(colorize(text, Colors.SUCCESS)) | 5,340,673 |
def random_walk_model(
data,
ep,
basic_R_prior=None,
r_walk_noise_scale_prior=0.15,
r_walk_period=7,
n_days_seeding=7,
seeding_scale=3.0,
infection_noise_scale=5.0,
output_noise_scale_prior=5.0,
**kwargs,
):
"""
Random walk only model
:param data: PreprocessedData ob... | 5,340,674 |
def create_unmerge_cells_request(sheet_id, start, end):
"""
Create v4 API request to unmerge rows and/or columns for a
given worksheet.
"""
start = get_cell_as_tuple(start)
end = get_cell_as_tuple(end)
return {
"unmergeCells": {
"range": {
"sheetId": shee... | 5,340,675 |
async def status(ctx: click.Context) -> None:
"""Get on-chain staker status."""
cfg = cli_config(ctx)
account_name = ctx.obj["ACCOUNT_NAME"]
if account_name:
account = ChainedAccount.get(account_name)
else:
accounts = find_accounts(chain_id=cfg.main.chain_id)
account = accoun... | 5,340,676 |
def list_to_str(slist, seperator=None):
"""Convert list of any type to string seperated by seperator."""
if not seperator:
seperator = ','
if not slist:
return ""
slist = squash_int_range(slist)
return seperator.join([str(e) for e in slist]) | 5,340,677 |
def log_web_error(msg):
"""Take a screenshot of a web browser based error
Use this function to capture a screen shot of the web browser
when using Python's `assert` keyword to perform assertions.
"""
screenshot = selene.helpers.take_screenshot(selene.browser.driver(),)
msg = '''{original_msg}
... | 5,340,678 |
def timelines(
T,
infile,
outfile,
limit,
timeline_limit,
use_search,
hide_progress,
**kwargs,
):
"""
Fetch the timelines of every user in an input source of tweets. If
the input is a line oriented text file of user ids or usernames that will
be used instead.
The inf... | 5,340,679 |
def parent_id_name_and_quotes_for_table(sqltable):
""" Return tuple with 2 items (nameof_field_of_parent_id, Boolean)
True - if field data type id string and must be quoted), False if else """
id_name = None
quotes = False
for colname, sqlcol in sqltable.sql_columns.iteritems():
# root table... | 5,340,680 |
def chunks(l, n):
""" Yield successive chunks from l which are at least of length n
From http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
"""
for i in xrange(0, len(l), n):
yield l[i:i+n] | 5,340,681 |
def test_transcoded_hls_video():
""" Tests that Video.transcoded_videos returns transcoded HLS videofile"""
video = VideoFactory()
videofiles = [
VideoFileFactory(
video=video, s3_object_key="original.mp4", encoding=EncodingNames.ORIGINAL
),
VideoFileFactory(
... | 5,340,682 |
def client():
"""Returns a Flask client for the app."""
return app.test_client() | 5,340,683 |
def pushTwitterConnections(self, twits, user, friends=True, cacheKey=False):
"""Push the Twitter connections of a given user to Neo4J.
Positional arguments:
twits -- a list of Twitter users as returned by Twython
user -- The screen_name of the user
Keyword arguments:
friends -- "twits" are... | 5,340,684 |
def _get_horizons_ephem(
id,
start: Time,
stop: Time,
step: str = "12H",
id_type: str = "smallbody",
location: str = "@TESS",
quantities: str = "2,3,9,19,20,43",
):
"""Returns JPL Horizons ephemeris.
This is simple cached wrapper around astroquery's Horizons.ephemerides.
"""
... | 5,340,685 |
def show_modal_data(nat_freq, damping):
"""
Show modal data in a table-like structure.
"""
print(' Nat. f. Damping')
print(23*'-')
for i, f in enumerate(nat_freq):
print(f'{i+1}) {f:6.1f}\t{damping[i]:5.4f}') | 5,340,686 |
def plot_map(map, affine, cut_coords=None, anat=None, anat_affine=None,
figure=None, axes=None, title=None, threshold=None,
annotate=True, draw_cross=True,
do3d=False, **kwargs):
""" Plot three cuts of a given activation map (Frontal, Axial, and Lateral)
... | 5,340,687 |
def get_mode(h5,songidx=0):
"""
Get mode from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.mode[songidx] | 5,340,688 |
def read_label_schema(path):
"""
Reads json file and returns deserialized LabelSchema.
"""
with open(path, encoding="UTF-8") as read_file:
serialized_label_schema = json.load(read_file)
return LabelSchemaMapper().backward(serialized_label_schema) | 5,340,689 |
def Dump(root):
"""Return a string representing the contents of an object.
This function works only if root.ValidateExports() would pass.
Args:
root: the object to dump.
Returns:
A big string containing lines of the format:
Object.SubObject.
Object.SubObject.ParameterName = %r
"""
h = ... | 5,340,690 |
def clean_profit_data(profit_data):
"""清理权益全为0的垃圾结算日"""
for i in list(range(len(profit_data)))[::-1]:
profit = profit_data[i][1] == 0
closed = profit_data[i][2] == 0
hold = profit_data[i][3] == 0
if profit and closed and hold:
profit_data.pop(i)
return profit_dat... | 5,340,691 |
def convert_single_example(ex_index, example, max_word_length,max_sen_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
text_sen = example.text_sen.strip().split()
text_pos=example.text_pos.strip().split()
text_ps = example.text_ps.strip().spli... | 5,340,692 |
def scrub_literal(value):
"""
Scrubs control characters from the incoming values to remove
things like form feeds (\f) and line breaks (\n) which might
cause problems with Jena.
Data with these characters was found in the Backstage data.
"""
if not value:
return None
if isinstanc... | 5,340,693 |
def mock_interface_settings_mismatch_protocol(mock_interface_settings, invalid_usb_device_protocol):
"""
Fixture that yields mock USB interface settings that is an unsupported device protocol.
"""
mock_interface_settings.getProtocol.return_value = invalid_usb_device_protocol
return mock_interface_se... | 5,340,694 |
def run_eval(exp_name: str) -> Mapping[str, Any]:
""" """
pred_log_dir = f"{_ROOT}/test_data/eval_tracking_dummy_logs_pred"
gt_log_dir = f"{_ROOT}/test_data/eval_tracking_dummy_logs_gt"
out_fpath = f"{_ROOT}/test_data/{exp_name}.txt"
out_file = open(out_fpath, "w")
eval_tracks(
path_tra... | 5,340,695 |
def check_dir(path):
"""
检查文件夹是否存在,存在返回True;不存在则创建,返回False
"""
if not os.path.exists(path):
os.makedirs(path)
return False
return True | 5,340,696 |
def MakeLocalSsds(messages, ssd_configs):
"""Constructs the repeated local_ssd message objects."""
if ssd_configs is None:
return []
local_ssds = []
disk_msg = (
messages.
AllocationSpecificSKUAllocationAllocatedInstancePropertiesAllocatedDisk)
interface_msg = disk_msg.InterfaceValueValuesEnu... | 5,340,697 |
def valid_variant(s, is_coding=True):
"""
Returns True if s is a valid coding or noncoding variant, else False.
Parameters
----------
s : `str`
Variant string to validate.
is_coding : `bool`
Indicates if the variant string represents a coding variant.
"""
_validate_s... | 5,340,698 |
def is_icon_address_valid(address: str) -> bool:
"""Check whether address is in icon address format or not
:param address: (str) address string including prefix
:return: (bool)
"""
try:
if isinstance(address, str) and len(address) == 42:
prefix, body = split_icon_address(address... | 5,340,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.