content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def parse_rnh_cdl(input_file):
"""Parses a space separated .cdl file for ASC CDL information.
**Args:**
input_file : (str)
The filepath to the CDL
**Returns:**
(:class:`ColorCorrection`)
The single ColorCorrection object retrieved from the beta CDL
... | 84b3b0f5bb17714c13139c4279ec4f6bd5412983 | 56,600 |
from masci_tools.util.schema_dict_util import eval_simple_xpath
from masci_tools.util.xml.converters import convert_to_xml
import numpy as np
from typing import Union
from typing import Iterable
from typing import Tuple
def set_kpointlist_max4(xmltree: Union[etree._Element, etree._ElementTree], schema_dict: 'fleur_sc... | bba037a7db41eae8663a85b8a44cfecca3f8d300 | 56,601 |
def RunSSHCmd(username, host, port, command, echo=True, options=None):
""" Login to the given host and run the given command.
username: ssh login name
host: hostname or ip address of the server
port: port on the server to use
command: (string) command to run on the server
options: list of extra options to ... | 5fb41e816afe1153c011185d0490c0b2c21b728d | 56,602 |
from typing import Tuple
async def infer_type_head(engine, tup):
"""Infer the return type of head."""
tup_t = await tup['type']
if not isinstance(tup_t, Tuple):
raise MyiaTypeError('head of non-tuple')
if not len(tup_t.elements) >= 1:
raise MyiaTypeError('head on empty tuple')
retu... | e3933541d3e36647affacb8510f5665a3518b49b | 56,603 |
def has_large_adenoma_precise(pm: PathManager, cm: CspyManager, min_size=10):
"""
Adds option of 'maybe'
WARNING: Logic will break down if >= 3 jars with the same location
:param pm:
:param cm:
:param min_size:
:return: 1=large adenoma, 0=no large adenoma, 9=maybe large adenoma
"""
... | ea4f469ed42ce964690f6f13ea287b9602bf0873 | 56,604 |
import os
def send_cssimages(path):
"""
Serve static CSS images files
"""
return flask.send_from_directory(os.path.join(static_folder,
'css', 'images'), path) | 21cadd42c10f9841fc79743850999ee0697373f0 | 56,605 |
def detail_url(recipe_id):
"""return detail url for a recipe"""
return reverse('recipe:recipe-detail', args=[recipe_id]) | 3ba1a75fd93326a4d25cb28a1b0e9efb305446c0 | 56,606 |
from typing import Callable
from typing import List
def create_track(track_func: Callable, distance: int,
frames: int = 100) -> List[int]:
"""創建軌跡
:param track_func: 所采用的轨迹函數
:param distance: 所要移動的距離
:param seconds: 操作執行時間
:param frames: 幀數
:param noice_func: 噪声函数, 计算的结果会叠加在轨迹... | 94a2b68540d4fe28e53e89594b1be22dc0c2ad5d | 56,607 |
def map_nested(f, itr):
"""apply a function to every element in a 2D nested array"""
return [[f(pt)
for pt in lst]
for lst in itr] | 6546781478ef0f1b53a257c3571a56dd77942014 | 56,608 |
def findmatch(x,
y,
xsearch,
ysearch,
dtol=4,
silent=0,
returndist=0,
xsorted=0):
"""FINDS AN OBJECT GIVEN A LIST OF POSITIONS AND SEARCH COORDINATE
RETURNS INDEX OF THE OBJECT OR n IF NOT FOUND"""
n = len(x)
... | 4833db9e7f54d5f009c24683f94e10ea3d3077dc | 56,609 |
def resource_from_collection(collection, name, child_resource):
"""Return a child resource from a collection by name. If no item is found,
return ErrorResource.
"""
item = collection.get_by_name(name)
if item is None:
return ErrorResource("Cannot find child '%s'" % name)
return child_re... | b822afea4526e084149fb6cd826d08bdd23a0c67 | 56,610 |
import tqdm
def get_positional_dataset_from_file(tokenizer, data):
"""
with open(file, 'rb') as f:
data = pickle.load(f)
"""
truncated_sequences = 0
for inst in tqdm(data):
tokenized_para = tokenizer.tokenize(inst['paragraph'])
tokenized_question = tokenizer.tokenize(inst['... | c58cde79dbca2340c33d9263142b82b3c8ee4cf0 | 56,611 |
import jinja2
def javascript_pack(*names, **kwargs):
"""
TODO: refactor
"""
tags = []
for name in names:
sub_tags = utils.get_as_tags(
name, extension="js", attrs=kwargs.get("attrs", "")
)
for sub_tag in sub_tags:
if sub_tag not in tags:
... | 6cbdae852c416b7d882d44f76955ff37edc6725e | 56,612 |
import sys
def horizontal_shift(dh,slope,aspect,plot=False, min_count=30):
"""
Compute the horizontal shift between 2 DEMs using the method presented in Nuth & Kaab 2011
Inputs :
- dh : array, elevation difference master_dem - slave_dem
- slope/aspect : array, slope and aspect for the same locatio... | 65992209375aa8ee04c4e49d6588bbae95c9d2b7 | 56,613 |
import os
def map_list_for_region(region):
"""returns a list of absolute paths to chart files for queried region"""
provider = _db.provider_for_region(region)
region = region.upper()
if _db.provider_has_region(provider, region):
if provider == provider_noaa:
reader = NoaaXmlReader(... | abdeb3f7102205b6c138d5b1e342fe1d3414b003 | 56,614 |
def inference(images_placeholder, keep_prob):
""""AIの学習モデル部分(ニューラルネットワーク)を作成する."""
def weight_variable(shape):
"""重みを標準偏差0.1の正規分布で初期化する."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
"""バイアスを標準偏差0.1の正規分布で初期化する."""
... | 220bd41ee60deb8b04a5f80cdaf89974c26396c5 | 56,615 |
def read_pickle(file_path: str, **kwargs):
"""
Returns functions to read any python object stored as a pickle file
Args:
file_path: file path to be loaded.
**kwargs: any other argument given to pandas.read_pickle
Returns:
"""
return lambda: pd.read_pickle(file_path, **kwargs) | 5dd9f52d694173d5feec0cd019ae93fdc6fa8781 | 56,616 |
def test_metrics_node(dcos_api_session):
"""Test that the '/system/v1/metrics/v0/node' endpoint returns the expected
metrics and metric metadata.
"""
def expected_datapoint_response(response):
"""Enure that the "node" endpoint returns a "datapoints" dict.
"""
assert 'datapoints' ... | 9d53978eeb3df874181a6081b3456dc85f1ab014 | 56,617 |
def valid_privkey(privkey):
"""Is valid RSA private key?
:param str privkey: Private key file contents in PEM
:returns: Validity of private key.
:rtype: bool
"""
try:
return OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM, privkey).check()
except (TypeError... | f5214da44c645fc31b32784eef1f31df6bb25080 | 56,618 |
def generate_data_model(data_type, verbose=False):
"""Load data model and sample info data"""
tcga_data = TCGADataModel(training_data=data_type,
test=True, verbose=verbose)
sample_info_df = du.load_sample_info(train_data_type=data_type,
... | 34505a05b87145c2a9f07ea4e469659e2f2f15f1 | 56,619 |
def pollard_rho(
num: int,
seed: int = 2,
step: int = 1,
attempts: int = 3,
) -> int | None:
"""
Use Pollard's Rho algorithm to return a nontrivial factor of ``num``.
The returned factor may be composite and require further factorization.
If the algorithm will return None if it fails to ... | 6089d12f22c4d5bfb4f306485d7dc028d7e1a2ff | 56,620 |
def concat(old_data, add_data):
"""input: 2d ndarray or pandas dataframe
newest first
"""
if not isinstance(old_data, pd.DataFrame):
if old_data.size == 0:
return add_data
if add_data.size == 0:
return old_data
overlap = np.argwhere(old_data[:, 0] == add_d... | 08107d49004370e0936f2250321df99f6ddb1305 | 56,621 |
def process_template_file(self, request, template_file, variable_encoding = None):
"""
Processes the given template file, using the given
variable encoding.
:type request: Request
:param request: The request to be used in the template
file processing.
:type template_file: Template
:para... | 036f28e44008f97498cbd5dcc756ee795f1c6d30 | 56,622 |
import re
def is_indvar(expr):
"""
An individual variable must be a single lowercase character other than 'e', 't', 'n', 's',
followed by zero or more digits.
@param expr: C{str}
@return: C{boolean} True if expr is of the correct form
"""
assert isinstance(expr, str), "%s is not a st... | c00e62199263214596a0b9519868ffdeb86e9580 | 56,623 |
def sample_gp_function(kernel, bounds, num_samples, noise_var,
interpolation='linear', mean_function=None):
"""
Sample a function from a gp with corresponding kernel within its bounds.
Parameters
----------
kernel: instance of GPy.kern.*
bounds: list of tuples
[(x... | 1466ed48105f6a3fe3622e912c230e7dd2e94614 | 56,624 |
def makeFileDataset(datasetType, dataId, filename):
""" Make a new FileDataset.
Args:
datasetType (lsst.daf.butler.DatasetType): The DatasetType object.
dataId (dict): The dataId.
filename (str): The filename.
Returns:
lsst.daf.butler.FileDataset: The FileDataset object.
... | e470f319f6a310fba1128d9b4a544255cbfbc8dd | 56,625 |
def bokeh_heatmap_cat(data, x_label, y_label, grid_column='zz'):
"""
Plot heatmap for categorical values (resolution defined by number of choices)
Grid-values are the values being filled in the headt-map rectangles
Parameters
----------
data: pandas.Dataframe
dataframe
x_label, y_la... | 55d9a4a2466568d35964c97367db242c3f89d25a | 56,626 |
def validate_sample_for_sampleSet(
queryDict, samplesetitem_label=_SampleSetItem.verbose_name
):
"""
basic validation of sample attributes for sample set item creation/update
return a boolean isValid and a list of text error messages
"""
errors = []
if not queryDict:
return (
... | 15f2a9f6a67cfbc10f488d8837bf39d313b9a74f | 56,627 |
from typing import Type
from typing import Callable
from typing import Sequence
from typing import Any
def polars_type_to_constructor(
dtype: Type[DataType],
) -> Callable[[str, Sequence[Any], bool], "PySeries"]:
"""
Get the right PySeries constructor for the given Polars dtype.
"""
try:
r... | 13a5128acd666c9e89b88c527986aaa57b91763a | 56,628 |
def cresci_genuine_accounts_users():
"""Load genuine_accounts/users.csv from cresci-2017"""
return CresciUserDataset(GENUINE_ACCOUNT_USER_PATH) | 86062d35f9af57f20ba1457dd164c67f24f82a98 | 56,629 |
import os
import configparser
import pytz
from datetime import datetime
import glob
import json
import requests
def getApi(apiName, url):
"""保存されているデータが古い、またはデータが存在しない場合、指定されたURL(エンドポイント)にアクセスし、api-logフォルダにJSON形式で保存し、読み込みます。
データが存在する場合はすでにあるデータを読み込みます。
いずれの場合もJSONの内容がdict化されて返されます。
引数`apiName`に`sale`、... | 8184ef98f3e61ba7fa8e099d7f8cff9a67e5b71d | 56,630 |
import six
def convert_ldap_result(ldap_result):
"""Convert LDAP search result to Python types used by OpenStack.
Each result tuple is of the form (dn, attrs), where dn is a string
containing the DN (distinguished name) of the entry, and attrs is
a dictionary containing the attributes associated with... | d1ca896f3cee22bcee5ff0a55bd7cbd164a5d221 | 56,631 |
def safe_iteritems(items):
"""Safely iterate over a dict or a list."""
# For dictionaries, iterate over key, value and for lists iterate over
# index, item
if hasattr(items, 'items'):
return _compat.iteritems(items)
else:
return enumerate(items) | 7e6ee430412c9b5b067bc28f3b5b6f6a9b36dbec | 56,632 |
import types
def appendStr(obj, st):
"""adds a string onto the __str__ output of an instance"""
def appendedStr(oldStr, st, self):
return oldStr() + st
oldStr = getattr(obj, '__str__', None)
if oldStr is None:
def stringer(s):
return s
oldStr = Functor(stringer, str... | f61994a6f37af3fe51caba1be526ec7a4b63c9fb | 56,633 |
from sys import stderr
from operator import sub
def argument_assignment(code, arg_space = True):
"""
Whitespace around = and the like.
"""
stderr.write('argument_assignment is not very precise; it will match some constructs such as (a,b)=(1,2) ' + \
'as well as any strings or comments; it won\'t break code but ... | d3f48bc76095d8729faca97bb6f59ae94ab99733 | 56,634 |
def get_umls_ticket(apikey=None, AuthClient=AuthClient, tgt=tgt):
"""
Get a single use ticket for the UMLS REST services.
It is supposed that an Author Client and a Ticket
Granting Service have already been set-up in case
the apikey = None. If an api-key is given, create the
above needed instanc... | 626ad36efed98bec4069b5d442aebaddfdd2ec23 | 56,635 |
import sys
def compare( value1, value2, epsilonFactor = 0 ) :
"""
This function compares two floats (or objects that can be converted to floats) in a fuzzy way
where the fuzz factor is epsilonFactor * sys.float_info.epsilon. This function returns
0 if the floats are comparable as given... | 2cb563f4785280c6827d321d98406dbb3c17cc43 | 56,636 |
def init_float64_multiarray(rows,columns):
"""!
Function that initializes a Float64MultiArray of size rows x columns.
@param rows: Number of rows of the returned multiarray.
@param columns: Number of columns of the returned multiarray.
@return empty Float64MultiArray instance.
"""
a = Float6... | 0480b8d3b86daea2f0d6b31e08f953c751d2598d | 56,637 |
from pathlib import Path
def _render_to_excel(doc: Document, file_name: Path) -> None:
"""WARN: This is untested."""
workbook = Workbook(str(file_name))
worksheet = workbook.add_worksheet()
row_index = 0
def next_row() -> int:
nonlocal row_index
res = row_index
row_index ... | 5edcebbcbaa2289957930d8d7a25e51b318f2f4d | 56,638 |
def partition(pred, iterable):
"""Use a predicate to partition entries into false entries and true entries.
:param pred: the predicate that divides the values
:param iterable: source of values
"""
# partition(lambda x: x % 2, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = it.tee(iterable)
... | 697173c169e5a8f42e3c7c361e01ea6f73b4ee3a | 56,639 |
def reset():
"""
Inserts the escape sequence of display reeet.
Returns
-------
seq : str
Escape sequence of display reeet.
"""
return display_reset() | 23094814ece1c551052179be1a837de761060444 | 56,640 |
def steffen_3d(
v_in,
z_in,
z_out,
z_min_surface,
z_max_surface,
lower_extrapolation_with_gradient=False,
upper_extrapolation_with_gradient=False,
):
"""
Performs Steffen interpolation on each individual column.
Steffen, M. (1990). A simple method for monotonic interpolation
... | 84733cbbf1075632cbeaa09a4e5f9872f53288c2 | 56,641 |
def _compute_attention(attention_mechanism, cell_output, attention_state,
attention_layer):
"""Computes the attention and alignments for a given attention_mechanism."""
alignments, next_attention_state = attention_mechanism(
cell_output, state=attention_state)
# Context is the inner ... | 37782abd6eb7d66eaa545e63f3203ee0440b1a2a | 56,642 |
import re
def clean_scenarios(row) -> pd.Series:
"""Helper function to extract select scenario details for final comparison plots."""
row = str(row)
sel_col = re.search(pattern="^s.*([13])", string=row).group(1) if re.match(pattern="^s.*([13])", string=row) else nan
pos_col = re.search(pattern="^s.*[1... | e346423b1bbec5d7f0db730a5f80fc62189b79b8 | 56,643 |
def GetNumRedisServers(redis_vm: _LinuxVirtualMachine) -> int:
"""Get the number of redis servers to install/use for this test."""
if FLAGS.num_cpus_override:
return FLAGS.num_cpus_override * _NUM_PROCESSES.value
return redis_vm.NumCpusForBenchmark() * _NUM_PROCESSES.value | 44b5561d9ab0ca4456fcdde2179d2e08589aeb06 | 56,644 |
import os
def getFileNames(event, client=None):
"""Return files for given DAS query"""
if client == 'das_client':
return getFileNames_das_client(event)
elif client == 'dasgoclient':
return getFileNames_dasgoclient(event)
# default action
for path in os.getenv('PATH').split(':'):
... | cd787a9676c5617b7cdd85b8e32c4d5a661931d9 | 56,645 |
def plot_evlossdistr(lossSamples, meanloss):
"""Plot historgram of the loss summary"""
ax = lossSamples.hist(cumulative=True, bins=len(lossSamples))
ax.vlines(lossSamples.median(), ymin=0, ymax=100, label="Sample Median")
ax.vlines(lossSamples.mean(), linestyles='dashed', ymin=0, ymax=100,
... | 6a665aa0a5d35422cb6e19ba66cca6667e76b620 | 56,646 |
import json
def main(vk_file, proof_file):
"""Verifies the proof.json using the vk.json"""
with open(vk_file, 'r') as vk_handle:
vk = VerifyingKey.from_dict(json.load(vk_handle))
with open(proof_file, 'r') as proof_handle:
proof = Proof.from_dict(json.load(proof_handle))
if not vk.veri... | 37ce16aec16698d4b37cffcbaf6f0e21429999f1 | 56,647 |
import os
def expand_all(filename):
"""
Expands ~ and ${ENV} in the string.
Raises DTConfigException if some environment variables
are not expanded.
"""
fn = filename
fn = os.path.expanduser(fn)
fn = os.path.expandvars(fn)
if '$' in fn:
msg = ... | df42d125f33c2652d03652b22419459350c1ba0d | 56,648 |
def reduce_opacity(im, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alph... | 662bcc4b6d68a87af07634ca464ed605a6c29846 | 56,649 |
import re
def crawllogs_to_df(logs_file_path):
"""Convert a crawl logs file to a DataFrame.
An interesting option while using the ``crawl`` function, is to specify a
destination file to save the logs of the crawl process itself. This contains
additional information about each crawled, scraped, blocke... | 53771cf36a0b9a47a95fafb0e1ef8bd4791c141a | 56,650 |
def centerImageFile(infile, outfile=None, targetRadius=None):
"""
Center the given image file on a target and save it to outfile, if given.
Returns x,y,foundRadius
"""
im = cv2.imread(infile, cv2.IMREAD_GRAYSCALE)
# find the bounding box of biggest object
# either a blob or a circle
bo... | fc3a3cbd407a4a0f67225c71a4c078f08c883055 | 56,651 |
def get_data(data):
"""Gets the section data payload from the given section data
Parses the given array of section data bytes and returns the section data. This is an array of data bytes.
It can be further parsed based on the type of section.
"""
offset = 3
sl = get_section_length(data)
data_len = sl
if get_... | 710edd4d2fb1f4295bc69fb751a42bc765749111 | 56,652 |
def uniq_count(data):
"""
Count number of unique elements in the data.
Args:
data (list): values.
Returns the number of unique elements in the data.
"""
uniq_atom_list = list(set(data))
return len(uniq_atom_list) | d61eff27aed7d788fa6cc80eb25661f0ebae7dfd | 56,653 |
def parse_output_minimap2(output, id):
"""
:param output: minimap2 stdout
:type output: io.TextIOBase or io.StringIO
:rtype: list[Alignment]
"""
alignments = []
for line in output:
split_line = line.rstrip().split("\t")
query_name = split_line[0]
query_len = int(spl... | 7450a3bd33f3d36e320115bf9339f690f8e22317 | 56,654 |
def try_float(x):
"""
Convert to float
:param x:
:return:
"""
if x is None:
return None
try:
return try_float(x)
except:
pass | 905b1cdedc086a2f6f6572bb720b9d04ef1aa2b6 | 56,655 |
def isBGS_colors(rfiberflux=None, gflux=None, rflux=None, zflux=None, w1flux=None, rfibertotflux=None,
maskbits=None, south=True, targtype=None, primary=None):
"""Standard set of color-based cuts used by all BGS target selection classes
(see, e.g., :func:`~desitarget.cuts.isBGS` for parameters)... | 0fc72308f9f9fd1383c5279beca1c7dac7c2bf3d | 56,656 |
def SubPhase( Fin, Phi):
"""
*Substitutes a given phase distribution in the field with.*
:param Phi: N x N square array of real numbers or scalar
:type Phi: numpy.ndarray, int, float
:return: output field (N x N square array of complex numbers).
:rtype: `LightPipes.field.Field`
:Exampl... | a341f27bb828a4eb8215c0028f8278e83188ab53 | 56,657 |
def void_ptrptr_generator(*args):
"""void_ptrptr_generator() -> void"""
return _cv.void_ptrptr_generator(*args) | b306bd1cd636ab205bec6cf1fa6903ec2258fe72 | 56,658 |
def get_e_b2(Theta_ex_Ave, L_BB_DHW_b2, f_hs):
"""浴槽自動湯はり時における日平均給湯機効率 (3e)
Args:
Theta_ex_Ave(ndarray): 日平均外気温度 (℃)
L_BB_DHW_b2(ndarray): 1日当たりの浴槽水栓湯はり時におけるバックアップボイラーが分担する給湯熱負荷
f_hs(float): 当該給湯機に対する効率の補正係数
Returns:
ndarray: 浴槽自動湯はり時における日平均給湯機効率
"""
# 日平均給湯機効率を計算するための回帰係数... | cbef9b2c5437083decb33db9bafb853fd42afb22 | 56,659 |
import pickle
def load_dt(filename):
"""
加载保存好的决策树
:param filename: 文件名
:return: python dict
"""
# 'b' 表示二进制模式
fr = open(filename, 'rb')
return pickle.load(fr) | c61772d6c8606e45ef323bd8dd30cb0c9e6ebf35 | 56,660 |
def compute_graham_scan( planars ):
"""
Attempt to clean the data,
and simplify it to an approximate shape
by returning the list of corners
corresponding to the convex hull of the
given points.
It attempts this using the Graham Scan
"""
return graham_scan.convex_hull( planars ) | 5c1ea0311be6baa9f76143ace1e71148a5dd5a4f | 56,661 |
import argparse
def parse_arguments():
"""
Parses the command-line arguments passed to the assembler.
"""
parser = argparse.ArgumentParser(
description="File listing and editing utility. See README.md for more "
"information, and LICENSE for terms of use."
)
parser.add_argument... | 264a9b2c9a608d3a63704881d449d82f6a556565 | 56,662 |
def hartmann3_by_2_1_01(x):
""" Summing two Hartmann3 functions to get a 6D function. """
return hartmann3_01([x[0], x[4], x[2]]) + hartmann3_01([x[3], x[1], x[5]]) | 3bac0289a7c18cb82cde87b79befdf70318df427 | 56,663 |
def bbox_to_segmentation(image, bbox, matter=None, seg_type='rle', mask_type='gaussian'):
"""
:param image: ndarry, (img_h, img_w, 3)
:param bbox: [int], x, y, w ,h
:param seg_type: 'rle', 'poly'
:param mask_type: 'gaussian', 'bbox', 'butterfly'
:param matting: bool, whether to mat the mask or ... | ee17d6eeedcc9219a3b69de9339ed6955c1754e5 | 56,664 |
def _get_feature_by_index(x, p_h, p_w):
"""gather feature by specified index"""
# x (n, c, h_in, w_in)
# p_h (n, h, w, k*k)
# p_w (n, h, w, k*k)
n, c, h_in, w_in = x.shape
_, h, w, k2 = p_h.shape
# (n, c, h_in, w_in) -> (n, h_in, w_in, c)
x = x.transpose(0, 2, 3, 1)
# the following... | 4c1b52935c88a5f7531c1ee00c469db10bca8b3a | 56,665 |
import subprocess
def create_worker_credentials(itype, max_run_time):
"""
Create worker node credentials
"""
root_ca = prepare_credential_content(CONFIG.get('credentials', 'root-ca'), itype)
signing_policy = prepare_credential_content(CONFIG.get('credentials', 'signing-policy'), itype)
mapfile... | 4c4d2603cac29a5f3a0b9809a23daadc8d8d5387 | 56,666 |
import argparse
def setup_parser() -> argparse.ArgumentParser:
"""
Loads the parser.
"""
# Main parser
parser = argparse.ArgumentParser()
parser.add_argument("--version", action="version", version=__version__)
# Required flags
parser.add_argument(
"--mpileup",
action="a... | 7ecb36b884633722d1f3a19d09506ef3fec66bf3 | 56,667 |
def parse_params(param_str, case_sensitive = False):
"""
parse_params(param_str, case_sensitive = False) -> a map of parameters
Parse parameter from given string. The string follows a format like
below:
param1=value1,param2=value2,...
We support escape token '\\' to escape "," and "=".
... | e43cf824fb232cba9ea3be53d50394d6a1cac08d | 56,668 |
import sys
import inspect
import os
import sympy
def linkcode_resolve(domain, info):
"""Determine the URL corresponding to Python object."""
if domain != 'py':
return
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
ret... | 27c3dccfeadaa940025a0cee936859d8cb0c708b | 56,669 |
def extract_top_level_dict(current_dict):
"""
Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params
:param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree.
:param value: Param value
:... | 52fd9592b514a925279e1a0ae64ebc6b62ab5d20 | 56,670 |
from pathlib import Path
import re
def extract_dependence():
"""
get all dockerfile dependence
"""
dockerfiles = Path("../").walkfiles("Dockerfile*")
dep_graph = {}
for i in dockerfiles:
with open(i, "r") as f:
match = re.search(r"FROM (.*):", f.readline().rstrip())
... | 666d9c0ae107f9b68b51ed03a81ed5c3d776a83f | 56,671 |
def getCoordonneesJoueur(plateau,numJoueur):
"""
retourne les coordonnées sous la forme (lig,col) du joueur passé en paramètre
paramètres: plateau: le plateau considéré
numJoueur: le numéro du joueur à trouver
resultat: un couple d'entier donnant les coordonnées du joueur ou None si
... | d3a4b88609df803850266097235fbdd852329c60 | 56,672 |
import subprocess
def PackageInstalled(pkg_name, compare_version=True):
"""Check if the package is installed or not.
This method will validate that the specified package is installed
(via apt cache policy) and check if the installed version is up-to-date.
Args:
pkg_name: String, the package ... | 5aaa4f333c1739d85f0547212d512bdab7326776 | 56,673 |
def wrap(tensor, is_stacked=True, is_sparse_stacked=False):
"""Helper to create a WrappedTensor object."""
assert isinstance(is_stacked, bool)
assert isinstance(is_sparse_stacked, bool)
assert isinstance(tensor, ops.Tensor)
assert not is_sparse_stacked or is_stacked, ("If the wrapped tensor is "
... | 4438fd9fa6ea7f3ede2b928d800597061b35acf6 | 56,674 |
def v_ext(x):
"""Ground-state external potential
"""
return 0.5*(0.25**2)*(x**2) | ea4f5f835ed99451a518c19e0e5accb84c576693 | 56,675 |
def _rrv_rdiv_ ( s , o ) :
"""(right) Division of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = num / var
"""
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , 'getVal' ) : o = o.getVal ()
#... | a21101e430b00a1d634a1c0ebc0fb0bc8bf7cc1a | 56,676 |
from typing import MutableSequence
from typing import Any
def swap(seq: MutableSequence[Any], frst_idx: int, snd_idx: int) -> MutableSequence[Any]:
"""Swaps two elements in the `seq`."""
if seq[frst_idx] == seq[snd_idx]:
return seq
seq[frst_idx], seq[snd_idx] = seq[snd_idx], seq[frst_idx]
retu... | 1d4c3260e57f827293d849b490bd35c2ae9f9698 | 56,677 |
import os
import re
import ast
def _astroid_parse_setup(path: str) -> list:
""" Extract requirements out of the setup call in a setup.py
If for som reason several setup calls are present,
their requirements are concatenated
:param path: Full path to the location of a setup.py file.
:returns: ... | 539b6f018a2671643261338cf64e74268c9f0239 | 56,678 |
def app_factory(global_config, **local_conf):
""" This function is defined as a `paste.app_factory` entry point in
`./setup.py` and is called with configuration settings by::
paster serve config.ini
"""
# merge the global and local config
config = global_config
con... | 6cfa012160543c522a168dde2a0f48c861be147c | 56,679 |
def get_call_tree(profile_file):
"""
Typical use case, gets all the information regarding the calltree
Parameters
==========
profile_file : str
Name of the ``.cubex`` file
Returns
=======
calltree : CubeTreeNode
A recursive representation of the call tree.
"""
#... | 4c7e8adea238f4e03c26082dc061781237ab512e | 56,680 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
problems = []
i = 0
while i < len(lines):
h, w = map(int, lines[i].split(" "))
problems.append((w, h, lines[i + 1:i + h + 1]))
i += h + 1
return problems | 883a6a7cfaa8104c171a6e166fcbb8f4403f4c01 | 56,681 |
import argparse
import sys
def get_args():
""" Get args """
parser = argparse.ArgumentParser(description='Head program',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n',
'--num',
help = 'Nu... | 9b00939d776baa70fbe0f26df698258b1dbca4a1 | 56,682 |
def home(request):
"""Search page for Organisation Unit / Default page."""
try:
orgs = get_list_types()
if request.method == 'POST':
form = FormRegistry(data=request.POST)
search_string = request.POST.get('org_unit_name')
org_type = request.POST.get('org_type'... | d6db7bf59e0f11480981c906bc2eb5aab0b1a919 | 56,683 |
import json
def _InternalRequest(connection_policy, request_options, request_body):
"""Makes one http request.
:Parameters:
- `connection_policy`: documents.ConnectionPolicy
- `request_options`: dict
- `request_body`: str, unicode or Non
:Returns:
tuple of (result, header... | bb914f6c293c08585c80f22b178b413618f84c74 | 56,684 |
def create_c2_arena(target_path, arena_name, max_reward=5, time=250,
max_num_good_goals=1, is_train=False):
"""
Create .yaml file for C2-type arena.
- Only goals.
- Different random size for all goals.
- At least one green and one red ball.
Parameters:
... | 7619ccd931a721c57cfa022bd2aeaa5719a29e7a | 56,685 |
def read_input(fpath):
"""
Read a specified file, and return a list of the file's contents
separated by new lines.
Args:
fpath (str): Path of the file to read.
Returns:
list
"""
with open(fpath, 'r') as f:
return f.read().splitlines() | ac10f24d7b5769ee85b3f13f3fde278d56ef1741 | 56,686 |
def move_ferry_with_new(instructions: list) -> np.ndarray:
"""Navigate ferry according to new navigation instructions."""
waypoint = np.array([10, 1]) # W/E and N/S directions
position = np.zeros(2, int)
for action, value in instructions:
if action == "F":
position += value * waypoi... | 35bd396e2fbf1856a12ee7cb239505e865efe1b9 | 56,687 |
import tempfile
import os
def make_tempfile():
"""创建临时文件"""
fd, temp_file_name = tempfile.mkstemp()
os.close(fd)
with open(temp_file_name, "w", encoding="utf8") as f:
f.write(lorem)
return temp_file_name | b56110947b78721bf65a43099b9cf77353c62841 | 56,688 |
def ndim(X):
"""Return the number of array dimensions."""
return X.ndim if issparse(X) else np.ndim(X) | 946a52b38534651bf2577174ebe679bf28592247 | 56,689 |
def safe_get(dictionary, key, default_value, can_return_none=True):
"""
Safely perform a dictionary get,
returning the default value if the key is not found.
:param dict dictionary: the dictionary
:param string key: the key
:param variant default_value: the default value to be returned
:par... | eb53ad7a17db3f2c66c8b16b20ae2aac9b1e34e3 | 56,690 |
def sizeof(C_type): # real signature unknown; restored from __doc__
"""
sizeof(C type) -> integer
sizeof(C instance) -> integer
Return the size in bytes of a C instance
"""
return 0 | 8eba27c0e08247dea9188806dcc2eee6b81e2afc | 56,691 |
def computeCostMulti(X, y, theta):
"""
computes the cost of using theta as the parameter for linear
regression to fit the data points in X and y
"""
m = y.size
J = 0.
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular ch... | 99b50b935266001c44b6b0645f73468888c0ba80 | 56,692 |
def process_video(video):
"""Process a video and extract the ball position during each frame
and the corresponding timestamp
Args:
video(cv2.VideoCapture): the video to be processed
Returns:
positions(pandas.DataFrame): a dataframe containing frame timestamp, ball x positio... | 22bb67621cfdc288521dc683589a93ff0dd1145a | 56,693 |
def load_star_file(fil, dic):
"""
Load star counts file into a dictionary.
:param fil: path to STAR counts file to load
:param dic: ``OrderedDict`` to load file to
:returns: updated ``OrderedDict``
"""
reader = get_open_function(fil)
with reader(fil, "rt") as fh:
for line in fh:
... | cf9d697d3012ccda0360ae2c1863cf92aa9f417b | 56,694 |
def parse_grid(grid):
"""
converts a grid like
K F A
L G B
M H C
N I D
O J E
to
ABCDEFGHIJKLMNO
"""
rows = [row.strip().split(" ") for row in grid]
return "".join(rows[row][col] for col in range(2, -1, -1) for row in range(0, 5)) | f1cb825e3d20edd2db92fee4104204e9bcb1f54a | 56,695 |
def DecodeFltZero(x) -> int:
"""Returns the integer representation of 32 bit float zero"""
assert x == 0
return 0 | 69dc1e10dca39b2720d457f049260109a10bd48f | 56,696 |
def check_capthca(param: Param, request: Request):
"""
post 方法示例
- **type**: 类型
- **app_id**: 应用id
"""
type = param.type
app_id = param.app_id
return_dict = ResponseMessage(code=SUCCESS, message=ERR_MSG[SUCCESS], data={'check_status': '1'})
# 日志
log.info('xxx result : {}'.for... | 2b6b292e674a3a218bd68bd7b209a1eb52a1fa5d | 56,697 |
def user_custom_site(request):
"""
用户自定义源名称
"""
site_id = request.POST.get('site_id', '').strip()[:32]
site_name = request.POST.get('site_name', '').strip()[:20]
site_author = request.POST.get('site_author', '').strip()[:20]
user = get_login_user(request)
if user and site_id:
l... | 060c50ff8c353a368228cbaed786699e39294b24 | 56,698 |
def _find_clubs(search_terms):
""" Generate list of clubs matching all search terms.
:param List[str] search_terms: a list of search terms
:return: a list of organizations
:rtype: List[Organization]
"""
clubs = []
for club in get_organizations():
if all([(a in club.name) for a in s... | 26b73ba914fb05a3d269a11b034a640499eea22f | 56,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.