content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def convert_hdf_to_gaintable(f):
""" Convert HDF root to a GainTable
:param f:
:return:
"""
assert f.attrs['ARL_data_model'] == "GainTable", "Not a GainTable"
receptor_frame = ReceptorFrame(f.attrs['receptor_frame'])
frequency = numpy.array(f.attrs['frequency'])
data = numpy.array(f['da... | 5,339,100 |
def test_buffer_lag_increasing() -> None:
"""Test that each state only learns from observations buffer_timeout prior to the most recent observations.
Test using the increasing scheduler."""
buffer_timeout = 50
increase_rate = 1.0
buffered_classifier = BaseBufferedAdaptiveLearner(
classifier_... | 5,339,101 |
def list_files(directory):
"""Returns all files in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')] | 5,339,102 |
def test_bgp_attributes_for_evpn_address_family_p1(request, attribute):
"""
BGP attributes for EVPN address-family.
"""
tgen = get_topogen()
tc_name = request.node.name
write_test_header(tc_name)
check_router_status(tgen)
reset_config_on_routers(tgen)
add_default_routes(tgen)
i... | 5,339,103 |
def post_process(ctx, result_folder, the_executor):
"""
This method is invoked once the test generation is over.
"""
# Plot the stats on the console
log.info("Test Generation Statistics:")
log.info(the_executor.get_stats())
# Generate the actual summary files
create_experiment_descr... | 5,339,104 |
def condition_conjunction(conditions):
"""Do conjuction of conditions if there are more than one, otherwise just
return the single condition."""
if not conditions:
return None
elif len(conditions) == 1:
return conditions[0]
else:
return sql.expression.and_(*conditions) | 5,339,105 |
def get_claimed_referrals(char):
""" Return how many claimed referrals this character has. """
return db((db.referral.referrer==char) & (db.referral.claimed==True)).count() | 5,339,106 |
def groupsplit(X, y, valsplit):
"""
Used to split the dataset by datapoint_id into train and test sets.
The data is split to ensure all datapoints for each datapoint_id occurs completely in the respective dataset split.
Note that where there is validation set, data is split with 80% for training and 2... | 5,339,107 |
def multiprocessed_read():
"""
Get all the symbols from the database
Assign chunks of 50 symbols to each process worker and let them read all rows for the given symbol
1000 symbols, 100 rows
"""
conn = sqlite3.connect(os.path.realpath('database.db'))
symbols = conn.execute("SELECT DISTINCT S... | 5,339,108 |
def efficientnet_b0(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""EfficientNet-B0"""
model_name = "tf_efficientnet_b0"
default_cfg = default_cfgs[model_name]
# NOTE for train, drop_rate should be 0.2
# kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg
mo... | 5,339,109 |
def application(environ, start_response):
"""
make Passenger interpret PATH_INFO the same way that the WSGI standard
does
"""
environ["PATH_INFO"] = urllib.parse.unquote(environ["PATH_INFO"])
return app.app(environ, start_response) | 5,339,110 |
def run_experiment_here(
experiment_function,
variant=None,
exp_id=0,
seed=0,
use_gpu=True,
# Logger params:
exp_prefix="default",
snapshot_mode='last',
snapshot_gap=1,
git_infos=None,
script_name=None,
logger=default_logger... | 5,339,111 |
def normalize_chunks(chunks: Tuple[Tuple[int, int]]) -> Tuple[Tuple[int, int]]:
"""
Minimize the amount of chunks needed to describe a smaller portion of a file.
:param chunks: A tuple with (start, end,) offsets
:return: A tuple containing as few as possible (start, end,) offsets
"""
out = []
... | 5,339,112 |
def learning_rate_schedule(adjusted_learning_rate, lr_warmup_init,
lr_warmup_step, first_lr_drop_step,
second_lr_drop_step, global_step):
"""Handles linear scaling rule, gradual warmup, and LR decay."""
# lr_warmup_init is the starting learning rate; the learnin... | 5,339,113 |
def test_vgroup_remove(using_opengl_renderer):
"""Test the VGroup remove method."""
a = OpenGLVMobject()
c = OpenGLVMobject()
b = VGroup(c)
obj = VGroup(a, b)
assert len(obj.submobjects) == 2
assert len(b.submobjects) == 1
obj.remove(a)
b.remove(c)
assert len(obj.submobjects) == ... | 5,339,114 |
def set_power_state_server(power_state: ServerPowerState) -> List[float]:
"""Record the current power limit and set power limit using nvidia-smi."""
# Record current power limits.
if power_state.power_limit:
cmd = "nvidia-smi --query-gpu=power.limit --format=csv,noheader,nounits"
logging.in... | 5,339,115 |
def score_normalization(extracted_score: Union[str, None]):
"""
Sofa score normalization.
If available, returns the integer value of the SOFA score.
"""
score_range = list(range(0, 30))
if (extracted_score is not None) and (int(extracted_score) in score_range):
return int(extracted_score... | 5,339,116 |
def get_session():
"""Creates an authorized Requests Session."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
# Create a requests Session object wi... | 5,339,117 |
def wrap(wrapping_key_public, plaintext):
"""
RSA-OAEP key wrapping.
Args:
wrapping_key_public: The public key of the RSA wrapping key
plaintext: The plaintext key to wrap
"""
rsa_cipher = PKCS1_OAEP.new(
key=wrapping_key_public, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1... | 5,339,118 |
def get_output_filenames(output_path: str):
"""Returns a dict of output filenames."""
now = datetime.datetime.now()
now_string = now.strftime("%Y%m%d_%H%M%S")
filenames ={
'train': os.path.join(output_path, "train_split_"+now_string+".csv"),
'val': os.path.join(output_path, "val_split_"+now_string+"... | 5,339,119 |
def compute_horizontal_vessel_purchase_cost(W, D, F_M):
"""
Return the purchase cost [Cp; in USD] of a horizontal vessel,
including thes cost of platforms and ladders.
Parameters
----------
W : float
Weight [lb].
D : float
Diameter [ft].
F_M : float
Vessel ma... | 5,339,120 |
def format_dev_sub_dev_id(pciIdPair):
"""
pciIdPair (int pci device id, int pci sub device id or None)
"""
if pciIdPair[1] is None:
return "(0x%08X, None)" % pciIdPair[0]
return "(0x%08X, 0x%08X)" % pciIdPair | 5,339,121 |
def mychats():
"""
Show Chats where I can write
:return:
{
error: 0,
chats: [...Chat]
}
"""
result = {
'error': 0,
'chats': []
}
if 'user_id' in session:
chats_rows = query_db('SELECT * FROM chats WHERE user1_id = ? OR user2_id = ?', [session['... | 5,339,122 |
def polynom_prmzt(x, t, order):
"""
Polynomial (deterministic) parameterization of fast variables (Y).
NB: Only valid for system settings of Wilks'2005.
Note: In order to observe an improvement in DA performance w
higher orders, the EnKF must be reasonably tuned with
There is very ... | 5,339,123 |
def new_binning(xmin, xmax, nbin=25, bin_type='lin', out_type=int, custom_bins=None):
"""
Define the new binning.
Parameters
----------
Returns
-------
array
the array with the edges of the new binning
"""
if bin_type == 'lin' and custom_bins is None:
binning_ = np.linspace(xmin, x... | 5,339,124 |
def GenerateSurfaceAndBuriedResiduesVisualization():
"""Generate visualization for surface and buried residues."""
Outfile = OptionsInfo["PMLOutfile"]
OutFH = open(Outfile, "w")
if OutFH is None:
MiscUtil.PrintError("Failed to open output fie %s " % Outfile)
MiscUtil.PrintInfo("\nGener... | 5,339,125 |
def decode(s):
"""
Deserialize an EDS object from an EDS string.
"""
lexer = _EDSLexer.lex(s.splitlines())
return _decode_eds(lexer) | 5,339,126 |
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid < 0:
return False
import errno
try:
os.kill(pid, 0)
except OSError as e:
return e.errno == errno.EPERM
else:
return True | 5,339,127 |
def allowed_file(filename):
""" Verifies if file extension is compatible """
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 5,339,128 |
def clap_convert(txt):
"""convert string of clap values on medium to actualy number
Args:
txt (str): claps values
Returns:
number on claps (int)
"""
# Medium annotation
if txt[-1] == "K":
output = int(float(txt[:-1]) * 1000)
return output
else:
return int(txt) | 5,339,129 |
def hello(count: int, name: str):
""" Simple program that greets NAME for a total of COUNT times.
:param count: The number of times to repeat
:param name: The name to repeat"""
for _ in range(count):
print(f"Hello, {name}!") | 5,339,130 |
def write_phase1_capsummary(inst, isStringIO=True):
"""
Write out a multiweek summary of capacity, demand, understaffing.
:param inst: Model instance
:param isStringIO: True (default) to return StringIO object, False to return string
:return: capacity summary as StringIO object or a string.
"""... | 5,339,131 |
def glorot_uniform(shape):
"""
:param shape: tuple with the shape of the wanted output (filters_amount, depth, height, width)
:return: array (it's shape=param shape) with initialized values using 'glorot uniform' initializer
"""
fan_in, fan_out = _calc_fans(shape)
scale = 1. / ((fan_in + fan_out... | 5,339,132 |
def _test_atomic_write(file_size):
"""
Create a file of A's, use it to set_contents_from_file.
Verify the contents are all A's.
Create a file of B's, use it to re-set_contents_from_file.
Before re-set continues, verify content's still A's
Re-read the contents, and confirm we get B's
"""
... | 5,339,133 |
def main():
"""Creates a directory with a file for each article
:return: directory with a file for each article
"""
os.system('mkdir -p intermediary_corpus || true')
get_pdf_file_content('PDF_files/', 'intermediary_corpus/')
edit_text('intermediary_corpus/', 'corpus_B/')
os.system('rm -rf ... | 5,339,134 |
def get_server() -> str:
"""Generate a server information.
:return: server info
:rtype: str
"""
uname = platform.uname()
fmt_plat = f"OS: {uname.system} {uname.release} v{uname.version}\n"
fmt_plat += f"CPU: {uname.processor} ({os.cpu_count()} threads)\n"
fmt_plat += f"PID: {os.getpid()... | 5,339,135 |
def second_order_moments(n_components, e2, m1, alpha0):
"""Second-Order Moments
To prevent creating 2nd order moments explicitly, we construct its
decomposition with `n_components`. check reference [?] section 5.2
for details.
Parameters
----------
n_components: int
Number of compo... | 5,339,136 |
def callback_query_wrapper(func):
"""Create a session, handle permissions and exceptions for callback queries."""
def wrapper(update, context):
user = None
if context.user_data.get("ban"):
return
temp_ban_time = context.user_data.get("temporary-ban-time")
if temp_ba... | 5,339,137 |
def remove_names(df: pd.DataFrame) -> pd.DataFrame:
"""Convert personal names to numerical values."""
df = df.reset_index()
df.drop(columns='Name', inplace=True)
return df | 5,339,138 |
def handle_epoch_metrics(step_metrics, epoch_labels, epoch_predictions):
"""
Function that handles the metrics per epoch.
Inputs:
step_metrics - Dictionary containing the results of the steps of an epoch
epoch_labels - List of labels from the different steps
epoch_predictions - List ... | 5,339,139 |
def project_disk_sed(bulge_sed, disk_sed):
"""Project the disk SED onto the space where it is bluer
For the majority of observed galaxies, it appears that
the difference between the bulge and the disk SEDs is
roughly monotonic, making the disk bluer.
This projection operator projects colors that a... | 5,339,140 |
def load_image_url(image_url, image_size=(256, 256), preserve_aspect_ratio=True):
"""Loads and preprocesses images from a given url."""
# Cache image file locally.
image_path = tf.keras.utils.get_file(
os.path.basename(image_url)[-128:], image_url)
# Load and convert to float32 numpy array, add ... | 5,339,141 |
def qlog_numpy(q):
"""
Applies logarithm map to q
:param q: (4,)
:return: (3,)
"""
if all(q[1:] == 0):
q = np.zeros(3)
else:
q = np.arccos(q[0]) * q[1:] / np.linalg.norm(q[1:])
return q | 5,339,142 |
def ngrams(n, word):
"""
Generator of all *n*-grams of *word*.
Args:
n (int): The length of character ngrams to be extracted
word (str): The word of which the ngrams are to be extracted
Yields:
str: ngram
"""
for i in range(len(word)-n-1):
yield word[i:i+n] | 5,339,143 |
def merge_flow_relationship(flow_data, tx=None):
"""
This function focuses on just creating the starting/ending switch relationship for a flow.
"""
query = (
"MERGE " # MERGE .. create if doesn't exist .. being cautious
" (src:switch {{name:'{src_switch}'}}... | 5,339,144 |
def get_ML_features(df: pd.DataFrame, protease: str='trypsin', **kwargs) -> pd.DataFrame:
"""
Uses the specified score in df to filter psms and to apply the fdr_level threshold.
Args:
df (pd.DataFrame): psms table of search results from alphapept.
protease (str, optional): string specifying... | 5,339,145 |
def revcomp(sequence):
"""
Find reverse complementary sequence
:param sequence: The RNA sequence in string form
:return: The reverse complement sequence in string form
"""
complement = {"A": "U", "U": "A", "C": "G", "G": "C", "N": "N"}
revcompseq = ""
sequence_list = list(sequence)
s... | 5,339,146 |
def J(X, mean, r):
"""K-meansの目的関数(最小化を目指す)"""
summation = 0.0
for n in range(len(X)):
temp = 0.0
for k in range(K):
temp += r[n, k] * np.linalg.norm(X[n] - mean[k]) ** 2
summation += temp
return summation | 5,339,147 |
def get_all_subs():
""" Temporary function until we work out a better autocomplete
for createpost """
# TODO
return [x.name for x in Sub.select(Sub.name)] | 5,339,148 |
def timesince():
"""
Get the amount of time since 00:00 on 1 January 1970,
the raw date before formatting it.
"""
return time.time() | 5,339,149 |
def gencoords_outside(N, d, rad=None, truncmask=False, trunctype='circ'):
""" generate coordinates of all points in an NxN..xN grid with d dimensions
coords in each dimension are [-N/2, N/2)
N should be even"""
if not truncmask:
_, truncc, _ = gencoords_outside(N, d, rad, True)
return ... | 5,339,150 |
def map_orientation(cur_orientation, cur_count):
""" . . . . . x
. . . . . x
. . . . . x
. . . . . x
. . . . . x
. . . . . x
"""
right_edge = 34905131040
""" . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
... | 5,339,151 |
def glGetShaderInfoLog( baseOperation, obj ):
"""Retrieve the shader's error messages as a Python string
returns string which is '' if no message
"""
target = GLsizei()
glGetShaderiv(obj, GL_INFO_LOG_LENGTH,target)
length = target.value
if length > 0:
log = ctypes.create_string_buff... | 5,339,152 |
def _CheckGrdTranslations(grd_file, grd_lines, wanted_locales):
"""Check all <file> elements that correspond to an .xtb output file.
Args:
grd_file: Input .grd file path.
grd_lines: List of input .grd lines.
wanted_locales: set of wanted Chromium locale names.
Returns:
List of error message strin... | 5,339,153 |
def choose_diverging_palette(as_cmap=False):
"""Launch an interactive widget to choose a diverging color palette.
This corresponds with the :func:`diverging_palette` function. This kind
of palette is good for data that range between interesting low values
and interesting high values with a meaningful m... | 5,339,154 |
def get_lm_model(args, device, config):
"""Get language model(based on GPT-2) used for sequence prediction."""
ninp = config["ninp"]
nhead = config["nhead"]
initrange = config["initrange"]
dropout = config["dropout"]
vocab_size = config["vocab_size"]
nhid = config["nhid"]
ndecoder = con... | 5,339,155 |
def get_meminfo():
"""
Get and format the content of /proc/meminfo
"""
buf = open('/proc/meminfo').read()
buf = ','.join([v.replace(' ', '') for v in
buf.split('\n') if v])
return buf | 5,339,156 |
def effective_area(true_energy, reco_energy, simu_area):
"""
Compute the effective area from a list of simulated energy and reconstructed energy
Parameters
----------
true_energy: 1d numpy array
reco_energy: 1d numpy array
simu_area: float - area on which events are simulated
Returns
... | 5,339,157 |
def remove_vlan(duthost, vlan_id):
"""
Remove VLANs configuraation on DUT
Args:
duthost: DUT host object
vlan_id: VLAN id
"""
duthost.shell('config vlan del {}'.format(vlan_id))
pytest_assert(wait_until(3, 1, __check_vlan, duthost, vlan_id, True),
"VLAN RIF Vl... | 5,339,158 |
def execute(queries, arglists, fetchone=False):
"""Execute multiple queries to the sqlite3 jobtracker database.
All queries will be executed as a single transaction.
Return the result of the last query, or the ID of the last
INSERT, whichever is applicaple.
Inputs:
queri... | 5,339,159 |
def physical_cpu_mhz(vir_connection):
""" Get the CPU frequency in MHz using libvirt.
:param vir_connection: A libvirt connection object.
:type vir_connection: virConnect
:return: The CPU frequency in MHz.
:rtype: int
"""
return vir_connection.getInfo()[3] | 5,339,160 |
def test_pcall_sitepackages(venv, mocker, actioncls):
"""
Check that the sitepackages configuration in tox is passed to pipenv
"""
action = actioncls()
mocker.patch.object(os, "environ", autospec=True)
mocker.patch("subprocess.Popen")
venv.envconfig.sitepackages = True
result = tox_teste... | 5,339,161 |
def addstream(bot, input):
"""Add a stream from the notify list"""
if not input.admin: return False
if not input.group(2): return
stream = input.group(2).lower()
if not stream in bot.config.streams:
bot.config.set_add('streams', stream)
bot.reply("Added {0} to stream list".format(stream))
else:
bot.reply("{... | 5,339,162 |
def add_selection_logger(viewer: MjViewerBasic, sim: MjSim, callback=None):
"""
Adds a click handler that prints information about the body clicked with the middle mouse button.
Make sure to call env.render() so that a viewer exists before calling this function.
:param viewer: the MuJoCo viewer in use.
... | 5,339,163 |
def get_author(search):
"""
Queries google scholar to find an author given a
search string. If != 0 results are found it gives an error
"""
authors = list(scholarly.search_author(search))
if len(authors) > 1:
raise ValueError(f'Found >1 authors with search string: {searc}, try... | 5,339,164 |
def _named_tensor_generic_operation(
tensor: torch.Tensor,
tensor_ops_pre: callable = dummy,
tensor_ops_post: callable = dummy,
name_ops: callable = dummy) -> torch.Tensor:
"""
generic base function used by others
First store the names
Args:
tensor (): the named t... | 5,339,165 |
def test_lico():
"""Example basic usage where everything works"""
input_list = Table.init_from_path(RESOURCE_PATH / "a_csv_file")
output_list = lico.process(input_list, Concatenate(columns=['patient', 'date']))
file = StringIO()
output_list.save(file)
file.seek(0)
content = file.read()
... | 5,339,166 |
def test_stack_validation_fails_if_a_components_validator_fails(
stack_with_mock_components, failing_stack_validator
):
"""Tests that the stack validation fails if one of its components validates
fails to validate the stack."""
stack_with_mock_components.orchestrator.validator = failing_stack_validator
... | 5,339,167 |
def normalize_address_components(parsed_addr):
# type: (MutableMapping[str, str]) -> MutableMapping[str, str]
"""Normalize parsed sections of address as appropriate.
Processes parsed address through subsets of normalization rules.
:param parsed_addr: address parsed into ordereddict per usaddress.
... | 5,339,168 |
def test_models_edx_ui_problem_graded_with_valid_statement(statement):
"""Tests that a `problem_graded` browser statement has the expected `event_type` and
`name`."""
assert statement.event_type == "problem_graded"
assert statement.name == "problem_graded" | 5,339,169 |
def model_inputs():
"""
构造输入
返回:inputs, targets, learning_rate, source_sequence_len, target_sequence_len, max_target_sequence_len,类型为tensor
"""
inputs = tf.placeholder(tf.int32, [None, None], name="inputs")
targets = tf.placeholder(tf.int32, [None, None], name="targets")
learning_rate = tf.... | 5,339,170 |
def is_key_in_store(loc, key):
"""
A quick check to determine whether the :class:`pandas.HDFStore`
has datA for ``key``
:ARGS:
loc: :class:`string` of path to :class:`pandas.HDFStore`
key: :class:`string` of the ticker to check if currently
available
:RETURNS:
... | 5,339,171 |
def transform_rows_nonlinear06(data, **kwargs):
"""
Nonlinear row transformation 06. 12 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), sin(2*pi*x), cos(pi*x), cos(2*pi*x), x^5, exp2, log10(x-x.min()), boxcox(2), boxcox(4), boxcox(6).
"""
sources_transformers = [
1.0,
lam... | 5,339,172 |
def catch_parameter(opt):
"""Change the captured parameters names"""
switch = {'-h': 'help', '-o': 'one_timestamp', '-a': 'activity',
'-f': 'file_name', '-i': 'imp', '-l': 'lstm_act',
'-d': 'dense_act', '-p': 'optim', '-n': 'norm_method',
'-m': 'model_type', '-z': 'n_si... | 5,339,173 |
def generate_code_v2(program):
"""
Returns an instance of :class:`CodeGenerationResult`.
:param program: An instance of :class:`loopy.TranslationUnit`.
"""
from loopy.kernel import LoopKernel
from loopy.translation_unit import make_program
# {{{ cache retrieval
from loopy import CACH... | 5,339,174 |
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
... | 5,339,175 |
def train_concise_ch11(trainer_fn, hyperparams, data_iter, num_epochs=4):
"""Defined in :numref:`sec_minibatches`"""
# Initialization
net = nn.Sequential(nn.Linear(5, 1))
def init_weights(module):
if type(module) == nn.Linear:
torch.nn.init.normal_(module.weight, std=0.01)
net.... | 5,339,176 |
def list(tag_name=None, start_date=None):
""" List records for a given tag (optional: starting from a given date)
"""
if tag_name is not None:
if tag_name not in get_tags():
log.error(ERROR_UNKNOWN_TAG_NAME)
return
if start_date is not None:
if start_date... | 5,339,177 |
def get_mgr_pods(mgr_label=constants.MGR_APP_LABEL, namespace=None):
"""
Fetches info about mgr pods in the cluster
Args:
mgr_label (str): label associated with mgr pods
(default: defaults.MGR_APP_LABEL)
namespace (str): Namespace in which ceph cluster lives
(default... | 5,339,178 |
def normalise_architecture(architecture: Union[str, int]):
"""Convert any valid architecture alias to either 'x86_64' or 'i686'.
Raise an error for invalid input.
"""
for (true_name, aliases) in architecture_aliases.items():
if architecture in aliases:
return true_name
raise Valu... | 5,339,179 |
def process_m(filename, m, estimator):
"""Returns the list of file sizes and PSNR values for
compression method m.
"""
filesize, psnr = [], []
for q in range(0, 101, 5):
_size, _psnr = process_q(filename, q, m, estimator)
filesize.append(_size / 1024) # in kilobyte(s)
psnr.... | 5,339,180 |
def fmt(n):
"""format number with a space in front if it is single digit"""
if n < 10:
return " " + str(n)
else:
return str(n) | 5,339,181 |
def test_registration():
"""Test registering a magic and getting a copy of it and de-registering."""
manager.MagicManager.clear_magics()
def my_magic(cell=None, line=None):
"""This is a magic."""
if not cell:
cell = 'foo'
if not line:
line = 'bar'
return f'{cell}{line}'
my_magic.ma... | 5,339,182 |
def Show_Method(filename):
""" The function Show_Method(filename) reads the method contained in the file and displays its content
"""
global Method_Content
# Read the method and update the variable "Method_Content"
try:
with open(filename) as file:
Method_Content.set(file.read()) # Reads the content of the m... | 5,339,183 |
def mailer(recips, subject, report):
"""
Sends an email containing a report from a flushed MessageBuffer.
"""
if not recips:
logging.error("Recips was empty, adding error recip")
recips.append(setting('REPORT_TO', ''))
logging.info('Mailer is emailing, subject = %r, recipients=%r',
... | 5,339,184 |
def stop():
"""Stop cleaning
This is using docstrings for specifications.
---
definitions:
stop:
type: object
properties:
did:
type: string
siid:
type: integer
aiid:
type: integer
code:
type: in... | 5,339,185 |
def save_key(access_key, output_filename=DEFAULT_ACCESS_KEY_FILE):
"""
saves access key to .yc json file
"""
with open(output_filename, "w+") as f:
f.write(json.dumps(access_key, indent=4))
return output_filename | 5,339,186 |
def make_link_targets(proj_name,
user_name,
repo_name,
known_link_fname,
out_link_fname,
url=None,
ml_url=None):
""" Check and make link targets
If url is None or ml_url is None, ... | 5,339,187 |
def PutObject(object_id: str):
"""Add/replace DRS object with a user-supplied ID.
Args:
object_id: Identifier of DRS object to be created/updated.
Returns:
Identifier of created/updated DRS object.
"""
return register_object(
data=request.json,
object_id=object_id,... | 5,339,188 |
def get_handler_name(method: str, url_path: str, path_params: dict):
"""
Возвращает имя необходимого хендлера для рефлексифного вызова метода
:param method: Метод
:param url_path: URL
:param path_params: Параметры
:return:
"""
handler = url_path.replace('/', '_')
for key, value in pa... | 5,339,189 |
def parse_args():
"""Process input arguments"""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('genotypes', metavar='G', help="Genotype table")
parser.add_argument('mutations', metav... | 5,339,190 |
def test_validate_json_invalid_json():
"""
Unit test to check the validate_json function with invalid json_object inputs
"""
json_object = {
"cpu_cores": "0.1"
}
with pytest.raises(AMLConfigurationException):
assert validate_json(
data=json_object,
schema=... | 5,339,191 |
def cli_create_subscription_type(args: argparse.Namespace) -> None:
"""
Handler for "mnstr subtypes create".
"""
result = create_subscription_type(
args.id,
args.name,
args.description,
args.icon,
args.choices,
args.stripe_product_id,
args.stripe_p... | 5,339,192 |
def get_courses(terms, programs, synergis, whitelist=None):
""" yield a course augmented with sis info from a sorted list of courses for a list of terms & programs
gratitude to http://nedbatchelder.com/text/iter.html#h_customizing_iteration
NOTE: api returns courses in a subaccount AND ITS SUBACC... | 5,339,193 |
def write_single(filename, dic, data, overwrite=False):
"""
Write data to a single NMRPipe file from memory.
Write 1D and 2D files completely as well as NMRPipe data streams.
2D planes of 3D and 4D files should be written with this function.
See :py:func:`write` for documentation.
"""
# a... | 5,339,194 |
def plot_AP(file_path: str):
""" 绘制 AP 柱状图 """
with open(file_path, encoding='utf-8') as f:
result = json.load(f)
AP = []
classes = []
for k, v in result.items():
if k!='mAP':
AP.append(v['AP'])
classes.append(k)
fig, ax = plt.subplots(1, 1, num='AP 柱状图'... | 5,339,195 |
def partner_data_ingest_new_files(source, destination):
"""
:param source : list of files to process:
:param destination: destination to copy validated files
check s3 path for new file, trigger partner_data_ingest for new files.
"""
hook = S3SyncHook(aws_conn_id="aws_default", verify=True)
... | 5,339,196 |
def parse_data_describe(args: argparse.Namespace) -> None:
"""
Handler for the "data describe" command
"""
simiotics_client = client_from_env()
data_descriptions = data.describe_data(simiotics_client, args.source, args.ids)
print('*** Data descriptions ***')
for i, description in enumerate(d... | 5,339,197 |
def buildGeneRegions(infile, outfile):
"""build a :term:`bed` file of regions spanning whole gene models.
This method outputs a single interval spanning the genomic region
that covers all transcripts within a particular gene.
The name column of the :term:`bed` file is set to the `gene_id`.
Argume... | 5,339,198 |
def _mofval(value, indent, maxline, line_pos=0, end_space=0):
"""
Low level function that returns the MOF representation of a non-string
value (i.e. a value that cannot not be split into multiple parts, for
example a numeric or boolean value).
If the MOF representation of the value does not fit int... | 5,339,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.