content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def timestamp_to_datetime(
timestamp: float,
tzinfo: timezone = timezone.utc,
) -> datetime:
"""
Convert a given UNIX timestamp to a Python datetime object.
Args:
timestamp: A UNIX timestamp (as a float).
tzinfo: A timezone object. Usually, everything should be in UTC.
Returns:... | 5,294,200 |
def _register_key_managers():
"""Registers all currently known key managers in the Python registry."""
for key_type_identifier in ('AesCtrHmacAeadKey', 'AesGcmKey', 'AesGcmSivKey',
'AesEaxKey', 'XChaCha20Poly1305Key', 'KmsAeadKey',
'KmsEnvelopeAeadKey',):... | 5,294,201 |
def read_list_from_file(
files_list_path: str = FILES_LIST_PATH,
files_list_filename: str = FILES_LIST_FILENAME,
) -> list:
""" Import list from file """
if os.path.exists(f"{files_list_path}/{files_list_filename}"):
try:
with open(f"{files_list_path}/{files_list_filename}", "r") as... | 5,294,202 |
def handle_get(key):
"""Return a tuple containing True if the key exists and the message
to send back to the client."""
try:
return_value = DATABASE_DICT[key]
operation_status = True
except KeyError:
operation_status = False
return_value = None
return (operation_statu... | 5,294,203 |
def preprocess_document(text):
"""Wrapper of the above."""
return create_tokens(lowercase_text(text)) | 5,294,204 |
def analizar_propuesta(propuesta, codigo):
"""Determina aciertos y coincidencias"""
aciertos = 0
coincidencias = 0
for i in range(DIGITOS):
if propuesta[i] == codigo[i]:
aciertos += 1
elif propuesta[i] in codigo:
coincidencias += 1
return aciertos,coincidencias | 5,294,205 |
def conditions_gen(conditions, safe=True):
""" Generate comma separated conditions.
Args:
conditions: An iterator that yields ConditionClause tuples.
Returns:
The string of the query.
"""
conditions_str = ''
connector = None
for index, condition in e... | 5,294,206 |
def as_type(val, types):
"""Try converting `val`to each of `types` in turn, returning the first one that succeeds."""
errs = []
for type in make_seq(types):
try:
return type(val)
except Exception as e:
errs.append(e)
pass
raise TypeError('Could not con... | 5,294,207 |
def cjson_parser(cjsonfile, trajfile=None):
"""Parse CJSON files
Parameters
----------
cjsonfile : str
Path to the CJSON file.
trajfile : str, optional
Name of trajectory file to be saved, by default None.
Returns
-------
atoms
A list of Atoms objects.
"""
... | 5,294,208 |
def get_version_from_module(content: str) -> str:
"""Get the __version__ value from a module."""
# adapted from setuptools/config.py
try:
module = ast.parse(content)
except SyntaxError as exc:
raise IOError(f'Unable to parse module: {exc}')
try:
return next(
ast.l... | 5,294,209 |
def tableHeaders():
"""
tableHeaders table model headers
Returns:
list: header definitions
"""
data = [
[
"jobID",
{
"Type": "int",
"CastFunction": int,
"Label": " " + _(Text.txt0131) + " ",
"A... | 5,294,210 |
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
From Django 2.2
"""
value = str(value... | 5,294,211 |
def cfg_to_algorithm(config_file):
""" Return instance of classification algorithm helper from config file
Args:
config_file (str): location of configuration file for algorithm
Returns:
tuple: scikit-learn estimator (object) and configuration file (dict)
Raises:
KeyError: rais... | 5,294,212 |
def _parse_instance_info(node):
"""Gets the instance specific Node deployment info.
This method validates whether the 'instance_info' property of the
supplied node contains the required or optional information properly
for this driver to deploy images to the node.
:param node: a target node of the... | 5,294,213 |
def get_pdf_form():
"""
1. Call the envelope get method
"""
# import pdb; pdb.set_trace()
args = {
"account_id": session["ds_account_id"],
"document_id": 1,
"envelope_id": session["envelope_id"],
"envelope_documents": session["envelope_documents"],
"... | 5,294,214 |
def log_change_in_bugzilla_mapping(sender, request, release, **kwargs):
"""
This handler is executed after a new release is saved or an existing
release is updated. It looks if there is saved old value for bugzilla
mapping and creates appropriate changelog entries.
"""
old_data = getattr(request... | 5,294,215 |
def read_parameters_start(config):
"""
Read info on starting parameter values. The distributions can be
'gauss', 'uniform', or 'log-uniform'.
"""
section = 'EMCEE starting'
parameters_to_fit = [var for var in config[section]]
starting = {}
for param in parameters_to_fit:
words = ... | 5,294,216 |
def list_third_party_asi_vulnerable_components_command(client_obj: Client, args: Dict[str, Any]) -> CommandResults:
"""
Retrieves the attack surface vulnerable component information of the given third-party account.
:param client_obj: client object which is used to get response from API
:param args: it... | 5,294,217 |
def get_lon(da, errors="raise"):
"""Get the longitude coordinate
Parameters
----------
da: xarray.DataArray
{errors}
Return
------
xarray.DataArray or None
See also
--------
get_lat
get_depth
get_altitude
get_level
get_vertical
get_time
xoa.cf.CFSpe... | 5,294,218 |
def bundle_media_description(key, filename):
"""Bundle the media description necessary for uploading.
:param key: form-data key name
:param filename: Local file name or path.
:return: tuple of ('key name', ('file name', 'file object', 'MIME content-type')
:rtype: tuple
"""
content_type, _ ... | 5,294,219 |
def _getColor(*color):
"""Analyzes the color arguments and returns a proper 4-float tuple or None"""
if len(color) == 1 and type(color[0]) == tuple:
# a tuple, i.e., a value of type color, was passed rather than in-line values:
# no transformation takes place
assert (len(color[0]) =... | 5,294,220 |
def load_csv_data(file_path):
"""
Load csv file asa numpy array
:param file_path: path to csv file
:return: numpy array
"""
dir_name = os.path.dirname(os.path.abspath(os.path.abspath(__file__)))
path = dir_name + file_path
data = np.loadtxt(path, dtype=np.float32, delimiter=',')
data... | 5,294,221 |
def test_quantization(tmpdir, observe: str, fuse: bool):
"""Parity test for quant model"""
seed_everything(42)
dm = RegressDataModule()
trainer_args = dict(
default_root_dir=tmpdir,
max_epochs=10,
gpus=1 if torch.cuda.is_available() else None,
)
model = RegressionModel()
... | 5,294,222 |
def await_flow(f: flow.Flow) -> None:
"""Awaits flow until timeout is exceeded.
Args:
f: Flow to await.
Returns:
Nothing.
Raises:
FlowTimeoutError: Timeout is exceeded while awaiting a flow.
"""
if _FLOW_TIMEOUT == 0:
raise errors.FlowTimeoutError(f.client_id, f.flow_id)
try:
timeou... | 5,294,223 |
def test_wf_st_7(plugin):
""" workflow with three tasks, third one connected to two previous tasks,
splitter and partial combiner on the workflow level
"""
wf = Workflow(name="wf_st_7", input_spec=["x", "y"])
wf.add(add2(name="add2x", x=wf.lzin.x))
wf.add(add2(name="add2y", x=wf.lzin.y))
... | 5,294,224 |
def discoverer(regex, path, level=0, metric: Metric = None):
""" Scout the current path and fire the 'regex' into files """
if is_directory(path):
recursive_level = params.get_recursive_level()
for current_path in get_listdir(path):
# Increment files metrics
if isfile(cu... | 5,294,225 |
def format_write_request(address, value):
""" Format a write request based on an address and the value to write to
the FPGA.
:param address: address at which to write date.
:param value: data to write to the address.
:return: formatted request.
"""
if address >= 2**(4 * 8):
raise Va... | 5,294,226 |
def get_prob(board, policy_val):
"""Return the probabilities of selecting the children of a node given the policy
and removing illegal moves"""
x = (board[:, :, 0] == board[:, :, 1]).reshape(225,) * policy_val
return x / np.sum(x) | 5,294,227 |
def get_actor_method_function_id(attr):
"""Get the function ID corresponding to an actor method.
Args:
attr (str): The attribute name of the method.
Returns:
Function ID corresponding to the method.
"""
function_id_hash = hashlib.sha1()
function_id_hash.update(attr.encode("ascii"))
function_id =... | 5,294,228 |
def tangent_basis_transposed(v):
"""
"""
return v[:,:-1,...] - v[:,-1:,...] | 5,294,229 |
def downloadMinuteBarBySymbol(vtSymbol, end):
"""下载某一合约的分钟线数据"""
end = datetime.datetime.strptime(end, '%Y%m%d')
startTime = time.time()
cl = db[vtSymbol]
cl.ensure_index([('datetime', ASCENDING)], unique=True)
symbol, exchange ... | 5,294,230 |
def process(im, fname, params=None):
"""Processes the given image in some way, and returns rendered HTML.
'im' is the uploaded Image.
'fname' is the path to the image.
'params' is an optional dict with other parameters.
To refer to the uploaded image in the HTML, use '/'+fname
"""
from PIL i... | 5,294,231 |
def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, Roughness=None, NumOutlets=None, *, PipeRough=None):
"""Return the total head loss through the manifold.
:param FlowRate: flow rate through manifold
:type FlowRate: u.m**3/u.s
:param Diam: diameter of manifold
:type Diam: u.m
:param Leng... | 5,294,232 |
def get_pending_jobs_info(max_slots_filter=None, skip_if_state=None, log_pending_jobs=True):
"""
Retrieve the list of pending jobs.
:param max_slots_filter: discard jobs that require a number of slots bigger than the given value
:param skip_if_state: discard jobs that are in the given state
:param ... | 5,294,233 |
def reduce_squeeze(m):
"""Reduce model by removing length=one dimensions."""
out = m.copy()
print('input model has shape:{}'.format(m.param_shape()))
keep = np.array(m.param_shape()) != 1
for k,p in zip(keep,m.parameters):
if not k:
del out.param_values[p]
out.parameters =... | 5,294,234 |
def recreate_phage(phage_row):
"""
Input: the list of prophages for a particular timepoint (i.e phage[-1], where phages is read in above)
Output: the same line formatted as a list of lists of integers
"""
phage_list = []
phages_string = phage_row.decode("utf-8").split('[')[2:]
for phage... | 5,294,235 |
def PrintHexEdid(e):
"""Print the entire EDID in hexadecimal form.
Args:
e: The EDID to be printed.
"""
PrintHexData(e.GetData()) | 5,294,236 |
def get_chan_nbrs(geom, nbr_dist=70, n_nbrs=7, keep_less_nbrs=False, chans_exclude=None):
"""Get the channels with n_nbrs neightbors within nbr_dist radius on the electrode array.
Returns an array of such channels and a mapping of each channel to its neighbors.
Have the option to keep chennels with less ... | 5,294,237 |
def test_latest_version(pkgs):
"""
Test basic usage of pkgng.latest_version
"""
pkgs_mock = MagicMock(side_effect=pkgs)
search_cmd = MagicMock(return_value="bash-5.1.4")
with patch("salt.modules.pkgng.list_pkgs", pkgs_mock):
with patch.dict(pkgng.__salt__, {"cmd.run": search_cmd}):
... | 5,294,238 |
def getHashes():
""" Returns an element with the given itemid
:param str i: ItemID of the element
:return: the returned object from Monogo less the mongo object ID
:rtype: dict or None
"""
collection = asdb["hashes"]
e = collection.find({}, {"_id": False, "hash": True})
return list(e) | 5,294,239 |
def generate_default_function(node, base_name, func_counter):
"""Generate a default function from the given node
"""
ft = onnx_optype_to_nnabla_function_type.get(node.op_type)
if ft is None:
raise ValueError(
"op_type {} is currently not supported for NNP conversion".format(node.op_t... | 5,294,240 |
def merge(abi_into, abi_from, filename=None):
"""
From the variables present in the file 'abi_into'
will try to recover the value from 'abi_from'
if the value has changed, the value will be updated.
The new variables will be save in the given filename
If filename==None the new values will overw... | 5,294,241 |
def unicycle_to_single_integrator(dxu, poses, projection_distance=0.05):
"""A function for converting from unicycle to single-integrator dynamics.
Utilizes a virtual point placed in front of the unicycle.
dxu: 2xN numpy array of unicycle control inputs
poses: 3xN numpy array of unicycle poses
proje... | 5,294,242 |
def iter_hist_buckets(hist):
"""Return buckets for a histogram as a generator
"""
for full_name, labels, value in hist.collect()[0].samples:
if full_name.endswith("_bucket"):
yield full_name, labels, value | 5,294,243 |
def show_progress():
"""
function that loops through the <progress_bars> array until done is set to True
"""
os.system(r'printf "The task is in progress, please wait a few seconds\n" ')
while not done:
for progress_bar in progress_bars:
os.system(r'printf "\r{} Processing..."... | 5,294,244 |
def lloyd_fix(T, Rref, E0):
""" Lloyd & Taylor (1994) Arrhenius type with T0=-46.02 degC and Tref=10 degC
T Temperature [k]
Rref Respiration at Tref=10 degC [umol(C) m-2 s-1]
E0 Activation energy [K]
"""
Tref = 283.15 # 10 [degC]
T0 = 227.13 # -46.02 [degC]
... | 5,294,245 |
def merge(left, right):
"""
Merges two linked list, sorting by data in nodes
Returns a new, merged list
Runs in linear time
"""
#Create new linked list that contains node from
#merging left and right
merged = LinkedList()
#Add fake head discarded later
... | 5,294,246 |
def safe_interval_insert(M_new, interval):
"""
Deal with interval overlaps when adding a new one to the list
"""
for i, (a, b) in enumerate(M_new):
# overlap found, construct the larger interval
if (b >= interval.lower_bound) and (a <= interval.upper_bound):
lb = m... | 5,294,247 |
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'):
"""
:param bboxes: (xmin, ymin, xmax, ymax, score, class)
Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf
https://github.com/bharatsingh430/soft-nms
"""
classes_in_img = list(set(bboxes[:, 5]))
best_bboxes = []
for cls... | 5,294,248 |
def create_envelope(payload: dict) -> dict:
"""
Creates a dictionary with event label, timestamp and message field
:param payload: The payload dict
:return: An event message dictionary
"""
payload['timestamp'] = datetime.utcnow().timestamp()
if 'event' not in payload:
payload['event... | 5,294,249 |
def ConsValue(t,ma,st,ra,ds,m,sol,par,idx,ad=0,ad_min=0):
""" interpolate consumption and value (ad and ad_min are only so the couple model can look up in this function) """
# a. unpack solution
ad_idx = ad+ad_min
D = transitions.d_plus(t+ad-1,ds,par) # t-1 so we get choice set today
ra_look ... | 5,294,250 |
def deregister():
"""
Remove pandas' formatters and converters.
Removes the custom converters added by :func:`register`. This
attempts to set the state of the registry back to the state before
pandas registered its own units. Converters for pandas' own types like
Timestamp and Period are remove... | 5,294,251 |
def decipher(ciphered_name: str, key: int) -> str:
"""Decipher the room name."""
return "".join(shift(char, key) for char in ciphered_name) | 5,294,252 |
def notify_accepted_request(req):
"""Notify event managers and request managers about a accepted request.
:param req: the :class:`Request`
"""
yield notify_event_managers(req, 'accepted_to_event_managers.txt')
yield notify_request_managers(req, 'accepted_to_request_managers.txt') | 5,294,253 |
def os_path_separators():
""" list path spearators of current OS """
seps = []
for sep in os.path.sep, os.path.altsep:
if sep:
seps.append(sep)
return seps | 5,294,254 |
def get_request(request_url: str, token: str) -> dict:
"""
Wrapper for HTTP GET requests.
"""
session = requests.Session()
# Define the maximum number of retries and the time between each one
retries = Retry(total=5, backoff_factor=0.1)
# Mount both HTTP and HTTPS protocols
session.mo... | 5,294,255 |
def catch_web_page_demo():
"""抓取网页"""
# 构造请求头,以浏览器的方式发起请求
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
response = requests.get('https://www.zhihu.com/explore', headers=headers)
# 用正则表达式匹配问题内容
pattern = ... | 5,294,256 |
def tensor_to_local(tensor):
""" to local """
tensor = tensor.to_consistent(sbp=flow.sbp.broadcast).to_local()
return tensor | 5,294,257 |
def proceed(request):
"""
This is a fake "Terms" view that we overlay the login.
We link here from the Developer Hub landing page.
"""
if request.user.is_authenticated():
return submit(request)
agreement_form = forms.DevAgreementForm({'read_dev_agreement': True},
... | 5,294,258 |
def test_chain_method(qtbot, attr, dayu_type):
"""Test MPushButton class methods."""
widget = MPushButton()
if attr:
getattr(widget, attr)()
# widget.set_dayu_type(dayu_type)
qtbot.addWidget(widget)
assert widget.property('dayu_type') == dayu_type
assert widget.property('dayu_size') ... | 5,294,259 |
def angle(v1, v2):
"""Angular separation between two vectors."""
dot = vdot(hat(v1), hat(v2))
if np.ndim(dot) == 0 and dot > 1:
return 0
if np.ndim(dot) > 0:
dot[dot > 1] = 1
return np.degrees(np.arccos(dot)) | 5,294,260 |
def flex_convolution(features,
position,
neighborhood,
theta,
bias,
name=None):
"""Flex-Convolution computation.
Computes a convolution over arbitrary neighborhoods with elements of
arbitrary positions:
... | 5,294,261 |
def collect_factories(rootpath):
"""
Will collect (recursively) and return all factories found under given root path
"""
factories_collected = {} # <factory name> : <factory class>
factory_files = glob.glob(f"{rootpath}/**/factories.py", recursive=True)
for factory_file in factory_files:
... | 5,294,262 |
def test_searchparam_type_reference_literal(store: FHIRStore, index_resources):
"""Handle reference search parameters (Reference or canonical)"""
# [parameter]=[id] the logical [id] of a resource using
# a local reference (i.e. a relative reference)
result = store.search("Observation", query_string="su... | 5,294,263 |
def extract( # pylint: disable=too-many-locals, too-many-branches, too-many-statements
pdf_path: str,
pages: Optional[List[int]],
smart_page_crop: bool,
save_figures: bool,
figure_dir: Optional[str],
no_chapters: bool,
no_paragraphs: bool,
no_tables: bool,
no_figures: bool,
over... | 5,294,264 |
def serve(host='localhost', port=DEFAULT_PORT, abcs=None):
"""
start TexnoMagic TCP server and serve forever
"""
logging.info("START TexnoMagic TCP server %s on %s:%s ..." % (__version__, host, port))
if not abcs:
abcs = TexnoMagicAlphabets()
abcs.load()
with socketserver.TCPSer... | 5,294,265 |
def screen_clear():
"""Clears the terminal output and shows the game logo"""
os.system('cls')
print(logo) | 5,294,266 |
def _get_hop_2_neighbours(graph, input_list: list, hop_n: int) -> list:
"""
Find hop_n neighbours of each item in input_list
:param graph: NetworkX graph object
:param input_list: Input list
:param hop_n: Hop hop_n
:return: hop_n hop neighbours of the input list's items
"""
full_list = ... | 5,294,267 |
def crawl_news_job(update: telegram.Update, context: telegram.ext.CallbackContext):
""" Send notification to user """
update.message.reply_text('Activate News Job', reply_markup=markup2)
context.job_queue.run_repeating(crawl_news, interval=300, first=0) | 5,294,268 |
def test_attach_data_in_parametrized_fixture(attach_data_in_parametrized_fixture):
"""
>>> allure_report = getfixture('allure_report')
>>> for param in PARAMS:
... assert_that(allure_report,
... has_test_case('test_attach_data_in_parametrized_fixture[{param}]'.format(param=param)... | 5,294,269 |
def create_worker(host='localhost', port=4730, loop=None):
"""XXX
:param host:
:param port:
:param loop:
:return:
"""
loop = loop or asyncio.get_event_loop()
conn = yield from create_connection(host=host, port=port, loop=loop)
return GearmanWorker(conn) | 5,294,270 |
def prepare_template_data(fill_pairs):
"""
Prepares formatted data for filling template.
It produces mutliple variants of keys (key, Key, KEY) to control
format of filled template.
Args:
fill_pairs (iterable) of tuples (key, value)
Returns:
(dict)
... | 5,294,271 |
def make_movie(list_images, out_path, out_fname):
"""
:param list_images:
:param out_path:
:param out_fname:
:return:
"""
util.make_dir_if_missing(out_path)
convert_cmd = 'convert -delay 50 -loop 1 '+' '.join(list_images) + ' ' + out_path + os.sep + out_fname
subprocess.call(convert... | 5,294,272 |
def get_tokens():
"""
Returns a tuple of tokens in the format {{site/property}} that will be used
to build the dictionary passed into execute
"""
return (SECURITY_ENABLED_KEY, KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY, HIVE_PRINCIPAL_KEY, HIVE_PRINCIPAL_KEYTAB_KEY,
HIVE_USER_KEY, STACK_ROOT, LLAP_APP_NAM... | 5,294,273 |
def largest_cc(mask):
""" Return the largest connected component of a 3D mask array.
Parameters
-----------
mask: 3D boolean array
3D array indicating a mask.
Returns
--------
mask: 3D boolean array
3D array indicating a mask, with only one connected component.
"""
... | 5,294,274 |
def _expand_to(
a: tp.Union[np.number, np.ndarray, Variable],
ndim_or_shape: tp.Union[int, tp.Tuple[int, ...]],
axis: tp.Union[None, int, tp.Tuple[int, ...]] = None,
keepdims: bool = False,
) -> tp.Union[np.ndarray, Variable]:
"""Return expanded array.
Parameters
----------
a : tp.Tuple... | 5,294,275 |
def generate(env):
"""
Add Builders and construction variables for CUDA compilers to an Environment.
"""
if not cuda_exists(env):
print('Failed to build NVCC tool')
generate_dummy(env)
return
# create a builder that makes PTX files from .cu files
ptx_builder = SCons.Builder.Builder(action = '$... | 5,294,276 |
def get_feedback_average(action):
"""returns the average feedback rating for the given action."""
return ActionFeedback.objects.filter(
action=action).aggregate(avg=Avg('rating'))['avg']
#query_set = get_action_feedback(action)
#total = 0
#for i in xrange(1, 6):
# total += query_set.... | 5,294,277 |
def display_method_to_choose_etfs(selected_method_choose_dates, all_etfs, etf_data, sl_obj):
"""
Generates various streamlit options for selecting which ETFs to display.
Parameters
----------
selected_method_choose_dates : list of str
Strings of the various methods of selecting ETFs.
al... | 5,294,278 |
def example_task():
"""Example celery task."""
pass | 5,294,279 |
def genRoadMask(img_path, out_dir, model_path, is_directory = False):
"""Given an input image and model, generate and save the Road Mask image to the out_dir"""
model = _get_model(model_path)
if is_directory:
filelist = _image_file_list(img_path)
output_filelist = _out_file_list(filelist, img_path, out_dir)
x... | 5,294,280 |
def test_simple_imputer_real_data_default_args(test_dir, data_frame):
"""
Tests SimpleImputer with default options
"""
feature_col = "string_feature"
label_col = "label"
n_samples = 2000
num_labels = 3
seq_len = 100
vocab_size = int(2 ** 15)
# generate some random data
ran... | 5,294,281 |
def find_asset_for_pathrow(sqlite_path, **kwargs):
"""Find asset from database for pathrow
The querying is done inside a loop, so that if the query returns no results,
it can be repeated with relaxed parameters.
Args:
- sqlite_path: Path to sqlite database
- kwargs: Arguments passed to... | 5,294,282 |
def cband():
"""Pre-define idealized critical band filter bank.
:return: idealized critical band filter bank
"""
return np.array(
[
0,
100,
200,
300,
400,
510,
630,
770,
920,
... | 5,294,283 |
def write_configs(configs, telegraf_conf_dir, telegraf_d_conf_dir):
"""
Write the telegraf config created by config parser method to disk at the telegraf config location
:param configs: Telegraf config data parsed by the parse_config method above
:param telegraf_conf_dir: Path where the telegraf.conf is... | 5,294,284 |
def get_power_spectrum(array):
"""Calculate DFT and power spectrum from the given array.
:param array: a 2D array
:return: DFT array and the power spectrum
"""
fourier = np.fft.fft(array)
power = abs(fourier)**2
return fourier, power | 5,294,285 |
def compute_intensity_features(im_label, im_intensity,
num_hist_bins=10, rprops=None):
"""
Calculates intensity features from an intensity image.
Parameters
----------
im_label : array_like
A labeled mask image wherein intensity of a pixel is the ID of the
... | 5,294,286 |
def readFileLines(filepath: Path, f: Callable[[str], Any] = str) -> list:
"""Reads the lines in a file
Args:
filepath (Path): The path of the file to be read.
f (Callable[[str], Any], optional): Transformation for the lines. Defaults to `str`.
Returns:
list: list with the lines, with the defin... | 5,294,287 |
def get_default(arr, idx, default_value):
"""get arr[idx] or return default_value
"""
try:
return arr[idx]
except IndexError:
return default_value | 5,294,288 |
def task_complete_notify(result, task_id):
""" Notifies consumers that a task has been completed """
logging.debug('Task result is: %r', result)
logging.critical('Sending complete notification for id: %s', task_id)
msg = json.dumps({'task_id': task_id})
if mq_send_once(TASK_EVENTS, TASK_ROUTING_KEY,... | 5,294,289 |
def get_nag_version(conf, fc):
"""Get the NAG compiler version"""
version_re = re.compile(r"^NAG Fortran Compiler *Release *(?P<major>\d*)\.(?P<minor>\d*)", re.M).search
cmd = fc + ['-v']
out, err = fc_config.getoutput(conf,cmd,stdin=False)
if out:
match = version_re(out)
if not match:
match = version_re(... | 5,294,290 |
def add_namespace(conf, ns_dict, ns_hash):
"""Add options from a kind to an already existing config"""
for group_name, group in six.iteritems(ns_dict):
try:
title = group['object'].get('title', None)
help_msg = group['object'].get('help', None)
except AttributeError:
... | 5,294,291 |
def chat_words_conversion(text):
"""
converts common chat acronyms into it's fully spelled out phrase
"""
new_text = []
for w in text.split():
if w.upper() in chat_words_list:
new_text.append(chat_words_map_dict[w.upper()])
else:
new_text.append(w)
retur... | 5,294,292 |
def select(comps):
"""
Create the select composite action, execute it and push it onto the
undo queue.
"""
action = Composite([
Deselect(get_base().selection.comps),
Select(comps)
])
get_base().action_manager.push(action)
action()
get_base().doc.on_refresh(comps) | 5,294,293 |
def second(xs):
"""
Returns the second element of a list, or None if the list is empty
"""
if not xs:
return None
return xs[1] | 5,294,294 |
def p_numero(p):
"""numero : NUM_INTEIRO
| NUM_PONTO_FLUTUANTE
| NUM_NOTACAO_CIENTIFICA
"""
pai = MyNode(name='numero', type='NUMERO')
p[0] = pai
if str(p[1]).find('.') == -1:
aux = MyNode(name='NUM_INTEIRO', type='NUM_INTEIRO', parent=pai)
aux_val =... | 5,294,295 |
def get_disuser_message(usr):
"""Get message to display when disusered user tries to log in."""
file = os.path.join(rbconfig.dir_daft, usr.uid)
editor = os.environ.get('EDITOR', os.environ.get('VISUAL', 'vi'))
while 1:
if not os.path.isfile(file):
fd = open(file, "w")
f... | 5,294,296 |
def change_location(df: pd.DataFrame, orig_index: int, tokens_orig: list):
"""
Change location in sentence if one exists and if location is in CheckList's location lookup json
:param df: DataFrame containing sentences
:param orig_index: integer indicating the column index of the original sentence
:... | 5,294,297 |
def get_logger(module: str, file: str) -> logging.Logger:
"""Configure a file logger for use in a script.
Parameters
----------
module : str
The name of the module from which the logger is called
file : str
The name of the log file to which the logger will write
Returns
--... | 5,294,298 |
def filled_grasp_grid(empty_grasp_grid, grid_file):
"""Return a GraspGrid instance filled from the grid_file."""
empty_grasp_grid.read(grid_file)
grid_file.close()
return empty_grasp_grid | 5,294,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.