content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_emtpy_lines():
"""Empty lines are skipped."""
TEST = """
FOO=BAR
BAR=BAZ
"""
with tempfile.NamedTemporaryFile('w', delete=False) as f:
f.write(TEST)
env = core.read_dotenv(f.name)
assert len(env) == 2
assert env['FOO'] == 'BAR'
assert env['BAR'] == 'BAZ' | 10,700 |
def magerr2Ivar(flux, magErr):
"""
Estimate the inverse variance given flux and magnitude error.
The reason for this is that we need to correct the magnitude or
flux for Galactic extinction.
Parameters
----------
flux : scalar or array of float
Flux of the obejct.
magErr : scal... | 10,701 |
def create_policy_work_item_linking(repository_id, branch,
blocking, enabled,
branch_match_type='exact',
organization=None, project=None, detect=None):
"""Create work item linking policy.
"""
organiza... | 10,702 |
def center_data(X, y, fit_intercept, normalize=False, copy=True,
sample_weight=None):
"""
Centers data to have mean zero along axis 0. This is here because
nearly all linear models will want their data to be centered.
If sample_weight is not None, then the weighted mean of X and y
is... | 10,703 |
async def get_ipv4_internet_reachability(host, port, timeout):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
... | 10,704 |
def cov_pen(h_j, h_no_j):
"""
Personal implementation of covariance matrix with penalization.
:param h_j:
:param h_no_j:
:return:
"""
final_dim = h_j.shape[1]
cov_matrix = np.empty((final_dim, final_dim))
for row in range(final_dim):
for column in range(final_dim):
... | 10,705 |
def get_last_timestamp():
"""
获取当天23:59:59的时间戳
:return:
"""
# 获取明天0点的时间戳
future_timestamp = get_timestamp(-1)
# 明天0点的时间戳-1
last_timestamp = future_timestamp - 1
return last_timestamp | 10,706 |
def crawl(folder: str, search: str, maxnum: int, num_threads: int, crawlers: [List[str]] = ['GOOGLE', 'BING', 'BAIDU']) -> Dict[str, str]:
"""Crawl web sites for images"""
print('(1) Crawling ...')
# prepare folders
os.makedirs(folder, exist_ok=True)
sources = {}
for c in crawlers:
prin... | 10,707 |
def _get_all_subclasses(typ, # type: Type[T]
recursive=True, # type: bool
_memo=None # type: Set[Type[Any]]
):
# type: (...) -> Iterable[Type[T]]
"""
Returns all subclasses of `typ`
Warning this does not support g... | 10,708 |
def hdf5_load_frequencies(model, group, encoding):
"""loads the frequencies"""
keys = list(group.keys())
keys.remove('keys')
#spc_ids = _cast(group['keys'])
for freq_id in keys:
ifreq_id = int(freq_id)
cards_group = group[freq_id]
for card_type in cards_group.keys():
... | 10,709 |
def conditions_summary(conditions):
"""
Return a dict of consumer-level observations, say, for display on a
smart mirror or tablet.
"""
keys = ['timestamp', 'dewpoint', 'barometricPressure', 'windDirection',
'windSpeed', 'windGust', 'precipitationLastHour', 'temperature',
'relativeHumidity... | 10,710 |
def InsertOrganisation(cur, con, entity_name: str = "Organisation") -> int:
""" Inserts a new Organisation into the database """
# Get information about the video game
print(f"Enter new {entity_name}'s details:")
row = {}
row["Name"] = input(f"Enter the name of the {entity_name}: ") or None
row[... | 10,711 |
def main():
"""Entry point for qchess CLI"""
print('Hello, world!') | 10,712 |
def _rgb_to_hsv(rgbs):
"""Convert Nx3 or Nx4 rgb to hsv"""
rgbs, n_dim = _check_color_dim(rgbs)
hsvs = list()
for rgb in rgbs:
rgb = rgb[:3] # don't use alpha here
idx = np.argmax(rgb)
val = rgb[idx]
c = val - np.min(rgb)
if c == 0:
hue = 0
... | 10,713 |
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting crazy calculations...")
#print("The {}-th Fibonacci number is {}".format(args.n, trade_for_(args... | 10,714 |
def main():
"""Call script functions, measure script run-time, query user"""
start_time = time.time()
InformUser()
SecDegEqn()
end_time = time.time()
print("\nSpeed_check: script run time is {} seconds".format(end_time - start_time))
query = input("\nWould you like to run the s... | 10,715 |
def find_correlation(convergence_data, lens_data, plot_correlation=False, plot_radii=False, impact=False, key=None):
"""Finds the value of the slope for plotting residuals against convergence. Magnitude of slope and error
quantify correlation between the two.
Inputs:
conv -- convergence.
mu_diff ... | 10,716 |
def ELCE2_null_estimator(p_err, K, rng):
"""
Compute the ELCE^2_u for one bootstrap realization.
Parameters
----------
p_err: numpy-array
one-dimensional probability error vector.
K: numpy-array
evaluated kernel function.
rng: type(np.random.RandomState... | 10,717 |
def test_check_generic_constraint_rhs_calculation(casefile):
"""Check NEMDE input constraint RHS matches NEMDE solution RHS"""
constraints = (casefile.get('NEMSPDCaseFile').get('NemSpdInputs')
.get('GenericConstraintCollection')
.get('GenericConstraint'))
for i in con... | 10,718 |
def select_from(stdscr, x, y, value, slist, redraw):
"""
Allows user to select from a list of valid options
:param stdscr: The current screen
:param x: The start x position to begin printing
:param y: The start y position to begin pritning
:param value: The current value chosen
:param slist:... | 10,719 |
def show_errorbox_exception(msg):
"""Show both an error box and raise an Exception"""
show_errorbox(msg)
raise Exception(msg) | 10,720 |
def describe(r):
"""Return a dictionary with various statistics computed on r:
mean, variance, skew, kurtosis, entropy, median.
"""
stats = {}
stats['mean'] = r.mean()
stats['variance'] = r.var()
stats['skew'] = skew(r)
stats['kurtosis'] = kurtosis(r)
stats['median'] = np.median(... | 10,721 |
def test_s3_write_output_data(mp_s3_tmpdir):
"""Write and read output."""
output_params = dict(
grid="geodetic", format="PNG", path=mp_s3_tmpdir, pixelbuffer=0, metatiling=1
)
output = png.OutputDataWriter(output_params)
assert output.path == mp_s3_tmpdir
assert output.file_extension == ... | 10,722 |
def value_iteration(env,maxiter):
"""
Just like policy_iteration, this employs a similar approach.
Steps (to iterate over):
1) Find your optimum state_value_function, V(s).
2) Keep iterating until convergence
3) Calculate your optimized policy
Outputs:
- Your f... | 10,723 |
def is_excluded(branch_name):
"""
We may want to explicitly exclude some BRANCHES from the list
of BRANCHES to be merged, check if the branch name supplied
is excluded if yes then do not perform merging into it.
Args:
branch_name: The branch to check if to be inc... | 10,724 |
def configure_logging(enable_py_logger, level=logging.ERROR):
"""
Configure libyang logging behaviour.
:arg bool enable_py_logger:
If False, configure libyang to store the errors in the context until
they are consumed when Context.error() is called. This is the default
behaviour.
... | 10,725 |
def test_RNVPVelocityEGCL():
"""
test `RNVPVelocityEGCL` in the aperiodic case. we make sure log_s scales are invariant to rotation/translations while translation elements are
equivariant
"""
render_RNVPVelocityEGCL() | 10,726 |
def schedule_contrib_conv2d_winograd_without_weight_transform(attrs, outs, target):
"""Schedule definition of conv2d_winograd_without_weight_transform"""
with target:
return topi.generic.schedule_conv2d_winograd_without_weight_transform(outs) | 10,727 |
def preprocess_set_ica_comp_fif_to_ts(fif_file, subject_id, n_comp_exclude,
is_sensor_space):
"""Preprocess ICA fif to ts."""
import os
import sys
import mne
from mne.preprocessing import read_ica
from nipype.utils.filemanip import split_filename as split_... | 10,728 |
def plot(df, columns, df_clean, df_outliers, plot_cols=4):
"""Plots the dataframe and marks the outliers by a red cross.
Parameters:
----------
columns : str
A string of columns which will be plotted.
df_clean : dataframe
Dataframe without outliers.
df_outliers : dataframe
... | 10,729 |
def _phi(r: FloatTensorLike, order: int) -> FloatTensorLike:
"""Coordinate-wise nonlinearity used to define the order of the
interpolation.
See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition.
Args:
r: input op.
order: interpolation order.
Returns:
`phi_k` e... | 10,730 |
def mmodel():
"""Commands for the MONGOOSE meta study."""
pass | 10,731 |
def linbin(n, nbin=None, nmin=None):
"""Given a number of points to bin and the number of approximately
equal-sized bins to generate, returns [nbin_out,{from,to}].
nbin_out may be smaller than nbin. The nmin argument specifies
the minimum number of points per bin, but it is not implemented yet.
nbin defaults to th... | 10,732 |
def get_soup(url):
"""Gets the soup of the given URL.
:param url: (str) URL the get the soup from.
:return: Soup of given URL.
"""
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'}
return BeautifulSoup... | 10,733 |
def msd_id_to_dirs(msd_id):
"""Given an MSD ID, generate the path prefix.
e.g. TRABCD12345678 -> A/B/C/TRABCD12345678"""
return op.join(msd_id[2], msd_id[3], msd_id[4], msd_id) | 10,734 |
def get_data_path(sub_path):
"""Returns path to file in data folder."""
return join(_data_folder_path, sub_path) | 10,735 |
def read_avro_bytes(URL, open_with, start_byte, length, header, nrows=None):
"""Pass a specific file/bytechunk and convert to dataframe with cyavro
Both a python dict version of the header, and the original bytes that
define it, are required. The bytes are prepended to the data, so that the
C avro read... | 10,736 |
def get_launches(method="", **query):
"""Gets launches based on query strings
Gets launches based on query strings from
the API
Parameters
----------
method : str (optional)
the method used for the request
query : keyword args
keyword args based on t... | 10,737 |
def save_lang_to_idx(lang_to_idx: dict, ex: Experiment):
"""Saves the lang_to_idx dict as an artifact
Arguments:
lang_to_idx {dict} -- The dict to save in a file
"""
tmpf = tempfile.NamedTemporaryFile(dir="", delete=False, suffix=".pkl")
pickle.dump(lang_to_idx, tmpf)
tmpf.flush()
e... | 10,738 |
def test_fileinrewriterstep_bare_encoding_substitutions():
"""Encoding works with substitutions for bare encoding."""
context = Context({
'enc': 'arbenc',
'root': {'in': 'inpathhere',
'encoding': '{enc}'}})
with patch('pypyr.config.config.default_encoding', 'arb'):
... | 10,739 |
def test_main_load_config_not_present_but_needed(capsys):
"""Command ends indicating the return code to be used."""
cmd = create_command("cmdname", needs_config_=True)
with patch("charmcraft.main.COMMAND_GROUPS", [CommandGroup("title", [cmd])]):
retcode = main(["charmcraft", "cmdname", "--project-di... | 10,740 |
def xrandr_query():
"""
Returns all current available screen resolutions and refresh rate modes as a dictionary.
This method only works with installs X11.
"""
pattern_screens = r'([\w-]+)\s+connected\s+(primary|)?.+\n(\s+[x*+.\d\s]+\n)'
pattern_mode = r'^\s+(\d+)x(\d+)\s+([\d.]+)([ *+]{0,2})'
... | 10,741 |
def state(obj):
"""Gets the UnitOfWork state of a mapped object"""
return obj.__ming__.state | 10,742 |
def save_file_in_path(file_path, content):
"""Write the content in a file
"""
try:
with open(file_path, 'w', encoding="utf-8") as f:
f.write(content)
except Exception as err:
print(err)
return None
return file_path | 10,743 |
def export_entity_for_model_and_options(request):
"""
Export entity list in a list of 'format' type.
@note EntityModelClass.export_list() must return a list of results.
User of the request is used to check for permissions.
"""
limit = int_arg(request.GET.get('limit', 100000))
app_label = re... | 10,744 |
def table(self, name, cluster=None, node=None):
"""Create a table with given name and on specified cluster, if specified.
"""
if node is None:
node = self.context.node
try:
if cluster:
with Given(f"I create table {name}"):
node.query(f"DROP TABLE IF EXISTS {na... | 10,745 |
def gen_instance_hv_map(ann, crop_shape):
"""Input annotation must be of original shape.
The map is calculated only for instances within the crop portion
but based on the original shape in original image.
Perform following operation:
Obtain the horizontal and vertical distance maps for each
nuclear instan... | 10,746 |
def jaccard_loss(true, logits, eps=1e-7):
"""Computes the Jaccard loss, a.k.a the IoU loss.
Note that PyTorch optimizers minimize a loss. In this
case, we would like to maximize the jaccard loss so we
return the negated jaccard loss.
Args:
true: a tensor of shape [B, H, W] or [B, 1, H, W].
... | 10,747 |
def open_inbox():
"""Open currently selected email address at malinator.com."""
try:
selection = list_box.curselection()
slctd_adrs = list_box.get(selection[0])
except IndexError:
messagebox.showerror('Error:', 'Nothing selected')
return
# Remove @malinator.com f... | 10,748 |
def test_dedup_signatures() -> None:
"""Test signature deduplication."""
kp1, kp2 = Keypair(), Keypair()
transfer1 = system_program.transfer(
{"from_pubkey": kp1.pubkey(), "to_pubkey": kp2.pubkey(), "lamports": 123}
)
transfer2 = system_program.transfer(
{"from_pubkey": kp1.pubkey(),... | 10,749 |
def _get_distribution_schema():
""" get the schema for distribution type """
return schemas.load(_DISTRIBUTION_KEY) | 10,750 |
def compute_transforms(rmf_coordinates, mir_coordinates, node=None):
"""Get transforms between RMF and MIR coordinates."""
transforms = {
'rmf_to_mir': nudged.estimate(rmf_coordinates, mir_coordinates),
'mir_to_rmf': nudged.estimate(mir_coordinates, rmf_coordinates)
}
if node:
m... | 10,751 |
def merge_dicts(*list_of_dicts):
"""Merge a list of dictionaries and combine common keys into a list of values.
args:
list_of_dicts: a list of dictionaries. values within the dicts must be lists
dict = {key: [values]}
"""
output = {}
for dikt in list_of_dicts:
for k, v ... | 10,752 |
def highpass_filter(src, size):
"""
highpass_filter(src, size)
ハイパスフィルター
引数
----------
src : AfmImg形式の画像
size : 整数
フィルターのサイズ
戻り値
-------
dst : AfmImg形式の画像
フィルターがかかった画像
"""
def highpass(dft_img_src, *args):
dft_img = dft_img_src.copy()
#マ... | 10,753 |
def parse_target(target):
"""
解析目标为ip格式
:param str target: 待解析的目标
:return tuple scan_ip: 解析后的ip和域名
"""
scan_ip = ''
domain_result = ''
main_domain = ''
try:
url_result = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', target)
if url_result == []:
... | 10,754 |
def isWrappedScalarType(typ: Type) -> bool:
"""
Given a type, determine if it is a c10::scalar which we will wrap in a lazy Value.
Since we literally change the type from scalarT to valueT, information is lost.
This function helps build a list of wrapped scalars to save that information
"""
if i... | 10,755 |
def manual_decision():
""" Display the controls for allowing user to make manual decision """
col1, col2, col3 = st.columns(3)
successfully_posted_manual_dec = None
with col1:
if st.button("Manual Decision: Version A"):
successfully_posted_manual_dec = utils.post_manual_decision('a')... | 10,756 |
def test_hex_binary002_2068_hex_binary002_2068_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : test for simpleType List of hexBinary
"""
assert_bindings(
schema="msData/datatypes/hexBinary002.xsd",
instance="msData/datatypes/hexBinary002.xml",
class_name... | 10,757 |
def assign_topic(data, doc_topic_distr):
""" Assigns dominant topic to documents of corpus.
:param data: DF of preprocessed and filtered text data
:type data: pd.DataFrame
:param doc_topic_distr: Array of topic distribution per doc of corpus
:type doc_topic_distr: np.array
:return: DF incl assi... | 10,758 |
def _enable_scan_single_bytecode(code, name):
"""
Part of the ``_enable_scan`` that applies the scan behavior on a single
given list/set comprehension or generator expression code.
"""
bc = bytecode.Bytecode.from_code(code)
Instr = bytecode.Instr
# Updates LOAD_GLOBAL to LOAD_FAST when arg ... | 10,759 |
def composite_rotation(r, p1=qt.QH([1, 0, 0, 0]), p2=qt.QH([1, 0, 0, 0])):
"""A composite function of next_rotation."""
return next_rotation(next_rotation(r, p1), p2) | 10,760 |
def extract_vectors_ped_feature(residues, conformations, key=None, peds=None, features=None, indexes=False, index_slices=False):
"""
This function allows you to extract information of the ped features from the data structure. In particular allows:
- all rows or a specific subset of them, containing a certai... | 10,761 |
def plot_separate_info_plane_layer_view(MI_object, name, color_l, show_flag, save_flag):
"""
plots information plane separate into different layers
MI_object: mutual information object
name: name of the network
color_l: list of colours for different layers
show_flag:flag that decides if plot sho... | 10,762 |
def Load_File(filename):
"""
Loads a data file
"""
with open(filename) as file:
data = file.readlines()
return data | 10,763 |
def dadd_ru(x, y):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dadd_ru.html
:param x: Argument.
:type x: float64
:param y: Argument.
:type y: float64
:rtype: float64
""" | 10,764 |
def massage_isig_and_dim(isig, im, flag, band, nm, nu, fac=None):
"""Construct a WISE inverse sigma image and add saturation to flag.
unWISE provides nice inverse variance maps. These however have no
contribution from Poisson noise from sources, and so underestimate
the uncertainties dramatically in b... | 10,765 |
def sh(arg):
"""
Execute command in a background shell.
Args:
arg (str or list): shell command, or a list of shell commands.
"""
if isinstance(arg, list):
return [sh(a) for a in arg]
else:
return subprocess.check_output(arg, shell=True).decode("utf-8").strip() | 10,766 |
def uncapitalize(string: str):
"""De-capitalize first character of string
E.g. 'How is Michael doing?' -> 'how is Michael doing?'
"""
if len(string):
return string[0].lower() + string[1:]
return "" | 10,767 |
def _plot_observations_one_time(
valid_time_string, title_string, annotation_string, output_file_name):
"""Plots observations (NARR predictors and WPC fronts) for one valid time.
:param valid_time_string: Valid time (format "yyyy-mm-dd-HH").
:param title_string: Title (will be placed above figure).... | 10,768 |
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(os.path.join(config['database']))
rv.row_factory = sqlite3.Row
return rv | 10,769 |
def _sc_weights_trad(M, M_c, V, N, N0, custom_donor_pool, best_w_pen, verbose=0):
""" Traditional matrix solving. Requires making NxN0 matrices.
"""
#Potentially could be decomposed to not build NxN0 matrix, but the RidgeSolution works fine for that.
sc_weights = np.full((N,N0), 0.)
weight_log_inc =... | 10,770 |
def getargs():
"""Parse command line arguments"""
desc = (
"Analyze and query strace log given the strace log in CSV format "
"(STRACE_CSV). See 'strace2csv.py' for converting strace "
"log to the csv format expected by this tool."
)
epil = "Example: ./%s strace.csv summary" % os... | 10,771 |
def generate_on_message(
test_client: "DiscordTestClient", broker_id: int
) -> Callable[[discord.Message], Awaitable[None]]:
"""
Whenever a message comes in, we want our test client to:
1. Filter the message so we are only getting the ones we want.
2. Store received messages so we can inspe... | 10,772 |
def test_suite():
"""
Construct a TestSuite instance for all test cases.
"""
suite = unittest.TestSuite()
for dt, format, expectation in TEST_CASES:
suite.addTest(create_testcase(dt, format, expectation))
return suite | 10,773 |
def calcScipionScore(modes):
"""Calculate the score from hybrid electron microscopy normal mode analysis (HEMNMA)
[CS14]_ as implemented in the Scipion continuousflex plugin [MH20]_. This score
prioritises modes as a function of mode number and collectivity order.
.. [CS14] Sorzano COS, de la Rosa-Tr... | 10,774 |
def google_base(request):
""" view for Google Base Product feed template; returns XML response """
products = Product.active.all()
template = get_template("marketing/google_base.xml")
xml = template.render(Context(locals()))
return HttpResponse(xml, mimetype="text/xml") | 10,775 |
def get_agivenn_df(run_list, run_list_sep, **kwargs):
"""DF of mean amplitudes conditiontioned on differnet n values."""
n_simulate = kwargs.pop('n_simulate')
adfam_t = kwargs.pop('adfam_t', None)
adaptive = kwargs.pop('adaptive')
n_list = kwargs.pop('n_list', [1, 2, 3])
comb_vals, comb_val_res... | 10,776 |
def friendship_request_list_rejected(request, template_name='friendship/friend/requests_list.html'):
""" View rejected friendship requests """
# friendship_requests = Friend.objects.rejected_requests(request.user)
friendship_requests = FriendshipRequest.objects.filter(rejected__isnull=True)
return rend... | 10,777 |
def send_email_to_managers(subject=None, body=None,
template_prefix=None, vars=None,
cc=None, bcc=None, frm=None,
attachments=None, headers=None,
as_html=True):
"""
Send an email template to the site mana... | 10,778 |
def test_override_video_view_lists_collection_view_lists(
mock_user_moira_lists, request_data, video_permission, video
):
"""
A video with view lists should by viewable by users in those lists but not users in collection view lists,
if video permissions are enabled
"""
video_list = MoiraListFact... | 10,779 |
def test_ep1():
"""
Test against known values.
"""
d = n_mod_m(3, 2)
ep = ExtropyPartition(d)
string = """\
+----------+--------+
| measure | exits |
+----------+--------+
| X[0|1,2] | 0.000 |
| X[1|0,2] | 0.000 |
| X[2|0,1] | 0.000 |
| X[0:1|2] | 0.245 |
| X[0:2|1] | 0.245 |
| X[1:2|0] |... | 10,780 |
def test_basic() -> None:
"""Test rendering a basic schema with title"""
soup = _generate_case("basic")
_assert_basic_case(soup) | 10,781 |
def cycle_ctgo(object_type, related_type, related_ids):
""" indirect relationships between Cycles and Objects mapped to CycleTask """
if object_type == "Cycle":
join_by_source_id = db.session.query(CycleTask.cycle_id) \
.join(Relationship, CycleTask.id == Relationship.source_id) \
.filter(
... | 10,782 |
def Min(axis=-1, keepdims=False):
"""Returns a layer that applies min along one tensor axis.
Args:
axis: Axis along which values are grouped for computing minimum.
keepdims: If `True`, keep the resulting size 1 axis as a separate tensor
axis; else, remove that axis.
"""
return Fn('Min', lambda ... | 10,783 |
def sampling(args):
"""Reparameterization trick by sampling fr an isotropic unit Gaussian.
# Arguments
args (tensor): mean and log of variance of Q(z|X)
# Returns
z (tensor): sampled latent vector
"""
z_mean, z_log_var = args
batch = K.shape(z_mean)[0]
dim = K.int_shape(z_me... | 10,784 |
def test_file_sdf_gz(input_sdf):
"""Read a compressed sdf file."""
# without properties
df = load.file(f"{input_sdf}.gz", keep_props=False, in_id='_Name', out_id='idm')
assert len(df.index) == 5
assert list(df.columns.values) == ['idm', 'mol']
assert isinstance(df.iloc[0]['mol'], Mol) | 10,785 |
def get_expression_arg_names(expression, strip_dots=True):
"""
Parse expression and return set of all argument names. For arguments
with attribute-like syntax (e.g. materials), if `strip_dots` is
True, only base argument names are returned.
"""
args = ','.join(aux.args for aux in parse_definitio... | 10,786 |
def ORDER_CTIME(path: Path) -> int:
"""パスのソート用関数です。作成日時でソートを行います。
"""
return path.stat().st_ctime_ns | 10,787 |
def format_location(data, year):
""" Format any spatial data. Does nothing yet.
Parameters
----------
data : pd.DataFrame
Data before location formatting.
Returns
-------
data : pd.DataFrame
Data with location formatting.
"""
# No spatial data yet so does nothing.
... | 10,788 |
def deploy_ingestion_service(
featureset: Union[FeatureSet, str],
source: DataSource = None,
targets: List[DataTargetBase] = None,
name: str = None,
run_config: RunConfig = None,
):
"""Start real-time ingestion service using nuclio function
Deploy a real-time function implementing feature i... | 10,789 |
def add_user(email, passwd, admin):
"""adiciona novo usuario"""
# TODO(RichardOkubo): Tratar 'exception' caso 'user' já exista
user = create_user(email=email, password=passwd, admin=admin)
click.echo(f"Usuário {email} criado com sucesso!") | 10,790 |
def create_app(service: Service):
"""Start a small webserver with the Service."""
app = FastAPI()
@app.post("/query")
def query(params: Params):
"""The main query endpoint."""
return service.query(**params.query, n_neighbors=params.n_neighbors)
return app | 10,791 |
def test_user_relationship_api():
""" Test to check that user relationship API is not throwing
an index out of range error if user dont have any manager.
Creates a test user without manager and calls the user
relationship api for testing whether it is causing any
index out of range ... | 10,792 |
def cnn_prediction(index, prefix, output_prefix, model, dataset):
""" CNN predictions.
Run the CNN on a file and generate the output file but do not
process the file with the template matching code.
"""
logger = logging.getLogger(__name__)
logger.info("making predictions.")
start_time = t... | 10,793 |
def establecer_dominio(func_dist: Expr) -> dict:
"""Establece el dominio a partir de una FD.
Parameters
----------
func_dist
Distribución de probabilidad
Returns
-------
dict
Dominio
"""
equations = func_dist.atoms(Eq)
orders = func_dist.atoms(Rel) - equations
... | 10,794 |
def test_check_paths(var_file, input_file, output_file):
"""Test that check_paths works as expected."""
check_paths(variables=var_file, input=input_file, output=output_file) | 10,795 |
def random_init(n, max_norm):
"""Computes a random initial configuration of n 2D-vectors such that they all
are inside of a circle of radius max_norm
Parameters
----------
n : int
Number of vectors
max_norm : float or int
Radius of the circle or maximum possible distance from the ... | 10,796 |
def calc_cells(serial: int) -> Dict[Tuple[int, int], int]:
"""Calculate the power for all cells
and store them in a dict to retrieve them faster later
"""
r = {}
for i in range(300):
for j in range(300):
r.update({(i, j): calc_power((i, j), serial)})
return r | 10,797 |
def check_img(img, input_dir):
""" Checks whether the img complies with API`s restrictions.
Parameters
----------
img : str
Image name.
input_dir : str
Path to the dir with the image to check.
Returns
-------
Error message if image does not comply with A... | 10,798 |
def child_files_recursive(root: Union[str, pathlib.Path], ext: str) -> List[str]:
"""
Get all files with a specific extension nested under a root directory.
Parameters
----------
root : pathlib.Path or str
root directory
ext : str
file extension
Returns
-------
List... | 10,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.