content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def search_zipfile(zip_name, name_re, check_hash, master_hash):
"""
Returns a list of matched items
Required:
zip_name (arg): ZIP-like object path
name_Re (arg): Regex to match
check_hash (arg): A Boolean to check for file hashes
mster_hash (arg): The hash to check further f... | 74,600 |
def calculateOobeInterference(grants_cbsds_oobe_info, fss_point, fss_info):
"""Calculates the OOBE interference value (MCBSDi,ch + GCBSDi + PLinvi + GFSSi).
The interference values are calculated based on the grant with the highest
highFrequency value, and added back into the grant object under key:
'oobe_i... | 74,601 |
def repl_add(name: str, old: str, new: str):
"""
if the string old is in the string name, it is removed, and the string new
is added at the end of the string name
the updated string is returned
"""
if old in name:
name = name.replace(old, '')
name = name + new
return name | 74,602 |
def test_show_hist_large():
"""
This test only verifies that code up to the point of plotting with
matplotlib works correctly. Tests do not exercise matplotlib.
"""
matplotlib = pytest.importorskip('matplotlib')
try:
rand_arr = np.random.randn(10, 718, 791)
show_hist(rand_arr)
... | 74,603 |
def stack_analysis_check_companion_packages(context):
"""Check that the analyze packages and companion packages has no common item(s)."""
json_data = get_json_data(context)
# those two lists should have no element in common
analyzed_packages = get_analyzed_packages(json_data)
companion_packages = g... | 74,604 |
def RenderPassStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 74,605 |
def create_lab2d_settings(ascii_map: str,
num_players: int) -> Dict[str, Any]:
"""Returns the lab2d settings."""
ascii_map = ASCII_MAPS[ascii_map]
game_objects = create_game_objects(ascii_map)
extra_game_objects = create_avatar_objects(num_players)
game_objects += extra_game_objects
... | 74,606 |
def load2():
""" Route to return the posts """
time.sleep(0.2)
if request.args:
counter = int(request.args.get("c"))
if counter == 0:
print(f"Returning posts 0 to {quantity}")
res = make_response(jsonify(db3[0: quantity]), 200)
elif counte... | 74,607 |
def adapt_names(odds, site, sport, competition):
"""
Uniformisation des noms d'équipe/joueur d'un site donné conformément aux noms disponibles sur
comparateur-de-cotes.fr. Par exemple, le match "OM - PSG" devient "Marseille - Paris SG"
"""
new_dict = {}
id_competition = get_competition_id(compet... | 74,608 |
def sequence_generator(maps,edges):
"""
Calls the function to generate a sequence.
Parameters
----------
maps : dict
key: node [int]
value: state [float]
edges : list
A list of tuples where each tuple represents an edge connection between two nodes, e.g., (2,10)
Returns
-------
[str]
A... | 74,609 |
def calc_radial_distribution(arr):
"""
Calculate 1D-radially averaged distrubution profile
from 2D-PNBD diffraction pattern.
Parameters
----------
arr : 2D-numpy array
The numpy array which contains the 2D-PNBD pattern.
Returns
-------
radial_distance, intensity... | 74,610 |
def evaluate_epoch(
eval_fn: Callable,
data_loader: DataLoader,
use_cuda: bool = False,
) -> float:
"""
Go through a dataset and return the total loss
:param eval_fn: typically either SVI.step (for training)
or SVI.evaluate_loss (for testing)
:param data_loader: the data... | 74,611 |
def get_drift(x: int) -> int:
"""Returns an int if not zero, otherwise defaults to one."""
return int(x) if isinstance(x, int) and x != 0 else 1 | 74,612 |
def train(train_loader,
model,
criterion,
optimizer,
scheduler,
args):
"""Train the model.
Args:
train_loader (DataLoader): The training data loader.
model (CNNs): The model.
criterion (Loss): The loss function.
optimizer (Optimi... | 74,613 |
def get_hd_used_space():
"""
get_hd_used_space()
Returns the amount of space used on the machine (float)
"""
capacity = float(get_hd_capacity())
available = float(get_free_hd_space("gigabytes"))
return capacity - available | 74,614 |
def i_am_the_spooler():
"""I am the spooler.""" | 74,615 |
def create_project(projectname):
"""
Create a new project on the specified storage
Returns a json object
"""
auth_id = request.get_json().get("auth_id")
storage_accesses = request.get_json().get("storage_accesses", [])
response = jsonify(
admin.create_project(current_session, project... | 74,616 |
def get_feature_size_per_file(f_name):
"""
Return the dimensionality of the features in a given file.
Typically, this will be the number of bins in a T-F representation
"""
shape = get_shape(os.path.join(f_name.replace('.data', '.shape')))
return shape[1] | 74,617 |
def test_join():
"""
`Join` makers should return a the value of one or more items (python strings
or makers) joined together.
"""
# Configured with a list of python strings
maker = text_makers.Join(['foo', 'bar', 'zee'])
# Check the assembled result
assembled = maker._assemble()
as... | 74,618 |
def load_settings (filename):
"""Load the settings file"""
settings = {}
data_reader = csv.reader(open(filename, 'rU'), delimiter='\t')
# Ignore header
header = next(data_reader)
# Process each line
for row in data_reader:
if len(row) == len(header):
sample = row[0]
sample_data = {}
for el_idx, el in ... | 74,619 |
def gen_program(min_size, max_size):
"""gen_program generates a random program."""
size = random.randrange(min_size, max_size)
prog = []
for _ in range(size):
# Randomly pick if we add a program symbol or random word.
if random.choice([True, False]):
prog.append(random.choice... | 74,620 |
def _get_sort_function(camera: Camera):
"""Given a scene object, get a function to sort wobject-tuples"""
def sort_func(wobject_tuple: WorldObject):
wobject = wobject_tuple[0]
z = (
Vector3()
.set_from_matrix_position(wobject.matrix_world)
.apply_matrix4(proj... | 74,621 |
def test_notify_messagebird_plugin(mock_post):
"""
API: NotifyMessageBird() Extra Checks
"""
# Disable Throttling to speed testing
plugins.NotifyBase.request_rate_per_sec = 0
# Prepare our response
response = requests.Request()
response.status_code = requests.codes.ok
# Prepare Mo... | 74,622 |
def run_benchmark(exe_filepath, n_repeats=1, csv_out_file=None):
"""
Runs a benchmark
:param exe_filepath: path to the benchmark executable
:param n_repeats: how many times to repeat each benchmark
:param csv_out_file: path to csv fle to store benchmark results into
"""
command = [exe_filepa... | 74,623 |
def check_aws_libs() -> bool:
"""Check Imports for AWS libs"""
libs = ["boto3", "botocore"]
return check_import_libs(libs) | 74,624 |
def run_platform_imputation(
mt: hl.MatrixTable,
plat_min_cluster_size: int,
plat_min_sample_size: int,
plat_assignment_pcs: int,
) -> hl.Table:
"""
Run PCA using sample callrate across gnomAD's evaluation interval and create Hail Table
with platform PCs and assigned platform.
:param Mat... | 74,625 |
def main():
"""An undefined CLI"""
pass | 74,626 |
def main():
"""TODO..."""
# PARSE OPTIONS ###########################################################
parser = argparse.ArgumentParser(description="Make statistics on results files (JSON files).")
parser.add_argument("fileargs", nargs=1, metavar="FILE",
help="The JSON file to ... | 74,627 |
def main():
"""Main"""
lines = get_challenge()
grid = draw_grid(lines)
print("A: {}".format(solve_a(grid)))
print("B: {}".format(solve_b(grid))) | 74,628 |
def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None,
full_output=0, disp=1, retall=0, callback=None, initial_simplex=None):
"""
Minimize a function using the downhill simplex algorithm.
This algorithm only uses function values, not derivatives or second
derivatives.
... | 74,629 |
def train(args, device, train_loader, net, writer, test_loader, summary,
val_loader):
"""
Train the given network on the given training dataset with DTP.
Args:
args (Namespace): The command-line arguments.
device: The PyTorch device to be used
train_loader (torch.uti... | 74,630 |
async def test_user_flow_show_form(hass):
"""Test user step form."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={CONF_SOURCE: SOURCE_USER},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user" | 74,631 |
def draw_fps(pil_image, fps_only_network):
"""Draw FPS information to image object.
Args:
pil_image (PIL.Image.Image): Image object to be draw FPS.
fps_only_network (float): FPS of network only (not pre/post process).
Returns:
"""
font_size = 14
PIL.ImageDraw.Draw(pil_image).t... | 74,632 |
def validate_endpoint_put(request: Request) -> str:
"""Ensure that the given endpoint is valid. If not raise a 405."""
endpoint = validate_endpoint_get(request)
if endpoint not in request.app["put_endpoints"]:
logging.info("Failed to put %s", endpoint)
raise web.HTTPMethodNotAllowed(method... | 74,633 |
def get_sat_pos_vel_acc(t, eph):
"""Calculate positions, velocities, and accelerations of satellites.
Accepts arrays for t / eph, i.e., can calculate multiple points in time
/ multiple satellites at once.
Does not interpolate GLONASS.
Implemented according to
Thompson, Blair F., et al. “Compu... | 74,634 |
def main():
"""[summary]
"""
assets = toml.load("assets.toml", _dict=dict)
for key in assets.keys():
if key != "title":
assets_name = assets[key]["name"]
tickers = assets[key]["tickers"]
data_price,data = get_yahoo_data(tickers=tickers)
plot_... | 74,635 |
def git_version() -> str:
"""Get the current git head sha1."""
# Determine if we're at master
try:
out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"])
git_revision = out.strip().decode("ascii")
except OSError:
git_revision = "Unknown"
return git_revision | 74,636 |
def create_gScore(self):
"""Creates and returns a data structure that holds the cost of getting from the start node to that node, for each node.
The cost of going from start to start is zero."""
# TODO: a data structure that holds the cost of getting from the start node to that node, for each node.
# f... | 74,637 |
def _parse_seconds_fraction(frac: str) -> int:
""" Parse the fraction part of a timestamp seconds, using maximum 9 digits
Returns the nanoseconds
"""
ns = 0
mult = MAX_NANOSEC
for c in frac:
if c < '0' or c > '9' or int(mult) < 1:
break
mult = mult // 10
ns +=... | 74,638 |
def create_default_data_file(fname='datafile'):
"""Creates datafile initialized with 5 lines of zeros."""
create_file(fname, ['0','0','0','0','0']) | 74,639 |
def test_ignores_letter_versions():
"""Ignore letters such as 1.8b.
See ticket https://github.com/tony/tmuxp/issues/55.
In version 0.1.7 this is adjusted to use LooseVersion, in order to
allow letters.
"""
result = has_minimum_version('1.9a')
assert result
result = has_minimum_versio... | 74,640 |
def test_increment_as_decorator():
"""We test that the `ProgressExt.report` function works as a context manager
- Click the button multiple times and check that the progress is reset every 2 clicks
"""
progress = ProgressExt()
run_button = pn.widgets.Button(name="Click me")
@progress.i... | 74,641 |
def project_post_save(sender, instance, created, **kwargs):
"""
Automatically assigns all permissions to the owner. If the owner changes
it's up to the user/developer to remove the previous owner's permissions.
"""
for perm in get_perms_for_model(sender).all():
assign_perm(perm.codename, ins... | 74,642 |
def link_filtered_DLC_predictions(nwb_file,video_dir): # add the DLC files (need code/write code)
""" Function to link filtered DLC predictions to a NWB file"""
return nwb_file | 74,643 |
def read_data(f_name):
"""
Given an input file name f_name, reads the JSON data inside returns as
Python data object.
"""
f = open(f_name, 'r')
json_data = json.loads(f.read())
f.close()
return json_data | 74,644 |
def load_df(df_path):
"""
Parameters
---
df_path: string
absolute path to where a pandas DataFrame generated by the match_to_GLEAM function
has been generated
Returns
---
table: DataFrame
the loaded pandas DataFrame
"""
table = pd.read_pickle(df_p... | 74,645 |
def user(db):
"""A user for the tests."""
user = UserFactory(password='myPrecious')
db.session.commit()
return user | 74,646 |
def logistic(x, x0=0, L=1, k=1):
""" Calculate the value of a logistic function.
# Arguments
x0: The x-value of the sigmoid's midpoint.
L: The curve's maximum value.
k: The logistic growth rate or steepness of the curve.
# References https://en.wikipedia.org/wiki/Logistic_function
... | 74,647 |
def reverse_string_recursive(s):
"""
Returns the reverse of the input string
Time complexity: O(n^2) = O(n) slice * O(n) recursive call stack
Space complexity: O(n)
"""
if len(s) < 2:
return s
# String slicing is O(n) operation
return reverse_string_recursive(s[1:]) + s[0] | 74,648 |
def checkIsHours(value):
"""
checkIsHours tries to distinguish if the value describes hours or degrees
:param value: string
:return:
"""
if not isinstance(value, str):
return False
if '*' in value:
return False
elif '+' in value:
return False
elif '-' in va... | 74,649 |
def _map_las_file_to_metadata(file_directory: str, file_name: str) -> Optional[str]:
"""Performs mapping of las plot level file to associated JSON metadata file
Arguments:
file_directory: the directory of the file
file_name: the name of the file to map
Returns:
The mapped filename or... | 74,650 |
def gnome_sort(a):
"""
Sorts the list 'a' using gnome sort
>>> from pydsa import gnome_sort
>>> a = [5, 6, 1, 9, 3]
>>> gnome_sort(a)
[1, 3, 5, 6, 9]
"""
i = 0
while i < len(a):
if i != 0 and a[i] < a[i-1]:
a[i], a[i-1] = a[i-1], a[i]
i -= 1
el... | 74,651 |
def clear():
"""
Clears the process list of all waiting processes.
"""
_process_list.clear() | 74,652 |
def get_choices_roles():
"""
Restituisce i ruoli utente (Admin/Operator)
:return:
"""
try:
return [(i.role, i.role) for i in agency.models.Role.objects.all().order_by('role')]
except:
return [] | 74,653 |
def get_boxscore_from_game_id(
cz_game_id : str
,**request_kwargs
)->defaultdict:
"""Returns a curling boxscore (dict) based on the cz_game_id."""
url = 'https://www.curlingzone.com/game.php?1=1&showgameid=%s#1'%cz_game_id
soup = make_soup(url=url,**request_kwargs)
return _get_boxscore_from_g... | 74,654 |
def fig_prior_vs_posterior(outfile='fig_prior_vs_posterior.png',
POx_secure=associate_defs.POx_secure,
prior_mode='conservative'):
"""
Args:
outfile:
Returns:
"""
set_mplrc()
frb_pre = analysis.get_candidates()
# Init prior
... | 74,655 |
def lpf_smooth(s3d, a, b):
"""
:param s3d: K x J x 3
:param a: [5,]
:param b: [5,]
:return:
"""
lpf_num = len(a)
s3d_y_ = [s3d[0].copy() for _ in range(lpf_num - 1)]
s3d_x_ = np.pad(s3d, ((lpf_num - 1, 0), (0, 0), (0, 0)), 'edge')
for i, s3d1f in enumerate(s3d_x_):
if i ... | 74,656 |
def write_to_file(trie_root, output_stem):
"""
write trie to file
:param trie_root: root node of trie
:param output_stem: output file stem
"""
fout_key = open('%s.trie' % output_stem, 'wb')
fout_val = open('%s.val' % output_stem, 'w')
val_serial = 0
nodes = trie_root.breadth_first_traverse()
f... | 74,657 |
def STOK(df):
"""
Stochastic oscillator %K
"""
result = pd.Series((df['Close'] - df['Low']) / (df['High'] - df['Low']), name='SO%k')
return out(SETTINGS, df, result) | 74,658 |
def prepare(ctx, new_version=None, version_part=None, hide=True,
dry_run=False):
"""Prepare the release: bump version, build packages, ..."""
if new_version is not None:
bump_version(ctx, new_version, version_part=version_part,
dry_run=dry_run)
build_packages(ctx, hi... | 74,659 |
def scaleLongSide(ip, longSide):
""" Scale the image with respect to the longSide parameter (new size along the long side of the image should equal the longSide parameter) """
w = ip.width
h = ip.height
l = max(w,h)
s = float(longSide)/l
imp = ImagePlus('scaleLongSide',ip)
IJ.run(imp, "Scale...", "x="+str(s)+" y... | 74,660 |
def load_pipeline(*, file_name: str) -> Pipeline:
"""Load a persisted pipeline."""
file_path = TRAINED_MODEL_DIR / file_name
trained_model = joblib.load(filename=file_path)
return trained_model | 74,661 |
def init_logger():
"""将日志信息输出到控制台
Params:
asctime: 打印日志的时间
levelname: 打印日志级别
name: 打印日志名字
message: 打印日志信息
"""
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
l... | 74,662 |
def WIFI(frame, no_rtap=False):
"""calls wifi packet discriminator and constructor.
:frame: ctypes.Structure
:no_rtap: Bool
:return: packet object in success
:return: int
-1 on known error
:return: int
-2 on unknown error
"""
pack = None
try:
pack = WiHelper.g... | 74,663 |
def delete_shard(name):
"""usage: delete_shard NAME
Delete a shard.
Hermit will prompt you to confirm whether or not you really want to
delete the given shard.
If you agree, the shard will be deleted in memory. You must run the
`write` command to delete the shard from the filesystem.
Examples:
... | 74,664 |
def get_files_being_copied(directories: Set[str]) -> Dict[str, DiskCopyInfo]:
"""Get all the files which are not accessible for write (i.e. being copied)
Parameters
----------
directories : Set[str]
Directories where to search for files, which cannot be accessed (i.e. being copied)
previous... | 74,665 |
def test_list_unsigned_short_length_1_nistxml_sv_iv_list_unsigned_short_length_2_3(mode, save_output, output_format):
"""
Type list/unsignedShort is restricted by facet length with value 6.
"""
assert_bindings(
schema="nistData/list/unsignedShort/Schema+Instance/NISTSchema-SV-IV-list-unsignedSho... | 74,666 |
def time_elapsed(func):
"""
记录函数运行耗时的生成器
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
timestamp = time.time() * 1000
ret = func(*args, **kwargs)
now_ts = time.time() * 1000
elapsed = now_ts - timestamp
print('%s costs time: %.2... | 74,667 |
def _get_params(args, opts):
"""
Get params from conffile
"""
logger = logging.getLogger('fms')
simconffile = _get_simconffile(args)
if os.path.splitext(simconffile)[-1] == '.xml':
logger.debug("Calling XmlParamsParser on %s" % simconffile)
params = XmlParamsParser(simconffile)
... | 74,668 |
def Weight(*args):
"""Weighting factor for this Sensor measurement with respect to other Sensors. Default is 1."""
# Getter
if len(args) == 0:
return lib.Sensors_Get_Weight()
# Setter
Value, = args
lib.Sensors_Set_Weight(Value) | 74,669 |
def train(model, train_target, valid_target, out_dir, use_gpu=False):
"""
Factorize the training matrix of song-playlist pairs. Monitor on a
validation dataset. Return nothing.
Parameters
----------
model: model file
Model specification.
train_target: numpy array, shape (num songs, ... | 74,670 |
def load_from_arff(filename, labelcount, endian="big",
input_feature_type='float', encode_nominal=True, load_sparse=False,
return_attribute_definitions=False):
"""Method for loading ARFF files as numpy array
Parameters
----------
filename : str
path to ARFF file
labelcount: integer
... | 74,671 |
def hashimoto(dataset_lookup: Callable[[uint32_hash_array, int], uint32_hash]) -> Callable[[bytearray, bytearray, int, uint32_hash_array], Mapping[str, bytes]]:
""" Decorator function. Returns the hashimoto algorithm.
Args:
dataset_lookup (Callable[[list, int], List[int]]): data item lookup function
... | 74,672 |
def run_in_thread_pool (*, callbacks = (), callbacks_kwargs = ()):
"""将函数放入线程池执行的装饰器"""
def decorator (func):
@wraps(func)
def wrapper (*args, **kwargs):
future = EXECUTOR.submit(func, *args, **kwargs)
for index, callback in enumerate(callbacks):
... | 74,673 |
def evaluate_position(board, colour, legal_moves):
""" Evaluation function for chess game """
white = chess.WHITE
black = chess.BLACK
pieces = {}
# Counting pieces depeneding on colour
wking = bin(board.occupied_co[white] & board.kings).count('1')
wqueen = bin(board.occupied_co[white] & boar... | 74,674 |
def rotate_point_cloud_and_gt(batch_data,batch_gt=None):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"... | 74,675 |
def repost_ad(args, api=None):
"""
Repost ad
Try to delete ad with same title if possible before reposting new ad
"""
delete_ad(args, api)
# Must wait a bit before posting the same ad even after deleting it, otherwise Kijiji will automatically remove it
print("Waiting 3 minutes before post... | 74,676 |
def signal_resample(
ser_raw:pd.Series,
resample_method:str='linear',
resample_timestep:str='100ms'
) -> pd.Series:
"""
Resample the data and fill the values following 3 methods:
* linear will apply:
* linear interpolation when 1 point is missing
* Akima interpolation when more p... | 74,677 |
def _ToDatastoreError(err):
"""Converts an apiproxy.ApplicationError to an error in datastore_errors.
Args:
err: apiproxy.ApplicationError
Returns:
a subclass of datastore_errors.Error
"""
errors = {
datastore_pb.Error.BAD_REQUEST: datastore_errors.BadRequestError,
datastore_pb.Error.CONCURR... | 74,678 |
def client_script():
""" Reads qtwebchannel.js from disk and creates QWebEngineScript to inject to QT window.
This allows for JavaScript code to call python methods marked by pyqtSlot in registered objects.
Args:
None.
Returns:
None.
Raises:
"""
qwebchannel_js = QFile(... | 74,679 |
def suppress_other_loggers(*excludes):
"""Suppress log messages from some of the other common loggers."""
if len(excludes) == 0:
excludes = DEFAULT_EXCLUDES
for name in logging.root.manager.loggerDict:
for part in excludes:
if part in name:
logging.getLogger(name... | 74,680 |
def thread_first(val, *forms):
""" Thread value through a sequence of functions/forms
>>> def double(x): return 2*x
>>> def inc(x): return x + 1
>>> thread_first(1, inc, double)
4
If the function expects more than one input you can specify those inputs
in a tuple. The value is used as ... | 74,681 |
def test_incomplete_infix_operator():
"""Binary infix operator with too few arguments."""
with pytest.raises(PythonParseError):
compileScenic('x = 3 @')
with pytest.raises(PythonParseError):
compileScenic('x = 3 at') | 74,682 |
def _get_parent_object(obj: dict, dotted_path: List[str]):
"""
Given a nested dictionary, return the object denoted by the dotted path (if any).
In particular if dotted_path = [], it returns the same object.
:param obj: the dictionary.
:param dotted_path: the path to the object.
:return: the t... | 74,683 |
def vm_info(name):
"""
Wrapper around VBoxManage showvminfo
Return all the information about an existing VM
:param name: str
:return: dict[str,str]
"""
try:
INFO_PARSER = re.compile(
r'^("(?P<quoted_key>[^"]+)"|(?P<key>[^=]+))=(?P<value>.*)$')
info = {}
fo... | 74,684 |
def shell(*args, **kwargs):
""" A really roundabout way to issue a system call """
import subprocess
sys.stdout.flush()
# Parse the keyword arguments
verbose = kwargs.get('verbose', False)
detatch = kwargs.get('detatch', False)
shell = kwargs.get('shell', True)
# Print what you are abo... | 74,685 |
def create_type_file(user_id):
"""
Function: create_type_file
Description: Checks if the event type file exists, and creates it if it doesn't
Input:
user_id - String representing the Discord ID of the user
Output: Creates the event type file if it doesn't exist
"""
if not os.path.exi... | 74,686 |
def test_show_confusion_matrix():
"""Tests the show confusion matrix function in Random Forest Classifier."""
clf = RandomForestClassifier(no_points=10)
clf.train()
fig = clf.show_confusion_matrix(return_fig=True)
assert isinstance(fig, Figure) | 74,687 |
def fmod(x, y):
"""Return fmod(x, y), as defined by the platform C library.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0 | 74,688 |
def load_observation(db, obs_id, dets=None, prefix=None):
"""Load the data for some observation. You can restrict to only some
detectors. Coming soon: also restrict by time range / sample
index.
This specifically targets the pipe-s0001 sim format.
Arguments:
db (ObsFileDB): The database d... | 74,689 |
def read_mrk(fname):
"""Marker Point Extraction in MEG space directly from sqd
Parameters
----------
fname : str
Absolute path to Marker file.
File formats allowed: *.sqd, *.mrk, *.txt, *.pickled
Returns
-------
mrk_points : numpy.array, shape = (n_points, 3)
Marker... | 74,690 |
def ModelFileName(suffix):
"""Location of filename `Description()`_`suffix` in `dataset_dir/dumps`."""
return os.path.join(dataset_dir, 'dumps',
'%s_%s' % (Description(), suffix)) | 74,691 |
def softModCtx(q=1,e=1,ds="string",ex=1,fc=1,i1="string",i2="string",i3="string",rst=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/softModCtx.html
-----------------------------------------
softModCtx is undoable, queryable, and editable.
Controls the softMod context.
-----... | 74,692 |
def test_double_bonding(one_node_network_fn):
"""
Feature file: consensus.feature
Scenario: Bonding a validator node twice to an existing network.
"""
bonding_amount = 1
stakes = [1, 2]
assert_pre_state_of_network(one_node_network_fn, stakes)
block_hash = bond_to_the_network(
one... | 74,693 |
def get_tickers(fiat="ALL"):
"""
마켓 코드 조회 (업비트에서 거래 가능한 마켓 목록 조회)
:return:
"""
try:
url = "https://api.upbit.com/v1/market/all"
contents = _call_public_api(url)[0]
if isinstance(contents, list):
markets = [x['market'] for x in contents]
if fiat == "K... | 74,694 |
def print_session(session):
"""
Prints info from the current session.
WARNING: ONLY FOR DEBUGGING. MAJOR SECURITY RISK!
"""
print "<h3>Session Data</h3>"
print "<dl>"
for name in session:
print "<dt>%s <i>%s</i></dt>"%(name, type(session[name]))
print "<dd>%s</dd>"%repr(session[name])
print "</dl>" | 74,695 |
def xlsx(data_iterator, spreadsheet_filepath, callback=None):
"""xlsx - put a dataset to an xlsx spreadsheet
Parameters:
an iterator which will supply [(Sheet Name, [Column Names / Types], [Rows]), ...]
spreadsheet_filepath - full path to a spreadsheet
"""
ROWSET_SIZE = 1000
wb = o... | 74,696 |
def EulerFluxX(u):
"""Calculate the x-direction Euler flux from a solultion vector"""
dens = u.dens()
momX, momY, momZ = u.momX(), u.momY(), u.momZ()
en = u.energy()
pressure = u.pressure()
x_flux = np.array(
[
momX,
momX * momX / dens + pressure,
momX... | 74,697 |
def add_sequence_args(subparsers):
"""Parser with sequence as starting point"""
from_sequence_subparser = subparsers.add_parser("seq")
add_default_args(from_sequence_subparser)
from_sequence_subparser.add_argument("--nodca", default=False, action="store_true", help=argparse.SUPPRESS)
from_sequence_s... | 74,698 |
def copy_local_directory_to_gcs(project, local_path, bucket_name, gcs_path):
"""Recursively copy a directory of files to GCS.
local_path should be a directory and not have a trailing slash.
"""
assert os.path.isdir(local_path)
for local_file in glob.glob(local_path + '/**'):
if not os.path.isfile(local_f... | 74,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.