content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import inspect def get_exposed_members(obj, only_exposed=True, as_lists=False, use_cache=True): """ Return public and exposed members of the given object's class. You can also provide a class directly. Private members are ignored no matter what (names starting with underscore). If only_exposed is ...
daefa6230a0e6aad5d54e2f5f45777e1d9f42e57
3,618,220
def remove_group_project(repo, groupid, username=None, namespace=None): """Remove the specified group from the project.""" if not pagure_config.get("ENABLE_USER_MNGT", True): flask.abort( 404, description="User management is not allowed in this " "pagure instance", ...
3b52052d7242f63c1139144ddc8b7c9bb016aaef
3,618,221
def get_residue_sequence_poly_seq(cf, align_seq=True, verbose=False): """ used to work with load_struct_from_pdbfile, now uses load_pdbfile output :param structure: :return: """ # residue_sequence = list(np.array([[residue.resname.capitalize(), int(residue.id[1])] for residue in # ...
161b79385a2fb0c9e6078b440705643dab484683
3,618,222
import torch def _demo_head_inputs(input_shape=(1, 512, 8, 8)): """Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions """ (N, C, H, W) = input_shape rng = np.random.RandomState(0) features = rng.rand(*input_...
cd313f89ac28cbaf98f1e39cb7760ca393e9e565
3,618,223
import torch def load_ckp(checkpoint_fpath,model): """ checkpoint_path: path to save checkpoint model: model that we want to load checkpoint parameters into optimizer: optimizer we defined in previous training """ # load check point # checkpoint = torch.load(checkpoint_fpath) ch...
c6d37907ec8a9a90dd11b9a48ceae46d59938aca
3,618,224
def get_config_string(config): """ Use the given config to extract one string for the output. :param config: a dictionary of configs from a Build object :return: string representation """ configs = {} for key, entry in config.items(): abbrev = entry.get('abbreviation') value ...
15c38f062af7900cb457ff5dfbad287a0edb75e3
3,618,225
def _api_shutdown(name, output, kwargs): """ API: accepts output """ sabnzbd.shutdown_program() return report(output)
795ed94feff5cfb9a9f0f581ab9a705b62f41984
3,618,226
def combine_loss_components(critic_loss_val, actor_loss_val, entropy_val, actor_loss_weight, entropy_bonus): """Combine the components in the combined AWR loss.""" return critic_loss_val + (actor_loss_val * actor_loss_weight) - ( entropy_val * entropy_bonus)
1a060140aa3e08944d2e3f4cf1e4603c88e16921
3,618,227
import json import logging def country_filter() -> str: """ find selected country to gather news from from config.json """ with open('config.json') as config_file: data = json.load(config_file) logging.info('Countries for news briefing located') return data['news_briefing'][0]['country']
35cfee9c0239dfef7ad352f2c17c2d3a4d140eb9
3,618,228
def get_env_agent_current(env = Depends(get_env)) -> str: """Returns name of currently expected agent.""" return env.agent_selection
07bb77fe10919b3ac9ec9401e420cf0fb32d96a0
3,618,229
import random import math def exponential_backoff(attempt_num): """Returns an exponential backoff value in seconds.""" assert attempt_num >= 0 if random.random() < _PROBABILITY_OF_QUICK_COMEBACK: # Randomly ask the bot to return quickly. return 1.0 # If the user provided a max then use it, otherwise ...
4be20f57a48a10bf085ae74d36f9b8ef85dc3e01
3,618,230
def _stop_container(container): """ Force remove a container """ try: logger.info(f'Stopping container {container.id}') container.remove(force=True) except: pass finally: return True
99cff9920c5e1789ec0f83c0b306d406cd47a17c
3,618,232
import warnings def _wmd(embedding_1, embedding_2, word_freq_1, word_freq_2, constraint_matrix=None): """ Calculate the Word mover´s Distance parameters --------- - embedding_1 : np.array (distinct words x embedding dimensions) -> embedding of the first article - ...
41e2e042eecc330f85124f09def5e707f2d63653
3,618,233
def converter(): """Bits to Target""" bits = int(request.form['bits'], 16) response = bits_to_target(bits) return jsonify(response), 200
d4e2aa29951cfe57f5cd1f1c809683d81b832725
3,618,234
def _coerce_exceptions(function): """ Decorator that causes exceptions thrown by the decorated function to be coerced into generic exceptions from the hadoop.fs.exceptions module. """ def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except Exception as e: e.msg = force...
fc10e071b5448c0f859f38bb0df523f1d53b7f64
3,618,235
def decode_der(cert_der): """Decode cert DER string to Certificate object. Args: cert_der : Certificate as a DER encoded string Returns: cryptography.Certificate() """ return cryptography.x509.load_der_x509_certificate( data=cert_der, backend=cryptography.hazmat.backends.defau...
007e40763c82c19c9ae9858fd9be0d5115c6e1d9
3,618,236
def find_threshold_by_precision(precisions, thresholds, p_cutoff): """This function finds the lowest index that guarantess a precision of at leat p_cutoff.""" return thresholds[np.argmax(precisions >= p_cutoff)]
b12990b505ed6ccdd2c5aad615ac21e2f9f9d2bd
3,618,237
def compare_vectors(phi, index1, index2): """ A function which compares the directions of two vectors given by polar co-ordinates. The two vectors are identified as being in the same (or opposite) directions for x and y. The returned array indicates which one of 4 possible alignments the two vecto...
11f033aa980c2883ad8d1bc5dafe01da917fd6b6
3,618,238
def cmplx(a,b,*vars): """ See VSIP specification for Information Convert Convert real, imaginary (a,b) into complex Usage: cmplx(a,b,c) where a and b are views of type vview_f or vview_d c is a compliant view of type cvview_f or cvview_d OR: c = cmplx(a,b) ...
dd98372ca40fc9199ad556e752afa186686826aa
3,618,239
def build_vtk_colormap(colormap, vtk_colormap=None) : """ Build either a ``vtkLookupTable`` or a ``vtkColorTransferFunctionWithAlpha`` from the given colormap. The colormap is specified as a custom table -- which must respect the formats of the dictionaries defined in :func:`build_lookup...
3d85011fe2ba6c243192a9955d56d759dc659a23
3,618,241
def _get_message_from_model(message_model): """Converts the FeedbackMessageModel to a FeedbackMessage. Args: message_model: FeedbackMessageModel. The FeedbackMessageModel to be converted. Returns: FeedbackMessage. The resulting FeedbackMessage domain object. """ return ...
e67876b3e044475a66b06c7146df399c0a5894f2
3,618,242
import traceback def get_survey_ids(): """ categoryIdを元に、予約データのsurveyIdを取得する """ command = [] command.append('aws') command.append('dynamodb') command.append('scan') command.append('--table-name') command.append(table_name_survey_results) command.append('--profile') command...
1ff7522aa1502e96bfc83c9613de6796cdb608ae
3,618,243
def list_tracker_issue_field_value(tracker_id: str, field: str, project=None): """ GET /api/tracker/{tracker_id}/issue_field/{issue_field_id} :param tracker_id: :param field: :param project: :return: """ try: return { 'title': 'Succeed to list Issue Field Value from t...
8d0e404c06fde6339c4f1d2dd9b30ddd90f54c8e
3,618,244
def isogenies_5_1728(E): """ Returns a list of 5-isogenies with domain ``E`` when the j-invariant is 1728. OUTPUT: (list) 5-isogenies with codomain E. In general these are normalised; but if `-1` is a square then there are two endomorphisms of degree `5`, for which the codomain is the sam...
43a1ef6e70deedcf90c67ce3da86323fa472da69
3,618,245
from typing import Any def _parse_link(link: str) -> Any: """Parse rapid upload link Format 1: cs3l://<content_md5>#<slice_md5>#<content_crc3>#<content_length>#<filename> Format 2: <content_md5>#<slice_md5>#<content_length>#<filename> Format 3: bdpan://{base64(<filename>|<content_length>|<content_md5...
31dadddaa8cba85ccc954e3176b4fe2be9546bb3
3,618,246
def change_zone_to_coordinates(changing_data, which=None): """ Change zone data into coordinate. Get data with zone data and add coordinate data into original data. Last modified: 2019-11-24T22:19:49+0900 Args: changing_data (DataFrame): Mandatory. The DataFrame which contains zone data. ...
7da7f0f6d2468a87234f50cc39843ab08dcf17d6
3,618,247
def create_unwarp_workflow(name="unwarp", fieldmap_pe=("y", "y-")): """Unwarp functional timeseries using reverse phase-blipped images.""" inputnode = Node(IdentityInterface(["timeseries", "fieldmap"]), "inputs") # Calculate the shift field # Note that setting readout_times to 1 will give a fine # ...
eb7c5b94fbeeb7c5cc9eddb281b629c1da68a8f2
3,618,248
def delete_group_resource_permissions_view(request): """ Delete a permission from a specific resource for a group. """ group = ar.get_group_matchdict_checked(request) resource = ar.get_resource_matchdict_checked(request) permission = ar.get_permission_multiformat_body_checked(request, resource) ...
442d75af042feb96a3a6c47945e90db87f0bb1c0
3,618,252
def get_bins(data): """Return bin edges for all unique values in data. """ bins = np.unique(data) return np.append(bins[~np.isnan(bins)], max(bins) + 1)
ebdcc658d7d1f6fc34865a9ee2e199c5b86e9c58
3,618,253
def filter_in_out_by_column_values (column, values, data, in_out): """Include rows only for given values in specified column. column - column name. values - list of acceptable values. """ if in_out == 'in': data = data.loc[data[column].isin (values)] else: data = data.loc...
191fa20edae7f67b245ad31658297d4a114f59fe
3,618,254
def parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields: ima...
a654e1ddcc35b2ec834de7bbc1a99c8fe7764eba
3,618,255
def intersection(set_1, set_2): """realisation of two sets intersection(simple set generator inside)""" return {i for i in set_1 if i in set_2}
d46a206e6c202343615c3b045a8885d8efd56607
3,618,256
import inspect def simulated_quantize_compute(attrs, inputs, out_type): """Compiler for simulated_quantize.""" assert len(inputs) == 5 assert attrs.sign assert attrs.rounding == "round" axis = attrs.axis data, in_scale, out_scale, clip_min, clip_max = inputs data = my_print(data, '\n\n***...
54a54e067da92903eb1af88797104f4035f02899
3,618,257
def dy(series, n=1): """Difference over n years""" return (series-series.shift(n*series.index.freq.periodicity))
1cc0561ea0bed5a11dee8da8d285c5faf402648c
3,618,258
def inad(V1,V2): """ Inertial advective wind <div class=jython> INAD ( V1, V2 ) = [ DOT ( V1, GRAD (u2) ), DOT ( V1, GRAD (v2) ) ] </div> """ return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2))))
d47240b55401df317fc76fb15d821d9d98406829
3,618,259
def get_node_log(request, biz_cc_id, node_id): """ @summary: 查看某个节点的日志 @param request: @param biz_cc_id: @param node_id @return: """ task_id = request.GET.get('instance_id') history_id = request.GET.get('history_id') try: task = TaskFlowInstance.objects.get(pk=task_id, b...
a5365648857caaf46c9cfe132d0d7c2cec33c5d1
3,618,260
def _app_options(self, url, headers=None, status=None, expect_errors=False): """ To be injected into TestApp if it doesn't have an options method available """ req = TestRequest.blank(path=url, method='OPTIONS', headers=headers, environ=self.extra_environ) return self.do_request(req, status, expect_...
6c78a9a4dc2b7d953fa9c0bacc1fd374a62e287c
3,618,261
from typing import Iterable from typing import Tuple def iter_with_final(it: Iterable[E]) -> Iterable[Tuple[E, bool]]: """ Change given iterator to new one yielding additional *final* flag. >>> list(iter_with_final(iter([1, 2, 3]))) [(1, False), (2, False), (3, True)] >>> list(iter_with_final(it...
8e4392066353b4226d90df2360ed37837280c1f3
3,618,262
def remlplen_herrmann(fp,fs,dp,ds): """ Determine the length of the low pass filter with passband frequency fp, stopband frequency fs, passband ripple dp, and stopband ripple ds. fp and fs must be normalized with respect to the sampling frequency. Note that the filter order is one less than the filt...
f4d3c2d96b5e15ac909155d5b0cb6d53d439352f
3,618,263
def CreateBooleanIntersection1(curveA, curveB, tolerance, multiple=False): """ Calculates the boolean intersection of two closed, planar curves. Note, curves must be co-planar. Args: curveA (Curve): The first closed, planar curve. curveB (Curve): The second closed, planar curve. Re...
13257250aa675ed25d50acd960093c1c8e527980
3,618,264
def pointer_scope(func): """The FDB format has a lot of pointers to structures, so this decorator automatically reads the pointer, seeks to the pointer position, calls the function, and seeks back.""" def wrapper(self, *args, **kwargs): pointer = kwargs.get("pointer") if pointer == None: pointer = self._read_...
a83abfcd0cb9b641aec3125fb267cc6c6f134884
3,618,265
import re def create_example_gpt(example: Example, tokenizer: Tokenizer) -> Example: """ Create example for GPT-[1,2] Substitute mask with <pad>, and store where the token was placed. During repr. collection, we'll need it. Example: >>> x = 'Most apples are [MASK].' ... tokenizer = transfo...
1b5c869ea63582ef2fef434d98add37e18200c94
3,618,266
from enum import Enum def should_smooth_series(tag: Enum) -> bool: """ :param tag: :return: """ if tag is TrainingScalars.training_loss: return True elif tag is TrainingScalars.validation_loss: return True return False
5661773451b0edda0bab8fcf32113e74f13ae518
3,618,267
from typing import Set from typing import Optional def load_all_plugins(module_path: Set[str], plugin_dir: Set[str]) -> Set[Plugin]: """ :说明: 导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入! :参数: - ``module_path: Set[str]``: 指定插件集合 - ``plugin_dir: Set[str]``: 指定插件路径集合 ...
cc7e7fd5cc6b2479e4ea5c1256ba88bba6031f70
3,618,268
import inspect def lineno(): """Returns the current line number in our program.""" return str( inspect.currentframe().f_back.f_lineno )
c973d4a0614cd6dafa5e67d0d4dda7f3d347d51a
3,618,269
def positive_rates(df, score_col, label_col, thresholds): """Compute false positive and true positive rates.""" tpr = [] fpr = [] for threshold in thresholds: confusion = confusion_matrix_counts(df, score_col, label_col, threshold) if ( confusion["tp"] + confusion["fn"] == 0 ...
081cc95b0aa2da7b17065e9aaa7dd54083a69fb2
3,618,270
def get_phrases(): """ Returns a phrases dictionary of the form <callback>:<list of phrases> """ return _config_object["phrases"]
43eb77cbac5274b638a5d8bde1c70dfaad339400
3,618,271
def graham_scan(points: np.ndarray) -> np.ndarray: """Find vertices of convex hull around points. Args: points: (x, y) coordinates of points. Returns: hull: points that are vertices on convex hull. """ primary, remaining_points = extract_primary(points) sorted_points = sort_for...
38dd708ade892c162067f9275e27d9865cd386e5
3,618,272
def waitfor(css_selector, text=None, classes=None): """ Decorator for specifying elements (selected by a CSS-style selector) to explicitly wait for before taking a screenshot. If text is set, wait for the element to contain that text before taking the screenshot. If classes is present, wait until th...
13130146441f20cfd424e52e46f2f2e3a7e33d3f
3,618,273
def grandac(e, a, r, f_e): """Returns integrand for probability density of orbital radius where semi-major axis is a constant Args: e (float): Value of eccentricity a (float): Value of semi-major axis (AU) r (float): Value of orbital radius (A...
3e401dae075ceeba52dab250c7d979b23d2f3c85
3,618,275
def get_default_path(name): """this function takes a an import name and returns the path full bash of the library if the library is in stdlib""" name_ = name if isinstance(name, (DottedName, Symbol)): name_ = str(name) if name_ in pyccel_external_lib.keys(): name = pyccel_external...
c19d5e8b06616b1ee595098b4007d21f32117506
3,618,276
def get_requested_countries(countries, country_names): """ gets requested countries for visualization and info :param countries: list of all available countries for research :param country_names: list :return: (list, str) """ print(country_names) # gather the requested information c...
b96f3b001e5a421c333c366f3cdca656d97fe933
3,618,277
def retrieve_plain(monitor, object_string): """Retrieves the request object as-is (doesn't apply any modification). This is valid only for objects which are single values (items from a tensor) :param monitor: either a training or evaluation monitor :param object_string: string to identify the object to...
7fc5042422ae70933691202718036703554cff3e
3,618,278
from typing import Any def unique_id(context: Any) -> str: """ Returns a new unique string that can be used as an id="" attribute in HTML. Usage: {% with new_id=request|unique_id %} <label for="input:{{ new_id }}"> I am labelling a far-away input </label> ... <input id="i...
53bbf556749243591059e91e5342348abb7e8ce2
3,618,279
def get_contrast_in_df(df, img, img_name, contrast_type, grating_mask, white_mask, black_mask, metadata, x0, y0, angle, contrast_prefix=''): """helper function that handles inserting the contrast into the df """ if contrast_type == 'fourier': grating_1d = utils.extract_1d_grat...
7f1f0d5b509666c3fa352889ce099ca9f4d8d9e9
3,618,280
import time import logging import random def cash(ttl=60, key=None, ver=CURRENT_VERSION_ID, pre="", off=False): """ Copyright (C) 2009 twitter.com/rcb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"...
79add02d254e2fd069be9414a71f0cd47ff0953e
3,618,281
def enquiry_client_add(request): """ Add new enquiry and see the list of clients """ success_message, error_message = None, None form = ClientForm clients = Client.objects.all() enquiry_form = EnquiryClientForm enquiry_clients = EnquiryClient.objects.all() if request.method=="POS...
00b55395fcc705a0095000f7fe8b43301254ebdd
3,618,282
def transpose(table): """ Returns a copy of table with rows and columns swapped Example: 1 2 1 3 5 3 4 => 2 4 6 5 6 Parameter table: the table to transpose Precondition: table is a rectangular 2d List of numbers """ # LIST COMPREHENSIO...
2a393a9e3606022d945454da55fd68543e59476b
3,618,283
def memsizeformat(size): """Returns memory size in human readable (rounded) form. """ if size > 1048576: # 1024**2 return "{0} GB".format(size / 1048576) elif size > 1024: return "{0} MB".format(size / 1024) else: return "{0} KB".format(size)
0cd812d83bd85b1e2690e0404a4eb833e2e9824f
3,618,284
def q5(): """Identifying outliers.""" # Definindo os quartis: Q1 = countries['Net_migration'].quantile(q= 0.25) Q3 = countries['Net_migration'].quantile(q= 0.75) # Intervalo interquartil: IQR = Q3 - Q1 # Limite inferior: lim_max = (countries['Net_migration'] < (Q1 - 1.5 * IQR)).sum() ...
8f4d0f3323720af05020619e381c9533d923f4ad
3,618,285
import torch def matrix_div(model_out, *derivative_variable): """Computes the divergence for matrix/tensor-valued functions. Parameters ---------- model_out : torch.tensor The (batch) of matirces that should be differentiated. derivative_variable : torch.tensor The spatial variabl...
ed433674ee85895980b9212ac642ab1545d656ab
3,618,286
def flip_dataframe(df, new_colname='index'): """Flips table such that first row becomes columns Args: df (DataFrame): Data frame to be flipped. new_colname (str): Name of new column. Defaults to 'index'. Returns: DataFrame: flipped data frame. """ colnames = [new_...
3a7c733644e2c67398a511c9dea7fa80845bbecf
3,618,287
def ca65_bytearray(s): """Convert a byteslike into ca65 constant byte statements""" s = [' .byt ' + ','.join("%3d" % ch for ch in s[i:i + 16]) for i in range(0, len(s), 16)] return '\n'.join(s)
8bdc868cc659e6b99f01449c6bf41884c0635c14
3,618,288
def read_basis_shell_num(trexio_file) -> int: """Read the basis_shell_num variable from the TREXIO file. Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function. Returns: ~num_r~: int Integer value of basis_shell_num variable read from ~trexio_file~. Rai...
831962f686ecaf22c199eaf6d0c87eb9d7269410
3,618,290
from typing import Optional from typing import Any def get_codec( cls: AnyType, /, *, using: Optional[Codec[Any]] = None, fallback: bool = False, ) -> Result[Codec[Any], TestplatesError]: """ Retrieves codec from structure type. If there are multiple codecs attached to given stru...
0a011b8b11038a45d42bf5a70559cea54a6ab6f1
3,618,291
def convert_db_fetch_to_df(fetched, column_names=None): """ This method converts the cursor.fetchall() output of SELECT query into a Pandas dataframe. :param fetched: the output of SELECT query :type fetched: list of row tuples :param column_names: column names to use for the dataframe :type col...
f2ffdb2472076fd034e7d16b8cc42893358bf866
3,618,293
def get_synsets(s): """Suggested helper method for `synset_featurizer`. This should be completed so that it returns a list of stringified Synsets associated with elements of `s`. """ # Use `parse_lem` from the previous question to get a list of # (word, POS) pairs. Remember to convert the PO...
98ce2c1ce849d2771ab2bae03e0e740c8c3de32e
3,618,294
from typing import List from typing import Any from typing import Callable def tpe_submit_commands( cmds: List[Any], thread_count: int, timeout: int, fn: Callable = subprocess_commands_pipe, di=DI, ) -> list: """Run commands on multiple threads. Stdout and stderr are logged on function su...
ff8d18490b1184625ee6121ad5cf50dd7446b463
3,618,295
def register(): """Register new user.""" form = RegisterForm(request.form, csrf_enabled=False) if form.validate_on_submit(): User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True) flash('Thank you for registering. You can now log in.', 'succ...
8847e4153e0e9767298debe4f7c480c3b344327e
3,618,296
def ind2latlon(index, filePath): """ Use gdal/osr to get latlon point location from georeferenced array indices """ # Load georeferencing ds = gdal.Open(filePath) proj = ds.GetProjection() gt = ds.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt(proj) x0 = gt[0] ...
55c8005c8106905370631c5a990b2835c0b5b322
3,618,297
def is_response_paginated(response_data): """Checks if the response data dict has expected paginated results keys Returns True if it finds all the paginated keys, False otherwise """ try: keys = list(response_data.keys()) except AttributeError: # If we can't get keys, wer'e certainl...
521c28c1d6e29e5785b3bcbd5d2604210b3a3874
3,618,298
def store_tweets(statuses): """ Stores the tweet in the mongoDB :param tweet: dict or list of dicts to store """ if isinstance(statuses, dict): statuses = [statuses] try: result = db.tweets.insert_many(statuses, ordered=False) return result except BulkWriteError as ...
7349074c4c0087a333b3a7385585e85b1ce57b83
3,618,300
def test_func(G, p0, q0, bif_type): """ Parameters ---------- """ q0 = np.zeros(q0.shape) q0[0] = 1 p0 = np.zeros(p0.shape) p0[0] = 1 return bordered_system(G, p0, q0, bif_type)
99f59e76e912565e54254d7e1238b66fd814846d
3,618,301
from typing import List def build_actions_embed(actions: List[LoggingActions]) -> discord.Embed: """ A method that generates an embed detailing with LoggingActions are currently enabled. Parameters: actions (List[LoggingActions]): A list of currently enabled logging actions. Returns: ...
bc9c452aea4d70456d24f24cd4d5fc7fd8135502
3,618,302
def get_tag_for_physical_resolution(res): """Input a physical resolution string or value, output a formatted string tag to be used in filenames. """ check_flag, res_value = is_physical_resolution(res, return_value=True) if check_flag: sigfigs = 0 fmt_str = '{:.%df}'%(sigfigs) res...
3db530e14f6bc5894ac63a58c6e5f1f580e8d62e
3,618,304
def search_dnb(query_params): """ Queries the dnb-service with the given query_params. E.g.: {"duns_number": "29393217", "page_size": 1} {"search_term": "brompton", "page_size": 10} """ if not settings.DNB_SERVICE_BASE_URL: raise ImproperlyConfigured('The setting DNB_SERVICE_BAS...
64a1034398b65f48dd7adf8f0169ab5e609bf901
3,618,305
def connect_to_zone(zone, access_key_id, secret_access_key, lowercase=True): """ Connect to one of zones in shanhe by access key. """ if lowercase: zone = zone.strip().lower() return APIConnection(access_key_id, secret_access_key, zone)
757ab871338e08fdca4dac1a5950dda88f56101d
3,618,306
import re def compare_versions(value, required, verbose): """Compares the numerical value of two dot-separated version strings :type value: str :type required: str """ # allow for unexpected input for value. # required is within our control. val = [int(x) for x in re.split(r"\D+", value)...
636550b35235dcb661e78cc38df3d856fcd263ae
3,618,307
def single_resonance_statistics(r): """ Compute global, sequence-specific ncIDP-based chemical shifts using resonance list """ seq = sequence.molecule_sequence(r.condition.molecule).one_letter_codes path = get_sparky_home()+'/Python' prediction = compute_RC(path+'/ncIDP-cs.tab', path+'/ncIDP-dev.tab', seq...
ba19d8b338a7bcf36d668810fba8503b93af3751
3,618,308
def get_response(message, code): """ Create a response. Args: message (str): The message to include in the response code (str): The return code to include in the response Return: a dict, if present key = 'Accept' """ response = HttpResponse(status=code) # pylint: d...
9f7adc270d8d4183b93664bb705482abbd577d79
3,618,309
def rk4(data, critic, step, num_step = 1): """Assumes data is a batch of images, critic is a Kantorovich potential, and step is desired step size. Applies fourth order Runge-Kutta to the data num_step times with stepsize step/num_step. Unused in TTC""" h = step/num_step for j in range(num_step): ...
11f4892e1b91b2f50823d6865cdbd4420a965735
3,618,310
def configure_subinterfaces_for_vlan_range( device, interface, vlan_id_start, vlan_id_step, vlan_id_count, network_start, network_step,host_address_step, netmask, ospf_network_type=None): """ Configures multiple subinterfaces looping through vlan range Args: device ('obj'): Device t...
127c592acc36d98425bbfde529efd712457f64d1
3,618,311
import logging from datetime import datetime def post_new_patient(): """This is the function that receive the post request fom patient client The in_data is sent by the patient side client. It is a dictionary with the following keys: "patient_name" (str): the uploaded patient's name "MRI" (str): ...
a0325f5ca13497c7b1c4a23c806eed0f5680f68f
3,618,312
def weighted_scalarizer(xs: np.ndarray, ws: np.ndarray) -> np.ndarray: """A simple linear weight based scalarizer. Args: xs (np.ndarray): Values to be scalarized. ws (np.ndarray): Weights to multiply each value in the summation of xs. Returns: np.ndarray: An array of scalar...
73dcc450fe59fdcd81e80d6da6681b3cfc92c858
3,618,313
def blueschist_felsic(): """ Elastic constants of Felsic Blueschist (GPa) from Cao et al. (2013), in Voigt notation - Abbreviation: ``'BS_f'`` Returns: (tuple): tuple containing: * C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``) * rho (float): Density (2...
96243d1ff842d01838e5be0e7f1f8b5205432d72
3,618,314
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights): """ Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful ValueError if otherwise. """ if not isinstance(wide_weights, np.ndarray): msg = "wide_weights MUST be a ndarray." raise ValueError(msg) ndim = wide_w...
28757950b28d37edad7796daed8ec9803a4aad9a
3,618,315
def LMPR_complexity(dist, rvs=None, rv_mode=None): """ Compute the LMPR complexity. Parameters ---------- dist : Distribution Distribution to compute the LMPR complexity of. rvs : list, None The indexes of the random variable used to calculate the LMPR complexity. If Non...
49de6fc709f4894298e013b9a319381308aceccd
3,618,316
from typing import List async def read_users( skip: int = 0, limit: int = 100, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) ) -> List[User]: """ Read all users with all the information: - **skip**: Number of records to be skipped ...
55e9ee59e7aca321209bc10b6785d315e0f136e9
3,618,317
import typing def load_private_key( data: bytes, passphrase: typing.Optional[bytes] = None, ) -> RSAPrivateKey: """Loads the private key and returns a Key interface. If the private key was not encrypted duting the serialization, ``passphrase`` must be ``None``, otherwise it must be a ``bytes`` ob...
381bdcdfe8f354080dd5b3ee96971fad0f33fc1f
3,618,318
def nb_argsort(x, axis): """ Implementation of numpy.argsort in numba. """ assert (axis==0) | (axis==1), "axis must be set to either 0 or 1." ordered = np.zeros_like(x) if axis == 0: for i in range(x.shape[1]): ordered[:, i] = np.argsort(x[:, i]) return ordered elif axis ...
b8200775307bd28413a10532f8487bd26cb9db52
3,618,319
def edge_color(lattice: Lattice, n_colors:int = 3, all_solutions = False, n_solutions = None, fixed = []): """Return a coloring of the edges using n_colors different labels. Args: adjacency (np.ndarray): A list of pairs of vertex indices representing edges. n_colors (int): The maximum number of...
6179524dbc3ba2e3f475b83dbc732d3b46702def
3,618,320
def read_labels(geojson_dict, crs_transformer, extent): """Construct ClassificationLabels from GeoJSON containing grid of cells. If the GeoJSON already contains a grid of cells, then it can be constructed in a straightforward manner without having to infer the class of cells. Args: geojson_dic...
812ce5d999d0d571b8ab4ce96f5b7996aed4acac
3,618,321
import six def server_hardware_from_local_link_information_list( oneview_client, local_link_information_list): """Get the Server Hardware from Local Link Information. :param oneview_client: a instance of the OneView Client; :param local_link_information_list: an list of local link information; ...
69e38d20d4bc0eb48804e2226d52a8a688b61977
3,618,322
def maya_window(): """Return the MayaWindow if in Maya else None.""" for each in QtWidgets.QApplication.topLevelWidgets(): if each.objectName() == "MayaWindow": return each return None
f119e7f985001671b8003ef26f5adc50dec3e1c5
3,618,323
def get_ode_solver(args): """get the ODE solver based on the given argument""" if args.ode_solver == 'heun': return heun_solver if args.ode_solver == 'euler': return euler_solver if args.ode_solver == 'rk4': return rk4_solver if args.ode_solver == 'midpoint': return m...
2eddd0e6803563e3d79d8d0f6a0877fc4742d225
3,618,324
def create_metadata_dict(): """A Python dictionary will be created to hold the relevant metadata. :return: dictionary with keys for the relevant metadata :rtype: dict """ metadata = {'Directory': None, 'Filename': None, 'Extension': None, 'ImageType'...
1cb7a42e21df76c13eed3fe905030bd55c7f4af9
3,618,326
import time def email_change_emails(driver, inbox, Users, ISAAC_WEB, GUERRILLAMAIL, WAIT_DUR, **kwargs): """Test if the email change confirmation emails are recieved. - 'driver' should be a Selenium WebDriver. - 'inbox' should be a GuerrillaInbox object. - 'Users' must be a TestUsers obje...
7bdfb744f6cc9d87030100b98c9465e749e7b41a
3,618,327
def compute_power(rawvolts, rawamps): """ Compute the power. Looks trivial, but I'm gonna implement smoothing later. """ power = rawvolts * 1.58 power_low = rawvolts * 1.51 power_high = rawvolts * 1.648 return power, power_low, power_high
9202e456d4655de12ec5608011e80647cf62f7ab
3,618,328
async def selector(ctx, header, select_from, timeout=120, max_len=20): """ Interactive routine to prompt the `ctx.author` to select an item from a list. Returns the list index that was selected. Parameters ---------- header: str String to put at the top of each page of selection options...
e13f7343d24706c1121fc9630877d1c2c7cc1504
3,618,331
def prettify_labels(labels, format=None): """ Prettify label for typesetting in various formats :param labels: a list of length-2 tuples, in the format(position, label) :param format: a string with the format for the prettifier (e.g. 'agr', 'matplotlib', ...) :return: the same list as labe...
dbcf4ed5d553d732c4bb3509f226fcb8ec8b22d9
3,618,332