content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_msg_lang(msg, locale='en'):
""" get_msg_lang(msg, locale='en'): Retrieve language string for codename
@param msg <- str: the codename
@param locale <- str: language to retrieve
@return msg -> str: translated string """
langs = {'en', 'zh', 'jp'}
lang_list = {
'ALREADY_ONLINE': {
... | e772d18ebddde34f23ba9721bcd03a8eb50fb80a | 38,533 |
def get_end_stamp(bag):
"""
Get the latest timestamp in the bag.
@param bag: bag file
@type bag: rosbag.Bag
@return: latest timestamp
@rtype: rospy.Time
"""
end_stamp = None
for connection_end_stamp in [index[-1].time for index in bag._connection_indexes.values()]:
if not ... | 5524aa70f29b7a00fb95fe49076bf64f69fe01fd | 38,534 |
import decimal
def time_to_str(time):
"""
Change an integer duration to be represented as d days h hours m mins s secs
but only use the two major units (ie, drop seconds if hours and minutes are
populated)
"""
DAY = 86400
HOUR = 3600
MIN = 60
max_units = 2
num_units = 0
i... | 041fd0dca99c8d1747a7e15430de1f81513c7d85 | 38,536 |
from typing import Optional
from typing import Sequence
import argparse
def parse_args(argv: Optional[Sequence[str]]) -> argparse.Namespace:
"""Parse and return the parsed command line arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
pa... | 601db2d21def696a29ee0d7025fdac4c34d7f773 | 38,537 |
def human_size(size, units=(' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB')):
"""
Returns a human readable string representation of bytes
"""
return "{}".rjust(6 - len(str(size))).format(str(size)) + units[0] if size < 1024 else human_size(size >> 10, units[1:]) | 84dba431ddddbfd5a6d6c68712a448a8b970ee61 | 38,538 |
import random
import re
def generate_random_url():
"""Generates and returns 3x english words concatenated to use for random URL"""
url_string = ''
f = open('word_file.txt', 'r')
word_list = f.read().split()
word_file_length = len(word_list)
for i in range(3):
url_string += word_list[random.r... | fec621761a4f51ac50e610981d284ca487c891ab | 38,539 |
def parse_archive_filename(filename):
"""
Read the filename of the requested archive and return
both the chart name and the release version.
"""
chunks = filename[:-4].split('-')
chart_name = '-'.join(chunks[:-1])
version = chunks[-1]
return chart_name, version | c35f0e0f1eae45f1cd5f6317528341c6c507b32d | 38,540 |
def linalg_vector_len(a):
"""
Return length of vector
Parameters:
a (array): The vector
Return (number): The length of vector
"""
return len(a) | 988220d7995c6253fd85146f613a9f4b9a3a0d02 | 38,541 |
def have_same_shapes(array1, array2):
"""
Returns true if array1 and array2 have the same shapes, false
otherwise.
@param array1:
@param array2:
@return:
"""
return array1.shape == array2.shape | 58f5460687ce0ccb7e648527a025a3121b6d5f6b | 38,544 |
def get_file_or_default(metric_file):
""" Returns the module name from which to extract metrics. Defaults to cohorts.metrics
:param str metric_file: The name of the module to extract metrics from
:return: The name of the module where metric functions reside
"""
return metric_file if metric_file is... | 18cfc8a2a892af5cc038fd22aa7f88838aaec270 | 38,546 |
def main():
"""Generate a blank homepage"""
return "" | e061194f349597e2378c6967e2b89f495a58b6ea | 38,547 |
def _update_algorithm(data, resources):
"""
Update algorithm dict with new cores set
"""
new_data = []
for sample in data:
sample[0]['config']['algorithm'] = resources
new_data.append(sample)
return new_data | 87d5d78dae5817187eaf6e799511ec1bf0ad334d | 38,550 |
import requests
def get_gear(name,realm="sargeras"):
"""Query the raider.io server for gear information on a character and return as a formatted string"""
url = f"https://raider.io/api/v1/characters/profile?region=us&realm={realm}&name={name}&fields=gear"
response = requests.get(url).json()
gear = res... | ebe1f53eed37b0dadccb3ca25c5e7a5384f66228 | 38,552 |
def template_format(template):
"""Parse template string to identify digit formatting,
e.g. a template med#####.xml.gz will give output (#####, {:05})
"""
num_hashes = sum([1 for c in template if c == "#"])
return "#"*num_hashes, "{:0" + str(num_hashes) + "}" | 16e4b7d24a992b82aa652d4918319f9bbecca5b4 | 38,553 |
import logging
def getRequestLogger():
"""
Used for logging information produced after an endpoint request.
"""
return logging.getLogger("controller_request") | 40fb8e2411534eb7b05dd45dae7c5ab80db5b763 | 38,554 |
def rxn_query_str(reactant, product, rxn_id):
"""
Generate cypher MERGE query for reactant and product node.
"""
return "MERGE (r: Molecule {smiles_str:\""+ reactant +"\"}) MERGE (p: Molecule {smiles_str:\""+ product +"\"}) MERGE (r)-[:FORMS {rxn_id: "+ str(rxn_id) +"}]->(p)" | 3f28f800013a19d8a608c42dd8013ad66fa42e26 | 38,555 |
def _set_context(obj, stack):
"""Helper function to place an object on a context stack"""
if stack is None:
return obj
return stack.enter_context(obj) | ef56de573f1bb169f2dbccc183db45052cbb8a2f | 38,556 |
def grid_points_2d(length, width, div, width_div=None):
""" Returns a regularly spaced grid of points occupying a rectangular
region of length x width partitioned into div intervals. If different
spacing is desired in width, then width_div can be specified, otherwise
it will default to div. If div < 2 ... | b3ef8807fcca1c518b73e6a7339a45f8aa3cd4e1 | 38,557 |
def arr_map(arr, fcn):
"""
arr is a bit-planed numpy array
returns arr with fcn applied to each pixel in arr
where pixel is defined in iterate_pixels
"""
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
arr[i,j] = fcn(arr[i,j])
return arr | bbb65011900eadce2c19f6049cab6373b8cc43b2 | 38,559 |
def p_a2(npsyns, ninputs):
"""
Probability of selecting one input given ninputs and npsyns attempts. This
uses a binomial distribution.
@param npsyns: The number of proximal synapses.
@param ninputs: The number of inputs.
@return: The computed probability.
"""
p = 1. / ninputs
return npsyns * p * ((1 -... | 9a245105445c07e31e74aa2fe56cec31612cb7aa | 38,560 |
from typing import OrderedDict
def unique_list(sequence):
"""
Creates a list without duplicate elements, preserving order.
Args:
sequence (Sequence): The sequence to make unique
Returns:
list: A list containing the same elements as sequence, in the same order, but without duplicates.... | 1939aca821e745959c3ab9be35e304fb453b55dc | 38,561 |
import torch
def calc_mats(v, v_mask, v_w, q, q_mask, q_w, a):
"""
calc all matrices scores: vv, qq, qa, va, vq
1. use ans select img_feat: no, doesn't make sense
2. use q select v
ans * v to select v, tentatively select 7 boxes
ans * q to highlight q and select len(q) rois for visualize
"... | 7f1d9769b55fbde5a0e2bad4edfdb7ff298f4641 | 38,562 |
from typing import Tuple
def string_from_sentence(sentence: Tuple[Tuple]) -> str:
"""Get sentence as string from list of list representation
Args:
sentence (Tuple[Tuple]): Sentence in list of list representation
Returns:
str: Sentence as string
"""
return ''.join([edge[-1] for edge in sentence]) | c7abf8ff452835b6bbc5706e5e3718453dc5162c | 38,563 |
import re
def import_file(
client, filename, file_type=None, dirname=None, new_name=None, new_model_type="asm"
):
"""Import a file as a model.
Note: This function will not automatically display or activate
the imported model. If you want that, you should take the file name
returned by this functi... | 5f1e329e101bba6b71c57dbcd650ee0ced033044 | 38,565 |
def select_unique_pvcs(pvcs):
"""
Get the PVCs with unique access mode and volume mode combination.
Args:
pvcs(list): List of PVC objects
Returns:
list: List of selected PVC objects
"""
pvc_dict = {}
for pvc_obj in pvcs:
pvc_data = pvc_obj.get()
access_mode... | 03d46bd9d3350d84205c8031bdf6143f2e3bbf8c | 38,566 |
def headers(group_id, token):
"""
Generate the headers expected by the Athera API. All queries require the active group, as well as authentication.
"""
return {
"active-group": group_id,
"Authorization" : "Bearer: {}".format(token)
} | f86edb9151da099bf9818ffbf8a4eb66f4becb67 | 38,567 |
def get_shorter_move(move, size):
"""
Given one dimension move (x or y), return the shorter move comparing with opposite move.
The Board is actually round, ship can move to destination by any direction.
Example: Given board size = 5, move = 3, opposite_move = -2, return -2 since abs(-2) < abs(3).
""... | 635ee3038a4b78318658288f7876144f82333ebb | 38,568 |
def verb_forms(s):
"""
From a given verb makes 4-element tuple of:
infinitive: The verb itself
-s: The third form
-ing: Continuous tense
-ed: Past simple tense
"""
words = s.split()
verb = words.pop(0)
third = cont = past = None
if ve... | ab343e5a64f082e42601a0911f399b0c088f1bc7 | 38,570 |
import torch
def generate_code(model, dataloader, code_length, num_classes, device, dynamic_meta_embedding, prototypes):
"""
Generate hash code
Args
dataloader(torch.utils.data.dataloader.DataLoader): Data loader.
code_length(int): Hash code length.
device(torch.device): Using gpu... | fe1ded1e5b1f297926eb19aabb75129d26e2a386 | 38,571 |
def is_dark(x, y):
"""
Determine if a given pixel coordinate is a 'dark' pixel or not.
"""
# Odds are (0,0), (0,2), (1,1), (1,3)
# Evens are (0,1), (0,3), (1,0), (1,2)
return (x + y) % 2 == 0 | 0bf137a98e89dc6f9b688aa8e467b709ff53991a | 38,572 |
from datetime import datetime
def create_database(redis_db):
"""
Create an empty Redis database structure.
"""
destiny_version = "D2"
db_revision = "0"
# Set revision to "0"
# print(destiny_version + ":" + revision)
# redis_db.set(destiny_version + ":" + "revision", "0")
# set metadata to empty:
redis_db... | 5191eedf75c075a0e855c1a4a087077a4c1dbdbc | 38,573 |
def _filter_tree(info, filters):
"""
Remove nodes from the tree that get caught in the filters.
Mutates the tree.
"""
filtered_children = []
for child in info.children:
if _filter_tree(child, filters):
filtered_children.append(child)
info.children = filtered_children
... | 32aa39a34dbf48af0ff23e7f0628f39afee7f71f | 38,574 |
import re
def tokenize(line):
"""Split up a line of text on spaces, new lines, tabs, commas, parens
returns the first word and the rest of the words
>>> tokenize("This,Test")
('This', ['Test'])
>>> tokenize("word1 word2 word3")
('word1', ['word2', 'word3'])
>>> tokenize("word1, word2, w... | 17b6b2b479208ed01be32b13b8231ed8c3adf143 | 38,575 |
def normalize(df):
""" Normalizes data to [0,1].
"""
# copy the dataframe
df_norm = df.copy()
# apply min-max scaling
for column in df_norm.columns:
df_norm[column] = (df_norm[column] - df_norm[column].min()) / (df_norm[column].max() - df_norm[column].min())
return df_norm | 67ed8ac72df8750b34ff87c132d22b04df9be918 | 38,576 |
def manifest_clinical_merge(manifest_df, clinical_df, target):
"""
AML_df = manifest_clinical_merge(manifest_df, aml_disc_df, 'TARGET-AML')
Parameters
----------------
manifest_df: dataframe of metadata of study
clinical_df: dataframe specific for disease with patient as rows
target: string... | 7695cbd7e1cbbd6f9492fe50460ebbea548adc7a | 38,577 |
def utf8len(strn):
"""Length of a string in bytes.
:param strn: string
:type strn: str
:return: length of string in bytes
:rtype: int
"""
return len(strn.encode("utf-8")) | d43215730e1bfbb9beb593033b6d8339b45cce2b | 38,578 |
def get_certificate_fields_list() -> list:
"""Function to get a list of certificate fields for use with struct.unpack()
:return: a list of certificate fields for use with struct.unpack()
:rtype: list
"""
return [
"signer",
"certificate_version_type",
"certificate_type",
... | ec960c5c8031e70bec37390e7164b4997bc18931 | 38,579 |
def to_density_matrix(state):
"""
Convert a Hilbert space vector to a density matrix.
:param qt.basis state: The state to convert into a density matrix.
:return: The density operator corresponding to state.
:rtype: qutip.qobj.Qobj
"""
return state * state.dag() | 4bdbb2e1dc142408628b5d769c368cbf8bbaf673 | 38,580 |
def append_code(html, code, *args):
"""
Appends the given code to the existing HTML code
"""
if args:
# Format added code first
code = code.format(*args)
return "{0}\n{1}".format(html, code) | 79d40e6f22c682c37a450c9a025ea09f4ba7a624 | 38,581 |
import torch
def vectorize(ex, model):
"""Vectorize a single example."""
src_dict = model.src_dict
tgt_dict = model.tgt_dict
code, summary, ref0, ref1, scr0, scr1 = ex['code'], ex['summary'], ex['ref0'], ex['ref1'], ex['score0'], ex['score1']
vectorized_ex = dict()
vectorized_ex['id'] = code.... | c8d8bf92c734bb4e1c349b80209e156e44514003 | 38,582 |
import math
def get_normalized(vector):
"""Returns normalized vector (2-norm) or None, if vector is (0, 0).
:param vector: of this vector a normalized version will be calculated
:type vector: 2d list
:rtype: normalized version of the vector
"""
result = None
x = vector[0]
y = vector[... | 8e21929bf5b64378d40ed1e1e546a5da9a74af2a | 38,583 |
import re
def extractMetabolicSystems(GEM, reactions_list, systemType, macrosystem=None):
"""
Extracts a list of metabolic subsystems or macrosystems as specified in "systemType"
from the list of reactions in "reaction_list". If macrosystem is not None,
then subsystems are retrieved such that the reac... | 6d417b9b1db5283a3ed8ed6a55d9402f5641f983 | 38,585 |
def tor_to_rune(tor):
"""
1e8 Tor are 1 Rune
Format depending if RUNE > or < Zero
"""
# Cast to float first if string is float
tor = int(float(tor))
if tor == 0:
return "0 RUNE"
elif tor >= 100000000:
return "{:,} RUNE".format(int(tor / 100000000))
else:
retu... | 17e32a430deb795ac6a041c7bd135ef304c6fd25 | 38,586 |
def ChangeShape3D(data, nx, ny, nz, dataLength, haloNum):
"""Converting the storage order of multidim array in 3D space."""
data = data.reshape((nz + 2 * haloNum, ny + 2 * haloNum,
nx + 2 * haloNum, dataLength))
return data.transpose((2, 1, 0, 3)) | ae9dc54e3432786aa930228e12c11ba25c2e991b | 38,587 |
def dir(object: object=None) -> object:
"""dir."""
return object.__dir__() | 65030402ac1afa5daa818aa7b25288997a3e15c7 | 38,589 |
def make_grad_fn(clf):
"""Return a function which takes the gradient of a loss.
Args:
clf (Classifier): the classifier whose gradient we are interested in.
Returns:
f (function): a function which takes a scalar loss and GradientTape and
returns the gradient of loss w.r.t clf.weights.
... | b94c72e0072107e3d9f0e4c8ce2b212fb3393cdd | 38,590 |
def add_to_readonly_fields():
"""
This adds the django-published fields to the readonly_fields list.
Usage (in your model admin):
def get_readonly_fields(self, obj=None):
return self.readonly_fields + gatekeeper_add_to_readonly_fields()
"""
return ['show_publish_status'] | 49bbd450e85aad4db4c7761cf4d3a245ba1ac12b | 38,591 |
import socket
def discover_bulbs(timeout=2):
"""
发现所有局域网内的Yeelight灯泡.
:param int timeout: 等待回复需要多少秒。发现将总是要花这么长的时间,
因为它不知道当所有的灯泡都响应完毕时。
:returns: 字典列表,包含网络中每个灯泡的IP,端口和功能。
"""
msg = 'M-SEARCH * HTTP/1.1\r\n' \
'ST:wifi_bulb\r\n' \
'MAN:"ssdp:discover"... | 2f48c98df2cec72a7beee572f359166a5b3b9555 | 38,592 |
from typing import List
from typing import Tuple
def breaking_records(scores: List[int]) -> Tuple[int, int]:
"""
>>> breaking_records([10, 5, 20, 20, 4, 5, 2, 25, 1])
(2, 4)
>>> breaking_records([3, 4, 21, 36, 10, 28, 35, 5, 24, 42])
(4, 0)
"""
maxs = mins = 0
_max_min = {scores[0]}
... | 0123ea5cbf7ae27fc14fea35dfb24a6c876fbb75 | 38,593 |
def cummulative_length(fasta, keys):
"""Return the sum of the lengths represented by `keys`."""
keys = set(keys)
lengths = []
for name, seq in fasta.records.items():
if name in keys:
lengths.append(len(seq))
return sum(lengths) | eb9daff5e8a6998dbada873900838bdd84fd6ba1 | 38,595 |
from typing import List
from typing import Union
def _from_dotlist(dotlist: str) -> List[Union[str, int]]:
"""Convert dot-list to list of keys.
Parameters
----------
dotlist : str
Dot-List
"""
keys: List[Union[str, int]] = []
for item in dotlist.split("."):
for it in item.... | 2545cd6dc54e5c1de9b5c8a90289c5635d8287ff | 38,596 |
import logging
def SanitizeDeps(submods, path_prefix, disable_path_prefix=False):
"""
Look for conflicts (primarily nested submodules) in submodule data. In the
case of a conflict, the higher-level (shallower) submodule takes precedence.
Modifies the submods argument in-place. If disable_path_prefix is True,... | dd7ef53cd0f18bf057a7ff8b95c108efdbcf68ab | 38,597 |
def create_test_attribute_types():
"""Create one of each attribute type.
"""
return [
dict(
name='Bool Test',
dtype='bool',
default=False,
),
dict(
name='Int Test',
dtype='int',
default=42,
minimum=-1... | f7477faf8f00d255b417d0e736391d782ab01b55 | 38,598 |
def need_comparison_query(count_types):
"""
Do we not need a comparison query?
"""
needing_fields = [c for c in count_types if not c in ["WordCount","TextCount"]]
return len(needing_fields) != 0 | 95c047bd12a29d006900d8a159798e6c6a00585b | 38,600 |
def clean_abstract(s):
"""Clean an abstract of a document."""
# Remove copyright statement, which can be leading or trailing
tokens = s.split(". ")
if "©" in tokens[0]:
return ". ".join(tokens[1:])
for idx in (-2, -1):
try:
if "©" in tokens[idx]:
return ".... | 47e31432410c7cc77c6e8484eceb09cf4e2c921f | 38,601 |
def determine_mapping_type(gene_table,pathways_to_genes,pathways_to_ecs):
"""
Determine if the input file is of gene families or EC abundance type
"""
all_genes=set()
all_ecs=set()
for pathway,genes in pathways_to_genes.items():
all_genes.update(genes)
all_ecs.update(pathway... | d2e913e6e41db4aa0bc2f97e54e5bc5229483eaf | 38,603 |
def adimensionalise(a,mach,rho,s,b,mac,m,I_xx,I_yy,I_zz,I_xz):
"""Find if longitudinal aerodynamic coef and derivative have normal sign according to
Thomas Yechout Book, P289
cd_u, cm_u, cl_u, X_wdot, cd_q, cd_eta are not tested beacause theire sign might vary according
to Thomas Yechout
Args:
... | f964a14892074b51ca61e227a879a4d07855dd05 | 38,605 |
def preset_t2s_flash_builtin():
"""
Preset to get built-in T2* maps from the FLASH sequence.
"""
new_opts = {
'types': ['T2S', 'T1w'],
'param_select': ['ProtocolName', '_series'],
'match': '.*T2Star_Images.*',
'dtype': 'float',
}
return new_opts | f6d99a75e6d5ab38948b8be5d02492f01c621eee | 38,606 |
from unittest.mock import call
def deterministic_key(seed, index):
"""
Derive deterministic keypair from seed based on index
:param seed: a securely generated hexadecimal seed of length 64
:type seed: str
:param index: number of permutations (check)
:type index: int
"""
action = 'det... | eba69b62df804d5ce7bb08a0e84aa2f36aa442bd | 38,607 |
import torch
def compute_bounds_from_intersect_points(rays_o, intersect_indices,
intersect_points):
"""Computes bounds from intersection points.
Note: Make sure that inputs are in the same coordiante frame.
Args:
rays_o: [R, 3] float tensor
inters... | c2692668531472008412c241c8a268a9334b17ad | 38,608 |
def choose_darktarget(data):
"""
nodata -> -1.0
dark target -> 0.0
"""
nodata = data[0][0][0]
ndvi = (data[1] - data[0]) / (data[1] + data[0])
cnt = 0 # count pixels to process
# mask -> 0.0
for idi, i in enumerate(data[5]):
for idj, j in enumerate(i):
#... | 063d6f48f6ee08503ba80b49b17dfd0c17ef7b44 | 38,609 |
def formatMinutes(m):
"""Format a number of minutes for human reading.
More or less follows Go-style convention of XhYm.
"""
hours, minutes = divmod(m, 60)
if hours:
return "%sh%sm" % (hours, minutes)
return "%sm" % (m,) | 21738f726dc510667de7f3dd2f0b88b7d283a74b | 38,610 |
def centerS(coor, maxS):
"""
Center vector coor in S axis.
:param coor: coordinate of vector from S center to M=0
:param maxS: value representing end of estatic axis
:return: S centered coordinate
"""
return int(maxS / 2.0 + coor) | d575ddece916889a614971e7c3e45ada12faac71 | 38,612 |
def write_tab(dframe):
"""Write tab-separated data with column names in the first row."""
return dframe | 4e1ce1127a68e359d4b53e824124ad726f6779b4 | 38,613 |
import torch
def mold_meta(meta):
""" flatten dict values """
out = []
for x in meta.values():
out.extend(x)
return torch.tensor(out) | 4d46ee520c92e75d5627826157eba24ba56856e0 | 38,614 |
def period_to_int(period):
"""
Convert time series' period from string representation to integer.
:param period: Int or Str, the number of observations per cycle: 1 or "annual" for yearly data, 4 or "quarterly"
for quarterly data, 7 or "daily" for daily data, 12 or "monthly" for monthly data, 24 or "hou... | c416acdaff008707bb1f5ad0143e984f4974d9c6 | 38,615 |
def formatter(format_string, kwargs):
"""
Default formatter used to format strings. Instead of `"{key}".format(**kwargs)`
use `formatter("{key}", kwargs)` which ensures that no errors are generated when
an user uses braces e.g. {}. Bear in mind that formatter consumes kwargs
which in turns replaces ... | 175a6279c8dca0276483b94ba2f6aed9215aefa5 | 38,616 |
def stations_by_river(stations):
"""
This map the rivers to their respective stations
"""
rivers_to_stations_dict = dict()
for station in stations:
if station.river in rivers_to_stations_dict:
rivers_to_stations_dict[station.river].append(station)
else:
rivers... | 926ee4099fb818410fce775dcf69292abbfbd03f | 38,617 |
def is_subdomain(a, b):
"""Returns True if a is equal to or a subdomain of b."""
if a is None or b is None or a == '' or b == '':
return False
if a == b:
return True
a_split = a.split('.')
a_split.reverse()
b_split = b.split('.')
b_split.reverse()
# b = evil.com [com,... | 1b7540731463cbc2ada056559ef743905ecc41de | 38,618 |
import subprocess
def CopyVASPIn(directory, origin=".", useCONTCAR=False):
"""Copy VASP input files from one directory to another.
Returns False if any files fail to copy."""
o = origin + "/"
if subprocess.check_call(["cp", o+"INCAR", directory]):
return False
elif subprocess.check_call(["cp", o+"POT... | d574e53a82a83fa0863aa9c64d8f3c67b7aaffc5 | 38,620 |
import sympy
def convolution(fx: str, gx: str):
"""卷积"""
t = sympy.symbols('t', real=True)
ft1 = fx.replace('x', 't')
gx_t1 = gx.replace('x', '(x-t)')
exec("ft2=" + ft1)
exec("gx_t2=" + gx_t1)
o1 = [None] # 必须用引用类型(比如列表),否则报错
exec("o1[0]=convolution1(ft2, gx_t2)")
return o1[0] | c09512d306c7f679e9869c0f204ddcd8ff5d3d1c | 38,621 |
def compute_flux_points_ul(quantity, quantity_errp):
"""Compute UL value for fermi flux points.
See https://arxiv.org/pdf/1501.02003.pdf (page 30)
"""
return 2 * quantity_errp + quantity | 63ddfcfe9a5c3837a27848ada5bd98a3a3c1dc12 | 38,622 |
def tree_attr_find(node, attr, attr_callable=False, find_first=True):
"""Walk urwid.TreeNode objects to parent searching for an attribute,
including node.
Args:
node: starting urwid.TreeNode.
attr: string attribute to search for.
attr_callable (optional): True to only match callable... | 7bbc0c44b633758f3df66efca4f39cc25bced911 | 38,623 |
def merge_pnslots(pns1, pns2):
"""
Takes two sets of pronoun slots and merges them such that the result is valid
for text that might follow text which resulted in either of the merged slot
sets.
"""
result = {}
for pn in pns1:
if pns1[pn][1] == pns2[pn][1]:
result[pn] = [max(pns1[pn][0], pns2[pn... | b2f9f43d0532c31aa407a8413565153cff836102 | 38,624 |
import json
def _getIdsFromSolrResponse(response_text, pids=[]):
"""
Helper to retrieve identifiers from the solr response
Args:
response_text: The solr response json text.
pids: A list of identifiers to which identifiers here are added
Returns: pids with any additional identifiers appended.
"""... | 22ec8840b47cc167c5217023b7c0368da146499a | 38,625 |
def setup_indicators(final_exam):
"""This function sets up the data needed to run plot_bl_indicators function.
Store the results of this functions in setup_indicators variable.
"""
ad_f = final_exam[(final_exam.DX == 'AD') & (final_exam.PTGENDER == 'Female')]
ad_m = final_exam[(final_exam.... | 6a601d90a201bd2a8f044e338fc6ff9aa19605f4 | 38,626 |
import math
def GrieFunc(vardim, x, bound):
"""
Griewangk function
wiki: https://en.wikipedia.org/wiki/Griewank_function
"""
s1 = 0.
s2 = 1.
for i in range(1, vardim + 1):
s1 = s1 + x[i - 1] ** 2
s2 = s2 * math.cos(x[i - 1] / math.sqrt(i))
y = (1. / 4000.) * s1 - s2 + 1... | a607f00aa44d55ba139cf4b766f334cccb9ffe11 | 38,627 |
import re
def get_cves_from_text(text):
"""
Extracts CVE from the input text.
:param text: text from which the CVEs are extracted
:return: extracted CVEs
"""
cve_pat = r'CVE-\d+-\d+'
return re.findall(cve_pat, text.upper()) | be97a73159cdc71d69db8504d91ea30d3a7d2d49 | 38,628 |
def sumof(nn):
"""
sum values from 1 to nn
"""
sum = 0
while nn > 0:
sum = sum + nn
nn -= 1
return sum | ac820306e8f50073e81b011702974c5b6f2517cd | 38,629 |
import os
import logging
def get_ephemeris_files():
"""Set the ephemeris files to use for the Earth and Sun.
This looks first for a configuration file `~/.pyfstat.conf`
giving individual earth/sun file paths like this:
```
earth_ephem = '/my/path/earth00-40-DE405.dat.gz'
sun_ephem = '/my/path... | f01605230ec546a216726cafcd6bc0d840f8ebd6 | 38,632 |
def _clean_listofcomponents(listofcomponents):
"""force it to be a list of tuples"""
def totuple(item):
"""return a tuple"""
if isinstance(item, (tuple, list)):
return item
else:
return (item, None)
return [totuple(item) for item in listofcomponents] | b8333fba3216b248a234ac124fb7d54a4bad09b1 | 38,633 |
def backend_echo(custom_backend, private_base_url):
"""Echo-api backend"""
return custom_backend("backend_echo", endpoint=private_base_url("echo_api")) | 643d45634be31382857ffc58cabfa9aba92858f9 | 38,634 |
import six
def get_strings(value):
"""
Getting tuple of available string values
(byte string and unicode string) for
given value
"""
if isinstance(value, six.text_type):
return value, value.encode('utf-8')
if isinstance(value, six.binary_type):
return value, value.decode('u... | 6517c5e2053d1facaf4282da720aaa91ca0ab2e7 | 38,635 |
def primes(n):
"""returns a list of primes in the range [2,n] computed via the sieve of
Erathosthenes. - pronounced civ (civ 5)"""
def sieve(lst):
if lst == []:
return []
return [lst[0]] + sieve(filter(lambda x: x % lst[0] != 0, lst[1:]))
return sieve(range(2, n + 1)) | 3178d9c1c6d0c561319177e0c03ff904bda9f6d3 | 38,637 |
def possible_bipartition(dislikes):
""" Will return True or False if the given graph
can be bipartitioned without neighboring nodes put
into the same partition.
Time Complexity: O(n*m) n dogs m how disliked they are?
Space Complexity: O(n)
"""
groups = [set(), set()]
not... | c1fa468b2e7cc743e8dbe37fc3b4c23ba16d9359 | 38,639 |
import argparse
def parse_command_line_args(args):
""" Parse command-line arguments and organize them into a single structured object. """
parser = argparse.ArgumentParser()
parser.add_argument(
'--agent',
type=str,
default="snn",
choices=['human', 'random', 'snn'],
... | a9f1a645f21d7b073ddbceaf7197cf668477cc69 | 38,640 |
import os
def get_free_space(path):
"""Get free space in path.
blocks = Size of filesystem in bytes.
bytes = Actual number of free bytes.
avail = Number of free bytes that ordinary users can use.
Returns tuple (blocks, bytes, bytes_avail)
"""
statvfs = os.statvfs(path)
return (sta... | 974b222674b82db224123fd6b0141307c9d6ac92 | 38,644 |
def enum_dict_keys(base, base_name=""):
"""dictのkeyを再帰的に列挙したリストを取得する
Args:
base (dict): 列挙するリスト
base_name (str, optional): 親の階層のkey.再起実行用. Defaults to "".
Returns:
list: dictのkeyのリスト
"""
key_list = []
for key in base.keys():
if base_name:
key_name = ... | 2105be34e680f8d05b6e8d505ea303e6cdcd023e | 38,645 |
def rotate_matrix(matrix):
"""
This solution works by working on the square matrix
from the outside in, switching one row with the row
to its right until a full circle is done, then proceeds
to do the same with its inner circle.
This solution runs in O(n^2).
"""
n = len(matrix)
... | 3a8186ac4ca3c83b1b2706260f50eca0f4a6062b | 38,646 |
from typing import Counter
def word_vocab_count(text):
"""
Counts the number of words and vocabulary in preprocessed text.
"""
counts = Counter([
word[0].lower()
for paragraph in text
for sentence in paragraph
for word in sentence
])
return sum(counts.values())... | b8e47ccc9a028a7d2fcc9ccabef6f833f0f9df34 | 38,648 |
def ensure_unicode(x, encoding='ascii'):
"""
Decode bytes to unicode if necessary.
Parameters
----------
obj : bytes or unicode
encoding : str, default "ascii"
Returns
-------
unicode
"""
if isinstance(x, bytes):
return x.decode(encoding)
return x | e37087eb0e2e17cd1b318cbe7bd997c3f3a1c0e2 | 38,649 |
def get_secondary_2_primaryTerm_dict_and_obsolete_terms_set(DAG):
"""
secondary terms consist of obsolete and alternative terms
primary terms are term.id and 'consider'
DOWNLOADS_DIR = r"/scratch/dblyon/agotool/data/PostgreSQL/downloads"
GO_basic_obo = os.path.join(DOWNLOADS_DIR, "go-basic.obo")
... | c55696b093d8f02251b5296f4ff1267b5efadc61 | 38,650 |
def mean(data):
"""
Get mean value of all list elements.
"""
return sum(data)/len(data) | 32884e9f1a29b2a37422ec1da04d0c59b6b67d3c | 38,651 |
from pathlib import Path
import pathlib
def notebook_path() -> Path:
"""Return path of example test notebook."""
notebook_path = pathlib.Path(__file__).parent / pathlib.Path(
"assets", "notebook.ipynb"
)
return notebook_path | a3c64350de0bdf680014a253fdbcb0e08ecd362a | 38,652 |
import multiprocessing
def detect_number_of_processors():
"""
Returns the number of available processors on the system.
:returns: The number of available processors on the current system.
"""
return multiprocessing.cpu_count() | 71ce62ba072e5d44c7e51cee53e1bb7250ff5c0b | 38,653 |
def ask_yes_no():
"""
gives the user a simple question with a yes/no answer, returns user's input
"""
answer = input().lower()
return answer | beef03afabb21061b2d8ea3acca35ec87f85dfad | 38,654 |
import math
def compute_idfs(documents):
"""
Given a dictionary of `documents` that maps names of documents to a list
of words, return a dictionary that maps words to their IDF values.
Any word that appears in at least one of the documents should be in the
resulting dictionary.
:param input: ... | a1b4c321233a246cc06270b622e945e3d5cb2268 | 38,655 |
def patch_grype_wrapper_singleton(monkeypatch, test_grype_wrapper_singleton):
"""
This fixture returns a parameterized callback that patches the calls to get a new grype wrapper singleton
at that path to instead return the clean, populated instance created by test_grype_wrapper_singleton.
"""
def _... | f95f45f80a8af1a71f1f8ee1ef55162b63ddc9af | 38,656 |
def bai_path(bamfilepath):
"""Return the path to BAI file in the same directory as BAM file."""
return f"{bamfilepath}.bai" | 16b642cb40d8c88cd08edba39fea758ec8a4be91 | 38,657 |
import os
import json
def get_rllib_config(path):
"""Return the data from the specified rllib configuration file."""
config_path = os.path.join(path, "params.json")
if not os.path.exists(config_path):
config_path = os.path.join(path, "../params.json")
if not os.path.exists(config_path):
... | e23ec364392706ce1719c1fc24f0dfef511e3111 | 38,658 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.