content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
def example_3() -> Body_System:
"""
Example 3: Random system with many bodies.
No doctest provided since this function does not have a return value.
"""
bodies = []
for i in range(10):
velocity_x = random.uniform(-0.5, 0.5)
velocity_y = random.uniform(-0.5, 0.5)
... | 1034578080f3a450bda0248897fa5d18133ef21c | 58,500 |
import scipy
def distribution1d(X, Y, title='', figshape=(1, 1), scatter=False, mean=False,
median=True, range=True, range_alpha=0.3, convolve=False,
xlog=False, ylog=True, labels=[]):
""" X,Y: lists of x,y data """
n_subplots = len(Y)
cols, rows = figshape
assert... | 40c4cc1833c25f2fd7a60d05efc22bbfdf1bac97 | 58,501 |
def get_dfs(object_ids):
"""Retrieve dataframes from the object store given their object IDs."""
buffers = client.get_buffers(object_ids)
return [pa.RecordBatchStreamReader(buf).read_next_batch().to_pandas()
for buf in buffers] | 770bcc4d2d56c3d7656a6f55ce320137b238ac78 | 58,502 |
import torch
def ce_loss(logits, targets):
"""
logits: (torch.float32) shape (N, C, H, W)
targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1}
"""
targets = targets.type(torch.int64)
ce_loss = F.cross_entropy(logits, targets)
return ce_loss | 9c5a5ebcd5f285cf39236e0c1926fbc291ba9b62 | 58,503 |
from typing import Callable
import tqdm
import time
def experiment(method: str, step_size: float, num_steps: int, num_samples: int, proposal: Callable, randomize_steps: bool):
"""Experiment to examine the use of different integrators for sampling from
Neal's funnel distribution. Given a proposal operator, att... | f547dbeabd6fb0b16c5fae11784c140f92b95f6a | 58,504 |
def get_pars(ts, coors, mode='qp',
equations=None, term=None, problem=None, **kwargs):
"""
The material nonlinearity function - the Lamé coefficient `mu`
depends on the strain.
"""
if mode != 'qp': return
val = nm.empty(coors.shape[0], dtype=nm.float64)
val.fill(1e0)
order... | 4ca313924c86f20f51943f2584279236b274758a | 58,505 |
def get_day_02():
"""Returns the ``Day02`` for the puzzle data."""
return Day02(
read_lines_of_datafile('day_02_data.txt')
) | fa97835d7af954f6028d0ad5a7e699fa8fe5ceed | 58,506 |
def post_process_tree(G):
"""
Given a networkx graph in the form of a tree, assign sample identities to character states.
:param graph: Networkx Graph as a tree
:return: postprocessed tree as a Networkx object
"""
new_nodes = []
new_edges = []
for n in G.nodes:
spl = n.split("... | aba4654d174e3bf5e8706ca3e8a8d2bae8461129 | 58,507 |
def init_db():
"""
Establishing the connection with MongoDB
"""
connection = MongoClient(cons.ip_port_initial_db)
connection.sampledb.authenticate(cons.mongoUserName, cons.mongoPasswd)
db = connection.sampledb
return db | fa135ddf1166cab5ad7588dbc6fd6ac9900e9c25 | 58,508 |
def select(text: str, cases: list, default: int = None, case_sensitive: bool = False):
"""
Let user select one of the cases.
Args:
text (str): Text.
cases (list[tuple]): Cases, should be list of tuples. Each tuple is in form `('display text', 'user's input')`.
For ex... | 0875134cd5f4f824a10ab4c51a6bd4f834830250 | 58,509 |
def _preprocess_data(lulc_lookup_dict, lulc_snapshot_list):
"""Preprocess data.
Args:
lulc_lookup_dict (dict): dictionary of lookup values
lulc_snapshot_list (list): list of raster paths
Returns:
transition_matrix_dict (dict): dictionary of transitions for transition
ma... | c287c16db0aa3e335e28931c8b48572ceb4a0e05 | 58,510 |
def k_means_cluster(colors):
"""
Color recovery has errors.
Hence, look at colors, cluster them, and pick an average color per cluster.
:param colors: Colors to cluster.
:return: Clustered colors.
"""
global kmeans_num_clusters
flattened = colors.reshape([-1, colors.shape[-1]])
km... | 359dce1267ddd114786a39ff6d3d537b495f3b83 | 58,511 |
def cluster_hyperbola(npts, fac=3.0):
"""Return a hyperbolic tangent clustering function."""
xhat = np.linspace(-1.0, 1.0, npts)
return np.tanh(fac * xhat) / 2.0 / np.tanh(fac) + 0.5 | 3f13e6076381cd9a3da8187e77536a111fa9cf02 | 58,512 |
def remote_db_val_from_raw_val(grpc_address: str) -> bytes:
"""Format a remote db value from it's grpc address string
Parameters
----------
grpc_address : str
IP:PORT where the grpc server can be accessed
Returns
-------
bytes
formated representation of the grpc address sui... | 4e4386391faf25e06bbf859fddd06812a0ce9c4c | 58,513 |
def list_snapshots(session, verbose):
# type: (Session, bool) -> Union[List[str], List[Dict[str,str]]]
"""List the snapshots in the current network."""
if not session.network:
raise ValueError("Network must be set to list snapshots")
url_tail = "/{}/{}/{}".format(
CoordConstsV2.RSC_NETWO... | d8e42ff7f97c9041b5234bf58bc81dc775f2a9cb | 58,514 |
import requests
def nlp_result(text, token_key, index=0, way='poem'):
"""
调用该函数返回生成的春联或者七言诗
:param text: 春联或诗的主题(官方限制不超过 5 个字符)
:param token_key: 通过调用 get_token_key() 获取的 token
:param index: 不同的 index 会输出不同的春联和诗
:param way: 通过传入该参数确认是生成对联还是生成诗,“poem”为写七言诗,“couplets”为写春联
:return: 获取的数据
... | 090ab944b751fcb940795beb5793c97c13e39b18 | 58,515 |
def __data_suppression(indicator_dataframe):
"""Helper function to reduce data used by the large indicator dataframe"""
# Couple columns we just don't need
indicator_dataframe.drop(columns = {'SpatialDimType','TimeDimType','DataSourceDimType',
'Date','TimeDimensionValue','TimeD... | fa9d205c2d5b9ae8a668247fc32abc76c562a9e7 | 58,516 |
def strip_email(s: str) -> str:
"""
Filter which extracts the first part of an email to make an shorthand
for user.
:param s: Input email (or any string).
:type s: str
:return: A shorthand extracted.
:rtype: str
"""
return s.split('@', 1)[0] | 36ea94b9eb12e0e64b78965c66233578790e6a13 | 58,517 |
def flat_node_and_edge(nodes, eids, weights=None):
"""flatten the sub-lists to one list"""
nodes = list(set(traverse(nodes)))
eids = list(traverse(eids))
if weights is not None:
weights = list(traverse(weights))
return nodes, eids, weights | f6103c00c374cca58884093de4ada3a319709f21 | 58,518 |
def name_item_info(mosaic_info, item_info):
"""
Generate the name for a mosaic metadata file in Azure Blob Storage.
This follows the pattern `metadata/quad/{mosaic-id}/{item-id}.json`.
"""
return f"metadata/quad/{mosaic_info['id']}/{item_info['id']}.json" | db78eb175f6530ace2037ed89cb090591c82147f | 58,519 |
import sys
def influxdb_get(uri, query, db=None):
"""Runs a query via HTTP GET and returns the response as a Python list."""
getparams = {"q": query}
if db:
getparams['db'] = db
try:
params = urlparse.urlencode(getparams)
uri = "{}&{}".format(uri,params)
req = urllib2... | f8f831c173c6bd3f3de95ac24a5a951b6f4362ad | 58,520 |
import itertools
import pandas as pd
def get_all_locations_from_jobs(jobs, start_time, end_time):
"""Return a list of Location objects collected from each job in jobs.
Pulls Location objects from each Job's associated Shift
Location list is sorted by timestamp.
Args:
jobs ([Job]): List of J... | b709cf141e6e432cc41f5c390059b40d5de31d3b | 58,521 |
from pathlib import Path
def load_sheets(t_list=None):
"""Load mapping for given sheets.
Loads a lsit of .xlsx files from disk as named in `t_list`. Generates a
nested dict through which individual codes can be accessed and decoded to
a human-readable format.
Parameters
----------
t_list... | 072cd5a782580e2ee5e5cedd035b947c85e4e143 | 58,522 |
def get_D_matrix_for_angle(angle, j, cached=True):
"""
Interface to *D_matrix_conj()*
:param angle: Dict of angle data {"alpha","beta","gamma"}
:param j: Integer :math:`2j` in the formula
:param cached: Haven't been used???
:return: Array of the conjugated D-matrices. Same length as the angle d... | df3ce7046b12c328087278d92dda1721ad6ca5c8 | 58,523 |
def ptfhost(testbed_devices):
"""
Shortcut fixture for getting PTF host
"""
return testbed_devices["ptf"] | 25fdbc9520c4cda9719887ff213ccb2b88918dcc | 58,524 |
from datetime import datetime
def add_current_time_to_state(state):
"""Annotate state with the latest server time"""
state['currentTime'] = datetime.now().timestamp()
return state | f61fa2d7b127fbebb22fc277e16f2f79cdd4acd3 | 58,525 |
def volCube(edge: float) -> float:
"""Finds volume of a cube"""
volume: float = edge * edge * edge
return volume | 34d42c35b04d73fb1a925076fcaab47a932ee394 | 58,526 |
import time
def delay(fn):
"""Decorator function to delay the execution of a function.
The function that use this decorator must have delay as a keyword
argument.
"""
def wrapper(*args, **kwargs):
seconds = kwargs.get('delay', 0)
time.sleep(seconds)
return fn(*args, **kwa... | 459fe2741af565225b1d9aee4e8841460d1bff4e | 58,527 |
import re
def normalize_rgb_colors_to_hex(css):
"""Convert `rgb(51,102,153)` to `#336699`."""
regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)")
match = regex.search(css)
while match:
colors = map(lambda s: s.strip(), match.group(1).split(","))
hexcolor = '#%.2x%.2x%.2x' % tuple(m... | e3650f525d1d9c1e7bbf7d5b4161712a7439b529 | 58,528 |
def validate_input_for_delete_role(role_for_the_profile_list) -> int:
"""ロール削除時のユーザー入力を validate"""
prompt_str = INPUT_No
min_menu_num = 1
max_menu_num = len(role_for_the_profile_list)
return ask_for_selection(prompt_str, min_menu_num, max_menu_num) | e9ec9856230da818c5a25ecd9c60f3c9476b9dc1 | 58,529 |
def replay():
"""
Function that asks the player if they want to play again and
returns a boolean True if they do want to play again.
:return:
"""
return input('Do you want to play again? \nEnter Yes or No: ').lower().startswith('y') | b95119baf68cf056a5abd9b5cb17036da8aa775a | 58,530 |
import os
def pdf_output_filename(
document_request_key: str, output_dir: str = settings.output_dir()
) -> str:
"""Given document_request_key, return the PDF output file path."""
return os.path.join(output_dir, "{}.pdf".format(document_request_key)) | 87d8f6c9c2b079749ee22c6e3b15b72a53472669 | 58,531 |
def _marble_of_player(player: Player) -> Marble:
"""Returns the corresponding `abalone_engine.enums.Marble` for a given `abalone_engine.enums.Player`.
Args:
player: The `abalone_engine.enums.Player` whose `abalone_engine.enums.Marble` is wanted.
Returns:
The `abalone_engine.enums.Marble` w... | 9860409c67625ff3ceefd4b006a1d3a22ddf30e5 | 58,532 |
def breadth_first_search(adjacency: sparse.csr_matrix, source: int, return_predecessors: bool = True):
"""Breadth-first ordering starting with specified node.
* Graphs
* Digraphs
Based on SciPy (scipy.sparse.csgraph.breadth_first_order)
Parameters
----------
adjacency :
The adjace... | 24a33f15d51191da38d33b054410894bbdd76cb2 | 58,533 |
def bessel2(order, x):
"""Evaluate `Bessel function of the second kind <https://en.wikipedia.org/wiki/Bessel_function>`_."""
if order == 0:
return y0(x)
if order == 1:
return y1(x)
return yv(order, x) | 4b565d85629749353eb9e5d02ef9bbb286148af9 | 58,534 |
from typing import Union
from typing import List
from typing import Dict
from typing import Tuple
from typing import Optional
def rdm_comparison_scatterplot(rdms,
show_marginal_distributions: bool = True,
show_identity_line: bool = True,
... | 2adac1b20660a174febc5cef4bdef9918318a010 | 58,535 |
import os
def on_app_engine():
"""
:return: bool
"""
if 'SERVER_SOFTWARE' in os.environ:
server_software = os.environ['SERVER_SOFTWARE']
if server_software.startswith('Google App Engine') or \
server_software.startswith('Development'):
return True
re... | 11390209888e3f3195bf8b1271eb881002f65b07 | 58,536 |
def start_end_temp_stats():
"""When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive."""
return jsonify() | 30a79b2c90a40a1822a1ff52515deb0209584c59 | 58,537 |
def bernoulli(X):
"""
If x1,x2,...xn ~iid~ BER(p), then the MLE, p-hat, is X-bar
Parameters
----------
X : array_like
Returns:
----------
bernoulli_mle : MLE calculation for p-hat for Bernoulli distribution
References
----------
[1] Casella, G., ... | 1891c179b5b4bbe0785234a8a10bb6da08ebf66f | 58,538 |
def fetch(station: str) -> str:
"""
Returns TAF report string or raises an error
Maintains backwards compatability but uses the new Service object.
It is recommended to use the Service class directly instead of this function
"""
return service.get_service(station)('taf').fetch(station) | 37acb01cb90aeee7d79f22a2dc1ed8308524f3cd | 58,539 |
def run(command, parser, known_args, unknown_args):
""" run command """
release_file = utils.get_heron_release_file()
with open(release_file) as release_info:
for line in release_info:
print line,
return True | 5e427e83ddaede4b7cb065212dcc6641c46f4099 | 58,540 |
def trial(df_train, test_data):
"""
Test 1: 1s followed by 3s
"""
my_test_data = test_data.drop(['avg_stand'], axis=1)
y = df_train['state'].values
X = df_train.drop(['avg_stand', 'stand', 'state', 'index'], axis=1)
if X.isnull().values.any() == False:
rf = RandomForestClassifier(b... | 08ad0fc14df736e21088e4eb6433bda6d4a30949 | 58,541 |
def dilated_residual_conv_block(dim, kernel, stride, dilation):
"""
Use dilated convs to enlarge the receptive field
"""
return pax.Sequential(
pax.Conv1D(dim, dim, kernel, stride, dilation, "VALID", with_bias=False),
pax.LayerNorm(dim, -1, True, True),
ReLU(),
pax.Conv1D... | 6ed7da173f612dac4ca475d601034971dd47f686 | 58,542 |
import typing
import concurrent
import tqdm
def get_sparse_matrix(documents: np.ndarray, words: dict, workers: int, weighting: typing.Any=weight) -> typing.Tuple[dok.dok_matrix, np.ndarray]:
"""
Parallelize Sparse Matrix Calculation
:documents: list of document strings
:words: dictionary of word freq... | e62737e74b03ca1031d2ce4d9e0b0085212d8604 | 58,543 |
def method_codes_to_geomagia(magic_method_codes,geomagia_table):
"""
Looks at the MagIC method code list and returns the correct GEOMAGIA code number depending
on the method code list and the GEOMAGIA table specified. Returns O, GEOMAGIA's "Not specified" value, if no match.
When mutiple codes are mat... | 7939704ba51f8e199b79ddf89611ec63c6ead703 | 58,544 |
import torch
def bbures_distance(Σ1, Σ2, sqrtΣ1=None, inv_sqrtΣ1=None,
diagonal_cov=False, commute=False, squared=True, sqrt_method='spectral',
sqrt_niters=20):
""" Bures distance between PDF. Batched version. """
if sqrtΣ1 is None and not diagonal_cov:
sqrtΣ1 =... | 6f07c0489f319d95775d2f4a116a4f9fe310bb3d | 58,545 |
import os
def receive_prediction(image_md5_hash: str = '', image_file_name: str = ''):
"""
Creates a new prediction using the model. This method must be called after the init() method has run
at least once, otherwise this will fail with a HTTP Error.
:param image_md5_hash: ID of job from server
:... | 5f90bc6523c90e27f1bfc092e4a21edf47e3855e | 58,546 |
def async(f):
"""
异步执行函数.
"""
@wraps(f)
def wrapper(*args, **kwargs):
thr = Thread(target=f, args=args, kwargs=kwargs)
# https://docs.python.org/2/library/threading.html#threading.Thread.daemon
# 重启Flask服务器时中止正在执行的异步线程
thr.setDaemon(True)
thr.start()
ret... | cef8b1a5b7665d37d6caa277b5f7d5c18ba8f755 | 58,547 |
import torch
import math
def decode_μ_law(x: torch.Tensor, μ: int = 255) -> torch.Tensor:
"""
Applies the element-wise inverse μ-law encoding to the tensor.
Args:
x: input tensor
μ: size of the encoding (number of possible classes)
Returns:
the decoded tensor
"""
x = ... | 84b991fdb80b845796ec751756ae56140dfc2f45 | 58,548 |
def _get_histogram_data(tracking_data):
"""Returns the histogram data for the plot.
Currently we return the bins and values of the last iteration tracked before
this plot.
Args:
tracking_data (pandas.DataFrame): DataFrame holding the tracking data.
Returns:
list: Bins of the histo... | 18afd4fc320ae67c25beb635144da76a0ca81b5f | 58,549 |
def get_linear_solver(solver_type: SparseSolver = preferred_type):
"""
Privide the chosen linear solver_type function pointer to solver_type linear systems of the type A x = b, with x = f(A,b)
:param solver_type: SparseSolver option
:return: function pointer f(A, b)
"""
if solver_type == SparseS... | 4e843c4a1ae56f21557a577c91b3e2b30ed05ff6 | 58,550 |
import os
def get_qt_type(path):
"""Finds the type of qt project the given path is"""
# check if there is config file
if os.path.exists(path + '/properties.ini'):
return get_configuration(path, 'project', 'type')
# check the res folder
if os.path.exists(path + '/res/ui'):
return ... | 0af2e605154191ea4022383951ad65d7a94fed57 | 58,551 |
def quick_kld(p_eval, q_eval, dx=0.01):
"""
Calculates the Kullback-Leibler Divergence between two evaluations of PDFs.
Parameters
----------
p_eval: numpy.ndarray, float
evaluations of probability distribution whose distance _from_ `q` will be calculated
q_eval: numpy.ndarray, float
... | 28d324ec5e81fd3f039747c43618264d71066097 | 58,552 |
import yaml
def dump_rendered_config_file(config):
"""Write config to file"""
return yaml.dump(config, default_flow_style=False) | 3efb499a8af1604e67906bc4c86e32c9441bd1a7 | 58,553 |
async def get_image_text(url: str, headers: dict, data) -> str:
"""
Request to a remote server for the text recognition function.
:param url: request url
:param headers: settings
:param data: data for OCR
:return: result
"""
async with ClientSession() as session:
async with sessi... | 0d82421c324948bb6224e9b0454964267ed79a67 | 58,554 |
import yaml
def get_account_stats(account, all_resources=False):
"""Returns stats for an account"""
with open("stats_config.yaml", 'r') as f:
resources = yaml.safe_load(f)
account = Account(None, account)
log_debug('Collecting stats in account {} ({})'.format(account.name, account.local_id))... | e141de8469de128e5407b2797ce61b029f48f9d7 | 58,555 |
import os
import gzip
def create_from_cellranger(indir: str, outdir: str = None, genome: str = None) -> str:
"""
Create a .loom file from 10X Genomics cellranger output
Args:
indir (str): path to the cellranger output folder (the one that contains 'outs')
outdir (str): output folder wher the new loom file sho... | ed8330380dc64eebdba1993f327c8444c42e6506 | 58,556 |
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def f(x):
total = 0
fact = len(L) - 1
for num in L:
print(num)
... | 724def67b2bca32d6cfa27ef83bb3b4eff009a73 | 58,557 |
import tqdm
def polymerize_cell(mol, n, m, terminate=None, terminate2=None, cell=None, density=0.1,
ff=None, opt='rdkit', retry=50, dist_min=0.7, threshold=2.0, work_dir=None, omp=1, mpi=1, gpu=0):
"""
poly.polymerize_cell
*** DEPRECATION ***
Unit cell generator of a homopolymer b... | 934e39fa105515abc62bfadb501372fe0e18c8fc | 58,558 |
def constant_array(context, builder, ty, pyval):
"""
Create a constant array (mechanism is target-dependent).
"""
return context.make_constant_array(builder, ty, pyval) | eefd69b2f8f355e2af61f7636a586dd87a0e0419 | 58,559 |
def shape_to_spacing(region, shape, pixel_register=False):
"""
Calculate the spacing of a grid given region and shape.
Parameters
----------
region : list = [W, E, S, N]
The boundaries of a given region in Cartesian or geographic
coordinates.
shape : tuple = (n_north, n_east) or... | bc943f55330c17295bdb078d732c6ebc9f8cecfe | 58,560 |
import math
def choose_grid_size(train_inputs, ratio=1.0, kronecker_structure=True):
"""
Given some training inputs, determine a good grid size for KISS-GP.
:param x: the input data
:type x: torch.Tensor (... x n x d)
:param ratio: Amount of grid points per data point (default: 1.)
:type rati... | 1d3e30a6b7b419a1e2fcdc245830aa00d1ba493d | 58,561 |
def ldamodel_top_word_topics(topic_word_distrib, vocab, top_n=10, val_fmt=None, topic_labels=DEFAULT_TOPIC_NAME_FMT,
col_labels=None, index_name='token'):
"""
Retrieve the top (i.e. most probable) `top_n` topics for each word in the topic-word distribution
`topic_word_distrib` a... | ad6c8c0f778473e4f83a73a0e35e92ef0537e76d | 58,562 |
def convert_to_location_dictionary(array, locations=REGIONS):
"""Convert array of values ``array`` with order ``locations`` to a dictionary:
{
'place name': value
}
Assumes that the first axis of the array matches the locations."""
size = array.shape[0]
if len(array.shape) ... | e2457311bd301d04cd48ac5741d0b2d714b22cec | 58,563 |
def multihead_attention_vars(
mesh, heads, io_channels, kv_channels, activation_dtype):
"""Create Parameters for Multihead Attention.
Args:
mesh: a Mesh
heads: a Dimension
io_channels: a Dimension
kv_channels: a Dimension
activation_dtype: a tf.dtype
Returns:
q_var: a Tensor with sha... | a245b7292529d56571e3144b9b550ab24ee14fd2 | 58,564 |
import math
def vertical_angle(img, p1, p2, p3, draw=False):
"""
Calculate the angle between segment(A,B) and vertical axe
"""
x1, y1 = p1[0], p1[1]
x2, y2 = p2[0], p2[1]
x3, y3 = p3[0], p3[1]
# Calculate the Angle
radius = math.atan2(y3 - y2, x3 - x2) - math.atan2(y1 - y2, x1 - x2)
angle = math.degrees(rad... | 2566989cbe24c4d3e690efffa7caceac2d83d09c | 58,565 |
import math
def factors_convert_fract2cartes(cif_data):
"""
Edge vectors (a, b, c) in fractional coordinate –> (x, y, z) in Cartesian coordinate
cos(alpha) = b*c/(|b||c|)
cos(beta) = a*c/(|a||c|)
cos(gamma) = a*b/(|a||b|)
a = (a, 0, 0)
b = (bcos(gamma), bsin(gamma), 0)
c = (cx, cy, c... | b60afbbed466efd0f2016e771323d3d56c3ffaf8 | 58,566 |
import scipy
def get_mvgcca_latents_space(X, W, model):
""" Return a list containing the common latent space Z and all the views latent space Z_m.
- X : [np.array(n x d1),...,np.array(n x dM)] multivews features ; n number of instances; dm dimension of views m ; M number of views
- W : ... | d513d54a3ec3dc2baed01c8dd04816f75753ad6e | 58,567 |
import transformers
def load_pipeline(**kwargs):
"""Load text generation pipeline."""
logger.info("Loading the pipeline...")
return transformers.pipeline("text-generation", **kwargs) | 6065791c6e89c7028ba123a4bc1df542ad786aad | 58,568 |
import subprocess
import errno
def jobs_running_between(start, end, keys=None):
"""Generate a list of Slurm jobs that ran between a time range
Args:
start (datetime.datetime): Find jobs that ended at or after this time
end (datetime.datetime): Find jobs that started at or before this time
... | 8231d2fce5f08042f2de50dfaf4431b8b6eaa506 | 58,569 |
import os
def _extract_NetCDF_layer_data(ncpath, layer_indexs = None):
"""
Extracts one or more layers from an NetCDF file and returns a dictionary with
all the data available in the NetCDF layer for use in further format conversion
to better supported formats.
example:
ncpath = filepath to a... | dca28b6666e675822c9740e86c04f9e582f4d66a | 58,570 |
def get_table_column(tags, hdulist, idx=None):
""" Find a column in a FITS binary table
Used to return flux/error/wave values from a binary FITS table
from a list of tags.
Parameters
----------
tags : list
List of string tag names
hdulist : fits header data unit list
idx : int, op... | 7c8982ea56cf5ac7a5807317bd3d6c5a5f454391 | 58,571 |
def new_weights(shapes, names, random_types='truncated_normal', dtypes=tf.float32):
"""[Create a new trainable tensor as weight]
Arguments:
shapes {[Array of int]} -- [- example (convolution), [filter height, filter width, input channels, output channels]
- examp... | 50774aaf6c91c6ad5f586880bc2371db2fda7c18 | 58,572 |
import subprocess
def run_docker_compilation(image, incremental, tiny, config, seed,
silent, cpu_cores, boot, check_size):
"""Run a docker container to compiler a Linux kernel
:param image: docker image
:type image: str
:param incremental: steps for incremental compilation ... | 6d9c4a42a9e69f65ebb8f1dc8c5f57bf7978cfdc | 58,573 |
from madrona.common import default_mimetypes as mimetypes
from madrona.common.jsonutils import get_properties_json, get_feature_json, srid_to_urn, srid_to_proj
from madrona.features.models import FeatureCollection
import json
def geojson_link(request, instances):
"""
Generic view for GeoJSON representation of... | a84357d44c114423eca391906995bed5a8f45530 | 58,574 |
import requests
def get(path, params=None, filename=None, keyfile='api-key.txt'):
"""
Query Illustris API
Args:
path (str): API query path
params: ...
filename (str): filename and directory to save content.
"""
with open('api-key.txt', 'r') as myfile:
key=myfile.read()
... | b2f1226bd66325a012872d3d07d5c10648aa8680 | 58,575 |
def DistributedPushSumOptimizer(optimizer, model,
num_steps_per_communication=1):
"""
An distributed optimizer that wraps another torch.optim.Optimizer through
win_accumulate ops to implement the gradient push algorithm.
Returned optimizer has two extra parameters `self_... | 8fccd6edddd5f8268517d20ffa51d5f700fbff90 | 58,576 |
def compute_ngrams (sentence, n): # OK
"""la fonction qui renvoie la liste de ngrams à partir d'une phrase"""
sentence = sentence.lower()
ngrams = zip(*[sentence.split()[i:] for i in range(n)])
return [" ".join(ngram) for ngram in ngrams] | 495505f4183d56a5a76339826f8306186191c6b1 | 58,577 |
import requests
def get_nof_instances(marathon_url, app_id):
"""
Get number of running instances given an app_id.
marathon_url : [string] the URL of the marathon service
app_id : [string] ID of the running marathon app
Method : GET
"""
api_endpoint = '/v2/apps/'
headers = {'Content-Ty... | e7abad86dc46f9ced379c2fa8b0eeafac6edd657 | 58,578 |
import pandas
def cell_id_count(dataframe: pandas.DataFrame, col_name: str) -> pandas.DataFrame:
"""
Count/tally the unique cell ID's to generate coverage density.
In general this could work for any field
and was initi.
"""
counts = dataframe.groupby([col_name])[col_name].agg("count").to_frame... | 2d6e47efc181e00e102ae51adc85c674a2bf53f4 | 58,579 |
def parameter_tuple_parser(parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
return code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
retur... | f869240666f2adca0551a3620644023b88930a5a | 58,580 |
def navbar_tutorial_categories():
"""Navbar categories template-tag"""
categories = (
Category.objects.select_related("parent_category")
.order_by("parent_category")
.active_categories()
)
return {"categories": categories} | 20758b3521b7c9e5f4b771d3df756a7cf3ab9073 | 58,581 |
def sum_of_factorial_pure_recursion(number: int) -> int:
"""
>>> sum_of_factorial_pure_recursion(0)
0
>>> sum_of_factorial_pure_recursion(1)
1
>>> sum_of_factorial_pure_recursion(2)
3
>>> sum_of_factorial_pure_recursion(5)
153
"""
if number == 1 or number == 0:
return... | 12ca71c011535bcff990f49cf8716aca3ecc5226 | 58,582 |
from typing import List
from typing import Dict
from typing import Optional
def noisy_copy(
value: Outcome, probability: float = 0.9, domain: List[Outcome] = None
) -> Dict[Outcome, Optional[float]]:
"""specify a variable's CPD as copying the value of some other variable with a certain probability."""
dis... | 2a01b30edfa22fbf63baf033dbfabf6910853af5 | 58,583 |
from typing import Dict
def _serialize_issued_currency_amount(value: Dict[str, str]) -> bytes:
"""Serializes an issued currency amount.
Args:
value: A dictionary representing an issued currency amount
Returns:
The bytes representing the serialized issued currency amount.
"""
amo... | 17d1c5042038a380e0b3508acebafbf9bd7bc7b9 | 58,584 |
def parse_todo_identifier(line):
"""
Returns a string, striped of any task keyword flags, and a Boolean if a task keyword flag is found within the first several characters of the line. Parses and strips keyword flags '[]', '◦', '☐', and '# TODO: '. Supports variations for '#todo:'.
Args:
line ... | f54830bbd58dd6805d4430ce7c4af6761050c754 | 58,585 |
from dateutil import tz
import os
import glob
def get_genome_dir(gid, galaxy_dir, data):
"""Return standard location of genome directories.
"""
if galaxy_dir:
refs = genome.get_refs(gid, None, galaxy_dir, data)
seq_file = tz.get_in(["fasta", "base"], refs)
if seq_file and os.path.e... | 80f1c4fbd08c4430efa924ecf45288bc5cd8e518 | 58,586 |
def get_historical_price(crypto, fiat, date):
"""
Only one service is defined for geting historical price, so no fetching modes
are needed.
"""
return HistoricalPrice().action(crypto, fiat, date) | c54c320cfd918e66e013d2d56c5c86551bdaee3b | 58,587 |
def _compute_padding_to_prevent_task_description_from_moving(unfinished_tasks):
"""Compute the padding to have task descriptions with the same length.
Some task names are longer than others. The tqdm progress bar would be constantly
adjusting if more space is available. Instead, we compute the length of th... | 82a2fffa0a35036901affe11fdf98d875445ffea | 58,588 |
def mcity_to_lab(dim):
"""
Converts real-world dimension to model.
"""
return dim / scale | b8105e43e0bb7115e0106a4a902df85567d29836 | 58,589 |
from typing import List
def predict(model: SpacyModel, X: List[str]) -> List[str]:
"""
Predict the label for each text.
Parameters
-----------
- **model**: the model to use.
- **X**: the texts inputs.
Return
----------
A List containing the label of each text.
"""
predic... | 08ce3abf80f0aa47f1e2dd5bfe1462b74b908a42 | 58,590 |
import math
def float_in_range(value: float, lower: float, upper: float) -> bool:
"""Checks if a float is within a range.
In addition to checking if lower < value < upper, checks if value is close to the end points;
if so, returns True. This is to account for the vageries of floating point precision.
... | e971c082e8019f545c9ccc1024f37d3bab61b64e | 58,591 |
def view(request, acronym):
"""
View IETF Group details
**Templates:**
* ``groups/view.html``
**Template Variables:**
* group
"""
group = get_object_or_404(Group, acronym=acronym)
add_legacy_fields(group)
return render(request, 'groups/view.html', { 'group': group } ) | f6a39f05526977582f33edd069e111da10bfffae | 58,592 |
def to_header(axes):
"""
Converts the axes describing the rows/columns of a CIFTI-2 vector/matrix to a Cifti2Header
Parameters
----------
axes : iterable of :py:class:`Axis` objects
one or more axes describing each dimension in turn
Returns
-------
header : :class:`.cifti2.Cift... | 5e9c12bc9e76c79e9da8b4122f461b962d49f028 | 58,593 |
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
if isinstance( object, str ):
return add_article( object )
return add_article( object.__class__.__na... | 673176ee78a0e302af099e892ff585638ff3e0cd | 58,594 |
from typing import List
from pathlib import Path
import glob
async def densenet_xgboost_weights() -> List[str]:
"""
Get available weights options for model.
"""
return {
'denseNet': [Path(f).as_posix().rsplit('/', maxsplit=1)[-1].split('.')[0]
for f in glob.glob("model_wei... | cf346645a53d9937995958a9752bef001d2ff3fe | 58,595 |
def build_from_sample(samples, total_size):
"""Restores the image from the list of coordinate tuples."""
image = np.zeros([total_size, total_size])
for sample in samples:
x = sample[0]
y = sample[1]
image[x, y] += 1
return image | 6ea19f1030e90c53e1d3726fec43af60ee3f1fec | 58,596 |
import torch
def eval_batch_s2cnn(mlp, s2cnn, data, batch_idxs, criterion, device_id=0):
""" evaluate a batch for the s2cnn """
geometry = data["features"]["geometry"][batch_idxs, ...]
atom_types = data["features"]["atom_types"][batch_idxs, ...]
atom_types_one_hot = to_one_hot(atom_types, NUM_ATOM_TYP... | a8f23d8f36c449ddff9940e937df938136aa129f | 58,597 |
def dropout_forward(x, dropout_param):
"""
Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We drop each neuron output with probability p.
- mode: 'test' or 'train'. If ... | 6e867d67b726ac4e361ca424729e9293f3810940 | 58,598 |
def detect_spikes(df, spiky_var, sliding_window=624, z=4, daynight=False):
"""Detect spikes on slow data according to Papale et al. (2006)
Parameters
----------
df: pandas DataFrame that contains the spiky variable, a daytime key
(day=1, night=0)
spiky_var: string that designate the spiky v... | 586d71fbf220180697eb2842b8de3fe1d6adeef7 | 58,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.