content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def isnan(x: array, /) -> array:
"""
Tests each element ``x_i`` of the input array ``x`` to determine whether the element is ``NaN``.
Parameters
----------
x: array
input array. Should have a numeric data type.
Returns
-------
out: array
an array containing test results... | 5,319,600 |
def _replace_vars(text, param_dict):
"""
Given a block of text, replace any instances of '{key}' with 'value'
if param_dict contains 'key':'value' pair.
This is done safely so that brackets in a file don't cause an error if
they don't contain a variable we want to replace.
See http://stackoverfl... | 5,319,601 |
def test_get(api_client, api_settings) -> None:
"""Test get request on the home route."""
response = api_client.get("/")
assert response.status_code == 200
assert response.json() == {
"AppName": api_settings.app_name,
"SwaggerUI": api_settings.swagger_url,
"ReDoc": api_settings.... | 5,319,602 |
def import_key(filepath: Union[str, PathLike[str], Path], passphrase: Optional[str] = None) -> RsaKey:
"""
Import a secret key from file.
Parameters
----------
filepath : str | os.PathLike[str] | pathlib.Path
Filepath of RsaKey.
passphrase : str | None
Passphrase for the key.
... | 5,319,603 |
def GetZonesInRegion(region: str) -> Set[str]:
"""Returns a set of zones in the region."""
# As of 2021 all Azure AZs are numbered 1-3 for eligible regions.
return set([f'{region}-{i}' for i in range(1, 4)]) | 5,319,604 |
def test_delete_accessor(api_rf, km_user_accessor_factory):
"""
Sending a DELETE request to the endpoint should delete the accessor
with the given ID.
"""
accessor = km_user_accessor_factory()
km_user = accessor.km_user
api_rf.user = km_user.user
request = api_rf.delete("/")
respon... | 5,319,605 |
def compare_3PC_keys(key1, key2) -> int:
"""
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
"""
if key1[0] == key2[0]:
return key2[1] - key1[1]
else:
return key2[0] - key1[0] | 5,319,606 |
async def test_validate_config_ok(hass, hass_client):
"""Test checking config."""
with patch.object(config, "SECTIONS", ["core"]):
await async_setup_component(hass, "config", {})
client = await hass_client()
with patch(
"homeassistant.components.config.core.async_check_ha_config_file",... | 5,319,607 |
def merge_two_lists_heap(l1: ListNode, l2: ListNode) -> ListNode:
"""Returns a single sorted, in-place merged linked list of two sorted input linked lists
The linked list is made by splicing together the nodes of l1 and l2
Args:
l1:
l2:
Examples:
>>> l1 = linked_list.convert_l... | 5,319,608 |
def demo():
""" Step 1 of the authentication workflow, obtain a temporary
resource owner key and use it to redirect the user. The user
will authorize the client (our flask app) to access its resources
and perform actions in its name (aka get feed and post updates)."""
# In this step you will ... | 5,319,609 |
def get_blast(pdb_id, chain_id='A'):
"""
Return BLAST search results for a given PDB ID
The key of the output dict())that outputs the full search results is
'BlastOutput_iterations'
To get a list of just the results without the metadata of the search use:
hits = full_results['BlastOutput_iterat... | 5,319,610 |
def getDayBoundaryTimeStampFromUtcTimeStamp(timeStamp, timeZoneId):
"""
get to the day boundary given a local time in the UTC timeZone.
ts is the local timestamp in the UTC timeZone i.e. what you would
get from time.time() on your computer + the offset betwen your
timezone and UTC.
"""
(ts, ... | 5,319,611 |
def generate_cylinder_square_array(size, porosity, segmented=True):
""" Generate a 2D periodic array of circles
:param size: length of one side of the output domain
:type size: int
:param porosity: porosity of the output domain
:type porosity: float
:param segmented: return ... | 5,319,612 |
def run(config_path, pipeline_config_path=None):
"""Run the apply_image_model module.
Args:
config_path: path to a ModuleConfig file
pipeline_config_path: optional path to a PipelineConfig file
"""
config = ModuleConfig.from_json(config_path)
etam.setup(config, pipeline_config_path=... | 5,319,613 |
def test_patch_basket_clear_coupon_auto(
basket_client, basket_and_coupons, mock_context
):
""" Test that an auto coupon is applied to basket when it exists and coupons cleared """
basket = basket_and_coupons.basket
auto_coupon = basket_and_coupons.coupongroup_worst.coupon
original_basket = render_j... | 5,319,614 |
def main(args: argparse.Namespace):
"""Main entry point of the app
"""
logger = tf.get_logger()
logger.info("redneuronalsimple")
logger.info(args)
mnist_builder = tfds.builder("mnist")
mnist_builder.download_and_prepare()
ds = mnist_builder.as_dataset(split="train")
ds = ds.repeat()... | 5,319,615 |
def ephemerides(file_path,
P_orb=2.644,
T_e=2455959.0039936211,
e=0.152,
P_rot=None,
phase_start=None,
Rot_phase=False,
print_stat=True,
save_results=False,
save_name=None):
... | 5,319,616 |
def _GetMSBuildToolSettings(msbuild_settings, tool):
"""Returns an MSBuild tool dictionary. Creates it if needed."""
return msbuild_settings.setdefault(tool.msbuild_name, {}) | 5,319,617 |
def test_build_full_orm_compound(session, biology_qualifiers, namespaces):
"""Expect that a fully fleshed out compound can be deserialized."""
obj = CompoundModel.parse_obj(
{
"id": "1",
"notes": "bla bla bla",
"names": {
"chebi": [
... | 5,319,618 |
def _apply_color(color: str, message: str) -> str:
"""Dye message with color, fall back to default if it fails."""
color_code = AvailableColors["DEFAULT"].value
try:
color_code = AvailableColors[color.upper()].value
except KeyError:
pass
return f"\033[1;{color_code}m{message}\033[0m" | 5,319,619 |
def choice_geometry(elite):
""" Positions shapes for user selection """
geo = []
# Generate shape for selection
for i in range(6):
elite[i].evaluate()
print("Adding geometry: " + str(i))
offset = 100
offset_x = i % 3 * offset
offset_y = i % 2 * offset
geo.... | 5,319,620 |
def get_mel_spectrogram(audio, pextract=None):
"""Mel-band energies
Parameters
----------
audio : numpy.ndarray
Audio data.
params : dict
Parameters.
Returns
-------
feature_matrix : numpy.ndarray
(log-scaled) mel spectrogram energies per audio channel
"""
... | 5,319,621 |
def getName(value):
"""
Finds the name of a :model:`browseNet.path` or :model:`browseNet.Share`.
"""
if isinstance(value,Path):
return value.shortname
elif isinstance(value, Share):
return value.sharename
else:
return "??" | 5,319,622 |
def balanced_outward(source: str, pos: int) -> list:
"""
Returns balanced CSS model: a list of all ranges that could possibly match
given location when moving in outward direction
"""
pool = []
stack = []
result = []
prop = []
prop.append(None) # Get rid of pyLint rant
def scan_... | 5,319,623 |
def test_no_incompatible_ospf_sessions():
"""Confirm no-incompatible-ospf-sessions assert passes and fails as expected when specifying a session."""
bf = Session(load_questions=False)
with patch.object(
bf.q, "ospfSessionCompatibility", create=True
) as ospfSessionCompatibility:
# Test s... | 5,319,624 |
def float_2_bytes(f, is_little_endian=False):
"""
:param f:
:param is_little_endian:
:return:
"""
# 小端数据返回
if is_little_endian:
return struct.pack('<f', f)
# 大端数据返回
return struct.pack('>f', f) | 5,319,625 |
def _unimplemented(*args, **kwargs): #pylint: disable=W0613
"""
Null function.
"""
pass | 5,319,626 |
def setup_pluginbase(extra_policies_path=None):
"""Sets up plugin base with default path and provided path
Args:
extra_policies_path (str): Extra path to find plugins in
Returns:
PluginSource: PluginBase PluginSource for finding plugins
"""
here = pathlib.Path(__file__).parent.abso... | 5,319,627 |
def compute_balanced_class_weights(train_y: Union[np.array, pd.Series, List[any]]
) -> Dict[int, float]:
"""Computes balanced class weight dictionary from train targets.
The key is a index of sorted unique values occuring in train_y.
"""
unique = sorted(np.unique(t... | 5,319,628 |
def get_frames_index_range(filename, start, end):
"""
returns a range of frames as numpy array. The indecies comply with scimage
We can then supplement the above table as follows:
Addendum to dimension names and orders in scikit-image
Image type: 2D color video
coordinates: (time, row, col, ch... | 5,319,629 |
def create_job_env(profiler=False):
"""Create a dictionary that contains the jobs' environment.
The job environment is loaded at execution time and is available in
the process that runs the jobs command. This stores the values from the
current environment (usually the machine from which you submit your... | 5,319,630 |
def clean_up(inpfn):
"""Clean up for the given input file."""
backup_file = '{}.bak'.format(inpfn)
if os.path.isfile(backup_file):
os.remove(backup_file)
_LOGGER.debug("Deleting %s", backup_file) | 5,319,631 |
def create_conda(project_name):
"""Create conda environment if neccessary."""
# Check system for project tools.
tool_name = re.sub(r'[\s_]', '-', project_name)
# Check conda env and create if necessary.
envs = json.loads(subprocess.getoutput('conda env list --json'))['envs']
if not [i for i in... | 5,319,632 |
def killIfAlive(sprite, partner, game):
""" Perform the killing action, only if no previous collision effect has removed the partner. """
if partner not in game.kill_list:
killSprite(sprite, partner, game) | 5,319,633 |
def load_SMI_data_from_Helmholtz():
"""
Downloading SMI topsoil data from helmholtz website
"""
url = "https://www.ufz.de/export/data/2/237851_SMI_L02_Oberboden_monatlich_1951_2018_inv.zip" # noqa: E501
response = requests.get(url)
return response | 5,319,634 |
def get_yaml_test_method(test_file, expected_load_file, expected_dump_file, regen=False):
"""
Build and return a test function closing on tests arguments and the function
name.
"""
def closure_test_function(self):
with io.open(test_file, encoding='utf-8') as inp:
test_load = san... | 5,319,635 |
def read_date_dirs(dpath='.',dir_filter='*',
expected_date_format='%Y%m%d',
reader=pd.read_csv,
ext='csv',
verbose=False,
**kwargs):
"""Wrapper around pandas read_csv() or data reader function.
Additional readers:
... | 5,319,636 |
def find_wfss_config_filename(pathname, instrument, filtername, mode):
"""Construct the name of the WFSS configuration file given instrument parameters
Parameters
----------
pathname : str
Path where the configuration files are located
instrument : str
Instrument name (e.g. 'nircam... | 5,319,637 |
def create_mosaic_normal(out_img, maximum):
"""Create grayscale image.
Parameters
----------
out_img: numpy array
maximum: int
Returns
-------
new_img: numpy array
"""
new_img = np.array(
[np.hstack((
np.hstack((
np.flip(out_img[i, :, :], 1).T... | 5,319,638 |
def notices_for_cfr_part(title, part):
"""Retrieves all final notices for a title-part pair, orders them, and
returns them as a dict[effective_date_str] -> list(notices)"""
notices = fetch_notices(title, part, only_final=True)
modify_effective_dates(notices)
return group_by_eff_date(notices) | 5,319,639 |
def build_markdown_cpp_cell(cell):
"""
Save the C++ source code and try to build it
"""
# Comment out ```'s
txt = cell['source'].replace('```', '// ```')
cpp_file_name = get_filename_in_second_line(txt)
if not cpp_file_name:
# obtain temporary file name
cpp_file_name = get_... | 5,319,640 |
def compute_kdtree_and_dr_tractogram(tractogram, num_prototypes=None):
"""Compute the dissimilarity representation of the target tractogram and
build the kd-tree.
"""
tractogram = np.array(tractogram, dtype=np.object)
print("Computing dissimilarity matrices...")
if num_prototypes is None:
... | 5,319,641 |
def substitute(dictionary, variables, model_context, validation_result=None):
"""
Substitute fields in the specified dictionary with variable values.
:param dictionary: the dictionary in which to substitute variables
:param variables: a dictionary of variables for substitution
:param model_context: ... | 5,319,642 |
def get_status():
"""
Get status of working copy, return tuple of
(changed_paths, new_paths, deleted_paths).
"""
paths = set()
for root, dirs, files in os.walk('.'):
dirs[:] = [d for d in dirs if d != '.git']
for file in files:
path = os.path.join(root, file)
... | 5,319,643 |
def batch_query_entrez_from_locus_tag(locus_tag_list):
""" convert a list of locus tags to list of entrez ids
Keyword arguments:
locus_tag_list: a list of locus tags
"""
mapping_dict = {}
id_list = list(set(locus_tag_list))
# initiate the mydisease.info python client
client = get_client(... | 5,319,644 |
def _check_error_term(X):
"""Checks whether an error term was provided.
Parameters
----------
X : numpy.array
Design matrix.
"""
r = 1 - X @ la.pinv(X).sum(1)
if (r ** 2).mean() > np.finfo(float).eps:
warnings.warn("Did you forget an error term, I? :-)") | 5,319,645 |
def gather_2d(params, indices):
"""Gathers from `params` with a 2D batched `indices` array.
Args:
params: [D0, D1, D2 ... Dn] Tensor
indices: [D0, D1'] integer Tensor
Returns:
result: [D0, D1', D2 ... Dn] Tensor, where
result[i, j, ...] = params[i, indices[i, j], ...]
Raises:
ValueError... | 5,319,646 |
def test_pipeline_executor_py_file_without_code_reference_tracking(mocker):
"""
Tests whether the PipelineExecutor works for .py files
"""
before_call_pandas_spy = mocker.spy(PandasBackend, 'before_call')
after_call_pandas_spy = mocker.spy(PandasBackend, 'after_call')
before_call_sklearn_spy = m... | 5,319,647 |
def updateUserDetails(request, user_id):
"""
Update user details view
depending on is_admin flag, admin profile is either created or deleted.
"""
user = get_object_or_404(User, pk = user_id)
user_serializer = UserSerializer(user, data = request.data)
if user_serializer.is_valid():
... | 5,319,648 |
def png_load(pngfile):
"""
Load a PNG file. Returns a numpy matrix with shape (y, x, 3)
png = png_load(pngfile)
pix = png[4, 5]
r, g, b = pix
:param pngfile: the path of the png file
:return: a numpy array of shape (y, x, 3)
"""
#backends = [_pil_load, _pypng_load]
backends = [... | 5,319,649 |
def blackbody_ratio(freq_to, freq_from, temp):
""" Function to calculate the flux ratio between two frequencies for a
blackbody at a given temperature.
Parameters
----------
freq_to: float
Frequency to which to scale assuming black body SED.
freq_from: float
Frequency from which... | 5,319,650 |
def convert_to_date(col):
"""Convert datetime to date."""
return col.date() | 5,319,651 |
def cloud_fn_iot_capture_sensor(event, context):
"""
Listens on IOT PubSub topic and updates and forwards data from a SQL database to the Classified Cloud Run
application.
"""
if not bm.check_budget():
cloud_log(LogIDs.BUDGET_MANAGEMENT, "BUDGET ALERT: Cannot run cloud_fn_iot_capture... | 5,319,652 |
def orthogonal_projection(all_data, training_data):
"""Projection norm of all_data over space defined by training_data
"""
o, t = subset_PCA(normalize(all_data), normalize(training_data))
norms = numpy.apply_along_axis(numpy.linalg.norm, 1, o)
return norms, o, t | 5,319,653 |
def test_updated_regression(regtest, example_config):
"""Tests the full transform of the config file against accepted value"""
update_typedefs(example_config)
parse_typedefs_to_mem_maps(example_config, True)
regtest.write(json.dumps(example_config, sort_keys=True, indent=4)) | 5,319,654 |
def get_iocs(prefix):
"""
Get the list of available IOCs from DatabaseServer.
Args:
prefix : The PV prefix for this instrument.
Returns:
A list of the names of available IOCs.
"""
#
try:
rawjson = dehex_and_decompress(ChannelAccess.caget(prefix + DatabasePVNames.IOC... | 5,319,655 |
def __testFind():
"""
Debug only
"""
left, top, end_left, end_top = GAME_LOCATION
width = (end_left - left) * SCREEN_SCALE
height = (end_top - top) * SCREEN_SCALE
print("=> Game Size is ({}, {})".format(width, height))
monitor = {"top": top * SCREEN_SCALE, "left": left * SCREEN_SCALE, "... | 5,319,656 |
def perfect_match(_clipped, _seq, offset = 0, min_nt = 2):
"""
perfect match between clipped reads and breakend sequence
for whole length
min_nt : minimal nt match is better to be larger than 2,
1 nt match is 25% change by random,
2 nt match is 0.0625 change by random,
3 nt matc... | 5,319,657 |
def newton(
x0,
model_evaluator,
nonlinear_tol=1.0e-10,
newton_maxiter=20,
RecyclingSolver=krypy.recycling.RecyclingMinres,
recycling_solver_kwargs=None,
vector_factory_generator=None,
compute_f_extra_args={},
eta0=1.0e-10,
forcing_term="constant",
debug=False,
yaml_emitt... | 5,319,658 |
def load_images(path_to_directory):
"""Loads all images"""
images = {}
for dirpath, dirnames, filenames in os.walk(path_to_directory):
for name in filenames:
if name.endswith('.png'):
key = name[:-4]
img = pygame.image.load(os.path.join(dirpath, name)).con... | 5,319,659 |
def pareto_selection_diversify_ancestry(population):
"""Return a list of selected individuals from the population.
DANIEL: added comparison of lineage for each added individual. Before an inidividual is added, the lineage is
compared to the already added population. If the similarities are higher th... | 5,319,660 |
def train_classic_lda(dictionary, corpus, num_topics, seed, file_path):
"""
Trains a classic lda model and saves the model in filepath
:param dictionary: gensim.corpora.dictionary.Dictionary
:param corpus: list of (int, int)
:param num_topics: int, the number of topic the topic model should be train... | 5,319,661 |
def remove_continuous_aggregation_query(viewdef: ViewDefinition) -> Optional[str]:
""" Remove a continuous aggregation policy """
if not viewdef.aggregation_policy:
return None
__query = "SELECT remove_continuous_aggregate_policy('{view_name}');"
query = __query.format(view_name=viewdef.name)... | 5,319,662 |
def stop_gradient(x):
"""
Disables gradients for the given tensor.
This may switch off the gradients for `x` itself or create a copy of `x` with disabled gradients.
Implementations:
* PyTorch: [`x.detach()`](https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach)
* TensorFlow: [`tf.... | 5,319,663 |
async def test_async_migration_in_progress(
hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
):
"""Test async_migration_in_progress wraps the recorder."""
with patch(
"homeassistant.components.recorder.util.async_migration_in_progress",
return_value=False,
):
... | 5,319,664 |
def get_boundary_elevations(dataset):
"""
:param dataset: netcdf AEM line dataset
:return:
an array of layer top elevations of the same shape as layer_top_depth
"""
return np.repeat(dataset.variables['elevation'][:][:, np.newaxis],
dataset.variables['layer_top_depth'].shape... | 5,319,665 |
def test_arbitrary_plugin() -> None:
"""
We will test how an arbitrary-class-based plugin works with a workflow.
"""
# create an instance of `ArbitraryPlugin`.
arbitrary_plugin = ArbitraryPlugin(access=access, mutate=mutate)
# create an instance of a `Workflow`.
# we are calling the `arbitr... | 5,319,666 |
def validate_plus_and_minus(message: discord.Message):
"""Throws ValidationError if there are too many or too few pluses/minuses"""
content: str = message.content
lines = content.split("\n")
has_plus = False
has_minus = False
for line in lines:
match = line_regex.search(line)
# l... | 5,319,667 |
def get_input_args():
"""
Retrieves and parses the command line arguments provided by the user when
they run the program from a terminal window. If the user fails to provide
some or all of the arguments, then the default values are used for the
missing arguments.
This function returns these argu... | 5,319,668 |
async def train(
background_tasks: BackgroundTasks,
current_user: User = Depends(auth.get_current_user_and_bot),
):
"""
Trains the chatbot
"""
Utility.train_model(background_tasks, current_user.get_bot(), current_user.get_user(), current_user.email, 'train')
return {"message": "Model... | 5,319,669 |
def browse(urls=[], browser="firefox"):
"""
launch a web browser
"""
if browser == "firefox":
firefox(urls)
else:
print("Unknown broswer: %s" % browser) | 5,319,670 |
def get_header():
"""
It returns the Header element of the pmml.
Returns
-------
header :
Returns the header of the pmml.
"""
copyryt = "Copyright (c) 2019 Software AG"
description = "Default Description"
timestamp = pml.Timestamp(datetime.now())
application=pml.A... | 5,319,671 |
def Identifiers():
"""Returns a "fake" Identifiers field.
Field expects:
"<scheme1>": "<identifier1>",
...
"<schemeN>": "<identifierN>"
"""
return fields.Dict(
# scheme
keys=SanitizedUnicode(
required=True, validate=_not_blank(_('Scheme cannot be bla... | 5,319,672 |
def create_edge_map(x, N=4):
"""
Creates the edge maps for the given image
Args:
x: (ndarray / Tensor, shape (N, *size))
Returns:
x: (same as input) in-place op on input x
"""
# remove the batch dimension
# TODO: could be for every image in the batch -- ba... | 5,319,673 |
def chunks(json_rows, chunk_size):
"""break a list into chunks"""
for indx in range(0, len(json_rows), chunk_size):
# Create an index range for json_rows of chunk size of items:
yield json_rows[indx:indx+chunk_size] | 5,319,674 |
def reject_sv(m, s, y):
""" Sample from N(m, s^2) times SV likelihood using rejection.
SV likelihood (in x) corresponds to y ~ N(0, exp(x)).
"""
mp = m + 0.5 * s**2 * (-1. + y**2 * np.exp(-m))
ntries = 0
while True:
ntries += 1
x = stats.norm.rvs(loc=mp, scale=s)
u = sta... | 5,319,675 |
def log_student_updated_added_event(sender, **kwargs):
"""Writes information about newly added or updated student into log file"""
student = kwargs['instance']
msg = u"%s %s %s (ID: %d)" % (_(u'Student'), student, _(u'added') if kwargs['created'] else _(u'updated'), student.id)
logger = logging.getLog... | 5,319,676 |
def assemble(idof, jdof, jbc, a, aa):
"""
"""
# set ipv to the positions in the array of the nodes
ipv = [int(idof + i) for i in range(6)]
ipv.extend([int(jdof + i) for i in range(6)])
# store the values for individual array in global array
for i in range( 12 ):
try:
1.0 ... | 5,319,677 |
def get_verification_key_xsuaa(jku: str, kid: str) -> str:
"""
get verification key for xsuaa
"""
# TODO
raise NotImplementedError() | 5,319,678 |
def get_message(message_id):
"""
Shows details for a message, by message ID.
:param message_id: Specify the message ID in the messageId parameter in the URI.
:return: message details formatted in JSON
"""
api_node = "{}messages/{}".format(SPARK_API_URL, message_id)
headers = set_spark_heade... | 5,319,679 |
def testsuite(*args, **kwargs):
"""
Annotate a class as being a test suite
An :py:func:`@testsuite <testsuite>`-annotated class must have one or more
:py:func:`@testcase <testcase>`-annotated methods. These methods will be
executed in their order of definition. If a ``setup(self, env)`` and
``t... | 5,319,680 |
def GetClusterAdjcency(clusters, facedge):
""" Creates sparse cluster adjcent matrix """
# Get boundary clusters for adjcent cluster computation
edgeclus = clusters[facedge]
bmask = edgeclus[:, 0] != edgeclus[:, 1]
bclus = edgeclus[bmask]
a = np.hstack((bclus[:, 0], bclus[:, 1]))
b... | 5,319,681 |
def _strip(g, base, orbits, transversals):
"""
Attempt to decompose a permutation using a (possibly partial) BSGS
structure.
This is done by treating the sequence ``base`` as an actual base, and
the orbits ``orbits`` and transversals ``transversals`` as basic orbits and
transversals relative to... | 5,319,682 |
def list_physical_devices(device_type=None):
"""Return a list of physical devices visible to the runtime.
Physical devices are hardware devices locally present on the current machine.
By default all discovered CPU and GPU devices are considered visible. The
`list_physical_devices` allows querying the hardware ... | 5,319,683 |
def awards_grants_honors(p):
"""Make sorted awards grants and honors list.
Parameters
----------
p : dict
The person entry
"""
aghs = []
for x in p.get('funding', ()):
d = {'description': '{0} ({1}{2:,})'.format(
latex_safe(x['name']),
x.get('currency... | 5,319,684 |
def string_to_time(course_time): # '二1-2 三3-4'
"""
:param course_time: '二1-2'
:return: 十周或若干周的上课下课时间 [{start_time, end_time},...]
"""
course_times = []
course_minutes = [0, 55, 120, 175, 250, 295, 370, 425, 480, 535, 600, 655, 710]
available_weeks = range(1, 11)
text_times = re.findal... | 5,319,685 |
def main_master():
""" Runs the launch controller overriding commandline arguments in master mode """
log_controller = Controller(master=True)
run(log_controller) | 5,319,686 |
def baseurl(url: str):
"""Validate that the base_uri parameter is conformant"""
_is_type(
url,
str,
f"Base URL parameter should be a string, but was actually of type {type(url)}",
)
_assert(
Patterns.URLPROTO.match(url),
f"Base URL parameter ('{url}') must begin w... | 5,319,687 |
def get_parameters(model: str, group_id: int = 0,
t_in: int = 0, t_out: int = 0, p_th: int = 0) -> pd.DataFrame:
"""
Loads the content of the database for a specific heat pump model
and returns a pandas ``DataFrame`` containing the heat pump parameters.
Parameters
----------
... | 5,319,688 |
def gauss(x, mu, var, a=1):
"""
Gauss distribution value at x
:param x:
:param mu: expected value
:param var: variance, (sigma^2)
:param a: coefficient in cases total area != 1
:return:
"""
return a/(np.sqrt(2*var*np.pi)) * np.exp(- (x-mu)**2/(2*var)) | 5,319,689 |
def build_backbone(
image_size: tuple, out_channels: int, model_config: dict, method_name: str
) -> tf.keras.Model:
"""
Backbone model accepts a single input of shape (batch, dim1, dim2, dim3, ch_in)
and returns a single output of shape (batch, dim1, dim2, dim3, ch_out)
:param image_size: tuple, di... | 5,319,690 |
def create_subnet(client, cidr_blk, vpc_id):
"""
Create a subnet in the given CIDR block and VPC using client.
:param client: a valid boto3 EC2 client.
:param cidr_blk: a valid IP range in the format 'a.b.c.d/XX'
:type cidr_blk: str
:param vpc_id: the VpcID of the Databricks VPC.
:type vpc_i... | 5,319,691 |
def register(app, **kwargs):
"""
Registers Hooks API (generic, github, travis)
:param app: Flask application
:return: None
"""
app.add_url_rule('/external/hooks/generic',
view_func=GenericPostHookApi.as_view('generic-hook'),
methods=['POST'])
app.ad... | 5,319,692 |
def transform_annotation(event):
"""Add a {"nipsa": True} field on moderated annotations or those whose users are flagged."""
annotation = event.annotation
payload = event.annotation_dict
nipsa = _user_nipsa(event.request, payload)
nipsa = nipsa or _annotation_moderated(event.request, annotation)
... | 5,319,693 |
def get_hertz_feed(reference_timestamp, current_timestamp, period_days, phase_days, reference_asset_value, amplitude):
"""
Given the reference timestamp, the current timestamp, the period (in days), the phase (in days), the reference asset value (ie 1.00) and the amplitude (> 0 && < 1), output the current hertz value... | 5,319,694 |
def find_list_in_list(reference_array, inp):
"""
---------------------------------------------------------------------------
Find occurrences of input list in a reference list and return indices
into the reference list
Inputs:
reference_array [list or numpy array] One-dimensional reference l... | 5,319,695 |
def accuracy(output, target):
"""Computes the accuracy over the top predictions"""
with torch.no_grad():
batch_size = target.size(0)
_, preds = torch.max(output.data, 1)
correct = (preds == target).sum().item()
return correct/batch_size | 5,319,696 |
def test_doc_propagated_to_tooltip(flow):
"""Check that docs are propagated to tooltips"""
G = flow._deriver.export_dag(False)
dot = dagviz.dot_from_graph(G)
assert isinstance(dot, pydot.Dot)
assert get_pydot_attributes(0, dot)["tooltip"] == "a friendly greeting" | 5,319,697 |
def _main(**kwargs):
"""Query the IDR for a given provider's data, write results to csv file."""
# TODO: Add ability to tune columns, details of deidentification.
(_, rows) = claim_reader.query_claims_from_teradata_batch_provider(
[kwargs['provider_tin']],
[kwargs['provider_npi']],
k... | 5,319,698 |
def test_non_class_data():
"""Test the definition of a Data with a non-class parameter."""
attr = IntListData([0, 1, 42])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!int_list<[0, 1, 42]>" | 5,319,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.