content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bbox_from_points(points):
"""Construct a numeric list representing a bounding box from polygon coordinates in page representation."""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
return bbox_from_polygon(xys) | 75742907d85990ee3bbfa133d9ba51f70b3f76ee | 11,535 |
def return_true():
"""Return True
Simple function used to check liveness of workers.
"""
return True | 3c4b469ce28aef47723a911071f01bea9eb4cf27 | 11,536 |
def get_active_test_suite():
"""
Returns the test suite that was last ran
>>> get_active_test_suite()
"Hello"
"""
return TEST_RUNNER_STATE.test_suite | dc578da283429480a872175ff1cd5462bf803925 | 11,538 |
def header_from_stream(stream, _magic=None) -> (dict, list, int):
"""
Parse SAM formatted header from stream.
Dict of header values returned is structured as such: {Header tag:[ {Attribute tag: value}, ]}.
Header tags can occur more than once and so each list item represents a different tag line.
:p... | e0e071f38787950fa499344c63cc4040e5fccb23 | 11,539 |
def walk_binary_file_or_stdin(filepath, buffer_size = 32768):
"""
Yield 'buffer_size' bytes from filepath until EOF, or from
standard input when 'filepath' is '-'.
"""
if filepath == '-':
return walk_binary_stdin(buffer_size)
else:
return walk_binary_file(filepath, buffer_size) | 290ea9e159c8f0e3df6713b8abcd0c141cb4858a | 11,540 |
def register_device() -> device_pb2.DeviceResponse:
"""
Now that the client credentials are set, the device can be registered. The device is
registered by instantiating an OauthService object and using the register() method.
The OauthService requires a Config object and an ISecureCredentialStore object... | 5a3958456f55315fa91be4e60324be3e5d9d3af8 | 11,541 |
def _sto_to_graph(agent: af.SubTaskOption) -> subgraph.Node:
"""Convert a `SubTaskOption` to a `Graph`."""
node_label = '{},{},{}'.format(agent.name or 'SubTask Option',
agent.subtask.name or 'SubTask',
agent.agent.name or 'Policy')
return subgraph... | 311f591be99bc045d2572b22f9cd3462bce2b10c | 11,542 |
def filter_input(self, forced=False, context=None):
"""
Passes each hunk (file or code) to the 'input' methods
of the compressor filters.
"""
content = []
for hunk in self.hunks(forced, context=context):
content.append(hunk)
return content | 1ea0ac16cf1e20732ad8c37b6126c80fe94d2ee5 | 11,543 |
def delete(request, user):
""" Deletes a poll """
poll_id = request.POST.get('poll_id')
try:
poll = Poll.objects.get(pk=poll_id)
except:
return JsonResponse({'error': 'Invalid poll_id'}, status=404)
if poll.user.id != user.id:
return JsonResponse({'error': 'You cannot delet... | 36a46e1b72cd06178ac00706c24451736fd454cd | 11,544 |
def get_loader(path):
"""Gets the configuration loader for path according to file extension.
Parameters:
path: the path of a configuration file, including the filename
extension.
Returns the loader associated with path's extension within LOADERS.
Throws an UnknownConfigurationExce... | a122c67d6ebacf2943ec69765d5feab649f5c341 | 11,546 |
def mat_stretch(mat, target):
"""
Changes times of `mat` in-place so that it has the same average BPM and
initial time as target.
Returns `mat` changed in-place.
"""
in_times = mat[:, 1:3]
out_times = target[:, 1:3]
# normalize in [0, 1]
in_times -= in_times.min()
in_times /= ... | 204efb1d8a19c7efe0efb5710add62436a4b5cee | 11,547 |
def parse_range(cpu_range):
"""Create cpu range object"""
if '-' in cpu_range:
[x, y] = cpu_range.split('-') # pylint: disable=invalid-name
cpus = range(int(x), int(y)+1)
if int(x) >= int(y):
raise ValueError("incorrect cpu range: " + cpu_range)
else:
cpus = [int... | 51079648ffddbcba6a9699db2fc4c04c7c3e3202 | 11,548 |
def causal_parents(node, graph):
"""
Returns the nodes (string names) that are causal parents of the node (have the edge type "causes_or_promotes"), else returns empty list.
Parameters
node - name of the node (string)
graph - networkx graph object
"""
node_causal_parents = []
if list(gra... | 4618e9649d3ea37c9a3a0d8faf7a44b00e386f1c | 11,549 |
async def user_me(current_user=Depends(get_current_active_user)):
"""
Get own user
"""
return current_user | 40c5bb5a45cad8154489db3fc0da3c0fe54d783d | 11,551 |
from typing import Optional
from typing import Tuple
import crypt
def get_password_hash(password: str, salt: Optional[str] = None) -> Tuple[str, str]:
"""Get user password hash."""
salt = salt or crypt.mksalt(crypt.METHOD_SHA256)
return salt, crypt.crypt(password, salt) | ea3d7e0d8c65e23e40660b8921aa872dc9e2f53c | 11,552 |
def start_at(gra, key):
""" start a v-matrix at a specific atom
Returns the started vmatrix, along with keys to atoms whose neighbors are
missing from it
"""
symb_dct = atom_symbols(gra)
ngb_keys_dct = atoms_sorted_neighbor_atom_keys(
gra, symbs_first=('X', 'C',), symbs_last=('H',), ord... | baa4d463316d47611a696bea456f8e1d0e4b5755 | 11,553 |
def associate_kitti(detections,
trackers,
det_cates,
iou_threshold,
velocities,
previous_obs,
vdc_weight):
"""
@param detections:
"""
if (len(trackers) == 0):
return np.empty((... | 8f3fb7628940cacd68de4f93b8469e212a12d854 | 11,554 |
import json
import uuid
import time
def seat_guest(self, speech, guest, timeout):
"""
Start the view 'seatGuest'
:param speech: the text that will be use by the Local Manager for tablet and vocal
:type speech: dict
:param guest: name of the guest to seat
:type guest: string
:param timeout... | 42a8ccd03638dfb48072c1d1b10c0c05a8f867ec | 11,555 |
def retreive_retries_and_sqs_handler(task_id):
"""This function retrieve the number of retries and the SQS handler associated to an expired task
Args:
task_id(str): the id of the expired task
Returns:
rtype: dict
Raises:
ClientError: if DynamoDB query failed
"""
try:
... | c432d9f73f8d1de8fbcf48b35e41a2879ca25954 | 11,556 |
import torch
def decompose(original_weights: torch.Tensor, mask, threshould: float) -> torch.Tensor:
"""
Calculate the scaling matrix. Use before pruning the current layer.
[Inputs]
original_weights: (N[i], N[i+1])
important_weights: (N[i], P[i+1])
[Outputs]
scaling_matrix: (P[i+1], N[... | 844562c839b95eb172197f22781f2316639b2d95 | 11,557 |
def calc_Kullback_Leibler_distance(dfi, dfj):
"""
Calculates the Kullback-Leibler distance of the two matrices.
As defined in Aerts et al. (2003). Also called Mutual Information.
Sort will be ascending.
Epsilon is used here to avoid conditional code for checking that neither P nor Q is equal to 0.
... | fd66434557598717db7cc73ca9a88fde9ab7e73d | 11,558 |
def test_python_java_classes():
""" Run Python tests against JPY test classes """
sub_env = {'PYTHONPATH': _build_dir()}
log.info('Executing Python unit tests (against JPY test classes)...')
return jpyutil._execute_python_scripts(python_java_jpy_tests, env=sub_env) | 11a9e43126799738a7c8e5cf8614cbe63d15cd2f | 11,559 |
def trim_datasets_using_par(data, par_indexes):
"""
Removes all the data points needing more fitting parameters than available.
"""
parameters_to_fit = set(par_indexes.keys())
trimmed_data = list()
for data_point in data:
if data_point.get_fitting_parameter_names() <= parameters_to_fi... | 5a06f7f5662fb9d7b5190e0e75ba41c858a85d0b | 11,560 |
def _parse_field(field: str) -> Field:
"""
Parse the given string representation of a CSV import field.
:param field: string or string-like field input
:return: a new Field
"""
name, _type = str(field).split(':')
if '(' in _type and _type.endswith(')'):
_type, id_space = _type.split... | 413cc12675e57db57da75dd9044c1884e638282c | 11,561 |
import time
import scipy
def removeNoise(
audio_clip,
noise_thresh,
mean_freq_noise,
std_freq_noise,
noise_stft_db,
n_grad_freq=2,
n_grad_time=4,
n_fft=2048,
win_length=2048,
hop_length=512,
n_std_thresh=1.5,
prop_decrease=1.0,
verbose=False,
visual=False,
):
... | 3d92ae7427ab33cc875219b3f005ca86802dd4c2 | 11,562 |
from simulator import simulate
import logging
import json
def handle_request(r):
"""Handle the Simulator request given by the r dictionary
"""
print ("handle_request executed .. ")
print (r)
# Parse request ..
config = SimArgs()
config.machine = r[u'machine']
config.overlay = [r[u'top... | 73a55ec93bfdf398b896b3c208a476296c1c04f5 | 11,564 |
def number_empty_block(n):
"""Number of empty block"""
L = L4 if n == 4 else L8
i = 0
for x in range(n):
for y in range(n):
if L[x][y] == 0:
i = i + 1
return i | 1dc7f228cdcbf4c3a1b6b553bff75ba1bb95bdbe | 11,565 |
def compute_referendum_result_by_regions(referendum_and_areas):
"""Return a table with the absolute count for each region.
The return DataFrame should be indexed by `code_reg` and have columns:
['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B']
"""
ans = referendum_and_areas.... | fb02c28b5caca9147a27bd2f205c07d377d8561c | 11,566 |
def fixed_rho_total_legacy(data, rho_p, rho_s, beads_2_M):
"""
*LEGACY*: only returns polycation/cation concentrations. Use updated version
(`fixed_rho_total()`), which returns a dictionary of all concentrations.
Computes the polycation concentration in the
supernatant (I) and coacervate (II) phase... | a13419c5dc95702e93dca48822e2731bd05745b5 | 11,567 |
def portfolio():
"""Function to render the portfolio page."""
form = PortfolioCreateForm()
if form.validate_on_submit():
try:
portfolio = Portfolio(name=form.data['name'], user_id=session['user_id'])
db.session.add(portfolio)
db.session.commit()
except (D... | adc84381bf6397023fc943f9c2edb1e34879400d | 11,569 |
def svn_client_get_simple_provider(*args):
"""svn_client_get_simple_provider(svn_auth_provider_object_t provider, apr_pool_t pool)"""
return apply(_client.svn_client_get_simple_provider, args) | dcdaaa1b448443e7b3cdb8984dc31d8a009c5606 | 11,570 |
def svn_client_invoke_get_commit_log(*args):
"""
svn_client_invoke_get_commit_log(svn_client_get_commit_log_t _obj, char log_msg, char tmp_file,
apr_array_header_t commit_items,
void baton, apr_pool_t pool) -> svn_error_t
"""
return apply(_client.svn_client_invoke_get_commit_log, args) | 5c4e8f30309037eabb74c99e77f1b0f4f3172428 | 11,571 |
import random
def find_valid_nodes(node_ids, tree_1, tree_2):
"""
Recursive function for finding a subtree in the second tree
with the same output type of a random subtree in the first tree
Args:
node_ids: List of node ids to search
tree_1: Node containing full tree
tree_2: N... | 88cfd535487ba460e3c212c9c85269abd68f6ef2 | 11,572 |
import torch
def pytorch_local_average(n, local_lookup, local_tensors):
"""Average the neighborhood tensors.
Parameters
----------
n : {int}
Size of tensor
local_lookup : {dict: int->float}
A dictionary from rank of neighborhood to the weight between two processes
local_tensor... | 294a4d63ce5eff42ccd3abe1354640f6f934e96f | 11,573 |
def get_rr_Ux(N, Fmat, psd, x):
"""
Given a rank-reduced decomposition of the Cholesky factor L, calculate L^{T}x
where x is some vector. This way, we don't have to built L, which saves
memory and computational time.
@param N: Vector with the elements of the diagonal matrix N
@param Fmat:... | 9a0aaa95d904b9bc993d295a49d95a48d0f6245f | 11,574 |
def get_poll_options(message: str) -> list:
"""
Turns string into a list of poll options
:param message:
:return:
"""
parts = message.split(CREATE_POLL_EVENT_PATTERN)
if len(parts) > 1:
votes = parts[-1].split(",")
if len(votes) == 1 and votes[0] == ' ':
return []... | fd1209403038d5b1ca75d7abd8567bb47fd6bd9a | 11,575 |
def get_avg_percent_bonds(bond_list, num_opts, adj_lists, num_trials, break_co_bonds=False):
"""
Given adj_list for a set of options, with repeats for each option, find the avg and std dev of percent of each
bond type
:param bond_list: list of strings representing each bond type
:param num_opts: num... | 74c34afea07ab98941c70b571197fe0ea43bcb88 | 11,576 |
from io import StringIO
def current_fig_image():
"""Takes current figure of matplotlib and returns it as a PIL image.
Also clears the current plot"""
plt.axis('off')
fig = plt.gcf()
buff = StringIO.StringIO()
fig.savefig(buff)
buff.seek(0)
img = Image.open(buff).convert('RGB')
plt... | 6da91a7157db0cd0df8ebc1e4f3d6007f35f2621 | 11,577 |
def get_bgp_peer(
api_client, endpoint_id, bgp_peer_id, verbose=False, **kwargs
): # noqa: E501
"""Get eBGP peer # noqa: E501
Get eBGP peer details # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> resp... | 3a9fa41b2918c1537402d8894fe3315ff90241e8 | 11,578 |
def rewrite_elife_funding_awards(json_content, doi):
""" rewrite elife funding awards """
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_content[i]
# add fundin... | aba819589e50bc847d56a0f5a122b2474425d39c | 11,579 |
def remove_subnet_from_router(router_id, subnet_id):
"""Remove a subnet from the router.
Args:
router_id (str): The router ID.
subnet_id (str): The subnet ID.
"""
return neutron().remove_interface_router(router_id, {
'subnet_id': subnet_id
}) | 4b7e9123f148fddaa3d53bcabe1f37b35c974162 | 11,580 |
def direct_to_template(request, template):
"""Generic template direction view."""
return render_to_response(template, {}, request) | 5a030f302450829d397fbc27f73bd24470bfe50b | 11,581 |
from datetime import datetime
def now():
"""Return the current time as date object."""
return datetime.now() | 79ddcf3c2e22ff57626520e0b41af8b0f58972d6 | 11,582 |
def is_valid_node_name(name):
"""
Determine if a name is valid for a node.
A node name:
- Cannot be empty
- Cannot start with a number
- Cannot match any blacklisted pattern
:param str name: The name to check.
:return: True if the name is valid. False otherwise.
:rtype: bool
""... | 6a935f7172e96fd418084543da0fe81d6bb77be5 | 11,583 |
def trajCalc(setup):
""" Creates trajectory between point A and the ground (B) based off of the initial position and the angle of travel
Arguments:
setup: [Object] ini file parameters
Returns:
A [list] lat/lon/elev of the tail of the trajectory
B [list] lat/lon/elev of the head of the traject... | 30614d0193aacdd594400fbbda396bca40a75156 | 11,584 |
from typing import Dict
async def health() -> Dict[str, str]:
"""Health check function
:return: Health check dict
:rtype: Dict[str: str]
"""
health_response = schemas.Health(name=settings.PROJECT_NAME,
api_version=__version__)
return health_response.dict() | ffda9fa5795c02bd197ed8715d44b384781c866f | 11,585 |
def projection_v3(v, w):
"""Return the signed length of the projection of vector v on vector w.
For the full vector result, use projection_as_vec_v3().
Since the resulting vector is along the 1st vector, you can get the
full vector result by scaling the 1st vector to the length of the result of
thi... | 3aeb8783a5eb680f0e2085d6a0f3b8b80511b10f | 11,586 |
import math
import collections
def bleu(pred_seq, label_seq, k):
"""计算BLEU"""
pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')
len_pred, len_label = len(pred_tokens), len(label_tokens)
score = math.exp(min(0, 1 - len_label / len_pred))
for n in range(1, k + 1):
num_m... | ae7485687a44afc9ced6f2f4ed5ac8fe0d67b295 | 11,588 |
def report_by_name(http_request, agent_name):
"""
A version of report that can look up an agent by its name. This will
generally be slower but it also doesn't expose how the data is stored and
might be easier in some cases.
"""
agent = get_list_or_404(Agent, name=agent_name)[0]
return report... | ee9daf5b7e7e5f15af3e507f55e0a5e2a1388aca | 11,589 |
def create_application(global_config=None, **local_conf):
"""
Create a configured instance of the WSGI application.
"""
sites, types = load_config(local_conf.get("config"))
return ImageProxy(sites, types) | c8d3c7158902df00d88512a23bb852bb226b5ba4 | 11,590 |
def dimensionState(moons,dimension):
"""returns the state for the given dimension"""
result = list()
for moon in moons:
result.append((moon.position[dimension],moon.velocity[dimension]))
return result | e67a37e4a1556d637be74992fc3801ee56f0e6f9 | 11,591 |
def login():
"""Log in current user."""
user = get_user()
if user.system_wide_role != 'No Access':
flask_login.login_user(user)
return flask.redirect(common.get_next_url(
flask.request, default_url=flask.url_for('dashboard')))
flask.flash(u'You do not have access. Please contact your administra... | f229ebbd0f77789784b2e8d05bb643d9b5cb1da1 | 11,592 |
def init_module():
"""
Initialize user's module handler.
:return: wrapper handler.
"""
original_module, module_path, handler_name = import_original_module()
try:
handler = original_module
for name in module_path.split('.')[1:] + [handler_name]:
handler = getattr(handl... | 148ed89ea8a9f67c9cef5bc209a803840ff9de56 | 11,593 |
from typing import List
def process(lines: List[str]) -> str:
""" Preprocess a Fortran source file.
Args:
inputLines The input Fortran file.
Returns:
Preprocessed lines of Fortran.
"""
# remove lines that are entirely comments and partial-line comments
lines = [
rm_t... | f3fd3bc75be544cd507dae87b80364c9b1c12f7c | 11,594 |
def _summary(function):
"""
Derive summary information from a function's docstring or name. The summary is the first
sentence of the docstring, ending in a period, or if no dostring is present, the
function's name capitalized.
"""
if not function.__doc__:
return f"{function.__name__.capi... | a3e3e45c3004e135c2810a5ec009aa78ef7e7a04 | 11,595 |
def findrun(base,dim,boxsize):
""" find all files associated with run given base directory
and the resolution size and box length """
if not os.path.isdir(base):
print base, 'is not a valid directory'
sys.exit(1)
#retreive all files that match tag and box size
#note this will inclu... | c14f885943a33df96cda28a4a84fdce332149167 | 11,596 |
def demand_mass_balance_c(host_odemand, class_odemand, avail, host_recapture):
"""Solve Demand Mass Balance equation for class-level
Parameters
----------
host_odemand: int
Observerd host demand
class_odemand: int
Observed class demand
avail: dict
Availability of demand ... | 7fda78ce632f1a26ec875c37abe5db40615aa351 | 11,597 |
from typing import Optional
def serve_buffer(
data: bytes,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = True,
as_inline: bool = False,
default_content_type: Optional[str] = MimeType.FORCE_DOWNLOAD) \
-> HttpResponse:
"""
... | aa41df168e3f84468293ca6653c06402e6c395fc | 11,598 |
def get_single_image_results(gt_boxes, pred_boxes, iou_thr):
"""Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
Args:
gt_boxes (list of list of floats): list of locations of ground truth
objects as [xmin, ymin, xmax, ymax]
pred_boxes (dict): dict of d... | ec97189c8c75686aa172292179228621e244982f | 11,599 |
def partition(arr, left, right):
"""[summary]
The point of a pivot value is to select a value,
find out where it belongs in the array while moving everything lower than that value
to the left, and everything higher to the right.
Args:
arr ([array]): [Unorderd array]
left ([int]... | 30f1448861a7a9fa2f119e31482f1f715c9e1ce0 | 11,600 |
def graphatbottleneck(g,m,shallfp=True):
"""handles the bottleneck transformations for a pure graph ae, return g, compressed, new input, shallfp=True=>convert vector in matrix (with gfromparam), can use redense to add a couple dense layers around the bottleneck (defined by m.redense*)"""
comp=ggoparam(gs=g.s.gs,par... | b46967b40fce669c3e74d52e31f814bbf96ce8c0 | 11,601 |
def categorical_onehot_binarizer(feature, feature_scale=None, prefix='columns', dtype='int8'):
"""Transform between iterable of iterables and a multilabel format, sample is simple categories.
Args:
feature: pd.Series, sample feature.
feature_scale: list, feature categories list.
pre... | eb3a2b38d323c72bb298b64ebbd6567d143471fc | 11,602 |
def add_selfloops(adj_matrix: sp.csr_matrix, fill_weight=1.0):
"""add selfloops for adjacency matrix.
>>>add_selfloops(adj, fill_weight=1.0) # return an adjacency matrix with selfloops
# return a list of adjacency matrices with selfloops
>>>add_selfloops(adj, adj, fill_weight=[1.0, 2.0])
Paramet... | 867bdf380995b6ff48aac9741facd09066ad03bd | 11,604 |
def handle(event, _ctxt):
""" Handle the Lambda Invocation """
response = {
'message': '',
'event': event
}
ssm = boto3.client('ssm')
vpc_ids = ssm.get_parameter(Name=f'{PARAM_BASE}/vpc_ids')['Parameter']['Value']
vpc_ids = vpc_ids.split(',')
args = {
'vpc_ids': vp... | 8cf0dc52b641bd28b002caef1d97c7e3a60be647 | 11,605 |
def _get_indice_map(chisqr_set):
"""Find element with lowest chisqr at each voxel """
#make chisqr array of dims [x,y,z,0,rcvr,chisqr]
chisqr_arr = np.stack(chisqr_set,axis=5)
indice_arr = np.argmin(chisqr_arr,axis=5)
return indice_arr | 9ac00310628d3f45f72542dbfff5345845053acd | 11,606 |
def noct_synthesis(spectrum, freqs, fmin, fmax, n=3, G=10, fr=1000):
"""Adapt input spectrum to nth-octave band spectrum
Convert the input spectrum to third-octave band spectrum
between "fc_min" and "fc_max".
Parameters
----------
spectrum : numpy.ndarray
amplitude rms of the one-sided... | 89c6be2be262b153bd63ecf498cf92cf93de9e31 | 11,608 |
def get_model_prediction(model_input, stub, model_name='amazon_review', signature_name='serving_default'):
""" no error handling at all, just poc"""
request = predict_pb2.PredictRequest()
request.model_spec.name = model_name
request.model_spec.signature_name = signature_name
request.inputs['input_in... | 6de7e35305e0d9fe9fe0b03e3b0ab0c82937778c | 11,609 |
def _make_feature_stats_proto(
common_stats, feature_name,
q_combiner,
num_values_histogram_buckets,
is_categorical, has_weights
):
"""Convert the partial common stats into a FeatureNameStatistics proto.
Args:
common_stats: The partial common stats associated with a feature.
feature_name: T... | 16b55556d76f5d5cb01f2dc3142b42a86f85bcb8 | 11,610 |
def get_device():
"""
Returns the id of the current device.
"""
c_dev = c_int_t(0)
safe_call(backend.get().af_get_device(c_pointer(c_dev)))
return c_dev.value | 4be37aa83bf822aac794680d9f30fe24edb38231 | 11,612 |
def plotLatentsSweep(yhat,nmodels=1):
"""plotLatentsSweep(yhat):
plots model latents and a subset of the corresponding stimuli,
generated from sweepCircleLatents()
---e.g.,---
yhat, x = sweepCircleLatents(vae)
plotCircleSweep(yhat,x)
alternatively,
plotLatents... | f43ffd9b45981254a550c8b187da649522522dd0 | 11,613 |
def calc_lipophilicity(seq, method="mean"):
""" Calculates the average hydrophobicity of a sequence according to the Hessa biological scale.
Hessa T, Kim H, Bihlmaier K, Lundin C, Boekel J, Andersson H, Nilsson I, White SH, von Heijne G. Nature. 2005 Jan 27;433(7024):377-81
The Hessa scale has been calcul... | a8858a62b3c76d466b510507b1ce9f158b5c8c9c | 11,614 |
def get_enrollments(username, include_inactive=False):
"""Retrieves all the courses a user is enrolled in.
Takes a user and retrieves all relative enrollments. Includes information regarding how the user is enrolled
in the the course.
Args:
username: The username of the user we want to retriev... | 0cbc9a60929fd06f8f5ca90d6c2458867ae474e7 | 11,615 |
async def connections_accept_request(request: web.BaseRequest):
"""
Request handler for accepting a stored connection request.
Args:
request: aiohttp request object
Returns:
The resulting connection record details
"""
context = request.app["request_context"]
outbound_handl... | 78a469d306c3306f8b9a0ba1a3364f7b30a36f85 | 11,616 |
def nearest(x, base=1.):
"""
Round the inputs to the nearest base. Beware, due to the nature of
floating point arithmetic, this maybe not work as you expect.
INPUTS
x : input value of array
OPTIONS
base : number to which x should be rounded
"""
return np.round... | ca1ddcd75c20ea82c18368b548c36ef5207ab77f | 11,617 |
def sort_nesting(list1, list2):
"""Takes a list of start points and end points and sorts the second list according to nesting"""
temp_list = []
while list2 != temp_list:
temp_list = list2[:] # Make a copy of list2 instead of reference
for i in range(1, len(list1)):
if list2[i] > ... | 11693e54eeba2016d21c0c23450008e823bdf1c1 | 11,618 |
def confusion_matrix(Y_hat, Y, norm=None):
"""
Calculate confusion matrix.
Parameters
----------
Y_hat : array-like
List of data labels.
Y : array-like
List of target truth labels.
norm : {'label', 'target', 'all', None}, default=None
Normalization on resulting matrix. Must be one of:
- 'l... | b1ed79b71cef8cdcaa2cfe06435a3b2a56c659dd | 11,619 |
def reroot(original_node: Tree, new_node: Tree):
"""
:param original_node: the node in the original tree
:param new_node: the new node to give children
new_node should have as chldren, the relations of original_node except for new_node's parent
"""
new_node.children = [
Tree(relation.l... | f37141fc7645dfbab401eb2be3255d917372ef11 | 11,620 |
import uuid
import time
def update_users():
"""Sync LDAP users with local users in the DB."""
log_uuid = str(uuid.uuid4())
start_time = time.time()
patron_cls = current_app_ils.patron_cls
patron_indexer = PatronBaseIndexer()
invenio_users_updated_count = 0
invenio_users_added_count = 0
... | 8aef4e258629dd6e36b0a8b7b722031316df1154 | 11,621 |
def opt(dfs, col='new', a=1, b=3, rlprior=None, clprior=None):
"""Returns maximum likelihood estimates of the model parameters `r` and `c`.
The optimised parameters `r` and `c` refer to the failure count of the
model's negative binomial likelihood function and the variance factor
introduced by each pre... | d40e63892676f18734d3b4789656606e898f69d9 | 11,622 |
import json
def unpackage_datasets(dirname, dataobject_format=False):
"""
This function unpackages all sub packages, (i.e. train, valid, test)
You should use this function if you want everything
args:
dirname: directory path that has the train, valid, test folders in it
dataobject_form... | d1748b3729b4177315553eab5075d14ea2edf3a7 | 11,623 |
from typing import Sequence
from typing import Tuple
import cmd
from typing import OrderedDict
def get_command_view(
is_running: bool = False,
stop_requested: bool = False,
commands_by_id: Sequence[Tuple[str, cmd.Command]] = (),
) -> CommandView:
"""Get a command view test subject."""
state = Comm... | 3eaf1b8845d87c7eb6fef086bd2af3b2dd65409a | 11,624 |
def get_node_ip_addresses(ipkind):
"""
Gets a dictionary of required IP addresses for all nodes
Args:
ipkind: ExternalIP or InternalIP or Hostname
Returns:
dict: Internal or Exteranl IP addresses keyed off of node name
"""
ocp = OCP(kind=constants.NODE)
masternodes = ocp.g... | 622217c12b763c6dbf5c520d90811bdfe374e876 | 11,626 |
def house_filter(size, low, high):
"""
Function that returns the "gold standard" filter.
This window is designed to produce low sidelobes
for Fourier filters.
In essence it resembles a sigmoid function that
smoothly goes between zero and one, from short
... | ef7f3fe3bb4410ce81fcd061e24d6f34a36f3a04 | 11,628 |
def PToData(inGFA, data, err):
"""
Copy host array to data
Copys data from GPUFArray locked host array to data
* inFA = input Python GPUFArray
* data = FArray containing data array
* err = Obit error/message stack
"""
################################################################... | 0f943a8340c2587c75f7ba6783f160d5d3bede76 | 11,629 |
def maker(sql_connection, echo=False):
"""
Get an sessionmaker object from a sql_connection.
"""
engine = get_engine(sql_connection, echo=echo)
m = orm.sessionmaker(bind=engine, autocommit=True, expire_on_commit=False)
return m | 1296fa49058c8a583cf442355534d22b00bdaeea | 11,631 |
def test_auth(request):
"""Tests authentication worked successfuly."""
return Response({"message": "You successfuly authenticated!"}) | 59e065687333a4dd612e514e0f8ea459062c7cb3 | 11,632 |
def streak_condition_block() -> Block:
"""
Create block with 'streak' condition, when rotation probability is low and
target orientation repeats continuously in 1-8 trials.
:return: 'Streak' condition block.
"""
return Block(configuration.STREAK_CONDITION_NAME,
streak_rotations... | 769b0f7b9ce8549f4bea75da066814b3e1f8a103 | 11,633 |
def resolve_appinstance(request,
appinstanceid,
permission='base.change_resourcebase',
msg=_PERMISSION_MSG_GENERIC,
**kwargs):
"""
Resolve the document by the provided primary key
and check the optional permissio... | bb17c2a842c4f2fced1bce46bd1d05293a7b0edf | 11,634 |
def statementTVM(pReact):
"""Use this funciton to produce the TVM statemet"""
T,V,mass = pReact.T,pReact.volume,pReact.mass
statement="\n{}: T: {:0.2f} K, V: {:0.2f} m^3, mass: {:0.2f} kg".format(pReact.name,T,V,mass)
return statement | cda356678d914f90d14905bdcadf2079c9ebfbea | 11,635 |
def fill_NaNs_with_nearest_neighbour(data, lons, lats):
"""At each depth level and time, fill in NaN values with nearest lateral
neighbour. If the entire depth level is NaN, fill with values from level
above. The last two dimensions of data are the lateral dimensions.
lons.shape and lats.shape = (data.s... | cacde1f5a7e52535f08cd1154f504fb24293182e | 11,636 |
from resource_management.libraries.functions.default import default
from resource_management.libraries.functions.version import compare_versions
import json
def check_stack_feature(stack_feature, stack_version):
"""
Given a stack_feature and a specific stack_version, it validates that the feature is supported by ... | e7417738f285d94d666ac8b72d1b8c5079469f02 | 11,638 |
def get_random_action_weights():
"""Get random weights for each action.
e.g. [0.23, 0.57, 0.19, 0.92]"""
return np.random.random((1, NUM_ACTIONS)) | da929c6a64c87ddf9af22ab17636d0db011c8a45 | 11,639 |
import time
from datetime import datetime
def rpg_radar2nc(data, path, larda_git_path, **kwargs):
"""
This routine generates a daily NetCDF4 file for the RPG 94 GHz FMCW radar 'LIMRAD94'.
Args:
data (dict): dictionary of larda containers
path (string): path where the NetCDF file is stored... | d59a46c2872b6f82e81b54cfca953ebc0bc18a90 | 11,640 |
def load_ssl_user_from_request(request):
"""
Loads SSL user from current request.
SSL_CLIENT_VERIFY and SSL_CLIENT_S_DN needs to be set in
request.environ. This is set by frontend httpd mod_ssl module.
"""
ssl_client_verify = request.environ.get('SSL_CLIENT_VERIFY')
if ssl_client_verify != ... | ff716c139f57f00345d622a849b714c67468d7bb | 11,641 |
def get_all_users():
"""Gets all users"""
response = user_info.get_all_users()
return jsonify({'Users' : response}), 200 | f178c509afdae44831c1ede0cdfee39ca7ea6cec | 11,642 |
def open_mailbox_maildir(directory, create=False):
""" There is a mailbox here.
"""
return lazyMaildir(directory, create=create) | c19e5bf97da7adfe9a37e515f1b46047ced75108 | 11,643 |
def TANH(*args) -> Function:
"""
Returns the hyperbolic tangent of any real number.
Learn more: https//support.google.com/docs/answer/3093755
"""
return Function("TANH", args) | 1bb3dbe8147f366415cf78c39f5cf6df3b80ffca | 11,644 |
def value_frequencies_chart_from_blocking_rules(
blocking_rules: list, df: DataFrame, spark: SparkSession, top_n=20, bottom_n=10
):
"""Produce value frequency charts for the provided blocking rules
Args:
blocking_rules (list): A list of blocking rules as specified in a Splink
settings d... | e9160c9cd14ced1b904fad67c72c10a027179f7f | 11,645 |
def getOfflineStockDataManifest():
"""Returns manifest for the available offline data.
If manifest is not found, creates an empty one.
Returns:
A dict with the manifest. For example:
{'STOCK_1':
{'first_available_date': datetime(2016, 1, 1),
'last_available_date': ... | 40482daa96bf18a843f91bb4af00f37917e51340 | 11,646 |
def align_buf(buf: bytes, sample_width: bytes):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf | 9d4996a8338fe532701ee82843d055d6d747f591 | 11,647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.