content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def search_in_table(text_value, table):
"""
Search for a text into a table and return the cell where found it.
:param text_value: Value to search as regex.
:type text_value: str
:param table: Table instance
:type table: Table
:return: A _Cell instances or None, if not matches ... | 0bc6ab868184f462d030606a0b98cb954b03fdd3 | 71,006 |
def _make_contiguous(Y):
"""Makes values of Y contiguous integers
Parameters
----------
Y : numpy.array
Array with uncontiguous numbers.
Returns
-------
numpy.array
Array Y converted to contiguous numbers in range(np.unique(Y).size).
"""
val = np.unique(Y)
for i... | b34ad610fb36567167d92240760aff4595624aeb | 71,007 |
def delete_cluster(
access_token,
project_id,
k8s_mesos,
cluster_id,
master_ip_list,
control_ip,
biz_id,
username,
websvr,
config=None,
platform=None,
): # noqa
"""集群删除流程"""
data = {
'type': k8s_mesos,
'cluster_id': cluster_id,
'master_ip_list... | 9eea136e00b49e194048f3486c397cd2fb531c35 | 71,008 |
def load_links(file_path):
"""
Load links object saved as a hdf5 file.
Args:
file_path (str): file path.
Returns:
Links: loaded links object.
"""
return load_hdf5(filename=file_path, obj_class=Links) | 1001e9ad720190737c2df0468ce88aac214c9a24 | 71,011 |
def list_transitions_data_for_issue(issue_id):
"""
This function performs the API call for getting a list of all possible transitions for a given issue.
:param issue_id: The ID of the issue.
:return: API raw response.
"""
url = f'rest/api/2/issue/{issue_id}/transitions'
return jira_req('GET'... | ef5937248e97f10447d1571018cd2b3175d2a132 | 71,012 |
def generate_image(model, landmark, e_vector, device):
"""
Generator generate image from landmark and e_vector
Args:
model(nn.Module) : Generator model which generate image from landmark and e_vector.
landmark(tensor) : Landmark which type is torch.tensor.
e_vector(tensor)
... | 1c0ee6ca116b663ab0d257d6e7c9a1e7a85aaa37 | 71,013 |
from typing import Callable
from typing import Generator
from typing import Any
from typing import List
def map(
func : Callable[P, R],
*generators : Generator[Any]
) -> Generator[R]:
"""A variadic map function of given input generators over types `A`, `B`, etc. to an output generator over type `R`.
... | 46bed3738ee0b2c2547205b58ed9d4b27bf57f20 | 71,014 |
def _check_intable(f):
"""If a float is a whole number, convert it to an integer"""
if(_is_int(f)):
return(int(float(f)))
else:
return(float(f)) | f71aaf1e259d10bd82ebeec8b7cbf6d01622fc99 | 71,015 |
def get_site(key: str = None) -> str:
"""
Return the runtime site.
Automatically creates directories if needed.
"""
path = CONF_PATH[SITE] if key is None else CONF_PATH[key]
return path | cf18876fa507cf4817e7ba7c2fed64a59f2c31dd | 71,016 |
def transform_file_directory_result(cli_ctx):
"""
Transform a the result returned from file and directory listing API.
This transformer add and remove properties from File and Directory objects in the given list
in order to align the object's properties so as to offer a better view to the file and dir
... | 11851d16d7d1e6cdec590f3adedae0b31cac6361 | 71,017 |
from typing import Sequence
def coords_in_datasets_are_equal(datasets: Sequence["pydicom.dataset.Dataset"]) -> bool:
"""True if all DICOM datasets have perfectly matching coordinates
Parameters
----------
datasets : sequence of pydicom.dataset.Dataset
A sequence of DICOM datasets whose coordi... | c888b5ba693ca9f65e9956b7348abea50ea791dd | 71,018 |
import uuid
def set_compose_session(request):
"""Initialize a new "compose" session.
It is used to keep track of attachments defined with a new
message. Each new message will be associated with a unique ID (in
order to avoid conflicts between users).
:param request: a Request object.
:return... | 57384af709ce69d648bf85bce0c8a157fa5627c4 | 71,019 |
import functools
def login_required(view):
"""
Creates a function wrapper that restrict access to base routes to logged-in users only.
Exceptions:
404 - Page Not Found: Directs users who are not logged in to a 404 Page Not Found.
"""
@functools.wraps(view)
def wrapped_view(**kwargs):... | 073b33705a76a0002eea48081fc0ab9391fc0ca9 | 71,020 |
def CreateLessThanOrEqualRegex(number):
""" Return a regular expression to test whether an integer less than or equal
to 'number' is present in a given string.
"""
# In three parts, build a regular expression that match any numbers smaller
# than 'number'.
# For example, 78656 would give a regular expr... | 1de3074ede96b2a2bd0a28cb3f0167da7a767d40 | 71,021 |
def binary_search_recursively_in_place(ls: list, item: object) -> bool:
"""Recursively binary-searches item in the list ls, assuming that ls is
sorted in increasing order.
It returns the index such that ls[index] == item, if item is in the list ls,
otherwise it returns -1.
This algorithm, as oppos... | 370e97cdbba34ca5842bbf3782a1298c1ff0a9ff | 71,022 |
from typing import Optional
from typing import Tuple
def find_cyclopentadienyl_site(mol: masm.Molecule) -> Optional[Tuple[int, int]]:
"""Returns atom index and site index pair"""
flat_carbon = partial(is_flat_carbon, mol=mol)
for permutator in mol.stereopermutators.atom_stereopermutators():
for s... | 6a7d611220358d098bff8f33e89f0dfafaca0937 | 71,023 |
def hdfs_data_loader(para):
""" load the log sequence matrix and labels from the file path.
Args:
--------
para: the parameters dictionary
Returns:
--------
raw_data: log sequences matrix
label_data: labels matrix
"""
file_path = para['path'] + para['log_seq_file_name']
label_path = para['path'] + para['l... | 1f9f1960d99c1521964e75dfb75224eaf1b41c85 | 71,024 |
def allowed_attrs(attrs, new=False):
"""Only allow href, target, rel and title."""
allowed = [
(None, 'href'),
(None, 'target'),
(None, 'rel'),
(None, 'title'),
'_text',
]
return dict((k, v) for k, v in attrs.items() if k in allowed) | 28f7e310f1ff1cbec58ea505c179494491af7171 | 71,025 |
def mask_mapper(mask=None, shape=None, space=None):
"""Factory method to create a chain of Flatten+StaticFeatureSelection Mappers
Parameters
----------
mask : None or array
an array in the original dataspace and its nonzero elements are
used to define the features included in the dataset. A... | fe9a14c7c6aac8f9206494674cd72d573e363bd0 | 71,026 |
def get_organization_by_abbr(org_abbr):
"""Return organization identified by
:attr:`~app.models.Organization.abbreviation`.
**Example request**:
.. sourcecode:: http
GET /api/1.0/organization/cert-eu HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example resp... | b886b042357af6481562bdae5cab62f519aebf59 | 71,028 |
def import_multipart(json_record):
"""Import multipart record."""
document_indexer = current_app_ils.document_indexer
series_indexer = current_app_ils.series_indexer
series_cls, series_pid_provider = model_provider_by_rectype("multipart")
document_cls, document_pid_provider = model_provider_by_recty... | 2c85324a097cebb853d711d2ed3ee48ae1fa7f03 | 71,029 |
def _get_generator_inputs(num_images_per_class, num_classes, noise_dims):
"""Return generator inputs for evaluation."""
# Since we want a grid of numbers for the conditional generator, manually
# construct the desired class labels.
num_images_generated = num_images_per_class * num_classes
noise = tf.random.no... | 01c17bfcb4c4d8569254fc7a0c618e27718c408e | 71,030 |
from typing import Sequence
from typing import Dict
from typing import Any
def get_yearly_chart_report_fields_list(report: str) -> Sequence[Dict[str, Any]]:
"""Gets the fields in the report chart
:param report: the kind of the report
:returns: list of fields in this report's monthly chart"""
fields =... | 124b5246a038e8c0aabdfc2e1310f5fa72c9db7b | 71,031 |
def windowed_run_count_ufunc(x, window):
"""Dask-parallel version of windowed_run_count_1d, ie the number of consecutive true values in
array for runs at least as long as given duration.
Parameters
----------
x : bool array
Input array
window : int
Minimum duration of consecutive ru... | ec06d97dc94dbe0c1ff1d29dfccf94bcc43e45d5 | 71,032 |
def get_sp_delta(*args):
"""get_sp_delta(func_t pfn, ea_t ea) -> sval_t"""
return _idaapi.get_sp_delta(*args) | 31ae03cd766d635715725b385faaaa662904ce56 | 71,033 |
def JOIN(item, leftseq):
"""
--- future ---
elif len(item) == 3:
# used to add prefix to keys to avoid conflicting name space
rightseq, leftkey, rightkey, key_prefix = item
"""
if len(item) == 2:
rightseq, leftkey = item
rightkey = leftkey
elif len(item) == 3:
... | 7e0495c9fddf67ebaff7f532e766328e36cbcf8b | 71,034 |
from typing import List
from typing import Union
def get_panel_albedo(
md_keys: List[str], md: pyexiv2.metadata.ImageMetadata
) -> Union[float, None]:
"""
Surface albedo of the active portion of the reflectance panel as
calculated by the camera (usually from the informatoin in the panel QR code)
"... | 73d05d22e24a8e75deaff3e041a5a0f1b3ed559d | 71,035 |
def conv(x, filter_height, filter_width, num_filters, stride_y, stride_x, name,
padding='SAME', groups=1):
"""Create a convolution layer.
Adapted from: https://github.com/ethereon/caffe-tensorflow
"""
# Get number of input channels
input_channels = int(x.get_shape()[-1])
# Create lambd... | c42fbe3c3568ec756092d44e45b8ad10def7ada2 | 71,036 |
def serversess(f_engine_address, f_engine_username, f_engine_password):
"""
Function to setup the session with the Delphix Engine
"""
server_session= DelphixEngine(f_engine_address, f_engine_username,
f_engine_password, "DOMAIN")
return server_session | 8879e23733007894a0a4ecd6387faf6cb9dfd38c | 71,037 |
def vec_3d_to_SO3(x):
"""
Based on the Lie Group mapping from the minimal vector space to the SO3 manifold (rot mat)
"""
device = x.device
bsz = x.shape[0]
assert x.shape == (bsz,3)
rot_mats = so3_exp_map(x)
return rot_mats | 842274d72dc956b4f3adfbcf5a2b6807c3e79f0e | 71,038 |
import six
def ValidateUpdateStatefulPolicyParams(args, current_stateful_policy):
"""Check stateful properties of update request; returns final device list."""
current_device_names = set(
managed_instance_groups_utils.GetDeviceNamesFromStatefulPolicy(
current_stateful_policy))
update_disk_names ... | 0055a42dcca43a7afb2b886e632174bbe82bfb1a | 71,039 |
import requests
import json
def get_iam_token(oauth_token):
"""
Получение IAM-токена.
@param oauth_token: OAuth-токен в сервисе Яндекс.OAuth
@return: (str) - IAM-токен.
"""
url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'
data = {'yandexPassportOauthToken': oauth_token}
with requ... | 939b4a512d20e5dd71c576f84d5a6ae10fb0e7e9 | 71,040 |
from typing import Dict
from typing import Any
from typing import Union
def type_factory_creator(
decl: Dict[str, Any], imports: Imports
) -> Union[TypeFactory, VariableFactory]:
"""Check the input and returns the corresponding type factory.
Arguments:
decl: A dict which indicates a portex type o... | 2799699be73bf204acaca751c5c0f6600253aae0 | 71,041 |
from typing import Tuple
from typing import List
def _select_galileo_signal(dset: "Dataset") -> Tuple[List[str], str]:
"""Select Galileo signal depending on given data in Dataset
Args:
dset: A dataset containing the data.
Returns:
Selected Galileo signal
"""
signals = dict()
... | 02583f80e0e2915798a2de9800fbbc3afa3656c9 | 71,042 |
import tqdm
def find_outliers(
model_path: str,
classes_names_path: str,
input_paths: list,
threshold: float = 0.5) -> tuple:
"""
Find outliers in folder
Args:
model_path: path to traced model file
classes_names_path: path fo text file with classes names
... | b0fcd4c39efc24be6605cc0d6d600db9efedce47 | 71,043 |
def _initialize_accumulated_quantities(
initial_kalman_filter_state,
observations,
num_timesteps,
):
"""Initialize quantities to accumulate, specifying dtype/shape."""
initial_arrays = []
for x in initial_kalman_filter_state:
# pylint: disable=cell-var-from-loop
initial_arrays.append(
... | facaa66dc2fcd5dbdc270668895993b48532fafc | 71,044 |
def get_simulator_names(simulator=None, kwargs=None, config=None):
"""Returns the names of the simulators to be used in lieu of hardware drivers.
Note that returning a list containing 'X' doesn't mean that the config calls for a driver
of type 'X'; that is up to the code working with the config to create d... | b64377e22b27652b5792983904523b06140d6f3a | 71,045 |
def deassign_task_members_milestone(request):
"""deassign tasks from members under specific milestone"""
task_id = int(request.GET.get('task_id'))
project_id = int(request.GET.get('project_id'))
milestone_id = int(request.GET.get('milestone_id'))
assigned_id = int(request.GET.get('assigned_id'))
... | f3e3b82d218d0d5331b96618fdd119bcef4082a0 | 71,047 |
import logging
def create_github_projects(github_api: github.MainClass.Github,
github_projects: list,
github_statuses: list) -> dict:
"""Recreates Jira projects as GitHub projects"""
# Create projects via GitHub API
logging.info('Populating %s Jira project(... | ed96e55bba5bcc7d510082f0df60d460115440cf | 71,048 |
def student_optimal(students, projects):
""" Solve the instance of SA to be student-optimal. The algorithm is as
follows:
0. Set all students to be unassigned, and every project (and supervisor)
to be totally unsubscribed.
1. Take any student, :math:`s`, that is unassigned and has a no... | 12f5e3dfefa23d673a8773388a72abf6a1294f96 | 71,049 |
import wave
def create_test_sound(pathname, freq=441, duration=None,
framerate=44100, nchannels=2):
""" create a sound file at pathname, overwriting exiting file """
sampwidth = 2
nframes = duration or framerate # defaults to 1 second duration
fid = wave.open(pathname, 'w')
... | 445e2ecc9e3660ec5c0f2eaed5746276c3bf7442 | 71,050 |
import time
def get_undirected(G):
"""
Convert a directed graph to an undirected graph that maintains parallel
edges if geometries differ.
Parameters
----------
G : networkx multidigraph
Returns
-------
networkx multigraph
"""
start_time = time.time()
# set from/to ... | cec8501248e24a7c7e8ae214dfd152d79dc837e1 | 71,051 |
def discrete(table, *condition, out=None, name=None):
"""
discrete probability function
Parameters
----------
table : (K, ...) np.ndarray or array-like
probability table
If a discrete variable A is conditioned with B and C,
table[a,b,c] give probability of A=a when B=b and C... | fcdfd06845c71b68a0a94fdc66b842e5f8ed02b3 | 71,053 |
import requests
def ack_url(url):
""" 访问网页 返回页面信息"""
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"}
response = requests.get(url=url, headers=headers)
return response.text | 8fa3f9c2b8983d45523461c0fa28cf9746d572c7 | 71,054 |
def readJacobians(testDir, varName, profList, chanList, pcrec=None, icldaer=0):
""" Read Jacobians from profiles_k.txt or profiles_k_rec.txt
testDir is the RTTOV test directory (e.g. tests.1.ifort/amsua/001)
varName is the variable of interest
profList is a list of profile numbers
... | 54a1334306f1ded3a67b6f250eefe00fe309dc1f | 71,055 |
def roundu(x: int, y: int, z: int) -> int:
"""Run calculation, round up, and return result."""
w = x * y / z
iw = int(w)
if iw - w != 0:
return iw + 1
return iw | 95a22ac5b7bd8d4054f83f3fa3daa56535f4fcdd | 71,057 |
import json
def card(username):
"""
Render the cluecard.
Args:
username: Username.
Returns:
HTML clue card.
"""
try:
id_database = json.load(open("ids.db"))
except FileNotFoundError:
id_database = {}
if username in id_database:
return render_te... | 17a007d6bd9b0cee81353409aea438a883ba37f3 | 71,059 |
def train_and_predict(k, D_tr, D_te, is_regressor):
"""Train classifier and predict gene responses.
"""
logger.info('Cross validating fold {}'.format(k))
X_tr, y_tr = D_tr
X_te, y_te = D_te
n_te_samples, n_feats = X_te.shape
if is_regressor:
## Train regressor and test
mod... | 88079939f840d20aa98cd6fccee2198ed3f4524f | 71,060 |
def hwc_to_chw(img):
"""
Transpose the input image; shape (H, W, C) to shape (C, H, W).
Args:
img (numpy.ndarray): Image to be converted.
Returns:
img (numpy.ndarray), Converted image.
"""
if is_numpy(img):
return img.transpose(2, 0, 1).copy()
raise TypeError('img s... | c2e1a7b0f683a1fc1e4201ac35acbdf1eb902634 | 71,061 |
def cmp(x, y): # from: https://portingguide.readthedocs.io/en/latest/comparisons.html
"""
Replacement for built-in function cmp that was removed in Python 3
Compare the two objects x and y and return an integer according to
the outcome. The return value is negative if x < y, zero if x == y
and str... | 1d141e389ecb20f180a7c1a6ef18b10b891eb41f | 71,063 |
from datetime import datetime
def convert_str_to_datetime(datetime_str, format=FMT):
"""
字串轉換成時間
字串預設可支援的格式:FMT = '%Y-%m-%d %H:%M:%S %Z%z'
"""
if datetime_str:
return datetime.datetime.strptime(datetime_str, format)
return None | bc3cc2acb5ee9d565ea8ef47ccb65e28223911eb | 71,064 |
def parse_cache_config_options(config, include_defaults=True):
"""Parse configuration options and validate for use with the
CacheManager"""
# Load default cache options
if include_defaults:
options = dict(type='memory', data_dir=None, expire=None,
log_file=None)
e... | 017d2c9c4f88a334d7b843965e310981081c5fed | 71,065 |
import curses
def _alternative_left_right(term):
"""_alternative_left_right(T) -> dict
Return dict of sequences ``term._cuf1``, and ``term._cub1``,
valued as ``KEY_RIGHT``, ``KEY_LEFT`` when appropriate if available.
some terminals report a different value for *kcuf1* than *cuf1*, but
actually s... | ffdbdbc3327af956c39ca1f806935c5dc651ff9b | 71,066 |
def gfMDS_make_cmd_string(info):
"""
Purpose:
Construct the command line options string passed to the MDS C code.
Usage:
Author: PRI
Date: May 2018
"""
# create the input files string
in_files = info["in_file_paths"][0]
for in_file in info["in_file_paths"][1:]:
in_files ... | 72a446bed8925b6b9ef20ebe21d2eb49982b86c2 | 71,067 |
def agg_post_stats(convo, filter_by=None):
"""
Computes a set of aggregate post statistical measures.
This is only computed for the integer and float subsets.
Specifically, the following stats are measured:
min, max, mean, median, standard deviation
Parameters
----------
convo : Conver... | 6742e6ef80c40a568d1d2d72a429d709a1599abe | 71,068 |
def main_diagonal_matrices_approximation(
level, max_level, dimension, probability, mu, nu, stimulus, model
):
"""
Creates the diagonal matrix A_{``level``, ``level``} in the approximating process X^{``model``}.
Parameters
----------
level : int
Level in the state space.
max_level :... | c1f520638b2b591c55571520b0d8561ff2bfe35d | 71,069 |
def admin_init(bot):
"""Step 1. Starts the service connection by redirecting to the service."""
dest = flask.request.args.get('dest', '')
redirect_uri = config.frontend_url + '/services/strava/admin/oauth?dest=' + dest
return _init(redirect_uri) | 07d826e8cadc035b423ae159d86062b1dee94842 | 71,071 |
from AyiinXd.modules.sql_helper.globals import gvarstatus
from AyiinXd.modules.sql_helper.pm_permit_sql import is_approved
async def permitpm(event):
""" Prohibits people from PMing you without approval. \
Will block retarded nibbas automatically. """
if not PM_AUTO_BAN:
return
self_user =... | 0b7153e2cfbec385d3bbd3b962b5cde72a9d131a | 71,072 |
def count_days(date1=None, date2=None, includeEnd=False):
"""Count the days between two dates
Parameters
----------
date1 : datetime.datetime object
Date 1
date2 : datetime.datetime object
Date 2
includeEnd : boolean
Whether to include the last day itself. Defaults to Fa... | 59732e02f209f91fabc20ae0ec4c76fb9c759ca7 | 71,073 |
from typing import List
from typing import Dict
def pyreq_list_nlu_intent(httpreq_handler: HTTPRequestHandler, project_id: int, locale: str) -> List[Dict]:
"""
Get the list of NLU intents in given locale in NLU model for Mix project
API endpoint
::
/v3/nlu/api/v1/ontology/{projectID}/intentio... | 1b90cdb5c052fa85a9abbcfcf766a05d66347a58 | 71,074 |
def _cluster_to_full_summary(cluster, now=None):
"""Convert a cluster to a full summary for use in creating a report,
including billing/usage information.
:param cluster: a :py:class:`boto.emr.EmrObject`
:param now: the current UTC time, as a :py:class:`datetime.datetime`.
Defaults to t... | a2b22af7ac6cbcca58f4564269680038f79708af | 71,075 |
import logging
def get_wandb_dir(cfg):
"""
Get the output directory where the wandb events will be written.
Args:
cfg (AttrDict): User specified config file containing the settings for the
wandb as well like log directory, logging frequency etc
Returns:
wandb_... | 9bd3de49891d6dcf41513adccc84ec954b28bc2c | 71,076 |
def _t0_afterglowpy_flux_model(time, burst_start, **kwargs):
"""
Afterglowpy based integrated flux models with burst_start as a parameter.
:param time: time in seconds
:param kwargs: Must include a burst_start and background_rate parameter. This background rate could be zero.
:return: integrated fl... | 2f210e1a7861fe9fee38073e807ee92adc37279f | 71,077 |
def common_model_config():
"""Returns common ModelConfig parameters."""
return {
'num_transformer_samples': FLAGS.samples_transformer,
'num_cnn_samples': FLAGS.samples_cnn,
'num_labels': FLAGS.num_labels,
'image_size': FLAGS.image_size,
'cnn_model_name': FLAGS.cnn_model_name,
'em... | 6d05db934e3196c053a3a7efe837848c28115a3d | 71,078 |
from typing import Callable
from re import A
from typing import Optional
from typing import Awaitable
import ray
def _try_eval_f_async_wrapper(
f: Callable[[A], B],
timeout_s: Optional[float],
success_handler: Callable[[B], C],
error_handler: Callable[[Exception], C],
num_cpus: int = 0,
) -> Calla... | f81accc8062d78c7c1d8b0105f0cc99d7d89a613 | 71,079 |
def transform_from_latlon(lat, lon):
"""
Input 1D array of lat / lon and output an Affine transformation.
Copied from Verseveld (2018).
"""
lat = np.asarray(lat)
lon = np.asarray(lon)
trans = Affine.translation(lon[0], lat[0])
scale = Affine.scale(lon[1] - lon[0], lat[1] - lat[0])
re... | 295657353ac55400c70b596decf4508e0d7b7cc4 | 71,080 |
def get_rest_url(model_name, host='127.0.0.1', port='8501', verb='predict', version=None):
""" generate the URL path"""
url = "http://{host}:{port}/v1/models/{model_name}".format(host=host, port=port, model_name=model_name)
if version:
url += 'versions/{version}'.format(version=version)
url += '... | 8399e75ad7b6991cb1ae56bd9d4020493741c484 | 71,081 |
def get_variable(name, stop_grad=False, ema=None, **kwargs):
""" utility to get variable"""
if stop_grad:
v = tf.get_variable(name, **kwargs)
v = tf.stop_gradient(v)
else:
v = tf.get_variable(name, **kwargs)
if ema is not None:
v = ema.average(v)
r... | 1dee83deed81b0e8a99e912fd644c6261aea9406 | 71,082 |
import json
def imageset_from_string(string, directory=None):
"""Load the string and return the models.
Params:
string The JSON string to load
Returns:
The models
"""
return imageset_from_dict(
json.loads(string, object_hook=_decode_dict), directory=directory
) | e12730e4ba6fe3fc2347ba2bd3811b0be09c079a | 71,083 |
def get_initial_state(inp):
"""
return tuple of (terminals,initial assignments) where terminals is a dictionnay key = target and value is a
list of start and end coordinates
"""
terminals = {}
assignments = {}
for row_ind in range(len(inp)):
for col_ind in range(len(inp[row_ind]... | 65189f967af0eaa41b914f2c2dd79f7e875fdafd | 71,084 |
def count_digit(value):
"""Count the number of digits in the number passed into this function"""
digit_counter = 0
while value > 0:
digit_counter = digit_counter + 1
value = value // 10
return digit_counter | f9b1738804b0a40aa72283df96d2707bcfd7e74c | 71,085 |
def remove_duplicates(nums):
"""
Remove the duplicates (more than twice) in the given sorted array in-place
:param nums: given array
:type nums: list[int]
:return: new length
:rtype: int
"""
if len(nums) <= 2:
return len(nums)
new_length = 1
for i in range(2, len(nums)):... | 30f388035ccedc4aab5e805930366eb99b29f780 | 71,086 |
def _query_search_async(q):
"""Searches for builds using NDB query. For args doc, see search().
Assumes:
- q is valid
- if bool(bucket_ids), permissions are checked.
"""
if not q.bucket_ids:
q.bucket_ids = yield user.get_accessible_buckets_async()
if q.bucket_ids is None:
# User has access to... | 344c6e842d98c6f57a62ee95ea394c4f26b9e085 | 71,087 |
def prepare_service(data):
"""Prepare service for catalog endpoint
Parameters:
data (Union[str, dict]): Service ID or service definition
Returns:
Tuple[str, dict]: str is ID and dict is service
Transform ``/v1/health/state/<state>``::
{
"Node": "foobar",
... | 5af6f0ae150fe21cd41d1ab14aa129d07efa08c5 | 71,088 |
def calculate_rms_means(means, corrected_means):
"""Calculates RMS of means from zero before and after correction
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
corrected_means: numpy array of corrected gaussian means for all PMT combs
Returns
------... | 2a04f27a9c795283031e552cc2c10ab62669cc44 | 71,089 |
import requests
import json
def organizations_import_from_master_server(request, state_code=''):
"""
Get the json data, and either create new entries or update existing
:return:
"""
messages.add_message(request, messages.INFO, "Loading Organizations from We Vote Master servers")
logger.info("L... | 217f4df36f31c91b4998d6e5fea3de537cb579e5 | 71,091 |
import requests
def bulk_avail(urllist):
"""
Filter 404 links out of URL list.
:param urllist: URLs to check.
:type urllist: list(str)
"""
sess = requests.Session()
url2 = [x for x in urllist if networkutils.availability(x, sess)]
return url2 | dea1ca64baf08363a5bb6f56d9c421df8fe79bc6 | 71,092 |
import json
def get_session(id):
"""
Get a session by Id
"""
url = "{}/{}".format(panopto_url("sessions"), id)
response = json.loads(get_resource(url))
return session_from_json(response) | 10dbcf4702c96f49a66c9b499bf93e1390930a84 | 71,093 |
def show_blog(title):
"""This will render a single blog
"""
form = CommentForm()
blog = Blog.query.filter_by(title = title).first()
comments = blog.comment
if form.validate_on_submit():
comment = Comment(comment_body = form.comment.data,author_id = current_user.id,blog_id = blog.id)
... | 5717e0a64ab25a39b0bf7341bfefd9f8573ee662 | 71,094 |
def _reciprocal_rank(target: np.array, preds: np.array):
"""
Implementation of reciprocal rank because couldn't find a good implementation.
`sklearn.metrics.label_ranking_average_precision_score` is similar but works in a different way
then the number of positive labels is greater than 1.
"""
as... | 83403bbf14479f2d2983fadfd7ef5bbe92fbb3ba | 71,095 |
def pull_images(aws_provider, remove_flag=False):
"""Pull images from AWS ECR
Args:
aws_provider (dict)
remove_flag (boolean)
Returns:
pulled_image_list (list)
"""
pulled_image_list = []
try:
for aws_config in aws_provider.values():
tmp = ecr.pull(... | b6d9ce88783b4fd45c97ab2156ee1ad5e5f8c7f2 | 71,096 |
import difflib
def compare_configs(cfg1, cfg2):
"""
This function, using the unified diff function, will compare two config files and identify the changes.
'+' or '-' will be prepended in front of the lines with changes
:param cfg1: old configuration file path and filename
:param cfg2: new configu... | a45afc01a5254950a9e0c97bdec2cd445c974d98 | 71,097 |
def _dataset_transform_fn(x, y):
"""Named transform function since lambda function cannot be pickled."""
return x, y | 03f4aecb76e85ad3b1b33e87739579c1f43357a1 | 71,098 |
from datetime import datetime
def delete_relationship(left_class=None, right_class=None,
left_type=None, left_id=None,
right_type=None, right_id=None,
rel_type=None, rel_date=None,
analyst=None, get_rels=True):
"""
Del... | 47b848aa90c379d45e7c27cec45c851578771a06 | 71,099 |
from scipy.spatial.distance import pdist, squareform
import warnings
def make_anisotropic_grf_psf_params(ntrain, nvalidate, nvisualize):
""" Make training/testing data for PSF with params drawn from anisotropic Gaussian random field.
"""
bd = galsim.BaseDeviate(314159+2718281828)
ud = galsim.UniformDe... | 073a2fab6238025b833aafb0a1cf8188f8f93f99 | 71,100 |
async def list_(hub, ctx, resource_group=None, **kwargs):
"""
.. versionadded:: 4.0.0
Lists all of the SSH public keys in the subscription.
:param resource_group: The name of the resource group to limit the results.
CLI Example:
.. code-block:: bash
azurerm.compute.ssh_public_key.li... | e94096f4bec362e35ae162e6b617c2a447354e60 | 71,101 |
import itertools
def load_simulation_params():
"""
Loads Utilities/SimulationParams
get all params from simulation params file.
and create dataframe with all the combinations that can be.
:return:
"""
temp_obj = SimulationParamsOptions()
list_of_params = []
simulations_params_name... | 2f5e82a406c063cc8a5cc3a55663b5d4d22f4407 | 71,102 |
def Specgram(X, W, H):
"""A function to compute the spectrogram of a signal
:parm X: N x 1 Audio Signal
:param W: Window Size
:param H HopSize
:returns: S, an N x NBins spectrogram array
"""
Q = W/H
if Q - np.floor(Q) > 0:
print('Warning: Window size is not integer multiple of ho... | 4a6144f386f9e82fa167d0a6ce4c3e8ee3cfd31e | 71,103 |
def to_3d(pos):
"""Convert 2d coords to 3d numpy arrays by adding a 0 in the z coordinate.
Converts already 3d coords to numpy arrays.
Parameters
----------
pos : tuple, list, ndarray
The coords to be converted to 3d.
Returns
-------
numpy array
3d coords.
"""
... | 38529e389f9a104beb38fe51fce1393e7bac2f67 | 71,104 |
def new_subpart_added(amendment):
""" Return True if label indicates that a new subpart was added """
new_subpart = amendment.action == 'POST'
label = amendment.original_label
m = [t for t, _, _ in amdpar.subpart_label.scanString(label)]
return (len(m) > 0 and new_subpart) | 4cb16044fbc1a8d6d0f8e05ba9185f5e04a08037 | 71,105 |
from typing import Union
from typing import List
from typing import Dict
def parameterised_pose_from_pdbblock(pdbblock: str,
wanted_ligands: Union[List[str], Dict[str, Union[str, None]]] = (),
force_parameterisation: bool = False,
... | 9621fd75b58c56d5fec6a53d4a32c5fd803c0d9a | 71,106 |
def get_peer_owned_files(conn: database.sqlite3.Connection, session_id: str) -> list:
""" Get all the files owned by the given peer
:param conn - the db connection
:param session_id - the session_id of the peer
:param source - 1 if we are interest only to files added originally by the peer, 0 if we are interest onl... | 24d7dbec32754f7250e6c1fd15e771b61bc5496b | 71,107 |
def make_objective(model_path,
param_names,
param_types,
job_path,
prop_name,
metric,
dic_path):
"""
Make objective function that gets called by `hyperopt`.
Args:
model_path (str): directo... | 524acf7fedafda7b5232525aaac5d338b6742a62 | 71,108 |
def build_qat_retinanet(
model: tf.keras.Model, quantization: common.Quantization,
model_config: configs.retinanet.RetinaNet) -> tf.keras.Model:
"""Applies quantization aware training for RetinaNet model.
Args:
model: The model applying quantization aware training.
quantization: The Quantization co... | e867c19e1ae87d1cfe0e8bbcb7704ee9b0d2b329 | 71,109 |
def update_graph_b(start_date, end_date, relayoutData, option_slctd) -> pd.DataFrame:
"""Depending on date picker, subplot figure and dropdown components inputs, update pie figure graph."""
if option_slctd == "AAPL":
df_sentiments_sum = datafetch.df_tweets_aapl_sentiments_minute
if option_slctd == ... | 73eb92d8491c63bf095914e39a96f56eb38b3548 | 71,110 |
def get_embedding(cnn, A, X, PS_params):
"""
Gets the embedding of the graph described by A and X using
Patchy-San and network cnn
Parameters :
cnn : Convolutional neural network giving the embeddings
A : Graph adjacency matrix
Xs: Graph features matrix
PS_params : Patch... | 5a52b0f680b32105616c427dfccb2dc2393fb1c9 | 71,111 |
def allnotq(X):
"""
Helper function used in manual_feature_extraction
Parameters
----------
X
dataframe to subset
Outputs
-------
Subsetted dataframe with no proteins quantified
"""
applied = X.apply(lambda x: np.sum(x),axis=1)
bools = np.where(applied == 0)
return X.iloc[bools].index.tolist() | afca863cdd36396cceb95a3fd48e6433eccf30ae | 71,112 |
def func_1(x: float, a: float, b: float) -> float:
""" Test function. """
return x + a + b | 776ad7473aa52b16fcd759e376f5f47a51c73013 | 71,113 |
def restart_hostagent(mac, **_):
"""
Ask a node to restart it's hostagent
Variables:
mac => mac address of the node
Arguments:
None
Data Block:
None
Result example:
{ "message_id": UUID } # UUID to look for in the
# control channel to get th... | b680ff1e9139fe12c3152fbbee15e8a101887e00 | 71,116 |
import socket
def get6addr(name):
"""Get IPv6 address for name. If necessary, an IPv4 over IPv6 address."""
try:
addr = socket.getaddrinfo(name, 'domain', family=socket.AF_INET6)
except socket.gaierror:
addr = socket.getaddrinfo(name, 'domain')
addr6 = '::ffff:' + addr[0][4][0]
... | 4ed93d37bf891b80a8a3ad0ff4eee3c1db643733 | 71,117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.