content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def override_config_file(src_path, dest_path, **kwargs):
"""
Override settings in a trainer config file. For example,
override_config_file(src_path, dest_path, max_steps=42)
will copy the config file at src_path to dest_path, but override the max_steps field to 42 for all brains.
"""
with op... | 5,336,200 |
def get_loss(pred, label):
"""
:param pred: BxNxC
:param label: BxN
:param smpw: BxN
:return:
"""
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=label, logits=pred)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)
tf.add_to_coll... | 5,336,201 |
def test_dependencies(dependencies_dialog):
"""Run dependency widget test."""
# Test sample
dependencies.add("zmq", "zmq", "Run introspection services", ">=10.0")
dependencies.add("foo", "foo", "Non-existent module", ">=1.0")
dependencies.add("bar", "bar", "Non-existing optional module", ">=10.0",
... | 5,336,202 |
def calculate_prec_at_k(k, prediction, target):
"""
Calculating precision at k.
"""
best_k_pred = prediction.argsort()[:k]
best_k_target = target.argsort()[:k]
return len(set(best_k_pred).intersection(set(best_k_target))) / k | 5,336,203 |
def get_ttl(cur):
"""Get the 'extract' table as lines of Turtle (the lines are returned as a list)."""
# Get ttl lines
cur.execute(
"""WITH literal(value, escaped) AS (
SELECT DISTINCT
value,
replace(replace(replace(value, '\\', '\\\\'), '"', '\\"'), '
... | 5,336,204 |
def pnm80(date1, date2):
"""
Wrapper for ERFA function ``eraPnm80``.
Parameters
----------
date1 : double array
date2 : double array
Returns
-------
rmatpn : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - - -
e r a P n m 8 0
- - -... | 5,336,205 |
def segment_experiment(experiment_root, model, channels='bf', use_gpu=True, overwrite_existing=False):
"""Segment all 'bf' image files from an experiment directory and annotate poses.
For more complex needs, use segment_images.segment_positions. This function
is largely a simple example of its usage.
... | 5,336,206 |
def db_table_ddl(conn, table_name, table_cols, table_seqs, table_cons, **kwargs):
""" Generate create table DDL
"""
# Sequences
if table_seqs:
for s_ in table_seqs:
c_ = _t.m.daffkv(table_cols, "col_name", s_["col_name"])
if c_:
c_["is_seq"] = True
... | 5,336,207 |
def ne_to_wgs(northing, easting):
"""
Convert Northings and Eastings (NAD 83 Alaska Albers
Equal Area Conic) to WGS84 lat/long .
:param northing: AK Albers in meters
:param easting: AK Albers in meters
:returns: transformed coordinates in WGS84 lat long
"""
wgspoint = osr.SpatialReferen... | 5,336,208 |
def test__set_variables_from_first_table_with_same_db_tables_in_parameters():
"""Test _set_variables_from_first_table() when the tables passed are with same tables in parameters"""
def dummy_function(param_1: str, param_2: str): # skipcq: PTC-W0049, PY-D0003
pass
handler = TableHandler()
hand... | 5,336,209 |
def register_api_routes(app: Flask):
""" use this function to register api routes"""
# register the api versions to the main application
app.register_blueprint(register_api_routes_v1(latest = True)) | 5,336,210 |
def check_for_greeting(sentence, context):
"""If any of the words in the user's input was a greeting, return a greeting response"""
if (sentence.strip() in GREETING_KEYWORDS) and (context==True):
return getCurrentTimeGreeting()+", "+random.choice(GREETING_RESPONSES)
else:
return random.choic... | 5,336,211 |
def user_is_aidant(view=None, redirect_field_name="next"):
"""
Similar to :func:`~django.contrib.auth.decorators.login_required`, but
requires the user to be :term:`allowed to create mandats`.
By default, this redirects users to home of espace aidants.
"""
def test(user):
return user.ca... | 5,336,212 |
def plot_images(a,b,x_train, y_train, y_pred):
"""
This function plots the images in a 5x5 grid
:param a: true class label
:param b: predicted class label
:param x_train: training data
:param y_train: training data labels
:param y_pred: prediction on the test data
:return: None
... | 5,336,213 |
def get_time_zone_offset(time_zone, date_time=None):
"""
Returns the time zone offset (e.g. -0800) of the time zone for given datetime
"""
date_time = datetime.now(utc) if date_time is None else date_time
return _format_time_zone_string(time_zone, date_time, '%z') | 5,336,214 |
def loss_fn_kd(scores, target_scores, T=2.):
"""Compute knowledge-distillation (KD) loss given [scores] and [target_scores].
Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged.
'Hyperparameter': temperature"""
device = scores.device
log_scores_norm ... | 5,336,215 |
def geom_cooling(temp, k, alpha = 0.95):
"""Geometric temperature decreasing."""
return temp * alpha | 5,336,216 |
def populate_db_from_sheet(sheet):
"""Given excel sheet, check required columns exist, and if so, empty and repopulate database"""
dct_index_of_heading = {}
for cx in range(sheet.ncols):
dct_index_of_heading[sheet.cell_value(0, cx)] = cx
not_founds = []
for expected in COLUMN_NAMES:
... | 5,336,217 |
def metadata_version(metadata, osmelem, grp_feat, res_feat, feature_suffix):
"""Compute the version-related features of metadata and append them into
the metadata table
Parameters
----------
metadata: pd.DataFrame
Metadata table to complete
osmelem: pd.DataFrame
original data us... | 5,336,218 |
def train_lin_reg():
"""Trains a LR model and persists it as pickle file"""
return render_template(
'default_html.html',
endpoint='train_model',
data=lr.train_model(),
) | 5,336,219 |
def bytes_to_escaped_str(data, keep_spacing=False, escape_single_quotes=False):
"""
Take bytes and return a safe string that can be displayed to the user.
Single quotes are always escaped, double quotes are never escaped:
"'" + bytes_to_escaped_str(...) + "'"
gives a valid Python string.
A... | 5,336,220 |
def _session_path():
"""
Return the path to the current session
:return:
"""
path = bpy.data.filepath
return path | 5,336,221 |
def user_auth(f):
"""Checks whether user is logged in or raises error 401."""
def decorator(*args, **kwargs):
if True is False:
abort(401)
return f(*args, **kwargs)
return decorator | 5,336,222 |
def is_tensorrt_plugin_loaded():
"""Check if TensorRT plugins library is loaded or not.
Returns:
bool: plugin_is_loaded flag
"""
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
... | 5,336,223 |
def check_md5(config):
"""
Find MD5 hash in providers.
:param config: Parameters object
:type config: Parameters
:return: plain string with text or exception if not found hash
:rtype: str
:raises: HashNotFound, InvalidHashFormat
"""
if not isinstance(config, Parameters):
r... | 5,336,224 |
def is_polindrom(string):
""" This function checks whether the given string is a polindrom or not. """
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True | 5,336,225 |
def check_files(hass):
"""Return bool that indicates if all files are present."""
# Verify that the user downloaded all files.
base = f"{hass.config.path()}/custom_components/{DOMAIN}/"
missing = []
for file in REQUIRED_FILES:
fullpath = f"{base}{file}"
if not os.path.exists(fullpath... | 5,336,226 |
def sensitive_file_response(file):
""" This function is helpful to construct your own views that will return the
actual bytes for a sensitive image. You need to pass the literal bytes for
sensitive photos through your server in order to put security checks in front
of those bytes. So for instance you might put ... | 5,336,227 |
def get_unmapped_read_count_from_indexed_bam(bam_file_name):
"""
Get number of unmapped reads from an indexed BAM file.
Args:
bam_file_name (str): Name of indexed BAM file.
Returns:
int: number of unmapped reads in the BAM
Note:
BAM must be indexed for lookup using samtool... | 5,336,228 |
def model_setup(model_dict, X_train, y_train, X_test, y_test, X_val,
y_val, rd=None, layer=None):
"""
Main function to set up network (create, load, test, save)
"""
rev = model_dict['rev']
dim_red = model_dict['dim_red']
if rd != None:
# Doing dimensionality reduction on... | 5,336,229 |
def AreEqual(image1, image2, tolerance=0, likely_equal=True):
"""Determines whether two images are identical within a given tolerance.
Setting likely_equal to False enables short-circuit equality testing, which
is about 2-3x slower for equal images, but can be image height times faster
if the images are not equ... | 5,336,230 |
def ppc_deconvolve(im, kernel, kfft=None, nchans=4,
same_scan_direction=False, reverse_scan_direction=False):
"""PPC image deconvolution
Given an image (or image cube), apply PPC deconvolution kernel
to obtain the intrinsic flux distribution.
If performing PPC deconvolution, make sure to... | 5,336,231 |
def worker(num):
"""thread worker function"""
print 'Worker:', num
return | 5,336,232 |
def test_force():
"""Verifies that the user can override the check to see if the resulting
tarball exists."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
result = helpers.execute_command(
["-v", "snapshot", "--name", "test", "--module", "test", "--force"],
comman... | 5,336,233 |
def linear_blending(aurox_dir_path, current_dirs, c_ome_path, yes_orig):
"""
Linear blend images. It saves two images:
A fused tiff from TileConfiguration.fixed.txt with Z axis set to 0,
saved into FUSED_TIFFS and a separate fused tiff from
TileConfiguration.txt with original positio... | 5,336,234 |
def split_data(ratings, min_num_ratings, p_test=0.1, verbose=False, seed=988):
"""
Splits the data set (ratings) to training data and test data
:param ratings: initial data set (sparse matrix of dimensions n items and p users)
:param min_num_ratings: all users and items must have at least min_num_rating... | 5,336,235 |
def _adjust_block(p, ip, filters, block_id=None):
"""Adjusts the input `previous path` to match the shape of the `input`.
Used in situations where the output number of filters needs to be changed.
Arguments:
p: Input tensor which needs to be modified
ip: Input tensor whose shape needs to be matched
... | 5,336,236 |
def import_reference_genome_from_ncbi(project, label, record_id, import_format):
"""Imports a reference genome by accession from NCBI using efetch.
"""
# Validate the input.
assert import_format in ['fasta', 'genbank'], (
'Import Format must be \'fasta\' or \'genbank\'')
# Format keys f... | 5,336,237 |
def filter_points(points: np.array, image_width: int, image_height: int) -> np.array:
"""
function finds indexes of points that are within image frame ( within image width and height )
searches for
points with x coordinate greater than zero, less than image_width
points with y coordinate gre... | 5,336,238 |
def url_of_LumpClass(LumpClass: object) -> str:
"""gets a url to the definition of LumpClass in the GitHub repo"""
script_url = LumpClass.__module__[len("bsp_tool.branches."):].replace(".", "/")
line_number = inspect.getsourcelines(LumpClass)[1]
lumpclass_url = f"{branches_url}{script_url}.py#L{line_num... | 5,336,239 |
def correlation_sum(indicators, embedding_dim):
"""
Calculate a correlation sum
Useful as an estimator of a correlation integral
Parameters
----------
indicators : 2d array
matrix of distance threshold indicators
embedding_dim : integer
embedding dimension
Returns
... | 5,336,240 |
def test_submit_data():
"""
Test that data is stored into the data after a submission
Test that columns are added to the dataframe as expected even when
using query string parameters in the URL hash
"""
form_id=str(uuid.uuid4())
# add a survey
app_tables.forms.add_row(form_id=form_id, last_modified=... | 5,336,241 |
def find_suitable_serializer(obj):
"""
Find serializer that is suitable for this operation
:param T obj: The object that needs to be serialized
:return: The first suitable serializer for this type of object
:rtype: mlio.io.serializers.implementations.SerializerBase
"""
for serializer in __s... | 5,336,242 |
async def test_subscribe_unsubscribe_logbook_stream(
hass, recorder_mock, hass_ws_client
):
"""Test subscribe/unsubscribe logbook stream."""
now = dt_util.utcnow()
await asyncio.gather(
*[
async_setup_component(hass, comp, {})
for comp in ("homeassistant", "logbook", "aut... | 5,336,243 |
def square(x):
"""Return x squared."""
return x * x | 5,336,244 |
def int_div_test(equation, val):
"""
Comparison for the integer division binary search.
:equation: Equation to test
:val: Input to the division
"""
r1 = equation(val)
if r1 == None:
return None
r2 = equation(val - 1)
if r2 == None:
return None
if r1 == 1 and r2 ... | 5,336,245 |
def get_market_deep(symbols=None, output_format='json', **kwargs):
"""
Top-level function to obtain DEEP data for a symbol or list of symbols
Parameters
----------
symbols: str or list, default None
A symbol or list of symbols
output_format: str, default 'json', optional
... | 5,336,246 |
def test_only_ParametersAction_parameters_considered(build):
"""Actions other than ParametersAction can have dicts called parameters."""
expected = {
'param': 'value',
}
build._data = {
'actions': [
{
'_class': 'hudson.model.SomeOtherAction',
'... | 5,336,247 |
def merge_duplicates(data: Sequence[Message]) -> Iterator[Message]:
"""Merge duplicate messages."""
for _, group_ in itertools.groupby(data, _get_line):
group = list(sorted(list(group_), key=_get_program_message))
for _, duplicates_ in itertools.groupby(group, _get_program_message):
... | 5,336,248 |
def _ensure_func_attrs(func):
"""Add the relevant attributes to the function.
"""
if not hasattr(func, '__args__'):
func.__args__ = []
func.__args_mapping__ = {} | 5,336,249 |
def read_ss(path, dataset, order=None):
""" Read secondary structure prediction file
using specified order or automatically determined order based on results"""
with open(path, 'r') as f:
lines = f.readlines()
lines = [line.split() for line in lines]
start = 0
length = len(dataset.sequences[0])
for i,... | 5,336,250 |
def test_multimodel_feature_extraction():
"""Illustrate multimodel feature extraction.
This is a test illustrating how to perform feature extraction with a
distributed model using tfutils.base.test_from_params.
The basic idea is to specify a validation target that is simply the actual output of
th... | 5,336,251 |
def handleCharacter(ch, time_str, caller_name, config):
"""Handles character.
Handles character. Options: q (quit)
Args:
ch: Character.
time_str: Time string.
caller_name: Calling function's name.
"""
global quit_all
name = inspect.stack()[0][3]
try:
... | 5,336,252 |
def get_model():
"""
"""
# Describe the Convolutional Neural Network
model = tf.keras.Sequential([
# Convolutions
# Pooling
# Flatten units
tf.keras.layers.Flatten(),
# Input Layer
# Avoid overfitting
# Output layer - NUM_SHAPE_TYPES units
... | 5,336,253 |
def test_simulated_module_annotation_crossref(simulated_ann_crossref_vcf,
simulated_ann_crossref_csv):
"""Test the cross-reference annotation of the simulated VCF file using the
imported module."""
annotate(SIMULATED_VCF, TEST_VCF, crossref=True, csv=True)
w... | 5,336,254 |
def Packet_genReadVpeMagnetometerAdvancedTuning(errorDetectionMode, buffer, size):
"""Packet_genReadVpeMagnetometerAdvancedTuning(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size) -> size_t"""
return _libvncxx.Packet_genReadVpeMagnetometerAdvancedTuning(errorDetectionMode,... | 5,336,255 |
def compare(times_list=None,
name=None,
include_list=True,
include_stats=True,
delim_mode=False,
format_options=None):
"""
Produce a formatted comparison of timing datas.
Notes:
If no times_list is provided, produces comparison reports on ... | 5,336,256 |
def spaces(elem, doc):
"""
Add LaTeX spaces when needed.
"""
# Is it in the right format and is it a Space?
if doc.format in ["latex", "beamer"] and isinstance(elem, Space):
if isinstance(elem.prev, Str) and elem.prev.text in ["«", "“", "‹"]:
return RawInline("\\thinspace{}", "te... | 5,336,257 |
def clean_caption(text):
"""
Remove brackets with photographer names or locations at the end of some captions
:param text: a photo caption
:return: text cleaned
"""
text = str(text)
text = re.sub(r'\s*\[.+?\]$', '.', text)
text = re.sub(r'\s*\(photo.+?\)', '', text)
return re.sub(r'-... | 5,336,258 |
def index(limit = None):
"""Prints a suitable index of blog posts, using limit if necessary."""
global dbh
c = dbh.cursor()
c.execute("SELECT post_name, post_date, post_title FROM %s WHERE post_type = %s AND post_status = %s ORDER BY post_date DESC", (table, "post", "publish"))
if limit:
rows = c.fetchmany(l... | 5,336,259 |
def test_ls372_stop_acq_while_running(agent):
"""'stop_acq' should return True if acq Process is running."""
session = create_session('stop_acq')
# Have to init before running anything else
agent.init_lakeshore(session, None)
# Mock running the acq Process
agent.take_data = True
res = age... | 5,336,260 |
def take_slasher_snapshot(client):
"""
Collects all the command changes from the client's slash command processor.
Parameters
----------
client : ``Client``
The client, who will be snapshotted.
Returns
-------
collected : `None` or `tuple` of (`dict` of (`int`, `list` o... | 5,336,261 |
def zigpy_device_mains(zigpy_device_mock):
"""Device tracker zigpy device."""
def _dev(with_basic_channel: bool = True):
in_clusters = [general.OnOff.cluster_id]
if with_basic_channel:
in_clusters.append(general.Basic.cluster_id)
endpoints = {
3: {
... | 5,336,262 |
def test_decorator():
"""It should be a decorator."""
breaker = CircuitBreaker()
@breaker
def suc():
"""Docstring"""
pass
@breaker
def err():
"""Docstring"""
raise DummyException()
assert 'Docstring' == suc.__doc__
assert 'Docstring' == err.__doc__
... | 5,336,263 |
def test_valid_mapping() -> None:
"""Use a correct mapping.
When ds_df_mapping is correctly provided, ensure that it is correctly
stored.
"""
events = pd.DataFrame({
'event_type': ['pass', 'goal'],
'start_frame': [1, 100],
'end_frame': [200, 250]
})
ds = xr.Dataset... | 5,336,264 |
def compute_average_precision(precision, recall):
"""Compute Average Precision according to the definition in VOCdevkit.
Precision is modified to ensure that it does not decrease as recall
decrease.
Args:
precision: A float [N, 1] numpy array of precisions
recall: A float [N, 1] numpy ... | 5,336,265 |
def minimize_experiment_document(document):
"""
Takes a document belonging to an experiment or to a library in an experiment
and strips it down to a subset of desired fields. This differs from other
non-experiment documents in that the attachment is a dictionary rather than
a simple string concaten... | 5,336,266 |
def detect_container(path: pathlib.Path) -> type[containers.Container]:
"""Detect the container of a file"""
container_type = filetype.archive_match(path)
container_mime_type = container_type.mime if container_type else None
return containers.get_container_by_mime_type(container_mime_type) | 5,336,267 |
def score_mod(mod, word_count, mod_count, mod_match_unlabel):
"""计算模式的评分"""
p = word_count[mod]
u = len(mod_match_unlabel[mod])
t = mod_count[mod]
return (p / t) * math.log(u + 1, 2) * math.log(p + 1, 2) | 5,336,268 |
def get_matrix(costs='direct'):
"""Table used to compare the most appropriate building class for DCs"""
health_care = eeio(['233210/health care buildings/us'], [1])
manu_bldg = eeio(['233230/manufacturing buildings/us'], [1])
util_bldg = eeio(['233240/utilities buildings and infrastructure/us'], [1])
... | 5,336,269 |
def redshift_resource(context):
"""This resource enables connecting to a Redshift cluster and issuing queries against that
cluster.
Example:
.. code-block:: python
from dagster import ModeDefinition, execute_solid, solid
from dagster_aws.redshift import redshift_resource
... | 5,336,270 |
def ifft2(a, s=None, axes=(-2, -1), norm=None):
"""Compute the two-dimensional inverse FFT.
Args:
a (cupy.ndarray): Array to be transform.
s (None or tuple of ints): Shape of the transformed axes of the
output. If ``s`` is not given, the lengths of the input along the
ax... | 5,336,271 |
def get_displayable_story_summary_dicts(user_id, story_summaries):
"""Returns a displayable summary dict of the story summaries
given to it.
Args:
user_id: str. The id of the learner.
story_summaries: list(StorySummary). A list of the
summary domain objects.
Returns:
... | 5,336,272 |
def checkRange(value, ranges):
"""Checks if the value is in the defined range.
The range definition is a list/iterator from:
- float values belonging to the defined range M{x \in {a}}
- 2-tuples of two floats which define a range not including the tuple values itself M{x \in ]a,b[}
... | 5,336,273 |
def __main__(argv):
"""Command Line parser for scRna-Seq pipeline.
Inputs- command line arguments
"""
# the first command, -c, tells us which arguments we need to check for next, and which function we are going to call
command = argv[1].replace('-c=', '')
# create the argument parser
parser ... | 5,336,274 |
def vertical_nemenyi_plot(data, num_reps,
alpha = 0.05,
cmap = plt.cm.Greens):
"""Vertical Nemenyi plot to compare model ranks and show differences."""
return | 5,336,275 |
def read_anno_content(anno_file: str):
"""Read anno content."""
with open(anno_file) as opened:
content = json.load(opened)
return content | 5,336,276 |
def test_example(tmpdir, example_name):
"""Builds an example, ensures the rendered output matches the expected."""
source_directory = os.path.join(PROJECT_ROOT, "examples", example_name)
working_directory = os.path.join(str(tmpdir), example_name)
shutil.copytree(source_directory, working_directory)
... | 5,336,277 |
def openRotatorPort(portNum=0, timeout=5):
"""
Open a serial port for the rotator
Open commport ``portNum`` with a timeout of ``timeout``.
Parameters
----------
portNum : integer, default: 0
commport for the serial connection to the rotator
timeout : number, default: 5 se... | 5,336,278 |
def disable_poll_nodes_list(
nodes: List[str],
credentials: HTTPBasicCredentials = Depends(
check_credentials
), # pylint: disable=unused-argument
) -> Dict[str, str]:
"""Disable (snmp) polling on a list of nodes.
Exple of simplest call :
curl -X GET --user u:p -H "Content-type: applic... | 5,336,279 |
def twitter_sp(name):
"""
This function is dedicated to extract location names from Twitter data(.txt file)
:param name: str, filename
:return: None
"""
def twitter_profile(user):
"""
This function fetch the the Twitter user's profiles for the location in them
:param use... | 5,336,280 |
def extrudePoints(points, disp):
"""
Return a list of points including the initial points and extruded end
"""
farEnd=deepcopy(points)
farEnd[:,0]+=disp[0]
farEnd[:,1]+=disp[1]
farEnd[:,2]+=disp[2]
return np.vstack( (points,farEnd) ) | 5,336,281 |
def hex_form(hash):
"""Returns the hash formatted in hexadecimal form"""
final_hash = ''
for i in range(len(hash)):
final_hash += format(hash[i], '02x')
return final_hash | 5,336,282 |
def construct_job_file(tile_list, job_path):
"""
Construct a CurveAlign job list for the CHTC batch processing software
:param tile_list: List of image files
:param job_path: Path to save the job file at
:return:
"""
with tarfile.open(job_path, 'w') as tar:
... | 5,336,283 |
def patch_init_py(init_py, version):
"""Patch __init__.py to remove version check and append hard-coded version."""
# Open top-level __init__.py and read whole file
log.info("patching %s to bake in version '%s'", init_py, version)
with open(init_py, 'r+') as init_file:
lines = init_file.readline... | 5,336,284 |
def rangeFromString(commaString):
""" Convert a comma string like "1,5-7" into a list [1,5,6,7]
Returns
--------
myList : list of integers
Reference
-------
http://stackoverflow.com/questions/6405208/\
how-to-convert-numeric-string-ranges-to-a-list-in-python
"""
listOfLists = [... | 5,336,285 |
def wup(synset1: Synset, synset2: Synset) -> float:
"""Return the Wu-Palmer similarity of *synset1* and *synset2*."""
lch = synset1.lowest_common_hypernyms(synset2, simulate_root=True)[0]
n = lch.max_depth() + 1
n1 = len(synset1.shortest_path(lch, simulate_root=True))
n2 = len(synset2.shortest_path(... | 5,336,286 |
def _adjust_mq_version_headers(ev):
""" Unify evidence table headers of different MQ versions. """
ev.rename(columns={
'Leading razor protein': 'Leading Razor Protein',
'Leading proteins': 'Leading Proteins'
}, inplace=True) | 5,336,287 |
def transform_staging_tables(cur, conn):
"""
This function is used once the connection to the Redshift cluster is effective
It executes SQL instructions based on queries provided in the transform_table_queries list
"""
for query in transform_table_queries:
cur.execute(query)
conn.com... | 5,336,288 |
def sum_per_agent(df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Calculates summed values per agent for each given column individually"""
all_values_per_agent = pd.DataFrame(columns=columns)
for column in columns:
function = calc_sum(column)
value_per_agent = call_function_per_age... | 5,336,289 |
def _add_last_conditional_coloring(
sheet, worksheet, status_col, last_col, update_cell, start_row, length
):
"""Mark running jobs without updates."""
status_col_name = string.ascii_uppercase[status_col]
last_col_name = string.ascii_uppercase[last_col]
time_different_rule = f"(TO_PURE_NUMBER({updat... | 5,336,290 |
async def vcx_ledger_get_fees() -> str:
"""
Get ledger fees from the sovrin network
Example:
fees = await vcx_ledger_get_fees()
:return: JSON representing fees
{ "txnType1": amount1, "txnType2": amount2, ..., "txnTypeN": amountN }
"""
logger = logging.getLogger(__name__)
if not ... | 5,336,291 |
def calc_one_sample_metric(sample):
""" 计算 V1 数据一个样本的 rouge-l 和 bleu4 分数 """
if len(sample['best_match_scores']) == 0: # bad case
return -1, -1
pred_answers, ref_answers = [], []
pred_answers.append({'question_id': sample['question_id'],
'question_type': sample['quest... | 5,336,292 |
def ta_1d(x, a, w_0, w_1):
"""1d tanh function."""
return a * np.tanh(w_0 + (w_1 * x)) | 5,336,293 |
def log(*args):
"""
<Purpose>
Used to store program output. Prints output to console by default.
<Arguments>
Takes a variable number of arguments to print. They are wrapped in str(), so it is not necessarily a string.
<Exceptions>
None
<Returns>
Nothing
"""
for arg in args:
print(ar... | 5,336,294 |
def get_flat_topic_df(all_topics, n_topics):
"""
Get df with Multiindex to plot easier
:param all_topics: the IDs of the topics as list
:param n_topics: the number of topics in the model
:return: df with index [TopicID, Word] and weight
"""
init_topic = all_topics.columns[0]
# TODO refat... | 5,336,295 |
def loadConfig(filename):
"""Load and parse .yaml configuration file
Args:
filename (str): Path to system configuration file
Returns:
dict: representing configuration information
Raises:
BdsError: if unable to get configuration information
"""
try:
with open(fi... | 5,336,296 |
def test_generate_script_salt_api(tmpdir):
"""
Test script generation for the salt-api CLI script
"""
script_path = cli_scripts.generate_script(tmpdir.strpath, "salt-api")
with open(script_path) as rfh:
contents = rfh.read()
expected = textwrap.dedent(
"""\
from __future... | 5,336,297 |
def scale_t50(t50_val = 1.0, zval = 1.0):
"""
Change a t50 value from lookback time in Gyr at a given redshift
to fraction of the age of the universe.
inputs: t50 [Gyr, lookback time], redshift
outputs: t50 [fraction of the age of the universe, cosmic time]
"""
return (1 - t50_val... | 5,336,298 |
def configure(
processors: Optional[Iterable[Processor]] = None,
wrapper_class: Optional[Type[BindableLogger]] = None,
context_class: Optional[Type[Context]] = None,
logger_factory: Optional[Callable[..., WrappedLogger]] = None,
cache_logger_on_first_use: Optional[bool] = None,
) -> None:
"""
... | 5,336,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.