content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def is_report_metrics_switch_on():
"""
Whether bagua report switch is on or not.
"""
return int(os.environ.get("BAGUA_REPORT_METRICS", 0)) == 1 | 2b6712a606cc5039cf7b9f56a418206a4e859878 | 37,900 |
def getinstructorData(courseIds):
"""
Gets and instructor object for the course id's given.
"""
instructorDict = {}
instructor = CourseInstructor.select().where(CourseInstructor.course << courseIds)
for i in instructor:
instructorDict.setdefault(i.course.id, []).append(i.user.firstName ... | 845c7cbc7a0eaa41072662d2669509c2b722ceb3 | 37,901 |
def convert_farenheit_to_celcius(temp):
"""Convert the temperature from Farenheit to Celcius scale.
:param float temp: The temperature in degrees Farenheit.
:returns: The temperature in degrees Celcius.
:rtype: float
"""
return (temp - 32) * 5 / 9 | a782550aa33641a719eb6b245d894248aeaa4985 | 37,902 |
from sys import version
def creates_app():
"""Create the application
Returns:
[sanic.Sanic]: the main application
"""
LOGGER.info("Create application %s", app_version.RELEASE)
app = sanic.Sanic(__name__)
app.static('/static', './static')
errors.add_exceptions_handlers(app)
ap... | 67ff34d48a5ff54d697391c408033fde5a2f50f1 | 37,903 |
import argparse
def parse_args():
"""Parse arguments and return them
"""
parser = argparse.ArgumentParser(
description='fpb is a fuel plugin builder which '
'helps you create plugin for Fuel')
# TODO(vsharshov): we should move to subcommands instead of
# exclusive group, because i... | 40a0801fa7c4a60d7d33ce6e0c7e8fc3daa477a6 | 37,904 |
def get_frequent_item(data):
"""
对于给定的字符串列表,找出其中出现次数最多的字符
参数
----
data: list[str],字符串列表
返回
----
re: list[str],出现次数最多的字符串
"""
_hash = word_count(data)
max_num = max(_hash.values())
return list(filter(lambda x: _hash[x] == max_num, _hash)) | 6cd1b6cd77e9855c6732614b3fbf2096ae1fcbfb | 37,905 |
def float_coords_(coords):
"""\
"""
return [float_recur(coord) for coord in coords] | c02fced6a0137a5bc933a81d0decc472f62faa62 | 37,906 |
def getLastSystemMessage(sensorId,sessionId):
"""
getLastSystemMessage - get last system message (metadata only) for the sensor.
URL Path:
- sensorId: The sensor ID for which the configuration is desired.
- sessionId: The session ID for the session.
HTTP Return Codes:
- 200 OK... | 62de832dbe2de69cf612c0830ecd3cea89a90c1f | 37,907 |
import subprocess
def assemble(filepath):
"""Converts human-readable LLVM assembly to binary LLVM bitcode.
Args:
filepath: The path to the file to assemble. If the name ends with ".bc", the
file is assumed to be in bitcode format already.
Returns:
The path to the assembled file.
"""
if not f... | 05802c5208deb783bff4cd2e54da8365d043a189 | 37,908 |
def invt_sample_z(log_density, size=1, rng=None, **log_cdf_kwargs):
"""
Inverse transform sampling to generate "true" z values for simulation:
"""
if rng is None:
rng = np.random.default_rng()
zgrid, log_cdf = get_log_cdf(log_density, **log_cdf_kwargs)
cdf = np.exp(log_cdf)
interp_... | 7f7e1cb86aa04dc6b00d8d35f3c8cb8028e326ab | 37,909 |
from functools import reduce
import operator
def fsort(l, signed=True, reverse=False):
"""Sort a sequence of strings with one or more floating point number fields
in using the floating point value(s) (and intervening strings are treated
as normally done). Note that + and - preceding a number are included ... | 75b9b465bca0e5792a128682a8b31756779173c5 | 37,910 |
import re
def food_parse(db, query):
"""
returns a jsonable dict for the autocomplete js library we are using
for a text field used to select a food item
:param db:
:param query:
:return:
"""
parts = re.split("\s+", query)
parts = [lemmer.lemmatize(part) for part in parts]
db_... | ab55b9e1bbdf3a248c46316cdb8e69400fac9876 | 37,911 |
from typing import Union
from pathlib import Path
from typing import Optional
from typing import Tuple
import numpy
from typing import Dict
def read_gpop_hdf5(
path: Union[Path, str], interior_path: str, dof: Optional[int] = None
) -> Union[
Tuple[numpy.ndarray, Dict[int, numpy.ndarray], Dict[int, numpy.ndarr... | 286886a9866bc77b9ab5610c95ec248ceb4839d5 | 37,912 |
def invite(request):
"""
Simple view to send invitations to friends via mail. Making the invitation
system as a view, guarantees that no invitation will be monitored or saved
to the hard disk.
"""
if request.method == "POST":
mail_addr = request.POST['email_addr']
raw_addr_list ... | 14ba6ebd044710649f82c6d7b94b4b752d24bfae | 37,913 |
from pathlib import Path
import sys
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
"""Builds a wheel, places it in wheel_directory"""
poetry = Poetry.create(".")
return unicode(
WheelBuilder.make_in(
poetry, SystemEnv(Path(sys.prefix)), NullIO(), Path... | 81c492da04b9e22dd126ec1027881a11f4bd5762 | 37,914 |
def cells():
"""Cells
From in 'Image manipulation and processing using Numpy and Scipy' section
2.6.6 Measuring object properties
<http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html>
No known copyright restrictions, released into the public domain.
"""
np.random.s... | 71a9fe2eda33585527b93710f97e76d6a9f8be10 | 37,915 |
import inspect
def jsonify_arg_input(arg):
"""Jsonify user input (in AssemblyPipeline `append` and `insert` methods)
into a standard step json."""
if isinstance(arg, RunnableArgument):
return arg.to_json()
# If a function object or name of a function is provided, we assume it
# does not ha... | ec5f04b42a410b8aea2ed9b01b5b506f1b9629ea | 37,916 |
def geodetic_to_ellipsoidal(lat: u.deg, lon: u.deg, height: u.m, ell):
"""Convert from geodetic to ellipsoidal-harmonic coordinates.
Parameters
----------
lat : ~astropy.units.Quantity
Geodetic latitude.
lon : ~astropy.units.Quantity
Geodetic longitude.
height : ~astropy.units.Q... | ffaf011660c9a21908aa25e04c64e6aa9bd8d6f4 | 37,917 |
def enc_backbuffer(backbuffer):
"""Helper function for RLE compression, encodes a string of uncompressable data."""
compdata = []
if len(backbuffer) == 0:
return compdata
while len(backbuffer) > 128:
compdata.append(127)
compdata.extend(backbuffer[0:128])
backbuffer = bac... | 75e9860cd0a8563f3e5655b998b4d0dfa1658e9c | 37,918 |
def fourier_features(index, freq, order):
"""
`Reference`_: https://www.kaggle.com/ryanholbrook/seasonality
Example:
>>> # Compute Fourier features to the 4th order (8 new features) for a
>>> # series y with daily observations and annual seasonality:
>>> # fourier_features(y, freq=365.25, order... | 1568aa388889ca01e47f3eb63fbf19a92bdcc0e9 | 37,919 |
def read_range(read):
"""Creates a Range proto from the alignment of Read.
Args:
read: nucleus.genomics.v1.Read. The read to calculate the range for.
Returns:
A nucleus.genomics.v1.Range for read.
"""
start = read.alignment.position.position
end = start + cigar.alignment_length(read.alignment.ciga... | 4a0c4519cde59484d5aae3acd72d71e870fecc60 | 37,920 |
def _get_label_members(X, labels, cluster):
"""
Helper function to get samples of a specified cluster.
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
cluster ... | 95c9f4e898b0636d3e7b6151f6d336137200143c | 37,921 |
def create_balcony(bm, faces, prop):
"""Generate balcony geometry
"""
for f in faces:
if not valid_ngon(f):
popup_message("Balcony creation not supported for non-rectangular n-gon!", "Ngon Error")
return False
f.select = False
normal = f.normal.copy()
... | 80a1d98b8b5fd89d7f3f594edf6d51c358eb3551 | 37,922 |
import os
def output_path(inid=None, ftype='data', format='json', site_dir='_site',
must_work=False):
"""Convert an ID into a data, edge, headline, json, or metadata path
Args:
inid: str. Indicator ID with no extensions of paths, eg '1-1-1'.
Can also be "all" for all data... | 39a0bd9dab42eae7c2ff9fa6fb407d291b5ecdbf | 37,923 |
def film_availability_keys():
"""
FilmAvailability definition
Optional keys: "id"
"""
return ["service", "displayName", "country", "url"] | 829ec5ea5492b58c19639f0f83245a88aedb6cc8 | 37,924 |
def get_label(scores):
""" Compute labels using score values.
Args:
scores: Score values for each detection.
Returns: Label for each detection.
"""
return tf.math.argmax(scores, axis=1) | abcd01c989f25d574236c19ffc6cafe2eb66257d | 37,925 |
def cm_step_summary(abf):
"""
Return a message displaying average stats
formatted like 'Cm = 34.56 +/- 3.21 pF'
"""
Ihs, Rms, Ras, Cms = cm_step_valuesBySweep(abf)
out = ""
out += "Ih = %.02f +/- %.02f pA\n" % (np.mean(Ihs), np.std(Ihs))
out += "Rm = %.02f +/- %.02f pA\n" % (np.mean(Rms)... | e4df5d9f524dfd450c05a407b6726ff75034638c | 37,926 |
from pathlib import Path
def check_arg_input_file(input_file: str) -> bool:
"""Return True of the input_file exists, raise an error otherwise.
:param input_file: the input file
:param input_format: the expected format of the input file
"""
path_input_file = Path(input_file)
if not path_input_... | df1f877be2afc1d37a008a551776a9adcc3f2b8a | 37,927 |
def V_tank_Reflux(Reflux_mass, tau, rho_Reflux_20, dzeta_reserve):
"""
Calculates the tank for waste.
Parameters
----------
Reflux_mass : float
The mass flowrate of Reflux, [kg/s]
tau : float
The time, [s]
rho_Reflux_20 : float
The destiny of waste for 20 degrees celc... | 3e1adc446bbe2dd936663af895c59222cd000a48 | 37,928 |
import sysconfig
import os
def locate_ob():
"""Try use pkgconfig to locate Open Babel, otherwise guess default location."""
# Warn if the (major, minor) version of the installed OB doesn't match these python bindings
if not is_package_installed("openbabel"):
raise RuntimeError("Error: Openbabel is... | db60512ea1c80ce9d8e73280c755269dabf601ff | 37,929 |
def angular_travel(angle_array):
"""
Takes in an array of angular change and returns the angles travelled. This is sensitive to changes in
direction, The angles travelled are returned as an array of stepwise values
"""
travelled = [0]
for a, angle in enumerate(angle_array):
travelled.app... | 0c9eca97614a38c7400796ae3930f18707bc948d | 37,930 |
import os
def check_output_dir(output_dir):
"""
Checks the output directory for files generated in previous runs, these can be skipped later by detect_trs()
Checking is done quite naively, only looking for files ending in '.pickle' (so no support for .pcl, .pkl ...)
Parameters:
output_dir (str): ... | 30e9945cabced00a65d4d5dc9d4194656d0083dc | 37,931 |
def IR_50(cfg):
"""Constructs a ir-50 model.
"""
input_size = cfg.INPUT.SIZE_TRAIN
model = Backbone(input_size, 50,cfg.MODEL.BACKBONE.BACKBONE_OUT_CHANNELS, 'ir')
return model | fef1dce13a8c4d50e669551b6b561ef1d9014007 | 37,932 |
def writeNetfile2(G, fname):
"""
write net file from G (networkx)
Parameters
----------
G: a neteworkx object
Returns
-------
file
"""
nZones = ''
nNodes = str(len(G.nodes()))
nLinks = str(len(G.edges()))
header = "<NUMBER OF ZONES> " + nZones + "\n<NUMBER OF NODES> " + nNodes + "\n<FIRS... | ea4b914c2169d3d3cc92a51c84ffcf89fe4bfd4e | 37,933 |
import torch
def attention_aggregator(embedding_lists, weights, embed_dim=0) -> torch.Tensor:
"""
Returns a weighted sum of embeddings
:param embedding_lists: list of n tensors of shape (l, K) embedding tensors (l can vary)
:param weights: list of n tensors of shape (l,) weights (l can... | 88fe01d8baea23321593bf88fd522eb0ef379be9 | 37,934 |
def _calculate_application_risk(module):
"""
Function to calculate Software risk due to application type. This
function uses a similar approach as RL-TR-92-52 for baseline fault
density estimates. The baseline application is Process Control
software. Every other application is ranked relative to ... | 703aaf086aecf717be5c13694a8f1dae9f70a86c | 37,935 |
def test():
""" Eventually this could become a convenience command for calling the
other test commands quickly with just test -x.
"""
return test_all() | 8a1bb5d89aa73f0236de0316b38c02ea17ae18cd | 37,936 |
import os
def callback():
"""
Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
global REDI... | 263e63ace22d49b7ec94316b1ccb2578f2f6c67c | 37,937 |
import os.path
def export_file(isamAppliance, file_path, filename, check_mode=False, force=False):
"""
Downloading a file from the file application log files area
"""
if force is True or (os.path.exists(filename) is False):
if check_mode is False: # No point downloading a file if in check_mo... | 06f8ae0a885745e9b5fd765cb45afd08db609bd4 | 37,938 |
def parse_mid_list(mid_list, transit_duration):
"""
TODO: make sure tdb iso is precise
output will be saved in csv
"""
t12 = ["ingress"]
tmid = ["midtransit"]
t34 = ["egress"]
for mid in mid_list:
ing = mid - dt.timedelta(days=transit_duration / 2)
egr = mid + dt.timedel... | baba7f12b2e4dd79d66b659f84839f728360110b | 37,939 |
import argparse
def get_args():
"""
desc: get cli arguments
returns:
args: dictionary of cli arguments
"""
parser = argparse.ArgumentParser(description="this script is used for downloading datasets for training this implementation of the Hierarchical Attention Networks")
parser.add_argument("dataset"... | 93c51d6471dae45ff20fee33b71fa9cdd4c213ef | 37,940 |
def RK(A,b,k=100, random_state=None):
"""
Function that runs k iterations of randomized Kaczmarz iterations (with uniform sampling).
Parameters
----------
A : NumPy array
The measurement matrix (size m x n).
b : NumPy array
The measurement vector (size m x 1).
k : int_, opti... | 375acf10f277ff7533b0b45058a836c46328deea | 37,941 |
def run_k_means(reduced_text: str, k: int, dataframe: pd.DataFrame)->None:
""" create dataframe column for k means cluster """
kmeans = KMeans(n_clusters=k, random_state=42)
y_pred = kmeans.fit_predict(reduced_text)
dataframe['y_pred'] = y_pred
return y_pred | 08fbf8cb54bc74d410f674924cc13bc82e376578 | 37,942 |
from typing import List
from typing import Tuple
def split_blank_line(
lines: List[str], line_offset: int = 0
) -> Tuple[List[str], List[str]]:
"""Split leading blank line from lines if one exists
Args:
lines: The lines to evaluate.
line_offset (optional): The offset into the overall docu... | c70cf05111ec17c12797b5d94a547db0b4d3427c | 37,943 |
from typing import Union
import requests
import json
def get_page_list_by_page(base_url: str, api_token: str, page_path: str, limit:Union[int, None]=None) -> dict:
"""
get page list under the specified page path
"""
req_url = '{}{}'.format(base_url, '/_api/pages.list')
limit = 1e10 if limit is Non... | dbf70ac34187748e9f6dbfc4296df738c98819b6 | 37,944 |
def erode_edges(mask, erosion_width):
"""Erode edge of objects to prevent them from touching
Args:
mask: uniquely labeled instance mask
erosion_width: integer value for pixel width to erode edges
Returns:
mask where each instance has had the edges eroded
"""
if erosion_widt... | 35a32f14b8ca9c54d090fe0e77e4108f02f8fe4b | 37,945 |
import re
def load_keel_file(path):
"""Load a keel dataset format.
Parameters
----------
path : str
The filepath of the keel dataset format.
Returns
-------
keel_dataset: KeelDataset
The keel dataset format loaded.
"""
handle = open(path)
try:
... | 55849a706cdc8a3790501f694329ac73dbe1cb0d | 37,946 |
import os
def get_annotations(directory):
""" Returns rel path for all anvil files in a directory"""
return (
os.path.join(directory, f)
for f in os.listdir(directory)
if f.endswith(".anvil")
) | 606fce3064f7fca95c0860d07829dc9f3e121be8 | 37,947 |
import torch
def searchsorted2d(a, b):
"""
Searches a sorted 2D array along the second axis. Basically performs a vectorized digitize. Solution provided here:
https://stackoverflow.com/questions/40588403/vectorized-searchsorted-numpy.
:param a: The array to take the elements from
:type a: torch.Te... | f46cf6217e7ec85ba0a27df8474b64bebc552759 | 37,948 |
def bytesToBits(numBytes):
"""
Converts number of bytes to bits.
:param numBytes: The n number of bytes to convert.
:returns: Number of bits.
"""
return numBytes * 8 | 6dc14c9d9f5829337e826c63a7772ea8d3c6962c | 37,949 |
def rankhist(X_f, X_o, X_min=None, normalize=True):
"""Compute a rank histogram counts and optionally normalize the histogram.
Parameters
----------
X_f: array-like
Array of shape (k,m,n,...) containing the values from an ensemble
forecast of k members with shape (m,n,...).
X_o: arr... | 91c60cdcd6b046a43fca6502ae83d8bba90e6569 | 37,950 |
def build_data_sampler(config, dataset):
"""Returns a data sampler object of :class:`colossalai.nn.data.sampler.BaseSampler`
constructed from `config`.
Args:
config (dict or :class:`colossalai.context.Config`): A python dict or
a :class:`colossalai.context.Config` object containing info... | 1afcf7dc176eba096dda3ca998f1cc075269e321 | 37,951 |
def to_kwargs(triangles):
"""
Convert a list of triangles to the kwargs for the Trimesh constructor.
Parameters
---------
triangles: (n,3,3) float, triangles in space
Returns
---------
kwargs: dict, with keys:
'vertices' : (n,3) float
'faces' : ... | 067afee9f1d848893198c94a9caef93a2667978a | 37,952 |
def get_model_field(model, name):
"""
Gets a field from a Django model.
:param model: A Django model, this should be the class itself.
:param name: A Django model's field.
:return: The field from the model, a subclass of django.db.models.Model
"""
return model._meta.get_field(name) | e0f692aff82c20c7817d7de5d1fbeec1b69d3a3d | 37,953 |
from scipy.stats.mstats import trimmed_mean, trimmed_std
def get_clean_sample_mask(log_mah_fit, logmp_sample, it_min, lim=0.01, z_cut=3):
"""Calculate mask to remove halos with outlier MAH behavior.
Parameters
----------
log_mah_fit : ndarray of shape (n_halos, n_times)
logmp_sample : float
... | d1c2e530c0e0feb14061a71c7cf71dcb8d1724d7 | 37,954 |
import os
def _get_answer_files(request):
"""
Gets the path to where the hashed and raw answers are saved.
"""
answer_file = f"{request.cls.__name__}_{request.cls.answer_version}.yaml"
raw_answer_file = f"{request.cls.__name__}_{request.cls.answer_version}.h5"
# Add the local-dir aspect of the... | 4d1faed155090f329c4d5efb78a606e25e9aca0f | 37,955 |
def inert_masses(m_1, H, z_m, E_1):
"""First stage inert masses.
Arguments:
m_1 (scalar): First stage wet mass [units: kilogram].
H (scalar): Fraction of the recovery vehicle dry mass which is added recovery
hardware [units: dimensionless].
z_m (scalar): Fraction of baseline... | 5698fcb36ef1f532cc8bc1dc0c86a25adc5bcab8 | 37,956 |
def _grid_mapping(pollon, pollat, mapping_name=None):
"""creates a grid mapping DataArray object"""
if mapping_name is None:
mapping_name = cf.DEFAULT_MAPPING_NCVAR
da = xr.DataArray(np.zeros((), dtype=np.int32))
attrs = cf.mapping.copy()
attrs["grid_north_pole_longitude"] = pollon
attrs... | 4a7478ee0ca612158b4eb3e5b83de511acf3b978 | 37,957 |
def retrieve_employees(page=1):
"""
Handle requests to the /employees/<int:page> route - @roles_required(xxx)
Retrieve all employee from the DB ordered by the First Name with the pagination support
Filter employees based on specified start date and end date
"""
employees_per_page = 7
employ... | 62cead2fcd605c8d884771ac0681e574db25b4b7 | 37,958 |
def __virtual__():
"""
Confine this module to yum based systems
"""
if __opts__.get("yum_provider") == "yumpkg_api":
return (False, "Module yumpkg: yumpkg_api provider not available")
try:
os_grain = __grains__["os"].lower()
os_family = __grains__["os_family"].lower()
exc... | 67daa8e6afdd95d6c2ffa0589579b22494869c94 | 37,959 |
def get_update_message(new_version, info_url):
"""Return a string suitable for notifying users about the status
of their update check. NEW_VERSION and INFO_URL generally come
directly from a call to update_check()."""
if new_version is None:
return (f'You are running the latest version ({__ver... | cfe8010e02d1a0f770e17c4615b737a42a98530f | 37,960 |
def str_url_encode(text):
"""
Encode package before send to Telegram API.
:param text: string.
:return: string.
"""
return quote(text) | 4c195f7df7830119277dfd6d5bb00ad9ffebdc6a | 37,961 |
from typing import Any
def block(func: AnyCallable, *args: Any, **kwargs: Any) -> Any:
"""
Run a function in a blocking manner, whether the function is async or blocking.
Args:
func - the function (async or blocking) to run
args - the args to run the function with
kwargs - the kwa... | dce4632e64f45106b66206bb7c5eca5ccdfc8335 | 37,962 |
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... | 25570f21f266a92b9e2291d7c6d8338e0a242e66 | 37,963 |
def commnets(milestone):
"""Filtrira milestone tako da nadje samo broj komentara za svaki pojedinacni"""
comments = milestone.event_set.filter(event_kind="K")
size = comments.count()
return size | 9c3654911fe993c359bc593433b6fde1c467a504 | 37,964 |
import six
def finish_login(request):
"""Complete OpenID Login Process"""
response = _finish_verification(request)
if not response:
# Verification failed, redirect to login page.
return redirect(request, 'mediagoblin.plugins.openid.login')
# Verification was successfull
query = O... | e3ceefa6ae768f8aba2e26970a39b2daf037a5c9 | 37,965 |
import re
def check_tweet_emphasis(tweet):
"""
Performs check whether words in a tweet have 3 or
more repeating characters. If the word has 3 or
more repeating characters, word will be replaced
by one that matches the original word as close as
possible repeated twice, otherwise original wor... | fa14474733f684767bb52c66a0d7da3ffcd0d010 | 37,966 |
def buildList(pdList, matrix):
"""Takes a list of primary datasets (PDs) and the AlCaRecoMatrix (a dictinary) and returns a string with all the AlCaRecos for the selected PDs separated by the '+' character without duplicates."""
alCaRecoList = []
for pd in pdList:
alCaRecoList.extend(matrix[pd].spli... | 7e9351f115aac1064068e16f12276ed5506217e4 | 37,967 |
import random
def random_wish(rankings):
"""
Select a wish randomly with exponential decay
:param rankings: ordered [(pitch, role)]
:return: i the index of the chosen wish in the rankings
"""
cum_weights = exp_cum(len(rankings))
total = cum_weights[-1]
hi = len(cum_weights) - 1
ret... | 9f229d9478655dedc7f8c63a39e0140f3a6884a8 | 37,968 |
def serialize_to_database(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, date):
return str(obj.isoformat())
if isinstance(obj, (DateRange, DateTimeRange)):
return f"[{obj.lower}, {obj.upper}]"
return obj | a537ac8096e6d7955608887c7c7c08ece9467092 | 37,969 |
def _flatten_dict_into_array(dictionary, dtype=np.float32):
"""
Flatten the given dictionary into an array of scalars, and return the beginning index of each sequence of values.
Parameters
----------
dictionary : dict
Some dictionary containing scalars or array of scalars as each of its key... | e4390204b1a64adac8b0788f9d5f3ec646cf1850 | 37,970 |
def DecoderBlock(d_model, d_ff, n_heads,
dropout, mode, ff_activation):
"""Returns a list of layers that implements a Transformer decoder block.
The input is an activation tensor.
Args:
d_model (int): depth of embedding.
d_ff (int): depth of feed-forward layer.
n_... | 9b5b4678ac988714e1d3af96c0dfb9ff43847c03 | 37,971 |
def get_gradient(pixels,processing = 'normalize'):
"""returns the gradient of an image, and does basic preprocessing"""
horgradient = ndimage.sobel(pixels, axis = 1)
vergradient = ndimage.sobel(pixels, axis = 0)
gradient = np.array((vergradient,horgradient))
if processing == 'normalize':
"... | d05f562b54fb2800fa1eb1a97d6373912906e40c | 37,972 |
def get_roommates():
"""Endpoint to get all rooms for the given search conditions."""
LOGGER.info(' Inside /api/getRoommates')
roommates_list = userscontroller.get_all_roommates("")
return roommates_list | 35c9ade000f2bd07dddc78cd0d9f0c24ea3516cb | 37,973 |
def log_mean_temp_diff(T_A_one, T_A_two, T_B_one, T_B_two):
"""
Calculate the logarithmic mean temperature difference (LMTD) of two fluid
streams `one` and `two` of a heat exchanger with two ends `A` and `B`.
Parameters:
-----------
T_A_one : float, int, np.array
Fluid temperature of st... | 63e683186ba0644222c5406807c605be662cfc40 | 37,974 |
from typing import Dict
from typing import Any
from typing import Optional
def trade_from_coinbase(raw_trade: Dict[str, Any]) -> Optional[Trade]:
"""Turns a coinbase transaction into a rotkehlchen Trade.
https://developers.coinbase.com/api/v2?python#buys
If the coinbase transaction is not a trade related... | 930db004948e3f73fb423a6920c4e7c87ccf1988 | 37,975 |
import os
def has_image_extension(uri) -> bool:
"""Check that file has image extension.
Args:
uri (Union[str, pathlib.Path]): the resource to load the file from
Returns:
bool: True if file has image extension, False otherwise
"""
_, ext = os.path.splitext(uri)
return ext.lowe... | e9f338ecda0fa5842fd1aeb15362718d6f026fe6 | 37,976 |
def infected():
"""
Real Name: b'Infected'
Original Eqn: b'INTEG ( Infection Rate-recovery rate, 1)'
Units: b'Person'
Limits: (None, None)
Type: component
b''
"""
return _integ_infected() | 5bab3a7b2be75fca2e1ef8dc15b1dc0ef681aee3 | 37,977 |
from typing import Optional
def get_dataproc_cluster(cluster_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDataprocClusterResult:
"""
Get information about a Yandex Data Proc cluster. For more... | a43b7db12fd88315ad28adb412dd18b915c9864d | 37,978 |
import ctypes
def GetNumberPreAmpGains(LR: ctypes, error: Error=default) -> tuple:
"""
Returns tuple(MsgError type, number)
"""
if not error['status']:
n = ctypes.c_int32(0)
number= ctypes.pointer(n)
executed = LR.GetNumberPreAmpGains(number)
return errorcodehandler(ex... | 5e30aa344860eb89d6ed112a1a283aa5f439eec0 | 37,979 |
import os
def write_file(self):
"""write file to disk with a random name (to compare)"""
self.is_private = 1
file_path = get_files_path(is_private=self.is_private)
if os.path.sep in self.file_name:
frappe.throw(_('File name cannot have {0}').format(os.path.sep))
# create directory (if not exists)
frappe.cre... | d538235cc156db758fd53ec16a6ca5e17d15d160 | 37,980 |
from typing import List
def ele2json(data: list) -> List[str]:
"""把元素为dict类型的list数据,转为,元素为json字符串的list数据
Args:
data: list类型的数据,元素为dict类型
Returns:
转换后的list数据
"""
return [dict2json(item) for item in data] | 2fc4b1d6328fd1101f89a8fbc6e177e177f51207 | 37,981 |
def remove_small_components(mesh, min_volume=5e-05):
"""Removes all components with volume below the specified threshold."""
if mesh.is_empty:
return mesh
out = [m for m in mesh.split(only_watertight=False) if m.volume > min_volume]
if not out:
return mesh
return trimesh.util.concatenate(out) | b2ec1f367a28aee505c569900edc035ded3e8331 | 37,982 |
def is_retriable(exception):
"""Returns True if this exception is retriable."""
errs = list(range(500, 505)) + [429]
errs += [str(e) for e in errs]
if isinstance(exception, HttpError):
return exception.code in errs
# https://cloud.google.com/storage/docs/key-terms#immutability
if isinsta... | 27d556924e521f970124e751144b5e2675d623f1 | 37,983 |
def var_to_struct(val, name, format='%s', do_trim=True, evaluate_full_value=True):
""" single variable or dictionary to Thrift struct representation """
debug_value = DebugValue()
try:
# This should be faster than isinstance (but we have to protect against not having a '__class__' attribute).
... | 04f0dcb1db352b557f88082da078d6988db52895 | 37,984 |
def parse_styles(cssfiles):
"""
Parse CSS files.
This parse some CSS files and build a map of each attribute with these values.
It's very useful to inline some CSS propety to html objects.
:param cssfiles: A list of CSS files
:type cssfiles: list
:return: A map of C... | 5193b3c672de6c434cc4475a4508ab2160aa4202 | 37,985 |
def sgld_gradient_update(step_size_fn, seed):
"""Optix implementation of the SGLD optimizer"""
def init_fn(_):
return OptixSGLDState(count=jnp.zeros([], jnp.int32),
rng_key=jax.random.PRNGKey(seed))
def update_fn(updates, state, params=None):
del params
lr = step_size_fn(... | 3b4c448027f0267082fd0d747e7280cbf348b79d | 37,986 |
import re
def _get_ip_addr_num(file_path):
"""Get the next IPADDR index num to use for adding an ip addr to an
ifcfg file.
"""
num = ''
with open(file_path, 'r') as f:
data = f.read()
data = data.splitlines()
for line in data:
found = re.search(r'IPADDR(\d?)=', line)
... | 09dfd6bc8a9da240d3044bd6f5b974c69cbebf76 | 37,987 |
def subsample(X, subsample=1, seed=0):
"""Subsample a fraction of 1/subsample samples from the rows of X.
Parameters
----------
X : np.ndarray
Data array.
subsample : int
1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.
seed : int
Seed for sampling.... | 2ce66b67b771bb5f7ab60d8b318cff732c292a66 | 37,988 |
def norm(collection: str, country_code: str, name: str, lang: str = DEFAULT_LANG) -> str:
"""Normalize the name with respect to a collection and country code.
>>> norm(CITY, 'RU', 'leningrad')
'Saint Petersburg'
>>> norm(CITY, 'RU', 'peterburg')
'Saint Petersburg'
>>> norm(CITY, 'RU', 'peterbur... | 925e8993dea77d88180c13ce3af42e90c80b49cb | 37,989 |
def createFeatureDF(pairs, classes, knownDrugDisease, drugDFs, diseaseDFs):
"""Create the features dataframes.
:param pairs: Generated pairs
:param classes: Classes corresponding to the pairs
:param knownDrugDisease: Known drug-disease associations
:param drugDFs: Drug dataframes
:param disease... | bf36f8cc23d50d553d00e419b781fa0d55bca029 | 37,990 |
def getBigram(words, join_string):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of bigram, e.g., ['I_am', 'am_Denny']
I use _ as join_string for this example.
"""
assert type(words) == list
L = len(words)
if L > 1:
lst = []
for i in range(L-1):
... | 07c0c421b6d5530059fc06e49b338f1984a445f8 | 37,991 |
def get_xqueue_callback_url_prefix(request):
"""
Calculates default prefix based on request, but allows override via settings
This is separated from get_module_for_descriptor so that it can be called
by the LMS before submitting background tasks to run. The xqueue callbacks
should go back to the L... | b4301e623eb3886d76430289473aea3288511241 | 37,992 |
def abi_extensions():
"""List with all the ABINIT extensions that are registered."""
return list(_EXT2VARS.keys())[:] | 41b47b2c96e65c3af3ab15a7ad4cddb3213c3a1c | 37,993 |
import glob
def load_csvs():
"""Returns dataframe containing all CSV files from directory 'cache' and returns a list of the filepaths.
"""
path = 'cache'
csv_list = glob.glob(path + "/*.csv") # collect all filepaths
df = pd.concat((pd.read_csv(f, index_col=0) for f in csv_list)) # concatenate all... | 648e0819ed696024f2dd2dd9f7bbd05faf0c25f9 | 37,994 |
def merge_networks_from_tags(shape, props, fid, zoom):
"""
Take the network and ref tags from the feature and, if they both exist, add
them to the mz_networks list. This is to make handling of networks and refs
more consistent across elements.
"""
network = props.get('network')
ref = props.... | f8d4f764f885c8db7c920169d65126a783f6c1ee | 37,995 |
def tabs(text: str) -> str:
"""Remove tabs.
If you want to replace tabs with a single space, use
`normalize.whitespace()` instead.
Args:
text (str): The text from which tabs will be removed.
Returns:
The stripped text.
"""
return resources.RE_TAB.sub("", text) | 494216fa8ad5570604a69c8c37e94797b268381a | 37,996 |
from numpy import nan
def tobool(value):
"""Convert value to boolean or Not a Number if not possible"""
if value is None: value = nan
else: value = bool(value)
return value | 9517d817381111c55e73e03256d516ccbbd940a2 | 37,997 |
import json
import collections
def load_synonyms(synonym_filepath=None):
"""Loads synonym dictionary. Returns as defaultdict(list)."""
with tf.gfile.Open(synonym_filepath) as f:
synonyms = json.load(f)
synonyms_ = collections.defaultdict(list)
synonyms_.update(synonyms)
return synonyms_ | 2d98df5edf7b116a7807851db234dfa322da9a99 | 37,998 |
def get_table_code(sol, table_name, unused_options):
"""
Gets the table code of a given parameter. For example, the
DISPLACMENT(PLOT,POST)=ALL makes an OUGV1 table and stores the
displacement. This has an OP2 table code of 1, unless you're running a
modal solution, in which case it makes an OUGV1 ... | d9840f55260b92f704160906cfb65baa678881ff | 37,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.