content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_user_missing_username():
"""Exception should be raised due to missing username"""
with pytest.raises(exceptions.MissingCredentialsException) as miserr:
_ = user.User(password="test")
assert "missing" in str(miserr.value) | 5,334,100 |
def sp_integrate_3Dy ( func ,
x , z ,
ymin , ymax , *args , **kwargs ) :
"""Make 1D numerical integration over y-axis
>>> func = ... ## func ( x , y , z )
## x , z , ymin , ymax
>>> print func.sp_integrate_y... | 5,334,101 |
def log_exp_sum_1d(x):
"""
This computes log(exp(x_1) + exp(x_2) + ... + exp(x_n)) as
x* + log(exp(x_1-x*) + exp(x_2-x*) + ... + exp(x_n-x*)), where x* is the
max over all x_i. This can avoid numerical problems.
"""
x_max = x.max()
if isinstance(x, gnp.garray):
return x_max + gnp.l... | 5,334,102 |
def connect_intense_cells(int_cells, conv_buffer):
"""Merge nearby intense cells if they are within a given
convective region search radius.
Parameters
----------
int_cells: (N, M) ndarray
Pixels associated with intense cells.
conv_buffer: integer
Distance to search... | 5,334,103 |
def _encode_decimal(value: Union[Decimal, int, str]):
"""
Encodes decimal into internal format
"""
value = Decimal(value)
exponent = value.as_tuple().exponent
mantissa = int(value.scaleb(-exponent))
return {
'mantissa': mantissa,
'exponent': exponent
} | 5,334,104 |
def add_columns(header, c):
"""
add any missing columns to the samples table
"""
for column in header:
try:
c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column))
except:
pass | 5,334,105 |
def test_valid_incremental_read_with_no_interval(mocker, logger):
"""Tests that an incremental read which doesn't specify a checkpoint interval outputs a STATE message only after fully reading the stream and does
not output any STATE messages during syncing the stream."""
stream_output = [{"k1": "v1"}, {"k2... | 5,334,106 |
def plot_diode_fold(dio_cross,bothfeeds=True,feedtype='l',min_samp=-500,max_samp=7000,legend=True,**kwargs):
"""
Plots the calculated average power and time sampling of ON (red) and
OFF (blue) for a noise diode measurement over the observation time series
"""
#Get full stokes data of ND measurement
... | 5,334,107 |
def jobcard(partcode, path, folder):
"""command for jobcard shortcut"""
shortcut = nav.Jobcard(partcode)
parse_options(shortcut, path, folder) | 5,334,108 |
def getPristineStore(testCase, creator):
"""
Get an Axiom Store which has been created and initialized by C{creator} but
which has been otherwise untouched. If necessary, C{creator} will be
called to make one.
@type testCase: L{twisted.trial.unittest.TestCase}
@type creator: one-argument calla... | 5,334,109 |
def update_origins(origin_list_, champions_list_, origin_counters_):
"""Checks nonzero counters for champions in pool and updates origins by
setting origin counters."""
logging.debug("Function update_origins() called")
origin_counters_value_list = [0] * len(origin_list_)
for i, origin_ in enumerate... | 5,334,110 |
def data_to_CCA(dic, CCA):
"""
Returns a dictionary of ranking details of each CCA
{name:{placeholder:rank}
"""
final_dic = {}
dic_CCA = dic[CCA][0] #the cca sheet
for key, value in dic_CCA.items():
try: #delete all the useless info
del value["Class"]
... | 5,334,111 |
def classify_document(Text=None, EndpointArn=None):
"""
Creates a new document classification request to analyze a single document in real-time, using a previously created and trained custom model and an endpoint.
See also: AWS API Documentation
Exceptions
:example: response = client.class... | 5,334,112 |
def quick_nve(mol, confId=0, step=2000, time_step=None, limit=0.0, shake=False, idx=None, tmp_clear=False,
solver='lammps', solver_path=None, work_dir=None, omp=1, mpi=0, gpu=0, **kwargs):
"""
MD.quick_nve
MD simulation with NVE ensemble
Args:
mol: RDKit Mol object
... | 5,334,113 |
def deg2hms(x):
"""Transform degrees to *hours:minutes:seconds* strings.
Parameters
----------
x : float
The degree value to be written as a sexagesimal string.
Returns
-------
out : str
The input angle written as a sexagesimal string, in the
form, hours:minutes:sec... | 5,334,114 |
async def test_proxy_binding21():
"""
14 None
24 None
24 24
----------
14
? JsComponentA
undefined
? JsComponentA
undefined
"""
# Test multiple sessions, and sharing objects
c1, s1 = launch(JsComponentB)
c2, s2 = launch(JsComponentB)
with c1:
c11 = J... | 5,334,115 |
def get_waveforms_scales(we, templates, channel_locations):
"""
Return scales and x_vector for templates plotting
"""
wf_max = np.max(templates)
wf_min = np.max(templates)
x_chans = np.unique(channel_locations[:, 0])
if x_chans.size > 1:
delta_x = np.min(np.diff(x_chans))
else:
... | 5,334,116 |
def chunk_it(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n] | 5,334,117 |
def rec_findsc(positions, davraddi, davradius='dav', adatom_radius=1.1,
ssamples=1000, return_expositions=True,
print_surf_properties=False, remove_is=True, procs=1):
"""It return the atom site surface(True)/core(Flase) for each atoms in
for each structure pandas dataframe. See m... | 5,334,118 |
async def accept_taa(
controller: AcaPyClient, taa: TAARecord, mechanism: Optional[str] = None
):
"""
Accept the TAA
Parameters:
-----------
controller: AcaPyClient
The aries_cloudcontroller object
TAA:
The TAA object we want to agree to
Returns:
--------
accept... | 5,334,119 |
def setdefault(self, other):
"""
Merge two dictionaries like .update() but don't overwrite values.
:param dict self: updated dict
:param dict other: default values to be inserted
"""
for k, v in other.items():
self.setdefault(k, v) | 5,334,120 |
def discoverYadis(uri):
"""Discover OpenID services for a URI. Tries Yadis and falls back
on old-style <link rel='...'> discovery if Yadis fails.
@param uri: normalized identity URL
@type uri: six.text_type, six.binary_type is deprecated
@return: (claimed_id, services)
@rtype: (six.text_type, ... | 5,334,121 |
def mapper_to_func(map_obj):
"""Converts an object providing a mapping to a callable function"""
map_func = map_obj
if isinstance(map_obj, dict):
map_func = map_obj.get
elif isinstance(map_obj, pd.core.series.Series):
map_func = lambda x: map_obj.loc[x]
return map_func | 5,334,122 |
def int_finder(input_v, tol=1e-6, order='all', tol1=1e-6):
"""
The function computes the scaling factor required to multiply the
given input array to obtain an integer array. The integer array is
returned.
Parameters
----------
input1: numpy.array
input array
tol: float
... | 5,334,123 |
def cell_info_for_active_cells(self, porosity_model="MATRIX_MODEL"):
"""Get list of cell info objects for current case
Arguments:
porosity_model(str): String representing an enum.
must be 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
Returns:
List of **CellInfo** objects
**CellInfo ... | 5,334,124 |
def features(x, encoded):
"""
Given the original images or the encoded images, generate the
features to use for the patch similarity function.
"""
print('start shape',x.shape)
if len(x.shape) == 3:
x = x - np.mean(x,axis=0,keepdims=True)
else:
# count x 100 x 256 x 768
... | 5,334,125 |
def create_processing_log(s_url,s_status=settings.Status.PENDING):
"""
Creates a new crawler processing status. Default status PENDING
:param s_url: str - URL/name of the site
:param s_status: str - The chosen processing status
:return: SiteProcessingLog - The new processing status log
"""
... | 5,334,126 |
def pick_action(action_distribution):
"""action selection by sampling from a multinomial.
Parameters
----------
action_distribution : 1d torch.tensor
action distribution, pi(a|s)
Returns
-------
torch.tensor(int), torch.tensor(float)
sample... | 5,334,127 |
def setMonitoringQuerys():
""" This will set the 'Accepted' Queries to 'Monitoring'
"""
rows = 0
with engine.begin() as conn:
upd = userQuery.update().where(userQuery.c.status=='Accepted').values(
status='Monitoring', message_text='CoWin Hawk is monitoring.',
timestamp=datetime.now())
rows = conn.execut... | 5,334,128 |
def word_tokenizer(text: str) -> List[str]:
"""Tokenize input text splitting into words
Args:
text : Input text
Returns:
Tokenized text
"""
return text.split() | 5,334,129 |
def event_loop():
"""Create an instance of the default event loop for each test case."""
loop = asyncio.new_event_loop()
yield loop
loop.close() | 5,334,130 |
def lookup_bigquery_dataset(project_id, dataset_id):
"""Retrieves Data Catalog entry for the given BigQuery Dataset."""
from google.cloud import datacatalog_v1beta1
datacatalog = datacatalog_v1beta1.DataCatalogClient()
resource_name = '//bigquery.googleapis.com/projects/{}/datasets/{}'\
.forma... | 5,334,131 |
def indicator_structure(Template, LC_instance):
""" given a Template A and a LC instance Sigma
builds the indicator structure of Sigma over A
and passes the identification object """
in_vars, in_cons = LC_instance
# Construct the domain of the indicator by factoring
arities = dict(in_va... | 5,334,132 |
def add_depth_dim(X, y):
"""
Add extra dimension at tail for x only. This is trivial to do in-line.
This is slightly more convenient than writing a labmda.
Args:
X (tf.tensor):
y (tf.tensor):
Returns:
tf.tensor, tf.tensor: X, y tuple, with X having a new trailing dimension.
... | 5,334,133 |
def catch_exceptions(warning_msg="An exception was caught and ignored.", should_catch=True):
"""Decorator that catches exceptions."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not should_catch:
return func(*args, **kwargs)
... | 5,334,134 |
def setSC2p5DAccNodes(lattice, sc_path_length_min, space_charge_calculator, boundary = None):
"""
It will put a set of a space charge SC2p5D_AccNode into the lattice as child nodes of the first level accelerator nodes.
The SC nodes will be inserted at the beginning of a particular part of the first level AccNode ele... | 5,334,135 |
def transmuting_ring_sizes_score(mapping: LigandAtomMapping):
"""Checks if mapping alters a ring size"""
molA = mapping.molA.to_rdkit()
molB = mapping.molB.to_rdkit()
molA_to_molB = mapping.molA_to_molB
def gen_ringdict(mol):
# maps atom idx to ring sizes
ringinfo = mol.GetRingInfo(... | 5,334,136 |
def cmp_policy_objs(pol1, pol2, year_range=None, exclude=None):
"""
Compare parameter values two policy objects.
year_range: years over which to compare values.
exclude: list of parameters to exclude from comparison.
"""
if year_range is not None:
pol1.set_state(year=list(year_r... | 5,334,137 |
def test_translate_six_frames(seq_record):
"""
Given a Biopython sequence record with a DNA (or RNA?) sequence,
translate into amino acid (protein) sequences in six frames.
Returns translations as list of strings.
"""
translation_list = []
for strand, nuc in [(+1, seq_record.seq), (-1, seq_record.... | 5,334,138 |
def from_sequence(seq, partition_size=None, npartitions=None):
""" Create dask from Python sequence
This sequence should be relatively small in memory. Dask Bag works
best when it handles loading your data itself. Commonly we load a
sequence of filenames into a Bag and then use ``.map`` to open them.... | 5,334,139 |
def smooth_trajectory(
df,
bodyparts,
filter_window=3,
order=1,
deriv=0,
save=False,
output_filename=None,
destfolder=None,
):
"""
Smooths the input data which is a multiindex pandas array generated by DeepLabCut as a result of analyzing a video.
Parameters
----------
... | 5,334,140 |
def write_certificate(crt, filename):
"""Write certificate to file using usual PEM encoding.
Args:
X509 obj, certificate
filename: str location to save file
"""
with open(filename, 'wb') as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, crt)) | 5,334,141 |
def _get_instances(consul_host, user):
"""Get all deployed component instances for a given user
Sourced from multiple places to ensure we get a complete list of all
component instances no matter what state they are in.
Args
----
consul_host: (string) host string of Consul
user: (string) us... | 5,334,142 |
async def pool_help(p: 'Player', c: Messageable, msg: Sequence[str]) -> str:
"""Show information of all documented pool commands the player can access."""
prefix = glob.config.command_prefix
cmds = []
for cmd in pool_commands.commands:
if not cmd.doc or not p.priv & cmd.priv:
# no d... | 5,334,143 |
def filter_params(params):
"""Filter the dictionary of params for a Bountysource account.
This is so that the Bountysource access token doesn't float
around in a user_info hash (considering nothing else does that).
"""
whitelist = ['id', 'display_name', 'first_name', 'last_name', 'email', 'avatar_ur... | 5,334,144 |
def build_vocab(tokens, glove_vocab, min_freq):
""" build vocab from tokens and glove words. """
counter = Counter(t for t in tokens)
# if min_freq > 0, use min_freq, otherwise keep all glove words
if min_freq > 0:
v = sorted([t for t in counter if counter.get(t) >= min_freq], key=counter.get, r... | 5,334,145 |
def test046():
"""
check that None instead of dict generates a warning
"""
om = ObjectMeta()
copy: ObjectMeta = om.dup()
copy.annotations = None
warnings = copy.get_type_warnings()
assert len(warnings) == 1, f"{len(warnings)} warnings"
assert warnings[0].cls == ObjectMeta
assert ... | 5,334,146 |
def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Checks the equality of two masked arrays, up to given number odecimals.
The equality is checked elementwise.
"""
def compare(x, y):
"Returns the result of the loose comparison between x and y)."
return ap... | 5,334,147 |
def to_bits_string(value: int) -> str:
"""Converts unsigned value to a bit string with _ separators every nibble."""
if value < 0:
raise ValueError(f'Value is not unsigned: {value!r}')
bits = bin(value)[2:]
rev = bits[::-1]
pieces = []
i = 0
while i < len(rev):
pieces.append(rev[i:i + 4])
i +=... | 5,334,148 |
def enumerate_names_countries():
"""Outputs:
1. Julian Australia
2. Bob Spain
3. PyBites Global
4. Dante Argentina
5. Martin USA
6. Rodolfo Mexico"""
for i in enumerate(zip(names, countries)):
print("{}. {:<10} {}".format(i[0] + 1, i[1]... | 5,334,149 |
def test_channel_opened_notification(node_factory):
"""
Test the 'channel_opened' notification sent at channel funding success.
"""
opts = [{}, {"plugin": os.path.join(os.getcwd(), "tests/plugins/misc_notifications.py")}]
amount = 10**6
l1, l2 = node_factory.line_graph(2, fundchannel=True, funda... | 5,334,150 |
def comp_days_centered(ndays, offset=0):
"""Return days for pre/onset/post composites centered on onset.
Parameters
----------
ndays : int
Number of days to average in each composite.
offset : int, optional
Number of offset days between pre/onset and onset/post
day ranges.
... | 5,334,151 |
def createDatabase(name: str) -> bool:
"""
Creates a database in the format of python. If spaces are in the name, it will be cut off through trim(). Returns true if the database is successfully created.
>>> import coconut
#The database format must always be python, it still supports if name has no .... | 5,334,152 |
def bedgraph_per_gene_ss(genes, bg_plus, bg_minus, bgfile):
"""
bedtools intersect genes with each of bg_plus and bg_minus.
Run separately so that gene coverage is consecutive by strand.
"""
# === split annotation ===
plus_bed = bgfile + '.genes.plus'
minus_bed = bgfile + '.genes.minus'
p = open(plus_bed, 'w')
... | 5,334,153 |
def sort_numbers(numbers: str) -> str:
""" Input is a space-delimited string of numberals from 'zero' to 'nine'.
Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
Return the string with numbers sorted from smallest to largest
>>> sort_numbers('three one... | 5,334,154 |
def linreg_fit_bayes(X, y, **kwargs):
"""
Fit a Bayesian linear regression model.
This is a port of linregFit.m from pmtk3.
:param X: N*D design matrix
:param y: N*1 response vector
"""
pp = preprocessor_create(add_ones=True, standardize_X=False) # default
prior = kwargs['prior'] if '... | 5,334,155 |
def getrv(objwave, objflam, refwave, refflam, maxrv=[-200.,200.], waverange=[-np.inf,np.inf]):
"""
Calculates the rv shift of an object relative to some reference spectrum.
Inputs:
objwave - obj wavelengths, 1d array
objflam - obj flux, 1d array
refwave - ref wavelengths, 1d arr... | 5,334,156 |
def me_show(ctx, verbose):
"""Show my own user information"""
result = ctx.obj['nc'].me()[0]
if verbose >= 1:
print_object(result)
else:
print_object(result, exclude=['APIKey'], only=ctx.obj['show_only']) | 5,334,157 |
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that some hosts may not respond to a ping request even if the host name is valid.
"""
# Ping parameters as function of OS
ping_param = "-n 1" if system_name().lower()=="windows" else "-c 1"
# Pinging
re... | 5,334,158 |
def remove_unpopulated_classes(_df, target_column, threshold):
"""
Removes any row of the df for which the label in target_column appears less
than threshold times in the whole frame (not enough populated classes)
:param df: The dataframe to filter
:param target_column: The target column with labels... | 5,334,159 |
def get_longest_substrings(full_strings):
"""Return a dict of top substrings with hits from a given list of strings.
Args:
full_strings (list[str]): List of strings to test against each other.
Returns:
dict: substrings with their respective frequencies in full_strings.
"""
combos =... | 5,334,160 |
def num_weekdays():
"""
Creates a function which returns the number of weekdays in a pandas.Period, typically for use as the average_weight parameter for other functions.
Returns:
callable: Function accepting a single parameter of type pandas.Period and returning the number of weekdays within this
... | 5,334,161 |
def setup_blast_args(args):
"""Set up the blast args."""
if args['no_filter']:
args['bit_score'] = 0
args['contig_length'] = 0 | 5,334,162 |
def largestSumSubArray(arr,size):
"""
* Kadane's algorithm is used to find the largest possible sum in a contiguous subarray
* The main idea is to find all positive contiguous segments in the array and try to update sum for all positive such
segments if the sum is greater
* We find s... | 5,334,163 |
def print_tohu_version(): # pragma: no cover
"""
Convenience helper function to print the current tohu version.
"""
print(f"Tohu version: {get_versions()['version']}") | 5,334,164 |
def reader_from_file(load_dir: str, **kwargs):
"""
Load a reader from a checkpoint.
Args:
load_dir: folder containing the reader being loaded.
Returns: a reader.
"""
shared_resources = create_shared_resources()
shared_resources.load(os.path.join(load_dir, "shared_resources"))
i... | 5,334,165 |
def add_special_param_to_dependency(
*,
dependency_param: inspect.Parameter,
dependant: Dependant,
) -> bool:
"""Check if param is non field object that should be passed into callable.
Arguments:
dependency_param: param that should be checked.
dependant: dependency which field would... | 5,334,166 |
def getBestStyleFit(c_path, styles_path):
"""
Finds the style that gives the lowest content loss
and saves it.
"""
choices = []
# Create the save path if it doesn't extis
if not os.path.exists(args.save_path):
os.mkdir(args.save_path)
# Go through all styles
for s_path in s... | 5,334,167 |
def mtask_forone_advacc(val_loader, model, criterion, task_name, args, info, epoch=0, writer=None,
comet=None, test_flag=False, test_vis=False, norm='Linf'):
"""
NOTE: test_flag is for the case when we are testing for multiple models, need to return something to be able to plot and analy... | 5,334,168 |
async def ga4gh_info(host: str) -> Dict:
"""Construct the `Beacon` app information dict in GA4GH Discovery format.
:return beacon_info: A dict that contain information about the ``Beacon`` endpoint.
"""
beacon_info = {
# TO DO implement some fallback mechanism for ID
"id": ".".join(reve... | 5,334,169 |
def p_declaracao_funcao(p):
"""declaracao_funcao : tipo cabecalho
| cabecalho
"""
pai = MyNode(name='declaracao_funcao', type='DECLARACAO_FUNCAO')
p[0] = pai
p[1].parent = pai
if len(p) == 3:
p[2].parent = pai | 5,334,170 |
def Random_Forest_Classifier_Circoscrizione(X, y, num_features, cat_features):
"""
Funzione che crea, fitta, testa e ritorna una pipeline con il RFC regressor,
(questa volta in riferimento al problema della classificazione di circoscrizioni)
con alcune caratterstiche autoevidenti da codice
Input: X ... | 5,334,171 |
def get_open_id_connection_providers_data():
"""Generate the OpenID connection providers' data"""
response = client.list_open_id_connect_providers()['OpenIDConnectProviderList']
iam_output['OpenIDConnectProviderList'] = response | 5,334,172 |
def test_jdbc_producer_multischema_multitable(sdc_builder, sdc_executor, database):
"""Test a JDBC Producer in a multischema scenario with different destination tables for each schema. We create 3
schemas with one table for each, with different names. Then we use an EL expressions to insert records according to... | 5,334,173 |
def convert_data_set(data_set, specific_character_set):
""" Convert a DICOM data set to its NIfTI+JSON representation.
"""
result = {}
if odil.registry.SpecificCharacterSet in data_set:
specific_character_set = data_set[odil.registry.SpecificCharacterSet]
for tag, element in data_set.items(... | 5,334,174 |
def test_slice_1():
""" Slice on index, <int> """
ad = AstroData(dataset=TESTFILE)
sub_ad = ad[1]
assert len(sub_ad) == 1 | 5,334,175 |
def log(do):
"""
This function logs events in a CSV. This is important to ensure that repeat
signals don't get blasted from the feed constantly.
""" | 5,334,176 |
def calc_distance(
p1: Location,
p2: Location
) -> float:
"""
Args:
p1 (Location): planet 1 of interest
p2 (Location): planet 1 of interest
"""
if p1.coords.galaxy != p1.coords.galaxy:
distance = 20000 * math.fabs(p2.coords.galaxy - p1.coords.planet)
else:
... | 5,334,177 |
def reset_noise_model():
"""Return test reset noise model"""
noise_model = NoiseModel()
error1 = thermal_relaxation_error(50, 50, 0.1)
noise_model.add_all_qubit_quantum_error(error1, ['u1', 'u2', 'u3'])
error2 = error1.tensor(error1)
noise_model.add_all_qubit_quantum_error(error2, ['cx'])
re... | 5,334,178 |
def parse_to_timestamp(dt_string):
"""Attempts to parse to Timestamp.
Parameters
----------
dt_string: str
Returns
-------
pandas.Timestamp
Raises
------
ValueError
If the string cannot be parsed to timestamp, or parses to null
"""
timestamp = pd.Timestamp(dt_s... | 5,334,179 |
def listen():
"""Start listening to slack channels the Testimonials Turtle bot is in."""
# STOPSHIP: better error handling so an exception doesn't crash the module
client = slackclient.SlackClient(
secrets.slack_testimonials_turtle_api_token)
if not client.rtm_connect():
logging.crit... | 5,334,180 |
def __factor(score, items_sum, item_count):
"""Helper method for the pearson correlation coefficient algorithm."""
return score - items_sum/item_count | 5,334,181 |
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray,
scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]:
"""
Evaluate metric by cross-validation for given estimator
Parameters
----------
estimator: BaseEstimator
... | 5,334,182 |
def get_img_path() -> Path:
"""
Gets the path of the Mac installation image from the command line
arguments. Fails with an error if the argument is not present or the given
file doesn't exist.
"""
args = sys.argv
if len(args) < 2:
sys.exit(
"Please provide the path to the... | 5,334,183 |
def test_sslscan_package_installed(host):
"""
Tests if sslscan is installed.
"""
assert host.package(PACKAGE).is_installed | 5,334,184 |
def global_info(request):
"""存放用户,会话信息等."""
loginUser = request.session.get('login_username', None)
if loginUser is not None:
user = users.objects.get(username=loginUser)
# audit_users_list_info = WorkflowAuditSetting.objects.filter().values('audit_users').distinct()
audit_users_list... | 5,334,185 |
def arcsech(val):
"""Inverse hyperbolic secant"""
return np.arccosh(1. / val) | 5,334,186 |
def addEachAtomAutocorrelationMeasures(coordinates, numAtoms):
"""
Computes sum ri*rj, and ri = coords for a single trajectory. Results are stored in different array indexes for different atoms.
"""
rirj = np.zeros((1, 3*numAtoms), dtype=np.float64)
ri = np.zeros((1, 3*numAtoms), dtype=np.float6... | 5,334,187 |
def api_posts_suggest(request):
"""サジェスト候補の記事をJSONで返す。"""
keyword = request.GET.get('keyword')
if keyword:
post_list = [{'pk': post.pk, 'title': post.title} for post in Post.objects.filter(title__icontains=keyword)]
else:
post_list = []
return JsonResponse({'post_list': post_l... | 5,334,188 |
def parse_config(args): # pylint: disable=R0912
"""parses the gitconfig file."""
configpath = os.path.join(HOME, ".gitconfig_2")
# config = configobj.ConfigObj(configpath, interpolation=None, indent_type="\t")
config = configparser.ConfigParser(interpolation=None)
config.read(configpath)
if "co... | 5,334,189 |
def _get_config_from_ini_file(f):
"""Load params from the specified filename and return the params as a
dictionary"""
from os.path import expanduser
filename = expanduser(f)
_log.debug('Loading parms from {0}'.format(filename))
import configparser
config = configparser.ConfigParser()
... | 5,334,190 |
def test_launch_with_none_or_empty_oauth_version_value():
"""
Does the launch request work with an empty or None oauth_version value?
"""
oauth_consumer_key = 'my_consumer_key'
oauth_consumer_secret = 'my_shared_secret'
launch_url = 'http://jupyterhub/hub/lti/launch'
headers = {'Content-Type... | 5,334,191 |
def read_task_values(task_result: TaskResult) -> Tuple[bool, str, List[float], int]:
"""Reads unitary and federated accuracy from results.json.
Args:
fname (str): Path to results.json file containing required fields.
Example:
>>> print(read_task_values(task_result))
(false, "Vision... | 5,334,192 |
def get_two_dots(full=1):
""" return all posible simple two-dots """
bg= bottomGates()
two_dots = [dict({'gates':bg[0:3]+bg[2:5]})] # two dot case
for td in two_dots:
td['name'] = '-'.join(td['gates'])
return two_dots | 5,334,193 |
def read_values_of_line(line):
"""Read values in line. Line is splitted by INPUT_FILE_VALUE_DELIMITER."""
if INPUT_FILE_VALUE_DELIMITER == INPUT_FILE_DECIMAL_DELIMITER:
exit_on_error(f"Input file value delimiter and decimal delimiter are equal. Please set INPUT_FILE_VALUE_DELIMITER and INPUT_FILE_DECIMA... | 5,334,194 |
def find_allergens(ingredients):
"""Return ingredients with cooresponding allergen."""
by_allergens_count = sorted(ingredients, key=lambda i: len(ingredients[i]))
for ingredient in by_allergens_count:
if len(ingredients[ingredient]) == 1:
for other_ingredient, allergens in ingredients.it... | 5,334,195 |
def test_second_apply(record_xml_attribute, app_path):
"""Test that we can run kfctl apply again with error.
Args:
kfctl_path: The path to kfctl binary.
app_path: The app dir of kubeflow deployment.
"""
_, kfctl_path = kfctl_util.get_kfctl_go_build_dir_binary_path()
if not os.path.exists(kfctl_path):... | 5,334,196 |
def write_lhc_ascii(output_path: Union[str, Path], tbt_data: TbtData) -> None:
"""
Write a ``TbtData`` object's data to file, in the ASCII **SDDS** format.
Args:
output_path (Union[str, Path]): path to a the disk locatino where to write the data.
tbt_data (TbtData): the ``TbtData`` object t... | 5,334,197 |
def send_calendar_events():
"""Sends calendar events."""
error_msg = None
try:
with benchmark("Send calendar events"):
builder = calendar_event_builder.CalendarEventBuilder()
builder.build_cycle_tasks()
sync = calendar_event_sync.CalendarEventsSync()
sync.sync_cycle_tasks_events()
ex... | 5,334,198 |
def custom_precision(labels: np.array, predictions: np.array, exp_path: str, exp_name: str):
"""
Calculate custom precision value.
Parameters
----------
exp_name : str
experiment name
exp_path : str
path to experiment folder
labels : np.array
predictions : np.array
... | 5,334,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.