content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import fastapi
def read_search(search_id: int, search_repository: repository.search_repository.SearchRepository = fastapi.Depends(),
user: auth.authentication.User = fastapi.Depends(auth.authentication.get_current_user)):
"""
Get the details for a previously submitted search request.
... | e3117f0ad4a66725c0117640d7a54a0f3dabdb19 | 3,617,871 |
def mask_colorize(mask, num_classes, color_map):
"""
transfor one mask to a maske with color
:param mask: mask with shape [h, w]
:param num_classes: number of classes
:param color_map: color map with shape [N, 3]
"""
color_mask = Image.fromarray(mask.astype(np.uint8)).convert('P')
color... | 27a9eb472af4633c7856ee0535334561b1e64723 | 3,617,872 |
import configparser
def parse_config(filename):
"""Parses github-snooze-button configuration files.
Args:
filename: The name of a file in ConfigParser .ini format, described
below.
Returns:
A dictionary of dictionaries, one inner dictionary per repository.
Default val... | 86067a6a6e570b540d576aed8cd684bcc826e038 | 3,617,873 |
def load_vehicles(country, vehicles, last_updated):
"""Load list of vehicles from given country into database."""
clean_vehicles(country)
with elastic() as client:
for vehicle in vehicles:
vehicle.save(using=client)
upsert_metadata(country, last_updated)
return True | d49060d4aa29539bb83c12ee50962298eba130fe | 3,617,874 |
def get_ini_conf(fname):
""" Very simple one-lined .ini file reader, with no error checking """
with open(fname, "r") as handle:
return {i.split("=")[0].strip(): i.split("=")[-1].strip() for i in handle.readlines() if i.strip()} | 180c3106bb40c26b6628ff19dcb2c233a7f6a8d7 | 3,617,875 |
def calc_ratios2(roi,edict,which=0):
""" edict is a dictionary containing the event information.
Calculate for each photon the ratio of the source to the background.
"""
#ens = [[b.emax for b in roi.bands if b.ct==0],[b.emax for b in roi.bands if b.ct==1]]
ens = [[b.emax for b in roi.bands if b... | b30c8fe6ef233911be893fa37947a401d3165318 | 3,617,876 |
def multiclass_jaccard_loss_softmax(logits, labels, weight_class_sample_prob=False, weight_class_global_prob=False, train_class_probs=None, name='loss'):
""" multiclass Jaccard loss measure, softmax is applied internally on the y_preds
Args:
logits the predicted logits with shape [batchsize, ..., c... | f75d858aed5a1632c1e25cffb1c959fed84ad39f | 3,617,877 |
def get_testbed_vars():
"""
returns the testbed variables in a dictionary
:return: testbed variables dictionary
:rtype: dict
"""
return getwa().get_testbed_vars() | 2a454b30bbdf5373b97b368d9501ceea64a66018 | 3,617,878 |
def sign_user(user_data, fields=None):
"""Sign user data."""
signer = Signer(current_app.config['SECRET_KEY'], salt='newdle-users')
return dict(
user_data,
signature=signer.get_signature(
_get_signature_source_bytes(user_data, fields)
).decode('ascii'),
) | bfc2cd033fb52ed38365619f81155fcef0a06e1b | 3,617,879 |
def svn_repos_parse_dumpstream3(*args):
"""svn_repos_parse_dumpstream3(svn_stream_t * stream, svn_repos_parse_fns3_t parse_fns, void * parse_baton, svn_boolean_t deltas_are_text, svn_cancel_func_t cancel_func, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_parse_dumpstream3(*args) | e9454e92e865e1885353b77f1b43f82d11af052b | 3,617,880 |
import re
def decode_string_six_bits(binary: str, max_chars: int) -> str:
"""Decode binary string by decoding every sequence of six bits.
Args:
binary (str): Binary string
max_chars (int): Maximum length of resulting string
Raises:
ConvertException: Resulting string too large
... | 71b88d4eeddd6558471fc5b2cb2a1f8737e40d68 | 3,617,881 |
import socket
def whois(ip_address):
"""Whois client for Python"""
whois_ip = str(ip_address)
try:
query = socket.gethostbyname(whois_ip)
except Exception:
query = whois_ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.ripe.net", 43))
s.send(query.... | 7440f936ca866bc74ccd4e0d81bff56e46b82f60 | 3,617,883 |
def get_interesting_columns_all2D(datapath, column_indices, number_of_spectra,
n_rows):
"""
This will return a LIST of 2D DATA SETS. Each 2D spectrum in the list
will just be from the columns chosen by the user.
"""
n_columns = len(column_indices)
all_relevant... | 1cdff842f34656a0b98741d1174bc4d0ed5c8fb6 | 3,617,884 |
def oned_bump_combined():
"""
display all 1d traveling bump figures in one.
"""
fig = plt.figure(figsize=(10,4))
"""
oned_const_vel
#(oned_const_vel_bump,[],['oned_const_vel_bump_fig.pdf']),
"""
#######################################################################################... | 8605f774a48fbd0945ca4a5b14c1fc373f070f7e | 3,617,885 |
def get_det_coords(size: int, spacing: float) -> np.ndarray:
"""Compute pixel-center positions for 2D detector
The centers of the pixels of a detector are usually not aligned to
a pixel grid. If we center the detector at the origin, odd images
will have a pixel at zero, whereas even images will have tw... | 76a4582107a36b39670a33fe464107585db86941 | 3,617,886 |
def inverse_document_frequency(word, document_number, document_frequency):
"""Calculate idf value of a word
Args:
word: the word to be scored.
document_number: number of documents in dataset.
document_frequency: Frequency of a word in documents dataset, i.e.
if a document ha... | 1efce5bc5ed0f9bebc555c736bce7a7b8fcf71fb | 3,617,887 |
def str_to_acemask(lvl, is_object):
"""Return the acemask from a simplified access level
:param lvl: the access level to map, in "none, "read", "write" or
"read/write"
:type lvl: str
:param is_object: defined if the level corresponds to a data object or a
coll... | 30a782770c8a74874130125683406314e051a4a9 | 3,617,888 |
import pickle
def min_probabilities(p=0.0):
"""
!! OBSOLETE FUNCTION !!
:param p: p percentage, int(0 < p < 1)
:return: list of families with min(can be tuned) probabilities larger than p
"""
min_prob = []
with open(saved_feature_path + '/prob_of_each_sample_25families', 'rb') as fp:
... | 78583ea256eea8e2293c9ea845263532f5d5318a | 3,617,889 |
from typing import Optional
from typing import Dict
from typing import Any
def BRANCH_DESCRIPTOR(
project: ProjectHandle,
branch: BranchHandle,
urls: Optional[UrlFactory]
) -> Dict[str, Any]:
"""Dictionary serialization for branch descriptor.
Parameters
----------
projec... | a8b4f98d57e2a477e15b21c98953da1178df074a | 3,617,890 |
def evaluate_lenet5(train_set_x, train_set_y, valid_set_x, valid_set_y, test_set_x, test_set_y,
learning_rate=0.1, n_epochs=10,
nkerns=[20, 50], batch_size=BATCH_SIZE):
""" Demonstrates lenet on MNIST dataset
:type learning_rate: float
:param learning_rate: learning ... | 5526e8edaa349159e399cc21f5125ccd53a7977f | 3,617,891 |
def require_volume_exists(f):
"""Decorator to require the specified volume to exist.
Requres the wrapped function to use context and volume_id as
their first two arguments.
"""
def wrapper(context, volume_id, *args, **kwargs):
db.api.volume_get(context, volume_id)
return f(context,... | 8894631eeee76c7c3656c533c2294df1becf4ec8 | 3,617,892 |
def longitudinal_distance(reference: StateSE2, other: Point2D) -> float:
"""
Longitudinal distance from a point to a reference pose
:param reference: the reference pose
:param other: the query point
:return: the longitudinal distance
"""
return float(
np.cos(reference.heading) * (oth... | d1e71ef1e1bed1e7daefc8f77d609ff9fb201edb | 3,617,893 |
import logging
def send_message_via_backend(msg, backend=None, orig_phone_number=None):
"""send sms using a specific backend
msg - outbound message object
backend - MobileBackend object to use for sending; if None, use
msg.outbound_backend
orig_phone_number - the originating phone number to use... | 8b2a8cf09a645be2c174335ea06d60809193d863 | 3,617,895 |
def check(text):
"""Check the text."""
err = "misc.bureaucratese"
msg = "'{}' is bureaucratese."
bureaucratese = [
"meet with your approval",
"meets with your approval",
]
return existence_check(text, bureaucratese, err, msg, join=True) | 574c078f44cd6189aab91da5b9e59601d8cae5e0 | 3,617,896 |
def create_label_colormap(no_class=7, dataset=None):
"""Creates a label colormap used in Cityscapes segmentation benchmark.
Returns:
A Colormap for visualizing segmentation results.
"""
# GTA 19 Classes
if (dataset == 'GTA') or ( no_class == 19) :
colormap = np.array([
#... | f9de66711b02cc21d222051cc07ae18eb0e665cc | 3,617,897 |
def confirm_current_token(token_type: str, revoked: bool = True) -> User:
"""
验证token
:param jti: str jti字符串
:param token_type: str token类型
:param revoked 是否撤销token
:return (state, user)
"""
try:
jti = get_raw_jwt()["jti"]
token = TokenBlackList.where(jti=jti, token_type... | 238dfa4fbce1f2c1fd2601f4e130d83f26b28885 | 3,617,898 |
import torch
def rotate_image(img, max_rot_angle, dim=32):
"""Rotate image."""
# Pad image
padding = int(dim * 1.5)
padded_img, (x1, y1) = pad_image(img, padding=padding)
# Rotate image
rotation_deg = np.random.uniform(-max_rot_angle, max_rot_angle)
x_np = padded_img.permute(1, 2, 0).numpy()
x_np = n... | aefdb7374037cf9423c4663926f383b0f8e4d18d | 3,617,899 |
def simplify_control(A, B, x0, u0):
"""
Given the linarized A and B matrices corresponding to the state:
x = [u, v, w, p, q, r, phi, th, dpsi, x_r, y_r, z_r]
u = [T, a, e, r]
this function simplifies the model to assume the body rates p, q, r
are directly controlled, by essentially just removing the ro... | 5a39f02300a272ae235bb5e6b2c2195b2455dd3b | 3,617,900 |
def hdot_chart_line(datum: int) -> str:
"""Produce one line of a dot chart (without the label)."""
return lit.HDOT_ONE * datum | ad84600ed6b37d7440d07368841da054366328af | 3,617,901 |
from typing import Counter
import torch
def align_features_to_words(roberta, features, alignment):
"""
Align given features to words. Without assert.
Args:
roberta (RobertaHubInterface): RoBERTa instance
features (torch.Tensor): features to align of shape `(T_bpe x C)`
alignment: ... | e041f0a9657767dbfd51927c331fe55f80688570 | 3,617,902 |
import json
def img_one_day(request, date):
"""
get one-day detected faces
:param request:http request
:param date: the day client chose
:return:url list of one-day detected faces, formatted with JSon
"""
result_list = reader.get_one_day_img(date)
return HttpResponse(json.dumps(result_... | 2e1f43ee8a128732f8f94ad61961c122a098ff12 | 3,617,903 |
from datetime import datetime
def get_date_age(date):
"""
Take a datetime and return its "age" as a string.
The age can be in second, minute, hour, day, month or year. Only the
biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will
be returned.
Make sure date is not in the ... | a70d1d1368c69d10cfebd6f23a96b5f68337de48 | 3,617,904 |
import json
import logging
def SubtractHistogram(histogram_json, start_histogram_json):
"""Subtracts a previous histogram from a histogram. Both parameters are json
serializations of histograms."""
start_histogram = json.loads(start_histogram_json)
# It's ok if the start histogram is empty (we had no data, ma... | ac346f7d2e132b8577c957f89cd7fb6150207bf1 | 3,617,905 |
def lev_from_alignment(x_y_alignment_list, lengths):
"""
Given a list of aligned pairs and a list of lengths, computes the
Levenshtein for each pair in the list. Returns a list of distances.
:param x_y_alignment_list: a list where each element is itself a list
containing tuples representing the... | ea9148eb052e7af1db79876e23de74bbccdc8bf8 | 3,617,906 |
def get_shortest_path_lengths(G: nx.Graph, origin_nodes: list, destination_nodes: list, weight: str):
"""
This function calculates the shortest paths based on weight parameter.
---
Args:
origin_nodes (list): list of origin nodes
destination_nodes (list): list of destination nodes
... | 7722c3cfee41b61fd1249bd114bbb68ee8d3fb50 | 3,617,907 |
def evaluateAllQuestions(groundtruth_list, predictions_list):
""" Prints classification report for all questions
Parameters
----------
groundtruth_list :
list of event tuples for all questions
predictions_list :
list of event tuples for all questions
"""
questions = ["Type 1... | caa8755a2640bea6c4052c850266e5b5ac923da1 | 3,617,908 |
def _front_left_tire_pressure_supported(data):
"""Determine if front left tire pressure is supported."""
return data["status"]["tirePressure"]["frontLeftTirePressurePsi"] is not None | b59ab6f4a9b3d0801c1c5c8798e7da2fab0b580d | 3,617,909 |
def index_exists(name: str) -> bool:
"""
Check if an index with this name exists
"""
return es.indices.exists(index=name) | 4aa20debf29d098a48e633d50e76034cc723a301 | 3,617,910 |
import _ssl
def sslwrap_simple (sock, keyfile=None, certfile=None):
"""A replacement for the old socket.ssl function. Designed
for compability with Python 2.5 and earlier. Will disappear in
Python 3.0."""
ssl_sock = _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
... | 9ad4a2d87533d3bb91a31b067a1385fdf3cdb0e7 | 3,617,911 |
def count_missing_doc_types(articles):
"""
:param articles A PyMongo collection of articles
:return: int: Number or articles without a a 'doc_type' property or having
it equal to the empty string ('')
"""
return articles.count_documents(
{"$or": [{"doc_type": {"$exists": False}}, {"doc_t... | b0e734590c4b74572382e377f9cd861fa5162af7 | 3,617,912 |
def segment_length(p1 : np.ndarray, p2 : np.ndarray):
"""
p1 (2,)
p2 (2,)
"""
return npla.norm(p2-p1) | b36f7638d6a7bcc463e0a34c4102b10a12b98c20 | 3,617,913 |
def calculate_average(storage):
"""
Function prototype:
calculate_average(storage)
Function parameters (required):
storage - a list of tuples with RGB values; this list will be iterated and, using the values obtained,
will find the average RGB value
Function parameters ... | 1fd9ff8637c610dbb65153efa7b64f94e29bb475 | 3,617,915 |
def update():
""" """
lan_object = Languages()
lan_object.update()
message = lan_object.message
status = lan_object.status
data = {
"success": True,
}
return data | 2d628e95f733fd83d307b462094b227cf0fd98d4 | 3,617,917 |
from datetime import datetime
def now_int():
"""
Returns the current POSIX time as an integer.
:return: integer POSIX time
"""
now = datetime.now() - datetime(1970, 1, 1)
return int(now.total_seconds()) | 3c70a3324b549d24aaac01f49a2ed7ef480a8eb7 | 3,617,920 |
import logging
def compute_fid_from_activations(fake_activations, real_activations):
"""Returns the FID based on activations.
Args:
fake_activations: NumPy array with fake activations.
real_activations: NumPy array with real activations.
Returns:
A float, the Frechet Inception Distance.
"""
log... | ef145dcfdd8635069868edd5c61c5d679807ea53 | 3,617,922 |
def homoRunForOneVariant(chr_fa_seq, variant):
"""
Calculate and return the length of the largest homopolymer
touching this variant. Compute homopolymer lengths on the
left and right, and return the largest.
Args:
chr_fa_seq: A fasta sequence of chromosome in `varianti.CHROM`
varian... | d4119e6e7234b9bbe9cc754afcf16a74f4919b0e | 3,617,923 |
from typing import Tuple
from typing import List
def _align_dtypes(
df_a: pd.DataFrame, df_b: pd.DataFrame
) -> Tuple[List[int], pd.DataFrame, pd.DataFrame]:
"""Try to enforce the dtypes of non-object type of one dataframe
on the other. Return a list of index values for those columns
where it is not p... | bd36b3b40e7e48baa668b7e91468a85d10e3cc3e | 3,617,925 |
from typing import Set
from typing import Tuple
def matrix_cfpq(
graph: nx.MultiDiGraph,
cfg: CFG,
start_nodes: Set[int] = None,
final_nodes: Set[int] = None,
start_variable: Variable = Variable("S"),
) -> Set[Tuple[int, int]]:
"""
Context-Free Path Querying based on matrix multiplication
... | fadcdb320264ea3f1d4e13dee715d2fe78dfe139 | 3,617,926 |
def module_loaded(module):
"""
Checks if the specified kernel-module has been loaded.
:param module: Name of the module to check
:return: True if the module is loaded, False if not.
"""
return any(s.startswith(module) for s in open("/proc/modules").readlines()) | f09e719acba7f8e2aed59816d3b99bd9575edcfd | 3,617,927 |
def IsMonophyleticForTaxa(tree,
taxa,
support=None):
"""check if a tree is monophyletic for a list of taxa.
Arguments
---------
tree : :class:`Tree`
Tree to analyse
taxa : list
List of taxa
support : float
Minimum bo... | fcb0066c4083183cc7b81195a0845897d95b1cde | 3,617,928 |
def cleanfieldlower(value):
"""
remove spaces and convert to lower case
so flag error
"""
if not value:
return None
value = str(value)
value = value.strip()
value = value.lower()
return value | 1745c75293ca69419408de7b2c77e8293b252e1e | 3,617,929 |
import re
def bs_preprocess(html):
"""remove distracting whitespaces and newline characters
(c) mail-group of beautifulsoup4"""
pat = re.compile('(^[\s]+)|([\s]+$)', re.MULTILINE)
html = re.sub(pat, '', html) # remove leading and trailing whitespaces
return html | 22d759a7b48970d01782fa01c031cc60e29ad416 | 3,617,930 |
def query_done_cb(request, server_id):
"""
A callback for query completion notification. When the query is done,
BeeswaxServer notifies us by sending a GET request to this view.
"""
message_template = '<html><head></head>%(message)s<body></body></html>'
message = {'message': 'error'}
try:
query_histo... | 2c358392a2f5a0579db9452e9a47382203f18d83 | 3,617,931 |
def get_user_info(request):
"""
A helper function which uses the user information in the request to get the Player object (which also contains the
user object).
:param request: A html request with user data (specifically username)
:return: None if no user found, otherwise the Player object.
"""... | 59bd9abbc3a0158a38b2afd1088ff06346f204f8 | 3,617,932 |
def enthalpyliq(temp=None,pres=None,dliq=None,chkvals=False,
chktol=_CHKTOL,temp0=None,pres0=None,dliq0=None,chkbnd=False,
mathargs=None):
"""Calculate ice-liquid liquid water enthalpy.
Calculate the specific enthalpy of liquid water for ice and liquid
water in equilibrium.
:arg temp: ... | e0b0c6419f4d3a6cc3ce1f8d118a91038fd54988 | 3,617,933 |
def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
#... | 07aa40b33aab7aa5ea93c6b02ac8ed1dc1830650 | 3,617,934 |
def web3_get_code_sha256_hash(web3, addr):
"""
web3: Web3
addr: address in hex string
"""
code = web3.eth.getCode(to_checksum_address(addr))
return compute_code_sha256_hash(code) | 8caa66bf1ed3c12ea10292d1bdb5f7bbd01857c0 | 3,617,935 |
def complete_cluster(cluster: Cluster, host: Host) -> Cluster:
"""Add service, component and host to cluster"""
cluster.host_add(host)
service = cluster.service_add(name="first_service")
cluster.hostcomponent_set((host, service.component(name="first_service_component_1")))
return cluster | 6011a6af4ee1ea32776a33528d7e65e1e3b6895a | 3,617,936 |
def year_range(entry):
"""Show an interval of employment in years."""
val = ""
if entry.get("start_date") is None or entry["start_date"]["year"]["value"] is None:
val = "unknown"
else:
val = entry["start_date"]["year"]["value"]
val += "-"
if entry.get("end_date") is None or ent... | 92f7f0bcb450303161b7f766148a9feac62f98d1 | 3,617,937 |
def hamming_dist(a,b):
"""Return number of non-equal entries of a and b."""
return np.linalg.norm(a-b,ord=1) | 6b86ac73cf598f71598289b62a396d1cd9eb782f | 3,617,938 |
from splitgraph.core.output import parse_repo_tag_or_hash
from typing import Callable
from typing import Tuple
import logging
def prepare_splitfile_sql(sql: str, image_mapper: Callable) -> Tuple[str, str]:
"""
Transform an SQL query to prepare for it to be used in a Splitfile SQL command and validate it.
... | 8d67a25c0de66a3d59133345d1734e753656989f | 3,617,939 |
def grr_hostname(line):
"""Returns hostname of the selected client.
Args:
line: A string representing arguments passed to the magic command.
Returns:
String representing hostname of a client.
Raises:
NoClientSelectedError: Client is not selected to perform this operation.
"""
del line # Unus... | f7e40c2edd49f54f66e2e54039ee24cb0e496a4f | 3,617,940 |
def halo_bias(cosmo, halo_mass, a, overdensity=200):
"""Tinker et al. (2010) halo bias
Args:
cosmo (:obj:`Cosmology`): Cosmological parameters.
halo_mass (float or array_like): Halo masses; Msun.
a (float): Scale factor.
overdensity (float): Overdensity parameter (default: 200).... | 378366193a7e613193ba90e42abd91669b9ee797 | 3,617,941 |
def test_targets():
"""Returns the test targets which contain the main package and tests folder
"""
return [package_name(), 'tests'] | 440929fc8a6f41a078c5bf2f743c54779234f986 | 3,617,942 |
def LU_lndet(matrix, permutation, sign):
"""
Compute the determinant of {matrix} given its LU decomposition
"""
# easy enough
return gsl.linalg_LU_lndet(matrix.data) | 6fa3ec99b83ec31ff1bfaf9c49a98ff317dc0fd9 | 3,617,943 |
def _sample_household_cluster(sampler, bin_lower, bin_upper, reference_age, n):
"""
Return list of ages in a household/location based on mixing matrix and reference person age
"""
ages = [reference_age] # The reference person is in the household/location
if n > 1:
idx = np.digitize(refere... | d0f1c3b37b4376bb89396cdaa6624f393361145f | 3,617,944 |
def extract_BIO_tagged_tokens(text, source_spans, tokenizer):
""" Разобьем на bio-токены по безпробельной разметке """
tokens_w_tags = []
for span in source_spans:
s,e,tag = span
tokens = tokenizer(text[s:e])
if tag == 'Other':
tokens_w_tags += [(token,ta... | 7b56295f36040b68a3ba7d6f8c817d9f9b4c5094 | 3,617,945 |
def delete_user(id):
"""Get a particular user with it's ID and delete it."""
user = Users.query.get(id)
if user.role_id is 1:
return jsonify({
"message": "YOU DON'T WANNA DO THAT! YOU CANT DELETE AN ADMIN",
"status": 400
}), 400
user.delete()
return jsonify({
... | 2826c5ae27cf5517b4eb50ec53a076f4bc18f688 | 3,617,946 |
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
cors.init_app(flask_app)
db.app = flask_app
bcrypt.init_app(flask_app)
if cli is True:
migrate.init_app(flask_app, db)
return flask_app | 1cff800aaf988db380cf5a12fc7372b3ad647039 | 3,617,948 |
from datetime import datetime
def get_current_time()->int:
"""
Returns current timestamp in milliseconds
"""
return int(datetime.datetime.now().timestamp() * 1000) | fabde93e63770e668c0f8326a6aeb0717277d88e | 3,617,950 |
def tokenize(sentence):
"""
Using the bag words algorithm, every sentence has to be deconstructed to a
list of relevant particles. This function ecibes a sequence and uses the
nltk.word_tokenize() functtion to return a tokenized list.
>>>tokenize('How are you?')
['how', 'are', 'you', '?']
"""
return nltk.word_... | 0441a54fe4f29697330aa05658c8b5b10b821acf | 3,617,951 |
def d_key_pressed(environment, ambient=0.001):
""" Takes user input for theta and updates display. Function called
after 'd' pressed during interactive mode.
"""
environment.clearSources()
environment.updateAmbient(ambient)
dir_mag = 1.0
dir_phi = 5 * np.pi / 4
while True:
... | 896aa9fc982dbe7f8ced1c038c38e19601611102 | 3,617,952 |
def format_duration(dur: float) -> str:
"""Formats duration (from minutes) into a readable format"""
if float(dur) >= 1.0:
return "{} min".format(int(dur))
else:
return "{} sec".format(int(round(dur * 60))) | 02393e051b751001af9c8092ff64ebcef7596d6f | 3,617,953 |
import struct
def unpack(structure, data):
"""
Unpack little endian hexlified binary string into a list.
"""
return struct.unpack('<' + structure, bytes.fromhex(data)) | 530cf57b74be1e171a6f0c7ba148bdf73e8a7612 | 3,617,955 |
import time
def identify_missing(df=None):
"""Detect missing values.
Identify the common missing characters such as 'n/a', 'na', '--'
and '?' as missing. User can also customize the characters to be
identified as missing.
Parameters
----------
df : DataFrame
Raw data for... | 8e543f95ad8667341fc80313b4ff81e706fe7ad7 | 3,617,957 |
def get_recall(indices, targets):
""" Calculates the recall score for the given predictions and targets
Args:
indices (Bxk): torch.LongTensor. top-k indices predicted by the model.
targets (B): torch.LongTensor. actual target indices.
Returns:
recall (float): the recall score
"... | 63f4d7f36f63d3110c33989b03f264e1fa4aa4ff | 3,617,958 |
def get_collection_no(row):
"""Get the collection number from an expedition row."""
if row.get('collector_number'):
return row.collector_number
num = row.get('collector_number_numeric_only', '')
verb = row.get('collector_number_verbatim', '')
if verb and len(num) < 2:
return row.coll... | a3e92e24a6a5a95651b7ccde183ecc6b083a649a | 3,617,960 |
def _mi_dr(X, Y, sigma, n_bases, maxiter):
"""Estimate mutual information between X and Y using density ratio estimation.
Parameters
----------
X : array-like, shape (n_samples, n_features_x) or (n_samples)
Observations of a variable.
Y : array-like, shape (n_samples, n_features_y) or (n_sa... | e483916b9499e53c73a47adb00b2961368c8a09f | 3,617,961 |
def normalizeRows(x):
""" Row normalization function
Implement a function that normalizes each row of a matrix to have
unit length.
"""
### YOUR CODE HERE
x_sum = np.sum(x)
x = x / x_sum
### END YOUR CODE
return x | 690eacd3dfc88526640a5241cbb2570aeda66845 | 3,617,962 |
import requests
def retrieve_cluster_info(cluster_type, cluster_name):
"""
获取指定集群的信息
:param cluster_type: 集群类型
:param cluster_name: 集群名
:return: 集群信息
"""
url = "{}/storekit/clusters/{}/{}/".format(DATAHUB_API_ROOT, cluster_type, cluster_name)
res = requests.get(url=url)
if res.sta... | 6f4d73760005aa43e75431670b41d95cd0677c7f | 3,617,963 |
from typing import Union
def merge_titles(existing_work: Work, inserting_work: Work) -> Union[str, None]:
"""
Merge two titles into the best possible option
:return: string if best is changed from existing else None
"""
if existing_work.title == inserting_work.title:
best_title = N... | 1b83dc8b882f5a1372725412c697790852048f4d | 3,617,964 |
def HzanalCirc(sig, f, I, a, flag):
"""
Hz component of analytic solution for half-space (Circular-loop source)
Src and Rx are on the surface and receiver is located at the center of the loop.
.. math::
H_z = -\\frac{I}{k^2a^3} \
\\left( 3 -(3+\\imath\\ k... | fbc3b9fe91ddf55ee8611d09a568829a738d3fee | 3,617,965 |
def _get_versioned_config(config, version = ""):
"""select version from config
Args:
config: config
version: specified version, default is "".
Returns:
updated config with specified version
"""
versioned_config = {}
versioned_config.update(config)
used_version = co... | 70528e14148358613d2561c90e741b3f49569136 | 3,617,966 |
def fitDtm(initWorkingSetName,
stepName,
requestInfo,
jobId,
outputFolder,
dsmFile,
outputPrefix,
iterations=None,
tension=None):
"""
Run a Girder Worker job to fit a Digital Terrain Model (DTM) to a
Digital Surface Mode... | 88d242406ad786731e147b21b27fa918141d6b91 | 3,617,967 |
from typing import Union
def deserialize_timestamp_from_kraken(time: Union[str, FVal, int, float]) -> Timestamp:
"""Deserializes a timestamp from a kraken api query result entry
Kraken has timestamps in floating point strings. Example: '1561161486.3056'.
If the dictionary has passed through rlk_jsonloads... | 294d96b4c1aa69ef8a4aec9b8c84d283c6cd2296 | 3,617,968 |
def anti_alias_filter(x,params):
"""
Anti_aliasing: use Nyquist frequ cutoff low-pass filter
:return: anti-aliased signal
"""
fs = params['fs']
assert(type(x)==np.ndarray)
# def build_aa_filter(fs):
# """
# :param fs: sampling rate
# :return: 1D array impulse respo... | e140183050c88c27e5d8b6923cb6660ad2860525 | 3,617,969 |
import torch
def get_optimizer(optimizer_name: str, *args, **kwargs) -> torch.optim.Optimizer:
"""
A simple utility function for retrieving the desired optimizer.
Not the most optimized algorithm, but the number of optimizers should never
exceed even 100 in my opinion so a linear time algorithm is acc... | cc2a58248147aef39308d20a6ce4ddb7388f4a05 | 3,617,971 |
def rand_unselected_dut(request, duthosts, rand_one_dut_hostname):
"""
Return the left duthost after random selection.
Return None for non dualtor testbed
"""
dut_hostnames = generate_params_dut_hostname(request)
if len(dut_hostnames) <= 1:
return None
idx = dut_hostnames.index(rand_... | 3880899961d6ee9b967716d91e05c6f5b101a9e9 | 3,617,972 |
def query_author_by_org(Session, orgs):
"""Return a query that, if run, would return all RFCs whose authors'
organizations match every string in `orgs`.
The matching on `orgs` is case-insensitive. Asterisks (*) in passed orgs
are replaced with percent signs (%) to function as wildcards in the actual
... | f4d92ab991064b8e4b11dfbb4e30254b782ed284 | 3,617,973 |
import configparser
from typing import Union
def _prompt_for_option_name (ARG_config_object: configparser.ConfigParser, ARG_section: str) -> Union[str, None]:
"""Prompts the user to enter a valid option name. Checks that option name exists.
Parameters
----------
ARG_config_object : configparser.Confi... | b9aea1ba8a19d0c3a104a4e661a4043e9ad33889 | 3,617,974 |
from typing import Union
from typing import BinaryIO
from typing import Tuple
def read_leader(f: Union[str, BinaryIO]) -> Tuple[Vocab, Vectors]:
"""Read vectors from a leader file.
This is our fully binary vector format.
The first line is a header for the leader format and it is a 3-tuple.
The eleme... | 0de3bab630d555277917e0e473d2024235a4f10f | 3,617,975 |
def find_direct_conflicts(pull_ops, unversioned_ops):
"""
Detect conflicts where there's both unversioned and pulled
operations, update or delete ones, referering to the same tracked
object. This procedure relies on the uniqueness of the primary
keys through time.
"""
return [
(pull_... | 5832a41b81cffd7e5c7d1f79472f9c44eaa3127a | 3,617,976 |
def unknown_id_to_symbol(unknown_id, header="X"):
"""Get the symbol of unknown whose id is |unknown_id|.
:type unknown_id: int
:type header: str
:param unknown_id: The ID of the unknown.
:param header: The symbol header.
:rtype : str
:return: A string that contains the symbol.
"""
... | 53081447eb0c5daf70d1af936337b35bffe4caf0 | 3,617,977 |
def get_bulk_subgraphs(bulk_structure_sg):
"""
Get all subgraphs of molecules that within or crosses the boundary of
original bulk.
Parameters:
-----------
bulk_structure_sg: StructureGraph.
The structure graph of bulk with local env strategy.
Returns:
--------
super_graphs... | e66eff5bc6ec99f7934606365d775b3ba046c1f6 | 3,617,979 |
import re
def markdown_to_doxygen(string):
"""Markdown to Doxygen equations"""
long_equations = re.sub(
r"(?<!\\)\$\$(.*?)(?<!\\)\$\$", r"\\f[\g<1>\\f]", string, flags=re.DOTALL
)
inline_equations = re.sub(r"(?<!(\\|\$))\$(?!\$)", r"\\f$", long_equations)
return inline_equations | 2cae07ccb661ef22fab518d4fae4a0cc22868d84 | 3,617,982 |
def dijkstra(graph, src, dest):
"""Find shortest path from src to dest
graph:
dict[list[(int, int)]]: {node: [adj_node1, adj_node2,...]}
src (int):
dest (int):
"""
to_process = PriorityQueue()
# Start with the source and zero cost
to_process.put((0, src))
# Now as y... | 6387e0e28a84a4ae94c8163c1757bd2d2f73fdcb | 3,617,983 |
def convert_3_class(data_dir, out_dir='three_class/'):
"""
Transform attribute labels in the dataset in data_dir to create a separate prediction class for not visible attributes
"""
def filter_not_visible(d):
certainty = np.array(d['attribute_certainty'])
not_visible_idx = np.where(cert... | 2564b42d1af6e7109d6043a6f12f6eb358891a9c | 3,617,984 |
from ggrc.notifications import cron_jobs
def get_jobs_to_register(name):
"""Get cron job handlers defined in `notifications` package.
Get cron job handlers defined in `notifications` package as `name`. Note
that handlers will be returned only if `NOTIFICATIONS_ENABLED` flag in
settings is set to `True` value... | ee2ac7487a96244b636a67dad4333f728a1e02e7 | 3,617,985 |
def is_network_exists(vca_client, network_name):
"""
network already exist
"""
return bool(vca_client.get_network(get_vcloud_config()['vdc'],
network_name)) | 6d72651019be58cefd878551970e257cf0bf78c4 | 3,617,986 |
def xml_dict_to_point(data: dict) -> Point:
"""
Create a Point from a dict representing a location in KML
Args:
data: xml dict data
Returns:
Point
"""
point = Point()
point.description = data['description']
point.name = data['name']
point.style = data['styleUrl']
... | b3a03be7a9bbdefad7e9401b3b623b6ed5c0ab3b | 3,617,987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.