content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_batch_norm(layer): """ Return True if `layer` is a batch normalisation layer """ classname = layer.__class__.__name__ return classname.find('BatchNorm') != -1
6494b75a3fbfbfd55ff43b05536a1094290ea915
25,700
import torch def predictive_entropy(y_input, y_target): """ Computes the entropy of predictions by the model :param y_input: Tensor [N, samples, class] :param y_target: Tensor [N] Not used here. :return: mean entropy over all examples """ y_input = torch.exp(y_input) # model output is log...
6c3c4c3cfc93d0c19e2662b54a9b6d41146264d5
25,701
def exec_cmd(cmd_args, *args, **kw): """ Execute a shell call using Subprocess. All additional `*args` and `**kwargs` are passed directly to subprocess.Popen. See `Subprocess <http://docs.python.org/library/subprocess.html>`_ for more information on the features of `Popen()`. :param cmd_args:...
c946fce186e56d19c2e182e2061f4f9739a2ce59
25,702
from datetime import datetime def roundTime(dt=None, roundTo=1): """Round a datetime object to any time period (in seconds) dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 1 second. Author: Thierry Husson 2012 - Use it as you want but don't blame me...
c17cbf9092cc2a88cb486afd1a7ff0ad984987bd
25,703
from typing import OrderedDict import requests def get_imagery_layers(url): """ Get the list of available image layers that can be used as background or foreground based on the URL to a WTML (WorldWide Telescope image collection file). Parameters ---------- url : `str` The URL of ...
9e5a37552d18ebd1994c892c2af07bd3a3445ac1
25,704
def _typecheck(op1, op2): """Check the type of parameters used and return correct enum type.""" if isinstance(op1, CipherText) and isinstance(op2, CipherText): return ParamTypes.CTCT elif isinstance(op1, PlainText) and isinstance(op2, PlainText): return ParamTypes.PTPT elif isinstance(op...
872a05347ac26324e26f7444798c977f5cfad2fa
25,705
def vm_update_cb(result, task_id, vm_uuid=None, new_node_uuid=None): """ A callback function for api.vm.base.views.vm_manage. """ vm = Vm.objects.select_related('dc').get(uuid=vm_uuid) _vm_update_cb_done(result, task_id, vm) msg = result.get('message', '') force = result['meta']['apiview']['...
3d7ad728cb6c3ddd8fe3638f98223635378ce8d7
25,706
from typing import Union def _class_effective_mesh_size( geo_graph: geograph.GeoGraph, class_value: Union[int, str] ) -> Metric: """ Return effective mesh size of given class. Definition taken from: https://pylandstats.readthedocs.io/en/latest/landscape.html """ class_areas = geo_grap...
fd98849f6a7ff9d9cf17ecd15a3bcd790f6dcb6f
25,707
def noam_schedule(step, warmup_step=4000): """ original Transformer schedule""" if step <= warmup_step: return step / warmup_step return (warmup_step ** 0.5) * (step ** -0.5)
ad42f6f478f06c2641cb189db769c4a6e0272f6f
25,708
import os def getoldiddfile(versionid): """find the IDD file of the E+ installation E+ version 7 and earlier have the idd in /EnergyPlus-7-2-0/bin/Energy+.idd """ vlist = versionid.split('.') if len(vlist) == 1: vlist = vlist + ['0', '0'] elif len(vlist) == 2: vlist = vlist + [...
8166a155b8ffcdd71de6f1e5ea7e6a2f517afc4f
25,709
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :...
954d1cefc521c2f8fd88492858590df8bc0ce120
25,710
from typing import List def _show_problems_info(id_tournament: int) -> List: """ Функция возвращает информацию о задачах турнира по его id(id_tournament) """ return loop.run_until_complete(get_request(f'https://codeforces.com/api/contest.standings?contestId=1477&from=1&count=5&showUnofficial=true'))['problems']
36bafa02b2523c538fefbb5d77496dfddcbda6a1
25,711
from typing import Dict from typing import Any def make_shell_context() -> Dict[str, Any]: """Make objects available during shell""" return { "db": db, "api": api, "Playlist": Playlist, "User": User, "BlacklistToken": BlacklistToken, }
c2121fc95a0916021338d2b39debcc7d88933982
25,712
async def find_user_by_cards(app, cards, fields=["username"]): """Find a user by a list of cards assigned to them. Parameters ---------- app : aiohttp.web.Application The aiohttp application instance cards : list The list of cards to search for fields : list, default=["username"...
ef5b20ea668b39eda51c859a3b33f1af30a644f5
25,713
def _calc_y_from_dataframe(trafo_df, baseR): """ Calculate the subsceptance y from the transformer dataframe. INPUT: **trafo** (Dataframe) - The dataframe in net.trafo which contains transformer calculation values. RETURN: **subsceptance** (1d array, np.complex128) - The subs...
f6b3493dd56d93a269b2c82431a5ef0a6a7ff946
25,714
def mutual_coherence(A, B): """"Mutual coherence between two dictionaries A and B """ max_val, index = mutual_coherence_with_index(A, B) return max_val
8e6f8d499e84394ef1af551d4fea9ab9a259c05a
25,715
def pdf_page_enumeration(pdf): """Generate a list of pages, using /PageLabels (if it exists). Returns a list of labels.""" try: pagelabels = pdf.trailer["/Root"]["/PageLabels"] except: # ("No /Root/PageLabels object"), so infer the list. return range(1, pdf.getNumPages() + 1) ...
133c97f4d25dc562d08a7d45c9f85cbe04776162
25,716
import torch def transform_points_torch(points, homography): """Transforms input points according to homography. Args: points: [..., H, W, 3]; pixel (u,v,1) coordinates. homography: [..., 3, 3]; desired matrix transformation Returns: output_points: [..., H, W, 3]; transformed (u,v...
f45bf1b94c360241272bc084adcf6fee1b9f3afe
25,717
def _sane_fekete_points(directions, n_dim): """ get fekete points for DirectionalSimulator object. use get_directions function for other use cases. """ if directions is None: n_dir = n_dim * 80 elif isinstance(directions, int): n_dir = directions else: try: ...
f1d0a7dfa1438f2a4071536fb048504074e8b95d
25,718
def backoffPolicy(initialDelay=1.0, maxDelay=60.0, factor=1.5, jitter=_goodEnoughRandom): """ A timeout policy for L{ClientService} which computes an exponential backoff interval with configurable parameters. @since: 16.1.0 @param initialDelay: Delay for the first reconnection at...
679185a35f4e830ded528d59d77b2bf91a548999
25,719
def block_group(inputs, filters, strides, block_fn, block_repeats, conv2d_op=None, activation=tf.nn.swish, batch_norm_activation=nn_ops.BatchNormActivation(), dropblock=nn_ops.Dropblock(), ...
990dae88aa1fcad078094f3a667ce5ae48f37521
25,720
def GeneratePublicKeyDataFromFile(path): """Generate public key data from a path. Args: path: (bytes) the public key file path given by the command. Raises: InvalidArgumentException: if the public key file path provided does not exist or is too large. Returns: A publi...
a233b31c3ca2328952b09592fe054aff69c5d4ce
25,721
import argparse def parse_overrides(overrides, pre): """Find override parameters in the cli args. Note: If you use the same cli flag multiple time the values will be aggregated into a list. For example `--x:a 1 --x:a 2 --x:a 3` will give back `{'a': [1, 2, 3]}` :param overrides: ...
21ba5674f25d7a7c1ca8485a7d57783e1fa5371e
25,722
def make_keyword_html(keywords): """This function makes a section of HTML code for a list of keywords. Args: keywords: A list of strings where each string is a keyword. Returns: A string containing HTML code for displaying keywords, for example: '<strong>Ausgangsw&ouml;rter:</stro...
71e35245ad7b2fe2c67f6a4c27d53374945089bd
25,723
def is_match(set, i): """Checks if the three cards all have the same characteristic Args: set (2D-list): a set of three cards i (int): characterstic Returns: boolean: boolean """ if (set[0][i] == set[1][i] and set[1][i] == set[2][i]): return True return False
bd4063dba02f10d7d9d4093aa8f0df8920db17b3
25,724
def notGroup (states, *stateIndexPairs): """Like group, but will add a DEFAULT transition to a new end state, causing anything in the group to not match by going to a dead state. XXX I think this is right... """ start, dead = group(states, *stateIndexPairs) finish = len(states) states.append...
9fecae45c8cadc2ba2a4a7962416b8b31e8b1bce
25,725
import os def copy_file_to(local_file_path_or_handle, cloud_storage_file_path, metadata=None): """Copy local file to a cloud storage path.""" if (isinstance(local_file_path_or_handle, basestring) and not os.path.exists(local_file_path_or_handle)): logs.log_error('Local ...
3e61e7b4c82ca65e2af47593aaaaccf3ad57eda7
25,726
import numpy as np def get_image_array(conn, image_id): """ This function retrieves an image from an OMERO server as a numpy array TODO """ image = conn.getObject("Image", image_id) #construct numpy array (t, c, x, y, z) size_x = image.getSizeX() size_y = image.getSizeY() size_...
25ff59658b189a412a449cad29662f9a3d22ed87
25,727
def test_softsign(): """Test using a reference softsign implementation. """ def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[...
1de242e1a545ca7a182c3e3b086a551c0774d578
25,728
def run( package_out_dir, package_tests_dir, work_dir, packages): """Deployes build *.cipd package locally and runs tests against them. Used to verify the packaged code works when installed as CIPD package, it is important for infra_python package that has non-trivial structure. Args: pack...
277613b42502725d751cfdc0493f545f4fb46125
25,729
def get_published_questions(quiz): """ Returns the QuerySet of the published questions for the given quiz """ questions = get_questions_by_quiz(quiz) #Questions are ordered by serial number return questions.filter(published = True)
19cec8b57954ae68605de1acefef57f0a68671da
25,730
def moving_average(x, window): """ :param int window: odd windows preserve phase From http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DataFiltering.ipynb """ return np.convolve(x, np.ones(window) / window, "same")
c0bd4438d54e3a26bf398f019ca40eec62db83a2
25,731
def validate_interval_avg_data(in_data): # test """Validates input to get_avg_since for correct fields Args: in_data: dictionary received from POST request Returns: boolean: if in_data contains the correct fields """ expected_keys = {"patient_id", "heart_rate_average_since"} f...
0fcf927c3912bea594554fdffc73312a7da4d628
25,732
def _get_cm_control_command(action='--daemon', cm_venv_name='CM', ex_cmd=None): """ Compose a system level command used to control (i.e., start/stop) CloudMan. Accepted values to the ``action`` argument are: ``--daemon``, ``--stop-daemon`` or ``--reload``. Note that this method will check if a virtualen...
d6c4448da86ddd790977c4c0c150b748dd8f26b7
25,733
def get_all_db_data() -> list: """Возвращает все строки из базы""" cursor.execute('''SELECT * FROM news''') res = cursor.fetchall() return res
52f0e59f892898f15a361c5d1de56898f48ac2d7
25,734
def astra_projector(vol_interp, astra_vol_geom, astra_proj_geom, ndim, impl): """Create an ASTRA projector configuration dictionary. Parameters ---------- vol_interp : {'nearest', 'linear'} Interpolation type of the volume discretization. This determines the projection model that is cho...
df3458ea09d2a9bffdced2738404aec419e7b48f
25,735
def __hit(secret_number, choice): """Check if the choice is equal to secret number""" return secret_number == choice
55bee8370a2480b5ca84cd5f478fd8eb367276bd
25,736
def minimal_product_data(setup_data): """Valid product data (only required fields)""" return { 'name': 'Bar', 'rating': .5, 'brand_id': 1, 'categories_ids': [1], 'items_in_stock': 111, }
ecf027704ea8533d71468527335201a021d8ae4f
25,737
def flatten_column_array(df, columns, separator="|"): """Fonction qui transforme une colonne de strings séparés par un séparateur en une liste : String column -> List column""" df[columns] = ( df[columns].applymap(lambda x: separator.join( [str(json_nested["name"]) for json_nested in x])...
770b519a5b086d872e4bd16bc92663f693453745
25,738
from typing import List def part2(lines: List[List[int]]): """ """ grid = Grid.from_text(lines) lim_x = grid.width() lim_y = grid.height() for by in range(5): for bx in range(5): if bx == by == 0: continue for dy in range(lim_y): ...
c11c452e71b61b7cda98acda6908832aec7bca60
25,739
def translate_point(point, y_offset=0, x_offset=0): """Translate points. This method is mainly used together with image transforms, such as padding and cropping, which translates the top left point of the image to the coordinate :math:`(y, x) = (y_{offset}, x_{offset})`. Args: point (~nump...
fffd18a2df12e8d51b0ea30fe378da37aa245d5d
25,740
def _get_tau_var(tau, tau_curriculum_steps): """Variable which increases linearly from 0 to tau over so many steps.""" if tau_curriculum_steps > 0: tau_var = tf.get_variable('tau', [], initializer=tf.constant_initializer(0.0), trainable=False) tau_...
a4ba777a70df55f22299e415e7998dc303c0b3cf
25,741
def des_descrypt(s): """ DES 解密 :param s: 加密后的字符串,16进制 :return: 解密后的字符串 """ iv = constants.gk k = des(iv, CBC, iv, pad=None, padmode=PAD_PKCS5) #print binascii.b2a_hex(s) de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5) print de return de
2a1224ec5a197928aedc6b4168762bac7f287624
25,742
import zipfile import io def ghg_call(url, response, args): """ Callback function for the US GHG Emissions download. Open the downloaded zip file and read the contained CSV(s) into pandas dataframe(s). :param url: :param response: :param args: :return: """ df = None year = args...
17665c9ddab5406c147b641b47376a089cf11206
25,743
def get_compound_coeff_func(phi=1.0, max_cost=2.0): """ Cost function from the EfficientNets paper to compute candidate values for alpha, beta and gamma parameters respectively. These values are then used to train models, and the validation accuracy is used to select the best base parameter...
ec2e3e07a93741827c934e05d2e4e7e5e4a54901
25,744
import re def get_kver_bin(path, split=False, proc=None): """ Get version of a kernel binary at 'path'. The 'split' and 'proc' arguments are the same as in 'get_kver()'. """ if not proc: proc = Procs.Proc() cmd = f"file -- {path}" stdout = proc.run_verify(cmd)[0].strip() msg...
212da809d1c2dc52e7bf7cee2aafd89d9437eadb
25,745
from datetime import datetime def post_apply_become_provider_apply_id_accept(request: HttpRequest, apply_id, **kwargs) -> JsonResponse: """ 允许成为设备拥有者 :param request: 视图请求 :type request: HttpRequest :param kwargs: 额外参数 :type kwargs: Dict :return: JsonResponse :rtype: JsonResponse "...
1440d2ae9495b75c398000d3367d68fdb84f2c00
25,746
import tokenize def get_var_info(line, frame): """Given a line of code and a frame object, it obtains the value (repr) of the names found in either the local or global scope. """ tokens = utils.tokenize_source(line) loc = frame.f_locals glob = frame.f_globals names_info = [] names =...
d584e1c83a9bf7d0134be1251b92cb789a7ac51c
25,747
import operator def filter_events_for_client(store, user_id, events, is_peeking=False, always_include_ids=frozenset()): """ Check which events a user is allowed to see Args: store (synapse.storage.DataStore): our datastore (can also be a worker store) ...
fdebb3cf493c14328d3292eb4f4adf4c370511c3
25,748
from typing import Union from typing import Optional def MPS_SimAddRule(event_mask: Union[IsoSimulatorEvent, FeliCaSimulatorEvent, VicinitySimulatorEvent, NfcSimulatorEvent, ...
d945885635eba27c74edb33eb72e6bac3791a190
25,749
def wr1996(size=200): """Generate '6d robot arm' dataset (Williams and Rasmussen 1996) Was originally created in order to test the correctness of the implementation of kernel ARD. For full details see: http://www.gaussianprocess.org/gpml/code/matlab/doc/regression.html#ard x_1 picked randomly in ...
112e4760db98f5ca32846a88429a15494d5fa814
25,750
import json def to_pretty_json(obj): """Encode to pretty-looking JSON string""" return json.dumps(obj, sort_keys=False, indent=4, separators=(',', ': '))
b325c4e6e150e089da1d9027299831bd1576e57f
25,751
def parse_access_token(request): """Get request object and parse access token""" try: auth_header = request.headers.get('Authorization') return auth_header.split(" ")[1] except Exception as e: return
a51d51d83cba5fc8e8eb7b9a9147a0219e2bcb20
25,752
def postscriptWeightNameFallback(info): """ Fallback to the closest match of the *openTypeOS2WeightClass* in this table: === =========== 100 Thin 200 Extra-light 300 Light 400 Normal 500 Medium 600 Semi-bold 700 Bold 800 Extra-bold 900 Black === ======...
4521375a668c81fdee9a3fc20391f633a60af777
25,753
def down_spatial(in_planes, out_planes): """downsampling 21*21 to 5*5 (21-5)//4+1=5""" return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=5, stride=4), nn.BatchNorm2d(out_planes))
2570eb4f837d45a3683f8594ef9ba0fa5b996445
25,754
def add_integral_control( plant, regulator=None, integrator_ugf=None, integrator_time_constant=None, **kwargs): """Match and returns an integral gain. This function finds an integral gain such that the UGF of the integral control matches that of the specified regulator. If ``integra...
16c6efe598e60e325f7be2fe018156f89deaac11
25,755
def script(): """Render the required Javascript""" return Response(response=render_template("settings/settings.js"), status=200, mimetype="application/javascript")
d879fded0ebf2e160d3dcbc541ae07bc08571b8e
25,756
def repr_helper(tuple_gen_exp, ind=2): """ given a sequence of 2-tuples, return a nice string like: .. code_block:: python (1, 'hi'), (2, 'there'), (40, 'you') -> .. code_block:: python [ 1] : hi [ 2] : there [40] : you """ lines = [] k_v = list(tuple_gen_exp)...
a80739ac09167ce582bf35dc8e7ce1c7654ba6e2
25,757
from IPython import get_ipython def in_ipython() -> bool: """Return true if we're running in an IPython interactive shell.""" try: return get_ipython().__class__.__name__ == 'TerminalInteractiveShell' except Exception: pass return False
f0a92dfc8c02da2761c5f2074b3928943e7abd8f
25,758
def demo_loss_accuracy_curve(): """Make a demo loss-accuracy curve figure.""" steps = np.arange(101) loss = np.exp(-steps * 0.1) * 20. + np.random.normal(size=101) * 2. loss = loss - np.min(loss) + .2 valid_steps = np.arange(0, 101, 10) valid_loss = (np.exp(-valid_steps * 0.1) * 25. + ...
1d530d0f4f6c830a974fd634c636f691595f1d38
25,759
import fbuild.builders import os import platform def guess_platform(ctx, arch=None): """L{guess_platform} returns a platform set that describes the various features of the specified I{platform}. If I{platform} is I{None}, try to determine which platform the system is and return that value. If the plat...
19a39bd4c6ecfa31b242b3362ab9574d2d6b1436
25,760
def text_filter(sentence:str)-> str: """ 过滤掉非汉字和标点符号和非数字 :param sentence: :return: """ line = sentence.replace('\n', '。') # 过滤掉非汉字和标点符号和非数字 linelist = [word for word in line if word >= u'\u4e00' and word <= u'\u9fa5' or word in [',', '。', '?', '!', ...
9c0949b2e9b374f1aa5392b5a4c215ebff21171b
25,761
import math def get_lr_schedule(base_lr, global_batch_size, base_batch_size=None, scaling=None, n_warmup_epochs=0, warmup_factor=-1, decay_schedule={}, is_root=True): """Get the learning rate schedule function""" if scaling == 'linear': scale_factor = global_batch_size / base_batch...
385d9f01992dc650732420580803b147068f70fc
25,762
import math def stdp_values(values, period=None): """Returns list of running population standard deviations. :param values: list of values to iterate and compute stat. :param period: (optional) # of values included in computation. * None - includes all values in computation. :rtype: list of w...
b3be172dc377325b75ac7f8fe908751b47ecca58
25,763
def json_serialize(item): """ A function similar to L{dumps}. """ def helper(unknown): if isinstance(unknown, PlatedElement): return unknown._asJSON() else: raise TypeError("{input} not JSON serializable" .format(input=unknown)) ret...
00ea0aa060eaf2335148402770eba173592e1a65
25,764
def get_sop_instance_uid(dicom): """ Return the SOP Instance UID. Args: dicom: pydicom Dataset """ return dicom.SOPInstanceUID
18991a81be2e143aecaf59bdf52e51ab2f9a621b
25,765
def remove_filter(): """ Removes a filter from the process Returns ------------- dictio Success, or not """ # reads the session session = request.args.get('session', type=str) # reads the requested process name process = request.args.get('process', default='receipt', typ...
887c985694fd11e5adeff23e001d9b94f7879ff5
25,766
def flag_data(vis_windows, flag_windows): """ Returns flag_windows untouched """ def _flag_data(vis_windows, flag_windows): return flag_windows return da.blockwise(_flag_data, _WINDOW_SCHEMA, vis_windows, _WINDOW_SCHEMA, flag_windows, _WINDOW_SCHEMA,...
55f3df8fa6ca30de2cd6c9bac5f55eb4fff0eb36
25,767
def preprocess_static_feature( static_feature_dict, imputation_strategy="median", standardize=False ): """Preprocessing for a dictionary of static features. Args: static_feature_dict: Dictionary of float values. imputation_strategy: "median" or "mean" or "most_frequent" imputation. standard...
a2bfbfc21afcd1ab03f86f82e72fff480746542e
25,768
import time import gzip import six import sys import io from io import StringIO import csv def auto_sampler(dataset, encoding, ui): """ Automatically find an appropriate number of rows to send per batch based on the average row size. :return: """ t0 = time() sample_size = AUTO_SAMPLE_SIZ...
ab90f55ce6d61de6559f1ab59a35f65c16e63166
25,769
from typing import List def from_emso(platform_code: str, parameters: List[str]=[], start_time: str='', end_time: str='', depth_min: float=None, depth_max: float=None, user: str='', password: str='', size: int=10, token: str='' ) -> WaterFrame: """ Get a WaterFrame wi...
d8ac4520a3364e92d5e52768e12211989cdc876b
25,770
def _get_all_pivots(Ao, number_of_subsamples): """ A dummy case where we return all the subsamples. """ return np.arange(1, len(number_of_subsamples))
886a32ac34f0eb3acafa15917258e87b68b7323c
25,771
def clang_find_var(tu, name, ts, namespace=None, filename=None, onlyin=None): """Find the node for a given var.""" assert isinstance(name, basestring) kinds = CursorKind.ENUM_DECL, decls = clang_find_decls(tu, name, kinds=kinds, onlyin=onlyin, namespace=namespace) decls = list(set(c.get_definition()...
cacdf6426353f99ed66f051c7d118706dc76f134
25,772
def ShouldRunOnInternalIpAddress(sending_vm, receiving_vm): """Returns whether a test should be run on an instance's internal IP. Based on the command line flag --ip_addresses. Internal IP addresses are used when: * --ip_addresses=BOTH or --ip-addresses=INTERNAL * --ip_addresses=REACHABLE and 'sending_vm' c...
961fc7343d6c3712d62fd1897f5897c49f6ec66d
25,773
def shn_get_crud_string(tablename, name): """ Get the CRUD strings for a table """ crud_strings = s3.crud_strings.get(tablename, s3.crud_strings) not_found = s3.crud_strings.get(name, None) return crud_strings.get(name, not_found)
106aba2b964b43d0afec45fa09cb68798bcc6a11
25,774
def default_invalid_token_callback(error_string): """ By default, if an invalid token attempts to access a protected endpoint, we return the error string for why it is not valid with a 422 status code :param error_string: String indicating why the token is invalid """ return jsonify({config.err...
70674a70a7b35838b154d2405e991c2653d02d8a
25,775
def bf_generate_dataplane(snapshot=None, extra_args=None): # type: (Optional[str], Optional[Dict[str, Any]]) -> str """Generates the data plane for the supplied snapshot. If no snapshot argument is given, uses the last snapshot initialized.""" return bf_session.generate_dataplane(snapshot=snapshot, extra_ar...
4134208bfef878e38f0428f8e8d830a7cc7b9377
25,776
def k_correction_pl(redshift, a_nu): """Calculate the k-correction for a power law spectrum with spectral index (per frequency) a_nu. :param redshift: Cosmological redshift of the source :type redshift: float :param a_nu: Power law index (per frequency) :type a_nu: float :return: K-correcti...
e8fb84f3b98f49d4f1bb904eee61916f4a4bc3de
25,777
def make_points_image(pts, mask, radius=5): """ Create label image from physical space points Creates spherical points in the coordinate space of the target image based on the n-dimensional matrix of points that the user supplies. The image defines the dimensionality of the data so if the input ima...
dfb94ca6a80e315571c53c1c4b5377f35eec771c
25,778
def map_replacements(): """ create a map of what resources are replaced by others. This is a tree. """ isreplacedby = {} # isreplacedby[x] is the number of things that are replaced by x replaces = {} # replaces[x] are the number of things that x replaces. for r in BaseResource.objects.all(): i...
faf4e63bd902325d9c0563e60db0bb1348ed3e38
25,779
def order_basemaps(key, out): """check the apy key and then order the basemap to update the select list""" # checking the key validity validate_key(key, out) out.add_msg(cm.planet.mosaic.load) # autheticate to planet planet.client = api.ClientV1(api_key=planet.key) # get the basemap name...
491296f3231e093817119cd4ed72f2c90b2e02d8
25,780
from typing import Any def explanare_optionem(thing: Any) -> str: """Output debug information from data structures used on HDP containers Args: thing (Any): Anything that can be converted to str Returns: str: String """ return str(thing)
59238b1f53382a4b925e39b4eac221a98b6af6fe
25,781
def compute_iou(box1, box2, yxyx=False): """Calculates the intersection of union between box1 and box2. Args: box1: a `Tensor` whose shape is [..., 4] and represents the coordinates of boxes in x_center, y_center, width, height. box2: a `Tensor` whose shape is [..., 4] and represents the coordinates ...
47c9f9d6a10cc35984640c177ff49d637cf9a656
25,782
from typing import Union import warnings def ensure_pyspark_df(spark_session: SparkSession, df: Union[pandasDF, sparkDF]): """Method for checking dataframe type for each onData() call from a RunBuilder.""" if not isinstance(df, sparkDF): warnings.warn( "WARNING: You passed in a Pandas DF, ...
0662665f93791640fed18d2615563e71d0abe1c3
25,783
from datetime import datetime def roundTime(dt=None, roundTo=60): """ Round a datetime object to any time lapse in seconds dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 1 minute. Author: Thierry Husson 2012 - Use it as you want but don't blame me. Example...
0c949a0c69e2a9db38cff6e83b299d022b095ad3
25,784
def sample_recipe(user, **params): """Create and return a sample recipe""" recipe_defaults = { 'title': 'simple ricepi shot', 'time_minutes': 10, 'price': 5.0 } recipe_defaults.update(params) return Recipe.objects.create(user=user, **recipe_defaults)
8142b277f193ad76d3bb6d287963c6699001c636
25,785
def read_nitf_offsets(filename): """Read NITF fields relevant to parsing SICD SICD (versions 0.3 and above) is stored in a NITF container. NITF is a complicated format that involves lots of fields and configurations possibilities. Fortunately, SICD only really uses a small, specific portion of the...
e2e8bb3ee6b32cf8964b1c13b4e8584cc7fd9917
25,786
from datetime import datetime def dttime(ts): """ 将DataTime对象转换为unix时间 :param ts: unix时间 :type ts: float :returns: datetime.datetime 对象 :rtype: datetime.datetime """ return datetime.datetime.fromtimestamp(ts)
7a3691df61f7fad641445b7b84ea88ae39f6dbb9
25,787
import copy def split_import(sc, node, alias_to_remove): """Split an import node by moving the given imported alias into a new import. Arguments: sc: (scope.Scope) Scope computed on whole tree of the code being modified. node: (ast.Import|ast.ImportFrom) An import node to split. alias_to_remove: (ast...
e83f2af8af108f3512e539ab50a8e264ccceb24f
25,788
def load_trace(path): """Load the trace located in path. Args: path (string): Path to the LTTng trace folder. Returns: babeltrace.TraceCollection: a collection of one trace. """ trace_collection = bt.TraceCollection() trace_collection.add_trace(path, 'ctf') return trace_col...
eed21b6d3ac62104e9661c26cd6d996768562e89
25,789
def get_repo_paths(config_file_path): """ Get a list of repository paths. Arguments: config_file_path (str): Path the to config file. Raises: (ConfigFileError): Raised if there was an error opening, reading or parsding through the config file. Returns: (list<str>): A list ...
2b79d55d83a40689206213097c1ddb8ed3535e69
25,790
async def get_bosswins_rank(conn : asyncpg.Connection, user_id : int) -> int: """Returns the rank in bosswins for the player given""" psql = """ WITH ranks AS ( SELECT ROW_NUMBER() OVER (ORDER BY bosswins DESC) AS rank, user_id, user_name, bosswins ...
f87746fd3e77b6e41922bc9efbe2e9a2fead8b09
25,791
def detect_objects_yolo(imgs, tensors): """This function makes use of multiprocessing to make predictions on batch. Parameters ---------- imgs : list-like of images tensors : dict Contains tensors needed for making predictions. Returns ------- boxes: tuple Tuple of leng...
41a511e2fea6cb5abe449f995245ba3a76ae38f2
25,792
def append_id(endpoint, _id): """ append '_id' to endpoint if provided """ if _id is not None: return '/'.join([endpoint.rstrip('/'), _id]) return endpoint
60586a70bc8b9c9b10c1d54f6810c4528c5c0dec
25,793
import time import statistics def records() -> dict: """ Displays TJ's all time bests. """ records = cube.load_file("records") times, people = records["records"], records["people"] refresh = False if "wca_token" in flask.session and "ion_token" in flask.session: me = cube.api_call("wca", "...
c711634dcd7e06de481fc169d538b03735396cf0
25,794
import re def get_info_media(title: str, ydl_opts=None, search_engine=None, result_count=1): """ :param title: :param ydl_opts: :param search_engine: :param result_count: :return: """ if ydl_opts is None: ydl_opts = { # 'format': 'best[ext!=wav]/best', ...
03f8be75da183a818961e4fa2c08ac554dac5841
25,795
def export_post(request, style, format=-1): """ :param request: :param style: :param format: :return: """ try: payload = request.get_json(force=True) # post data in json except: payload = dict(request.form) # post data in form encoding if not payload: retu...
7d26bffd25c7557453906ba9438b893bc957223f
25,796
def unpack_literal_map_to_sdk_object(literal_map, type_map=None): """ :param lytekit.models.literals.LiteralMap literal_map: :param dict[Text, flytekit.common.types.base_sdk_types.FlyteSdkType] type_map: Type map directing unpacking. :rtype: dict[Text, T] """ type_map = type_map or {} return...
1c5de0c99d7e43c0012bdc0ce97c549e0888f4be
25,797
import requests def get_data(user:str,num_last:int)->int: """获取关注者数数据,输出数据增量并返回数据;重试3次,全部失败则返回False""" # error=None global proxies for i in range(3): try: num_this=requests.get('https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names='+user,proxies=proxies,timeout=(10,30)).json()[0]['fo...
c72a8b4272e7432cfa81ace7344dba469082bcdd
25,798
import argparse def parse_cli() -> dict: """ Parse CLI arguments. :return: CLI Arguments dict. """ parser = argparse.ArgumentParser() parser.add_argument( "-s", "--settings_path", type=str, help="Path to settings YAML-file for RailLabel.", default="setti...
bb822edf30178753df3740a7cc493575fc03a8ef
25,799