content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
async def agather(aiter):
"""Gather an async iterator into a list"""
lst = []
async for elem in aiter:
lst.append(elem)
return lst | 0a7f278d38237a722724572b6705deab429c8e70 | 698,407 |
from datetime import datetime
import pytz
def now():
"""Returns the ISO 8601 formatted time in UTC"""
return datetime.now(pytz.utc).isoformat() | e423e8555315f551f284c92f4fee5b3f92c1f41d | 698,408 |
def r_value(aa1, aa2, aa_dict, matrix):
"""
:param aa1:
:param aa2:
:param aa_dict:
:param matrix:
:return:
"""
return sum([(matrix[i][aa_dict[aa1]] - matrix[i][aa_dict[aa2]]) ** 2 for i in range(len(matrix))]) / len(matrix) | 034d1d7eb0baa63cd5bd4572c87f86bcc8774de4 | 698,409 |
def init(param_test):
"""
Initialize class: param_test
"""
# initialization
default_args = ['-t mt/label/ -w mt/warp_template2mt.nii.gz -gm mt/mt1_gmseg.nii.gz -wm mt/mt1_wmseg.nii.gz -manual-gm mt/mt1_gmseg_goldstandard.nii.gz -sc mt/mt1_seg.nii.gz -param step=1,type=seg,algo=centermassrot,metric=M... | cd0b7e61cabda521c0f07e72e74316e7766ea2d2 | 698,410 |
def calculateProgressMetrics(job):
"""
job has the most recent values updated for the current event being processed. Calculate status
and progress metrics using the new information.
:param job: JSON job data struture from dynamodb
"""
progressMetrics = {}
# BASE TIMES FROM EVENTS
# cr... | 73524e53f5dd77c81cd0e9f6239588e41b9bc841 | 698,411 |
def rescale_boxes(boxes, current_dim, original_shape):
""" Rescales bounding boxes to the original shape """
orig_h, orig_w = original_shape
# The amount of padding that was added
pad_x = max(orig_h - orig_w, 0) * (current_dim / max(original_shape))
pad_y = max(orig_w - orig_h, 0) * (current_dim / m... | 769264b54e0a2dc438d78942e4c86f46c1b6470e | 698,412 |
import socket
def tcp_socket_open(host, port):
"""
Returns True if there is an open TCP socket at the given host/port
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
try:
return sock.connect_ex((host, port)) == 0
except socket.timeout:
return... | 11519e5d9f2d1de39d8091af011f0458e556021c | 698,413 |
def variance(data):
""" Assumes that an array of integers is passed """
mean = sum(data)/len(data)
tot = 0.0
for d in data:
tot += (d - mean)**2
return tot/mean | 3329792cf7043ad6e68cad39d6a07bf2909d1496 | 698,414 |
from typing import Optional
from typing import List
import math
import random
def sample_from_range(range_max: int,
sample_ratio: float,
max_samples: int,
preselected: Optional[List[int]]) -> List[int]:
"""
Given a range of numbers in 0..range_... | 8be7b5ded3b6f3b54da57027a5d7629a9bf5dc9f | 698,415 |
def occ(s1,s2):
"""occ (s1, s2) - returns the number of times that s2 occurs in s1"""
count = 0
start = 0
while True:
search = s1.find(s2,start)
if search == -1:
break
else:
count +=1
start = search+1
return count | 4f107e5552d794e9e82a8a6b19ec63992034e9f7 | 698,416 |
import functools
import operator
def prod(x):
"""Equivalent of sum but with multiplication."""
# http://stackoverflow.com/a/595396/1088938
return functools.reduce(operator.mul, x, 1) | 31f4defa3401d6dcf05f8ec70c32650f000a1852 | 698,417 |
def indent(text, prefix=" "):
"""
Add a prefix to every line in a string.
"""
return "\n".join(prefix+line for line in text.splitlines()) | e83cc0b14c5b8c304f6e41bf145b06b1de451e8c | 698,418 |
def get_resblock(model, layer_name):
"""
model is a class resnet
e.g. layer_name is "layer1.0.relu2"
"""
obj_name, b_idx, act_name = layer_name.split(".")
b_idx = int(b_idx)
block = getattr(model, obj_name)[b_idx]
return block | a4ae6c65df336b3dd36b53e9dd348a76b4a47b89 | 698,419 |
def compute_rolling_mean(df, window=30):
"""Return rolling mean of given values, using specified window size."""
df['SMA_{}'.format(str(window))] = df['Price'].rolling(window=window, center=False).mean()
return df | 36048112a720e0bdd66d2dfeeac6fb5cab62fa46 | 698,420 |
def FindClientNode(mothership):
"""Search the mothership for the client node."""
nodes = mothership.Nodes()
assert len(nodes) == 2
if nodes[0].IsAppNode():
return nodes[0]
else:
assert nodes[1].IsAppNode()
return nodes[1] | 06ac3bcde5571ca425d47885ad5839f2aa32ca0d | 698,421 |
import textwrap
def to_flatimage(pathfile, to="(-3,0,0)", width=8, height=8, name="temp"):
"""
Adds a flat image to the canvas.
"""
text = rf"""
\node[canvas is xy plane at z=0] ({name}) at {to}{{
\includegraphics[width={width}cm,height={height}cm]{{{pathfile}}}
}};
"""... | 61906516d85ba3311506067ad4ec81b32786f1b9 | 698,422 |
def CalculateMSE(xs_, mu):
"""
计算均方误差
xs_: 所有样本均值
mu: 总体均值
"""
return sum([(x - mu) ** 2 for x in xs_]) / len(xs_) | 45e90b003e05d54fdfa13c82b1f1332d0e68082a | 698,423 |
def _get_primary_status(row):
"""Get package primary status."""
try:
return row.find('div', {'class': 'pack_h3'}).string
except AttributeError:
return None | 1df5b66e9e16e17b8c5f3fc019a587a4320cf6d0 | 698,424 |
def calc_n_g(df_schedule, week):
"""Calculate list of games i.e. Ng
Each row has home_id, away_id, home_total_points, away_total_points
:param df_schedule: data frame with each matchup
:param week: current matchup period id
:return: list of games with team ids and scores for home/away
"""
df_scores = (
... | 1029840d28617d5de60fa499e8e6a9ae40b4ddea | 698,425 |
def is_string(s):
"""
Portable function to answer whether a variable is a string.
Parameters
----------
s : object
An object that is potentially a string
Returns
-------
isstring : bool
A boolean decision on whether ``s`` is a string or not
"""
return isinstance... | ed59a1b3a80f6695c971c49ff3b7936aa048523f | 698,426 |
from os.path import dirname
def default_install_dir():
"""Return the default install directory. Assumes this file lives in
a 'site-packages' directory.
Returns
-------
:class:`str`
The path to the install directory.
"""
return dirname(dirname(dirname(dirname(dirname(__file__))))) | 238ec1d309f6697978ef97198cc21b205e2dd6cb | 698,427 |
def flatten_nested_list(list_in, drop_dupes=False):
"""Function to take a nested list and flatten into a 1d list."""
is_nested=True if type(list_in[0]) ==type(['v','d']) else False
if is_nested is True:
list_out=[];
if drop_dupes is True:
for list_i in list_in:
... | d3580ea22458ef794bdef280cec650f1521fda04 | 698,428 |
def computeIchimokuCloud(candleSet):
""" compute current values of Ichimoku Cloud lines """
conversionLine = (max([x["High"] for i,x in candleSet.iloc[-9:].iterrows()]) + min([y["Low"] for i,y in candleSet.iloc[-9:].iterrows()]))/2
baseLine = (max([x["High"] for i,x in candleSet.iloc[-26:].iterrows(... | 781df8f002a7fc3f5f7b3dd854a123bb3f21c142 | 698,429 |
def update_subfield_snippet(context,
code,
subfield,
value):
"""
Replaces a new value in a subfield snippet for a MARC field
:param context: Context
:param code: Field code
:param subfield: MARC subfield, if numeric... | 67ddf74faef5295028d27725534e05c888fba36a | 698,430 |
from typing import Any
from typing import Optional
def _strat_has_unitary_from_has_unitary(val: Any) -> Optional[bool]:
"""Attempts to infer a value's unitary-ness via its _has_unitary_ method."""
if hasattr(val, '_has_unitary_'):
result = val._has_unitary_()
if result is NotImplemented:
... | 96965cfec5f5c3c29ea641c95f20a2d4b1f3b859 | 698,431 |
import os
import tarfile
def dir_to_tar(src_path, dst_path, dst_name=None):
"""
将目录打包为tar.gz文件
:param src_path: 被打包目录
:param dst_path: tar文件存放目录
:param dst_name: tar文件名
:return: tar.gz生成路径
"""
if not os.path.exists(src_path):
return ""
if not dst_name or "" == dst_name:
... | 8b5c031a4e80e43a13ca97fd4ab93e4e72ba8f9c | 698,432 |
def write_keyvalue_toxlsx(worksheet, row, key, value):
"""Write a dictionary to excel sheet."""
if type(value).__name__ == 'dict':
worksheet.write(row, 0, key)
row += 1
for dictkey, dictvalue in value.items():
row = write_keyvalue_toxlsx(worksheet, row, dictkey, dictvalue)
... | c89111a35b182824664624c9b41358a15351f91d | 698,433 |
def BFS(map_dict, start, end, verbose):
"""
BFS algorithm to find the shortest path between the start and end points
on the map, following the map given by map_dict
If an invalid end location is given then it will return the longest possible
path and its length.
Returns the length of t... | f6770fe8cd5f6c4ebffce2a78992c76cfbb5bd31 | 698,434 |
from functools import reduce
def pipeline(source, functions):
"""Apply an array of functions to a source iterable"""
return reduce(lambda x, y: y(x), functions, source) | c79977ce46a6be15fc428530d94f8c4878a68ede | 698,435 |
import torch
def project_pose(x, camera=None, **kwargs):
"""
Args
x: 3xN points in world coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera translation parameters
f: 2 Camera focal length
c: 2x1 Camera center
k: 3x1 Camera radial distortion coefficients
... | f407828feb3caf9812e41a79da90c8486b096c89 | 698,437 |
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str:
"""Return the updated view based on whether the guess matches position in puzzle
>>> update_letter_view('apple', 'a^^le', 2, 'p')
p
>>> update_letter_view('banana', 'ba^a^a', 0, 'b')
b
>>> update_letter_view('bitt... | b7c534acdbc57c04e1f7ee6a83fc94ff2734948a | 698,438 |
def multiplex(*brules):
""" Multiplex many branching rules into one """
def multiplex_brl(expr):
seen = set([])
for brl in brules:
for nexpr in brl(expr):
if nexpr not in seen:
seen.add(nexpr)
yield nexpr
return multiplex_br... | 5245b4eb68a7ae00bc15f9b8071a225d33376781 | 698,439 |
def _remove_duplicates(items):
"""Return `items`, filtering any duplicate items.
Disussion: https://stackoverflow.com/a/7961390/4472195
NOTE: this requires Python 3.7+ in order to preserve order
Parameters
----------
items : list
[description]
Returns
-------
list
... | b44a16ed815e8cc09598fe2dc8e9871d45d0ae7e | 698,441 |
import re
def seqs_dic_count_lc_nts(seqs_dic):
"""
Count number of lowercase nucleotides in sequences stored in sequence
dictionary.
>>> seqs_dic = {'seq1': "gtACGTac", 'seq2': 'cgtACacg'}
>>> seqs_dic_count_lc_nts(seqs_dic)
10
>>> seqs_dic = {'seq1': "ACGT", 'seq2': 'ACGTAC'}
>>> seq... | 4542885f22e255fa0f3d14a9d4ef523fdf19f2e8 | 698,442 |
def get_coa_urls():
"""
Get CoA URLs for given samples or projects.
"""
# Get certificate data and return the short links.
return NotImplementedError | 7401fd862d982d15d0ddbed93ae00792291526a0 | 698,443 |
def gaussian_kernel(D,
sigma):
"""
Applies Gaussian kernel element-wise.
Computes exp(-d / (2 * (sigma ^ 2))) for each element d in D.
Parameters
----------
D: torch tensor
sigma: scalar
Gaussian kernel width.
Returns
----... | 22885ccb785893522e57861b82612989945cd5cf | 698,444 |
def trigger_event(connection, id, fields=None, error_msg=None):
"""Trigger an event.
Args:
connection(object): MicroStrategy connection object returned by
`connection.Connection()`.
id(str): ID of the event
error_msg (string, optional): Custom Error Message for Error Handlin... | 418994565cd20cac681575286553d4fa92cf89c9 | 698,445 |
import argparse
def _parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser()
#parser.add_argument("--gpus", type = int, default = 1)
#parser.add_argument("--precision", type = int, default = 16)
parser.add_argument("--progress_bar_refresh_rate", type = int, default = ... | e4f9735ad9e90b8b840f3786e6ac614da9cbe45c | 698,447 |
def best_score(a_dictionary):
"""Returns a key with the biggest integer value.
Checks if a thing is a dicrionary with the is instance method"""
if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0:
return None
ret = list(a_dictionary.keys())[0]
big = a_dictionary[ret]
for k, ... | e168c86e615539af525050ce400fa578cac603b9 | 698,448 |
def eratosthenes(n):
"""
This function is titled eratosthenes(n) because it uses the Eratosthenes Sieve to produce a list of prime
numbers. It takes in one positive integer arguement, the returns a list of all the primes less than the
given number.
Args:
n (int): User input
... | 7c0e0e89c1571dfc7a87883423a217ef36a984af | 698,449 |
def y_aver_bot(yw_mol, ypf_mol):
"""
Calculates the average mol concentration at bottom of column.
Parameters
----------
yw_mol : float
The mol concentration of waste, [kmol/kmol]
ypf_mol : float
The mol concentration of point of feed, [kmol/kmol]
Returns
-------
... | 21a438551cc7f6c3774999bafa30495dffd99201 | 698,450 |
def _convert_to_numpy_obj(numpy_dtype, obj):
"""Explicitly convert obj based on numpy type except for string type."""
return numpy_dtype(obj) if numpy_dtype is not object else str(obj) | 54a7bd1576ec95456d47e2e3957370c0970cb376 | 698,451 |
from datetime import datetime
def start_of_month(dt, d_years=0, d_months=0):
"""
Given a date, return a date first day of the month.
@param dt: The date to base the return value upon.
@param d_years: Specify a delta in years to apply to date.
@param d_months: Specify a delta in months to appl... | 90976e7df97b8581622df77528540487181cbb8f | 698,452 |
import os
import uuid
def make_job_data(url, script_fn):
"""Choose defaults.
Run in same directory as script_fn.
Base job_name on script_fn.
"""
wd = os.path.dirname(script_fn)
job_name = '{0}-{1}-{1}'.format(
os.path.basename(script_fn),
url.split("/")[-1],
... | 8dcc4e0064421964b4e2c717d2e8927cfebd15ff | 698,453 |
def frames(string):
"""Takes a comma separate list of frames/frame ranges, and returns a set containing those frames
Example: "2,3,4-7,10" => set([2,3,4,5,6,7,10])
"""
def decode_frames(string):
print('s', string)
if '-' in string:
a = string.split('-')
start, en... | a00a80bba4ab369a9682db6b62dad88911ecc711 | 698,454 |
def key_exists(dictionary, *keys):
"""Check if key exist in a nested dictionary.
:param dictionary: Nested dicionary
:type dictionary: dict
:param keys: Keys to test agains the dictionary
:type keys: args
:return: ``True`` if at least one key is in the dicionary
:rtype: bool
:raise KeyE... | 5bf414987e3bf25083cecdcff0af5c201561b15a | 698,455 |
import importlib
def class_from_module_path(module_path):
"""Given the module name and path of a class, tries to retrieve the class.
The loaded class can be used to instantiate new objects. """
# load the module, will raise ImportError if module cannot be loaded
if "." in module_path:
module... | e1b4935efd165c38c6394274c030c52eca5e241d | 698,456 |
import json
def monitor(plugin):
"""Monitors channels of this node."""
reply = {}
reply['num_connected'] = 0
reply['num_channels'] = 0
reply['format-hint'] = 'simple'
peers = plugin.rpc.listpeers()
info = plugin.rpc.getinfo()
nid = info["id"]
chans = {}
states = {}
for p in... | 22a3dd3f161f2c5adc91d7d869981bab0ae73450 | 698,458 |
def get_ocr_json_url_for_an_image(first_three_digits,
second_three_digits,
third_three_digits,
fourth_three_digits,
image_name):
"""
Get the URL of a JSON file given a barcode ... | 44c4d70971f24beee622ff2e11bef0474001aaa3 | 698,459 |
def cumulate_productivity(df, window=5):
"""Compute productivity over current and past 4 years."""
return (df.pivot(index="scopus_id", columns="t", values="SJR")
.fillna(0).rolling(window, min_periods=1, axis=1).sum()
.reset_index().melt(id_vars="scopus_id", value_name="SJR")) | 2330b39408136b4a0609f02c1174498c857085cb | 698,460 |
def tupleRemoveByIndex(initTuple, indexList):
"""
Remove the elements of given indices from a tuple.
Parameters
----------
initTuple : tuple of any
The given tuple from which we will remove elements.
indexList : list of ints
The indices of elements that we want to remove.
R... | 17009fc3616afa586467f43b1e7910a17c89ed0d | 698,461 |
import argparse
def prepare_arguments():
""" Define and return arguments. """
parser = argparse.ArgumentParser(description="PyTorch Energy Experiment v0_1")
# model training
parser.add_argument("--batch-size", type=int, default=64, metavar="N",
help="input batch size for traini... | 8019c31bf529b14178b63498d54f9ec6fde6ea4f | 698,462 |
def format_one_query(q, read_seq, read_coords, barcode_dict=None):
"""Formats output.
Parameters
----------
q : dict
A dictionary of fuzzy searching result. Key is levenshtein distance.
Value is list of matched barcodes.
read_seq : str
A DNA string (full length read).
re... | 2523ca6e15547a89e466fc4b4c9dad322fe91dbf | 698,463 |
import torch
def regression(src_bbox, loc):
"""
Apply regression, by applying the offset coefficient
Input:
srx_bbox [N, R, 4]: coordinates of bounding boxes in XYXY.REL format
loc [N, R, 4]: offset coefficient t_x, t_y, t_w, t_h in CxCyWH.REL format
Return:
dst_bbox[N, R, 4]: ... | 1d6137ecf1895fc92f63c37a510f2d0f3d68f54f | 698,464 |
def _filter3(meta, filter_peak=0.5):
"""
Filter peak based on the number of cells.
"""
meta = meta[(meta>0).sum(axis=1)>meta.shape[1]*filter_peak]
return meta.T | 06842b557422cd63589c63d96ce3b19853357844 | 698,465 |
from typing import Tuple
def create_categorical_encoder_and_decoder(categorical_variables: list[str]) -> Tuple[dict, dict]:
"""
Given a list of categorical variables, returns an encoder and decoder.
Encoder Key = category. Value = integer encoding.
Decoder Key = integer encoding. Value = category.
... | 70de5c8a3e1667da2776a3750c1fae1edf9fd8ae | 698,466 |
def update_dependencies(new_dependencies, existing_dependencies):
"""Update the source package's existing dependencies.
When a user passes additional dependencies from the command line,
these dependencies will be added to the source package's existing dependencies.
If the dependencies passed from the c... | 7f520c0c980cd0b929be32d9d4cceb8c99f75934 | 698,467 |
def read_brecon(infile, tree, stree):
"""
Reads branch reconciliation from file
"""
brecon = {}
for line in infile:
tokens = line.rstrip().split("\t")
# parse node
node_name = tokens[0]
if node_name.isdigit():
node_name = int(node_name)
node = t... | 366295c2196df5c45bae9d8a59d068814285b168 | 698,468 |
def _convert_to_int_list(check_codes):
"""Takes a comma-separated string or list of strings and converts to list of ints.
Args:
check_codes: comma-separated string or list of strings
Returns:
list: the check codes as a list of integers
Raises:
ValueError: if conversion fails
... | 965a68466d0aab358043cedb4838ac9d99ce3249 | 698,469 |
def get_note_freq(p):
"""
Return the frequency corresponding to a particular
note number
Parameters
----------
p: int
Note number, in halfsteps. 0 is a concert a
"""
return 440*2**(p/12) | cec12355f481494fa53fb0ed535ecd82fd038016 | 698,470 |
def stringify_parameters(items):
"""
Convert all items in list to string.
"""
return [str(item) for item in items] | 41a47f611d1514043eeac27de6c8be6c01607649 | 698,471 |
def get_current_spec_list(ctx):
"""
Get the current spec list, either from -p/--project-specs or --specs-to-include-in-project-generation or
specs_to_include_in_project_generation in user_settings.options
:param ctx: Current context
:return: The current spec list
"""
try:
return ctx.... | e0e2788b86bf005b6986ab84f507d784ef837cca | 698,472 |
import os
import subprocess
def create_pager(highlight_text=None):
""" Returns a pipe to PAGER or "less" """
pager_cmd = os.environ.get('PAGER')
if not pager_cmd:
pager_cmd = ['less', '-r']
if highlight_text:
pager_cmd.extend(['-p', highlight_text])
pager = subprocess.Pop... | 1fde7ecffd050122b2f9b41b5cf5e43b0e7e688c | 698,473 |
def title_from_name(name):
"""
Create a title from an attribute name.
"""
def _():
"""
Generator to convert parts of title
"""
try:
int(name)
yield 'Item #%s'% name
return
except ValueError:
pass
it = iter(n... | 44182a7aefc552701517292563717884835230aa | 698,474 |
def fill_empties(abstract):
"""Fill empty cells in the abstraction
The way the row patterns are constructed assumes that empty cells are
marked by the letter `C` as well. This function fill those in. The function
also removes duplicate occurrances of ``CC`` and replaces these with
``C``.
P... | cc27354fd50ac8588c8374e06025a2ceeff691c6 | 698,475 |
def normal_shock_density_ratio(M, gamma):
"""GIves the normal shock density ratio as a function of upstream Mach number."""
return ((gamma+1.0)*M**2.0)/(2.0+(gamma-1.0)*M**2.0) | 780e435602278f02d3a1839f460edf1ce40a5a5a | 698,476 |
def pretty_print(state):
""" Returns a 3x3 string matrix representing the given state. """
assert len(state) == 9
str_state = [str(i) for i in state]
lines = [' '.join(map(str, l)) for l in [state[:3], state[3:6], state[6:]]]
return '\n'.join(lines) | 67fb7b091e7256d1fa71f2936d3c8989d5a90f0e | 698,477 |
def I_props(D, B, TF, TW, ETABS=True):
"""Properties of an I-section
>>> I_props(12, 15, 3, 2)
{'P': 74, 'A': 90, 'Avy': 72, 'Avz': 30, 'Iyy': 2767.5, 'Izz': 858.0}
"""
A = B*D - (B-TW)*(D-2*TF)
Iyy = B*D**3/12 - (B-TW)*(D-2*TF)**3/12
Zyy = 2 * Iyy / D
Syy = B * TF * (D - TF) + 0.25 * TW... | c10d8c0e0bf65bfa17d4b29250d42db30466eccc | 698,478 |
from typing import List
from typing import Dict
from typing import Any
def expand_decks_list(
decks: List[Dict[str, Any]],
deck_info: Dict[str, Any],
) -> List[Dict[str, Any]]:
""" Given a list of decks and their cards,
fills in the missing information using the detailed decks specification
"""
... | 1a50f5c2ba461be54605cf7637d64a8257200494 | 698,479 |
import json
def decode_req_encode_rsp(f):
"""Decorator to decode incoming requests and encode responses."""
def decode_inner(req):
return json.dumps(f(json.loads(req)))
return decode_inner | ee41df3de3c41fbe2f32ddf4a07e769abfe31fda | 698,480 |
import re
def find_images(document):
"""Returns the list of image filepaths used by the `document`."""
images = []
for line in document:
match = re.match(r"\.\. image::\s+(img\/.+)", line)
if match:
images.append(match[1])
return list(set(images)) | 2c58b04974f5ec0d1752cb405cfd314de81a841c | 698,481 |
def extract_kwargs_from_ctx(ctx):
""" Extracts kwargs from Click context manager. """
args = []
i = 0
for arg in ctx.args:
if arg[:2] == '--':
args.append([arg[2:]])
i += 1
else:
args[(i-1)].append(arg)
for i, arg in enumerate(args):
if le... | 678a819daf33a26c599cea08817397741bfbef8a | 698,482 |
def load_config(cfgfile):
""" Parses a configuration file """
cfgf = open(cfgfile,'r')
cfg = {}
for l in cfgf:
ps = [p.strip() for p in l.split(':')]
if len(ps)==2:
try:
cfg[ps[0]] = float(ps[1])
except ValueError:
cfg[ps[0]] = ps[... | 283a36f1d92c58b0018fe62714cc9dc23f96c898 | 698,483 |
import os
def get_file_with_different_version_location(file_name):
"""
Gets file location
:param file_name: File name
:return : File location
"""
sample_app_dir = os.path.dirname(os.path.realpath(__file__))
return sample_app_dir + '\\Sample_Apps_2\\' + file_name | 8200ae91ddc2c3833a1975aec1ec4664e1149337 | 698,484 |
def rotate(A, turns=1):
"""A matrix which is formed by rotating the given matrix, n times, in clockwise sense.
Args
----
A (compulsory)
A matrix.
turns (int, optional)
The number of turns to rotate the matrix. Defaults to 1.
Returns
-------
Matrix
The matrix obt... | c6fb428c15317b314443101093ec96019be52bfa | 698,485 |
def determine_time_system(header: dict) -> str:
"""Determine which time system is used in an observation file."""
# Current implementation is quite inconsistent in terms what is put into
# header.
try:
file_type = header['RINEX VERSION / TYPE'][40]
except KeyError:
file_type = header... | 00a7908aa5eaf21eaaa39d97b23304644ebe27b4 | 698,486 |
def _all(oper, left, right):
"""Short circuit all for ndarray."""
return all(oper(ai, bi) for ai, bi in zip(left, right)) | fe982f59086d2aa688004f83f9c63c6ecf6919f4 | 698,487 |
def expand_header(row):
"""Parse the header information.
Args:
List[str]: sambamba BED header row
Returns:
dict: name/index combos for fields
"""
# figure out where the sambamba output begins
sambamba_start = row.index('readCount')
sambamba_end = row.index('sampleName')
... | 740790e5aa0f5415d3cb0fc22902403b16bef455 | 698,488 |
def cap_text(text):
"""
Capitalize first letter of a string
:param text: input string
:return: capitalized string
"""
return text.title() | 8403db85d37399db3b4b0693bc9e578ddcf01c3b | 698,489 |
def size_as_recurrence_map(size, sentinel=''):
"""
:return: dict, size as "recurrence" map. For example:
- size = no value, will return: {<sentinel>: None}
- size = simple int value of 5, will return: {<sentinel>: 5}
- size = timed interval(s), like "2@0 22 * * *:24@0 10 *... | 203bc0697cca9b3710f4079de03e759659116883 | 698,490 |
def get_field_kwargs(field_name, model_field):
"""
Creates a default instance of a basic non-relational field.
"""
kwargs = {}
return kwargs | d05d5f42a4ecc2669486d049918d271013a6969f | 698,491 |
import argparse
def parse_command_line_arguments():
""" Parse command line arguments.
:return: parsed arguments
"""
parser = argparse.ArgumentParser(description="Pure Python command-line RSS reader")
parser.add_argument(
"--version",
action="version",
version="Version 5.0... | b271785eb92ade63f0c103ac83f4e71910bd41cd | 698,492 |
import requests
import json
def get_mactable(auth):
"""
Function to get list of mac-addresses from Aruba OS switch
:param auth: AOSSAuth class object returned by pyarubaoss.auth
:return list of mac-addresses
:rtype list
"""
headers = {'cookie': auth.cookie}
url_mactable = "http://" + ... | 96c064696bf47872e5a1bec5e8770d6470b76bfc | 698,493 |
def es_primo(n: int) -> bool:
"""Determina si un número es primo.
:param n: número a evaluar.
:n type: int
:return: True si es primo, False en caso contrario.
:rtype: bool
"""
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int... | fff4802d6e47c379b6510f13e2ffe9a9d56429d2 | 698,494 |
def replace_string(string_value, replace_string, start, end):
"""
Replaces one string by another
:param string_value: str, string to replace
:param replace_string: str, string to replace with
:param start: int, string index to start replacing from
:param end: int, string index to end replacing
... | b79d685a13c427334149789195e5fbbb4a6ad28d | 698,495 |
import hashlib
def hash_str(data, hasher=None):
"""Checksum hash a string."""
hasher = hasher or hashlib.sha1()
hasher.update(data)
return hasher | 5dd433a3cc04037bb439b64b71d3495d03f51ef1 | 698,496 |
def get_next_point(df, inc, axis):
"""
Increment to get the next points along.
Parameters
----------
df : pandas DataFrame
The dataframe of points
inc : int
The amount to increment
axis : str
The axis along which to increment. Can be 'x', 'y', or 'z'
"""
df =... | 5b91f2f23f188891ff04ded3f4a76e6b552fa2a0 | 698,497 |
def load_input(filename):
"""
Load poker hands from filename
"""
hands = []
with open(filename) as f:
for line in f.readlines():
tokens = line.strip().split(" ")
cards = []
for token in tokens:
value = token[0]
suit = token[... | ba79c8163098be587729f788ce231c02204f77ce | 698,498 |
def _getresponse(self):
"""Monkey-patched replacement getresponse method"""
intercept = self._intercept()
if intercept['mode'] == 'normal':
response = self._orig_getresponse()
if 'recorder' in intercept:
intercept['recorder']._record_response(response)
# ... | 9131ac0aa03c841cb971456d7b04b1e942dd1e78 | 698,500 |
import functools
def synchronize(lock):
""" Decorator that invokes the lock acquire call before a function call and releases after """
def sync_func(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock.acquire()
res = func(*args, **kwargs)
lock.r... | e9ac48d67cf45e1b0cf9b6e776a93f569726b5d4 | 698,501 |
def help_invocation_for_command(prefix, command, locale):
"""
Get the help command invocation for a command.
Parameters
----------
prefix: str
The command prefix to show.
command: senko.Command
The command to get the help invocation for.
locale: senko.Locale
The loca... | abf80554c479e3f766e6a7dc1e7bbcafdbaa6098 | 698,502 |
import torch
def derivative_sigmoid(x):
"""Compute the derivative of the sigmoid for a given input.
Args:
x (torch.Tensor): The input.
Returns:
(torch.Tensor): The derivative at the input.
"""
return torch.mul(torch.sigmoid(x), 1. - torch.sigmoid(x)) | 00da3734436294bc8bb40189bc1298972fbe7f93 | 698,503 |
def loginUser(username, password): # noqa: E501
"""
# noqa: E501
:param username: The user name for login
:type username:
:param password: The password for login in clear text
:type password:
:rtype:
"""
return 'do some magic!' | 20466f242fd92ae09113e6fe3b2ef0c1b03b85b8 | 698,504 |
import os
def parse_folder_info(path):
"""
Function: get the foldres and files within a particular path.
Input: path
Output: lists of folders and files
"""
folders = [f for f in os.listdir(path) if not os.path.isfile(os.path.join(path, f))]
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(pa... | 0d486a315348cdb87d696f66b95b54961a5427c4 | 698,505 |
def generate_all_nbr_from_dataframe(dist_df, nbr_distance = 100.0):
"""
Given a distance matrix, return a list of index positions of all neighbors
within a certain distance.
Parameters
----------
dist_df : DataFrame
nbr_distanace : float
Returns
-------
all_nbrs : list
... | a735c25febbab446e28486174aa2d5ef3cb3d5d0 | 698,507 |
from pathlib import Path
async def check_node_modules():
"""Check if node_modules exists and has contents.
Returns:
{bool} -- True if exists and has contents.
"""
ui_path = Path(__file__).parent / "ui"
node_modules = ui_path / "node_modules"
exists = node_modules.exists()
valid ... | e76703372c46982cf728b26125808e50e2b92907 | 698,508 |
def _execute_c2(state, context):
"""REP: Reset status bits.
When used, it will set the bits specified by the 1 byte immediate
value. This is the only means of setting the M and X status
register bits.
"""
state.flags &= ~state.current_operand
return context, None | d9ae38f7b9c3c8caf14e578b29693417f04b8234 | 698,509 |
def rowcol_to_xy(rows, cols, raster):
"""non-uri version of rowcol_to_xy_uri"""
gt = raster.GetGeoTransform()
X = gt[0] + cols * gt[1] + rows * gt[2]
Y = gt[3] + cols * gt[4] + rows * gt[5]
return (X, Y) | 26ccf8da771387fffdcfc4d5b188aa562fd7be7e | 698,510 |
import sys
def memory_check(block_sizes, qlength_max, estimate_memory):
"""Return amount of memory required.
Estimate memory consumption exactly as CESAR2.0 doest it.
"""
num_states, rlength, extra = 0, 0, 100000
for block_size in block_sizes:
num_codons = block_size // 3
num_... | 8539fe72e864c7aedb8e7d9daf65876e78ef2fad | 698,511 |
def test_call_fuzz():
"""Fuzz some functions."""
return """
fn main() {
{dest} = takes_args(fuzz(), fuzz(), fuzz());
}
fn takes_args(a: u8, b: u1, c: u4) -> u4 {
write_value(&b, 10);
return a + b + c;
}
fn write_value(ptr: *u1, val: u1) {
*ptr = val;
}... | 4291bc625b51715c286ef61ce910fae0257c4852 | 698,512 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.