content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_eia860_xlsx(years, filename, data_dir): """Read in Excel files to create Excel objects. Rather than reading in the same Excel files several times, we can just read them each in once (one per year) and use the ExcelFile object to refer back to the data in memory. Args: years (list):...
a9a92e52464836fa4881591ef0d9dad78cc24816
39,400
from datetime import datetime import sys def get_model_details(event, context): """ Extract the model attributes from the model passed as an argument """ # Get attributes from both the model and the associated dataset: model_name = event['model_name'] model_response = l4e_client.descr...
909f23bb400955d9b178f7fd8c0dcab4789d98cf
39,401
def get_aligned_args(args): """Loading aligned from args namespace from argparse """ if args.aligned_dir is not None: if args.aligned_name is not None: raise ValueError( "args -aligned_dir and -aligned_name should not be both set") return get_aligned_dir(args.alig...
3deb18db3e68d2604202c1761f9f64e6b4020bf7
39,402
from typing import List import statistics def SmoothArray(xx: List[float]) -> List[float]: """Runs the 353QH algorithm twice and returns smooth version of the input. For documentation see these proceedings https://cds.cern.ch/record/186223/ on page 292. The algorithm runs twice to avoid over-smoothing pe...
39e322178772cbf995a109de656898ed6c0a0696
39,403
from operator import sub def check_attack(board, bad_positions, snake): """ Determines if we have the opportunity to attack - doesn't seek out attacking but will attack given the opportunity """ possible_attacks = [] available_moves = available_next_positions(board, snake) # attack potential position...
2f8445dc816b1f88d652fcbe638bc3485942d744
39,404
def station(): """ Return a list of all stations from database. """ session = Session(engine) results = session.query(Station.name).all() session.close() station_dict = list(np.ravel(results)) return jsonify(station_dict)
a384c8fa1639ea3e76e1269907daf128f642ed3e
39,405
def dots2utf8(dots): """ braille dots to utf-8 hex codes""" code=0 for number in dots: code += 2**(int(number)-1) return hex(0x2800 + code)
0406c3cf18d5dbd66ea35b0862785371cdd68796
39,406
def set_domain_to_dns_name(session, domain_name, dns_resource, hosted_zone): """Updates or Creates a domain name with FQDN resource. Args: session (Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed domain_n...
bb3fc8d999039109bcd69fbe30e18458512eb1fc
39,407
import itertools from functools import reduce import operator def full_range_args_generator(**ranges): """ Cartesian production, generates all possible combinations of the arguments :param ranges: range(...) objects or lists, defines arguments' domains :return: """ res = itertools.product(*(r ...
96ccf2c576dfb06ea6e65853478e00adfc5dd1af
39,408
def _can_view_courseware_with_prerequisites(user, course): """ Checks if a user has access to a course based on its prerequisites. If the user is staff or anonymous, immediately grant access. Else, return whether or not the prerequisite courses have been passed. Arguments: user (User): the...
3d39e73b4217872776f4684201353581f525b24e
39,409
def _convert_to_coord_format(interaction_file, out_file): """make it easier to work with interaction file, produces start_id, end_id, score """ assert interaction_file.endswith(".gz") assert out_file.endswith(".gz") # reformat reformat = ( "zcat {} | " "awk -F ',' '{{ pr...
4e0626a631f23f902a2191ce8fe63e60b884f79b
39,410
import os def is_non_zero_file(fpath): # https://stackoverflow.com/a/15924160 """Returns TRUE/FALSE if file exists and non zero""" return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
4980d57828ddf4f7087dc9db876331667eb80af5
39,411
def add_num_epochs_and_checkpoints(config): """Add number of epochs and checkpoints where model will be saved to config.""" problem_cls = config["problem_cls"] num_epochs = DEFAULT_TEST_PROBLEMS_SETTINGS[problem_cls.__name__]["num_epochs"] config["num_epochs"] = num_epochs if "checkpoints" not in c...
c2827aca8ce69dd74cc856d5f75f782920765ad0
39,412
import ast def doCompare(op, left, right): """Perform the given AST comparison on the values""" top = type(op) if top == ast.Eq: return left == right elif top == ast.NotEq: return left != right elif top == ast.Lt: return left < right elif top == ast.LtE: return left <= right elif top == ast.Gt: retur...
b82a1c4d101428cf9ded532d65539cfe3195d8a1
39,413
import os from datetime import datetime import io def gen_html_report(summary, report_template=None, report_dir=None, report_file=None): """ render html report with specified report name and template Args: summary (dict): test result summary data report_template (str): specify html report tem...
fdf38e08aa0006c5c71404abca92315c41770a0c
39,414
def import_class(module_base_name, script_name): """ 导入指定模块的脚本,并返回 # from sys import stdin # sys = __import__('sys', fromlist = ['stdin']) :return: 所需模块 """ module_levels = script_name.split(".") file_module_name = module_levels[-1] class_name = String().class_name_normalize(fil...
fe4d9968d67ae2b8ec5908503c8b03ab16207cf1
39,415
def runGdScript(godot, filepath): """Run the given GdScript file and return the results as an array of strings""" return runGodot([godot, '-s', filepath])
956a7f572349f70bce58e27f8f27c1a2aef36d63
39,416
import torch def unmold_mask(masks, bboxes, image_shape): """Converts a mask generated by the neural network into a format similar to it's original shape, using overlap-tile strategy here. masks: [detect_num, depth, height, width, num_instances] of type float. A small, typically 28x28 mask. bboxes: [d...
94cae3ebd455e228ce67f1d9675b08e11c801ef9
39,417
def create_link_atoms(mol, qmatoms): """ Create hydrogen caps for bonds between QM and MM regions. Each link atom will have ``metadata.mmatom``, ``metadata.mmpartner`` attributes to identify the atom it replaces and the atom it's bonded to in the MM system. Raises: ValueError: if any MM/QM ato...
abc9a8feb74c0a411a79b00b4d729c4a82a1a39b
39,418
import hmac import hashlib def generate_signature(secret, verb, url, nonce, data): """Generate a request signature compatible with BitMEX.""" # Parse the url so we can remove the base and extract just the path. parsedURL = urlparse(url) path = parsedURL.path if parsedURL.query: path = path...
5d173a6f8ab472e8547e3739f19cfd73d9fb9c4b
39,419
def get2(request): """一键多值""" # 获取GET属性对应的queryDict类型的对象 query_dict = request.GET a = query_dict.getlist('a') # query_dict.get('a') 只会获取最后一个值 b = query_dict.get('b') c = query_dict.get('c') # 如果key不存在,返回None str = '%s - %s -%s' % (a, b, c) return HttpResponse(str)
c43c83c560e469a76af22b98e0c448e7ad84cf2e
39,420
from __init__ import identifier def signature(class_name): """return the signature for a port using one of the module classes defined in this file""" return ':'.join((identifier, class_name))
efcffe04c716c334e7e0e7d7507647cc48e0dbd0
39,421
from . import Label from . import get_volume_labels_from_aseg def get_volume_labels_from_src(src, subject, subjects_dir): """Return a list of Label of segmented volumes included in the src space. Parameters ---------- src : instance of SourceSpaces The source space containing the volume regio...
2a893f6462640bdd08c782d87e31a20894fd136e
39,422
import platform def get_path_name(obj_name, io=None): """ Returns a path and a name for where the downloaded objects (list or excel file) will be stored. :param str obj_name: a list name or a path to an excel file in sharepoint :param str io: path to where downloaded objects (list or excel file) will be s...
602436f393a74006f10be23efad3d0c58391d24f
39,423
def Lagrange_polynomials_01(x, N): """ Compute all the Lagrange polynomials (at x) for N+1 equally spaced interpolation points on [0,1]. The polynomials and points, as two separate lists, are returned. Works for symbolic and numerical computation of the polynomials and points (if x is sympy.Symb...
9bbb7d8b789ea90108ac471db232ae16e66d2f21
39,424
def _random_integer(minval, maxval, seed): """Returns a random 0-D tensor between minval and maxval. Args: minval: minimum value of the random tensor. maxval: maximum value of the random tensor. seed: random seed. Returns: A random 0-D tensor between minval and maxval. """ return tf.random.u...
0760098d43b41c66a5609295b6334cdb0f7349f4
39,425
def list_posts(page=1, num_items=10): """List all blog posts, in sets of 10.""" url = bottle.request.urlparts page = bottle.request.query.page or 1 try: page = int(page) if int(page) > 0 else 1 except: bottle.abort(404, "Page not found") count = db.zcard("content:posts:live") ...
8c400fef15f88429e178bf4f858c2e35dd934626
39,426
def read_dataset(path, header=None, columns=None, make_binary=False, binary_th=4.0, user_key='user_id', item_key='item_id', rating_key='rating', sep=',', user_to_idx=N...
9c071af4e026c437915b96f8f4cbbf6f200397c7
39,427
def _normalize_unknown_symbols(token): """Símbolos (letras) no reconocidos los decodifica a ASCII.""" return ''.join([ s if ALPHABET.match(s) else _to_unicode(unidecode(s)) for s in _to_unicode(token)])
31c63426358b649d4e2200fa02a4e7a0891a9d46
39,428
def _customized_dumper(container, dumper=Dumper): """ Coutnerpart of :func:`_customized_loader` for dumpers. """ def container_representer(dumper, data, mapping_tag=_MAPPING_TAG): """Container representer. """ return dumper.represent_mapping(mapping_tag, data.items()) def us...
a36bbfdfffefc278586c226c2404fe4c690c5cd0
39,429
def raw_encode(data): """Special case serializer.""" content_type = 'application/data' payload = data if isinstance(payload, unicode): content_encoding = 'utf-8' payload = payload.encode(content_encoding) else: content_encoding = 'binary' return content_type, content_enco...
e4f7042f0aea627913d554b2fc63b6f79771241c
39,430
def iou(box1, box2): """Computes pairwise intersection-over-union between box collections. Args: box1: a float Tensor with [N, 4]. box2: a float Tensor with [M, 4]. Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = intersection(box1, box2) areas1 = area(...
021056736b7cc128d34097da2cc5096b92e52935
39,431
def bytes_realize(space, py_obj): """ Creates the string in the interpreter. The PyBytesObject buffer must not be modified after this call. """ py_str = rffi.cast(PyBytesObject, py_obj) s = rffi.charpsize2str(py_str.c_buffer, py_str.c_size) w_obj = space.wrapbytes(s) track_reference(spac...
b3c5841f307ed30354632f256417c4b574375299
39,432
def get_interface_by_name(interfaces, name): """ Return an interface by it's devname :param name: interface devname :param interfaces: interfaces dictionary provided by interface_inspector :return: interface dictionary """ for interface in interfaces: if interface['devname'] == name:...
9d63bf667a0677ba7d0c3fdde2b4b35affc3b72b
39,433
import unicodedata def trata_texto(texto): """ Trata textos convertendo para maiusulo,\n sem acentos e espaços indesejaveis. """ texto = texto.strip().upper() texto = unicodedata.normalize("NFKD", texto) texto = texto.encode("ascii", "ignore") texto = texto.decode("utf-8").upper() # ...
0cced9e55fd3fc15a9cdbaa3899519658668025c
39,434
import os import sys def get_checkpoint(model, checkpoint='-1'): """Set the checkpoint in the model directory and return the name of the checkpoint Note: This function will modify `checkpoint` in the model directory. Args: model: The model directory. checkpoint: The checkpoint id. If None...
7e65cbab1029e9ae16b40cafb8e7d886621d3de8
39,435
def normalize_trans_probs(p): """ Normalize a set of transition probabilities. Parameters ---------- p : pandas.DataFrame, dtype float Unnormalized transition probabilities. Indexed by source_level_idx, destination_level_idx. Returns ------- pandas.DataFrame, dtype floa...
d484c4ac08ee785e5451b1aa92ff2b85fc945384
39,436
def vel(track, t_vel, r): """Randomly change the velocity of a note in a track""" time = 0 for msg in track: if msg.type == 'note_on' or msg.type=='note_off': time += msg.time if msg.type == 'note_on': if msg.velocity != 0: # To avoid messing with certain mid ...
dcce7b2810a5407444e4cd19cfd0eb363856d59c
39,437
def resize_with_fixed_AR(img, bboxes, h_dst, w_dst): """resize with fixed aspect ratio""" w_src = tf.cast(tf.shape(img)[1], tf.float32) h_src = tf.cast(tf.shape(img)[0], tf.float32) # resize image if h_dst > h_src * (w_dst / w_src): scale = (w_dst / w_src) else: scale = (h_d...
925105612073b1f241f533800254829ba630e6ad
39,438
def choose(): """ Get the user to choose which quiz. :returns: A HTML page with a form, then redirects them to the correct quiz's page once the form is submitted. """ # Ask user which quiz. if 'quiz' not in request.args: return render_template('new.html', quizzes=quizzes) ...
bde45765cdf5e4c7f53bc7c67f75df51c7d8e2d1
39,439
def get_number_of_ones(n): """ Deterine the number of 1s ins the binary representation of and integer n. """ return bin(n).count("1")
83fb14c29064008dd9f8e7ecea4c1d9dfae1dafa
39,440
def hierarchical_link_community(g_original: object) -> EdgeClustering: """ HLC (hierarchical link clustering) is a method to classify links into topologically related groups. The algorithm uses a similarity between links to build a dendrogram where each leaf is a link from the original network and branches ...
6558d218ffeb2f0c473c8e6bbd8a7deb1249b6ab
39,441
import math def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4): """Gets a bunch of sinusoids of different frequencies. Args: length: scalar, length of timing signal sequence. channels: scalar, size of timing emebddings to create. The number of differ...
dbf78c05540e3354a159d46f64949c90f819227d
39,442
def get(keys): """Wrapper around db.get that counts entities we attempted to get.""" DB_GET.inc(increment=_count(keys)) return db.get(keys)
7b194e2d63ff24ae0681be1cb57468c76c8b964e
39,443
import json def get_graph(request): """Function for getting graph This function allows to get the current graph from server. """ id_of_graph = request.GET.dict()["id"] graph = Graph.objects.get(id=int(id_of_graph)) with open(graph.path_to_graph) as file: data = json.load(file) ...
1a5b5bd5c55f04de5b0cae1c5103cbe665cfd856
39,444
def startswith(df_series, match:str): """ Filter pd.series with string and get index Parameters ---------- df_series : pd.Series match : str, to search the series Returns ------- idx: bool """ return np.array(df_series.str.startswith(match), dtype = bool)
9444412cfda0bf2e332c9f75f41a9d5081af8ff9
39,445
import os def get_params_path(reconstructor_key_name_or_type, dataset_name): """ Return path of the parameters for a configuration. It can be passed to :class:`Reconstructor.load_params` as a single argument to load all parameters (hyper params and learned params). Parameters ---------- r...
b38ec2fd44b1b37eaeb19ec5774de6718e5d6b5a
39,446
import math def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulu...
160043d91883f98978813cd58e74d26b9dd471c4
39,447
def _func_flagvalue(args, is_differentscenario, line, pos): """フラグの値を読む。""" _chk_argscount(args, 1, "FLAGVALUE", line, pos) _chk_string(args[0], "FLAGVALUE", 0) path = args[0].value event = cw.cwpy.event.get_nowrunningevent() if event and path in event.flags: flag = event.flags[path] ...
7811b641b2234850194cff57df37de0b75e13299
39,448
import os import subprocess def _find_depot_tools(): """Attempts to configure and return a wrapper for invoking depot tools. Returns: A helper object for invoking depot tools. Raises: _DepotToolsNotFoundException: An error occurred trying to find depot tools. """ class DepotToolsWrapper(object): ...
192c871683d2a70fde5941eab30faeb1c7552dff
39,449
import json def help(): """ Форма генерации счета для дебага. Принимает POST-запрос с пейлоадом, отдает PDF """ if request.method == "GET": payload_str = json.dumps(sample_payload_obj, indent=4, ensure_ascii=False) return render_template("sample_payload.html", sample_payload_obj=payloa...
4d2ca9c6b9254b00daa2ac043d91406aee26559c
39,450
def cast(variable, dtype): """ Cast sparse variable to the desired dtype. Parameters ---------- variable Sparse matrix. dtype The dtype wanted. Returns ------- Same as `x` but having `dtype` as dtype. Notes ----- The grad implemented is regular, i.e. no...
59f0f53020736673481afae6ad12b450717e450a
39,451
import tensorflow as tf import functools def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """ # TODO it keeps the graph alive GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_...
3d676e081a84be5d9a464b603cfb6916ee9d0be4
39,452
def get_smiles(inp_str, species): """ Get the inchi name of the species """ # Set the geom pattern smi_pattern = ('smiles' + zero_or_more(SPACE) + '=' + zero_or_more(SPACE) + capturing(one_or_more(NONNEWLINE))) # Obtain the appropriate species string species_str = get_spec...
1e34f809567a8633fdd0ed644d6e73bc35f6b7de
39,453
def find_recipes(recipes, cur_recipes, puzzle, condition, result): """Find recipes as long as condition function is True. Returns result of result function, based on recipes and puzzle. """ while condition(recipes, puzzle): next_recipe = sum(recipes[recipe] for recipe in cur_recipes) di...
0183e55941f565c5b34789cecfa89babc269442d
39,454
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre): """detector and beam are dxtbx objects, mosflm_beam_centre is a tuple of mm coordinates in order (slow, fast). supports 2-theta offset detectors, assumes correct centre provided for 2-theta=0 """ slow_fast_beam_centre = mosflm_beam_...
fd8ed3de6904f2ab2043d057474318ab43099872
39,455
def prob1(N=10000): """Return an estimate of the volume of the unit sphere using Monte Carlo Integration. Input: N (int, optional) - The number of points to sample. Defaults to 10000. """ points = np.random.rand(3, N) points = points*2 - 1 radiusMask = la.norm(points,ax...
aaf2e669aaa8be4d851a6dc9030cf9cd91b1e5e9
39,456
from typing import Iterable from typing import Dict from typing import Sequence import hashlib import mmap def verify_checksums(sources: Iterable[str], hashes: Dict[str, Sequence[str]]) -> bool: """Verify checksums for local files. Prints a message whenever there is a mismatch. Args: sources: An...
95abd66c3e6a007b8df8b2caaecde8a85a1f0886
39,457
def fix_pipe_arg(*args): """Use this function so that if a pipe is passed to it it will automatically use its open function wprk in progress""" print(args) new_args = [] for arg in args: if(type(arg) is Pipe): new_args.append(arg.open) else: new_args...
60fc14e8d16e143f5705d440b963dc143bb74291
39,458
def _list_setitem_with_number(data, number_index, value): """ Assigns value to list. Inputs: data (list): Data of type lis. number_index (Number): Index of data. value (Number): Value given. Outputs: list, type is the same as the element type of data. """ return...
00502cf0cf4f1df0b639ba2d40369f1eee4deb79
39,459
def convert_numpy_data_to_polydata(data, header, TNB=None, PT=None): """Converting a range of data to a vtk array. Args: data (numpy.ndarray): Data array. header (list): A list of names for each array. TNB (numpy.ndarray): Data array. PT (numpy.ndarray): Data array. Returns...
734efe64cc4dc3ffccf44c6bc5d7a729b7c87b83
39,460
def _get(url): """ Convert a URL into it's response (a *str*). """ if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib...
1906b7a5b6e6d285871373bf9b7095daa6ac8c8f
39,461
import types def fun_compose(g, f): """Function composition using the geach combinator for the appropriate type, defined above.""" if (not (g.type.functional() and f.type.functional() and g.type.left == f.type.right)): raise types.TypeMismatch(g, f, "Function composition type constrai...
97b2cd77ad9daeddf2ca45343cfe2e0b6814f70f
39,462
async def async_api_set_percentage(hass, config, directive, context): """Process a set percentage request.""" entity = directive.entity percentage = int(directive.payload['percentage']) service = None data = {ATTR_ENTITY_ID: entity.entity_id} if entity.domain == fan.DOMAIN: service = fa...
1f67845b681f5703927b1282dc85a1998c97a2d9
39,463
def login_user(username, password): """ Logs in a user Arguments: username <str>: The username of the user password <str>: The password of the user """ query = f""" SELECT * FROM users WHERE username = '{username}' AND password_hash = '{password}'; """ return ...
addd2e5a47db9d9f31a22f0e04be88fbd9101bb0
39,464
import urllib def rapids(expr): """ Fire off a Rapids expression. :param expr: The rapids expression (ascii string). :return: The JSON response of the Rapids execution """ result = H2OConnection.post_json("Rapids", ast=urllib.quote(expr)) if result['error'] is not None: raise EnvironmentError("rapi...
2b9a2be9253f77cf14f07b0034e9a125c32b4fb4
39,465
def get_aqi_pm10_24h(pm10_24h: float) -> (int, str, str): """ Calculates PM10 (24h) India AQI :param pm10_24h: PM10 average (24h), μg/m3 :return: PM10 India AQI, Effect message, Caution message """ cp = __round_down(pm10_24h) return __get_aqi_general_formula_texts(cp, IN_PM10_24H, IN_AQI_EF...
3a6591a0879c06103a9517da4d5187611364c9b9
39,466
import requests def add_user_to_role(user_id, role_id): """ Add a role to a user. Requires server role management. """ auth_headers = { "Authorization": f"Bot {DISCORD_BOT_TOKEN}", } url = f"{DISCORD_API_BASE_URL}/guilds/{DISCORD_GUILD_ID}/members/{user_id}/roles/{role_id}" response = requ...
c07df2fe8a428cae1504580d794d661356f95e9b
39,467
import scipy import signal def arcmatch(curve,sci,arc,yforw,widemodel,finemodel,goodmodel,linemodel,disp,mswave,extra,logfile): """ arcmatch(curve,sci,arc,yforw,widemodel,finemodel,goodmodel,linemodel ,disp,mswave,extra,logfile) Creates the full 2d distortion solution for a slit. Inputs: curve ...
f97652fe611c2d5cc6b431c00ad3cb725f3878c0
39,468
def format_rehydrate_payload(micro_form_data, application_id, page_name): """ Returns information in a JSON format that provides the POST body for the utilisation of the save and return functionality in the XGovFormBuilder Parameters: micro_form_data (dict): application data to refo...
29016442a8ea15c783c480afb4866c61e20acb6d
39,469
import re import os def autolist(ini_file, raw_dir, lst_dir, sel_obj=None, sel_band=None, extra_config=None, # withbands=True, spchar="_" ): """ create list for files in datadir, by their names 21a: use [re] but not [parse], [parse] does not work good at...
b3acf4a5dadd01d8654cc3e470be526899b39e30
39,470
def get_p_train_step(): """Wraps train_step with jax.pmap.""" p_train_step = jax.pmap(train_step, axis_name='batch', static_broadcasted_argnums=(3, 4)) return p_train_step
44512bf016aa74178d9d959642a6b2e0bdca8cc0
39,471
def proper_case(package_name): """Properly case project name from pypi.org.""" # Hit the simple API. r = _get_requests_session().get( f"https://pypi.org/pypi/{package_name}/json", timeout=0.3, stream=True ) if not r.ok: raise OSError(f"Unable to find package {package_name} in PyPI re...
a560b53449be8c65c46b63f17defe260591655a5
39,472
from datetime import datetime import requests import base64 def predict(url): """ Returns predicted label. params: link or image bytes """ # generating filename datetimeObj = datetime.now() # if url if as https://miro.medi... if "https" in url: response = requests.get(...
755b787440b837ba6d02a048a09b3ffe26e170a0
39,473
import warnings def read_inputs(nomefile, key_strings, n_lines = None, itype = None, defaults = None, verbose=False): """ Standard reading for input files. Searches for the keys in the input file and assigns the value to variable. :param keys: List of strings to be searched in the input file. :param d...
22db8d5199ced509938ff4570274c95e64d51100
39,474
import pyswagger.tests.data import os def get_test_data_folder(version='1.2', which=''): """ """ version = 'v' + version.replace('.', '_') folder = os.path.dirname(os.path.abspath(pyswagger.tests.data.__file__)) folder = os.path.join(os.path.join(folder, version), which) return folder
30937e97bdb7b375e3424111318413032374d9ab
39,475
import os import urllib import tarfile def maybe_download_and_extract(url, download_dir): """ Download and extract the data if it doesn't already exist. Assumes the url is a tar-ball file. :param url: Internet URL for the tar-file to download. Example: "https://www.cs.toronto.edu/~kriz...
f916bf9ad25fe94117b7e05c7c3f5c7ada0d4461
39,476
def _fn_tan_ ( self , b = 1 ) : """ Tangent function: f = tan(ab) >>> f = >>> a = f.tan ( ) >>> a = f.tan ( b ) >>> a = tan ( f ) """ return _fn_make_fun_ ( self , b , Ostap.MoreRooFit.Tan , ...
0d7c4567f8854bcadd2762d602863bcea8e407b2
39,477
def error_output_bf(number_of_parameters, parameters_file_name): """Write the optimized error values into the params file near the corresponding parameter identicator""" try: file2 = open(parameters_file_name, "a+") #file2.seek(0) #position2 = file2.tell() ...
4c9641719e463dc2c1470983a807664339db1775
39,478
from typing import Dict from typing import Union from typing import List async def test_locator_do_work_transfer_request_fc_its_over_9000(config, mocker): """Test that _do_work_transfer_request processes each file it gets back from the File Catalog.""" logger_mock = mocker.MagicMock() lta_rc_mock = mocker...
7838ca5704db67346da2c61234035f88ae23e154
39,479
def get_weekday_type(date_to_test): """Gets the weekday of a date Parameters ---------- date_to_test : date Date of a day in ayear Returns ------- daytype : str holiday or working day Note ---- Bank holidays are defined for the year 2002 - 2015. The whole week ...
ed8c11d3c5ce16c823eccfe3a27435e0a9c1a7dc
39,480
def multi_head(heads, loss_weights=None): """Creates a MultiHead stemming from same logits/hidden layer. Args: heads: list of Head objects. loss_weights: optional list of weights to be used to merge losses from each head. All losses are weighted equally if not provided. Returns: A instance o...
85e6a388168bfae8b4ce83155fba378fce42e136
39,481
import logging def alarm_content() -> str: """ Determines alarm content and adds it to alarm. Checks whether the news and weather briefing tickboxes have been ticked. If they have been ticked it will poll the corresponding api and provide the corresponding information when the alarm goes off. If ...
3d186336cad87ac205bcdccbdc0bb54c7450c039
39,482
import logging def map_package_to_dataset(package, portal_url): """Mapea un diccionario con metadatos de cierto 'package' de CKAN a un diccionario con metadatos de un 'dataset' según el estándar data.json.""" dataset = dict() resources = package["resources"] groups = package["groups"] tags = p...
48369c4221b358e2094fc04e6b5be1862d1306c5
39,483
def op_abs(x): """Returns the absolute value of a mathematical object.""" if isinstance(x, list): return [op_abs(a) for a in x] else: return abs(x)
62d337b11e20b863064d90c563161bc802418abb
39,484
def add_column(colname, desc=None): """Adds column in the form of dict.""" return {'name': colname, 'desc': desc}
e0b985f71e17bfef6096d1433c84b5c163d343ff
39,485
def mc_rollout( steps, checkpoint, environment, env_name, callbacks, loggers, output_dir, input_config, step_tolerance=1000000, algorithm="PPO", multi_agent=False, ): """ Monte Carlo rollout. Currently set to return brief summary of rewards and metrics. """ c...
f592eb546d69be6f5c72d894b3801a9f3ed99f7a
39,486
def VerifyDependents(pe_name, dependents, delay_loaded, list_file, verbose): """Compare the actual dependents to the expected ones.""" scope = {} try: execfile(list_file, scope) except: raise Error("Failed to load " + list_file) # The dependency files have dependencies in two section - dependents and...
903d028fb24a51e2ed4733de578a8a4f95ee61a4
39,487
import tqdm def word_by_category_cooccurrence(corpus, labels, tokenizer=None, min_count=0., max_count=None, max_words=None): """ Devuelve la matriz de coocurrencias entre palabras y la categoría a la que pertence el documento. Es decir, las filas de la matriz son las palabras y las columnas son t...
06ded3c07cc6580e729898bffab56e307249ca91
39,488
def timeit(fn): """ Timing decorator """ def timed(*args, **kwawgs): ts = time.time() result = fn(*args, **kwawgs) te = time.time() print '[time] %r: %2.2f sec' % \ (fn.__name__, te-ts) return result return timed
fa09fac6ffff7d8c642d1c15ecd2154c56c6463f
39,489
import re def ucnstring_to_python(ucn_string): """Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode (u'\\u4e00'). """ res = re.findall(r"U\+[0-9a-fA-F]*", ucn_string) for r in res: ucn_string = ucn_string.replace(text_type(r), text_type(ucn_to_unicode(r))) ucn_st...
3bf25a80f7c432e13631779fbec1bd3123693a49
39,490
def LOSToRedshift(xLOS, vLOS, H, split=False): """ Input: line of sight distances (Mpc), velocities (km/s) and Hubble constant. Output: relativistic (Doppler) and cosmological (Hubble) redshifts if split = True, otherwise the sum of these (default). """ c = 3.0e5 zREL = np.sqrt((1+vLOS/...
c4cbd6159f551e5d29757227903b15dff8a48c18
39,491
def keypoint_change_coordinate_frame(keypoints, window, scope=None): """Changes coordinate frame of the keypoints to be relative to window's frame. Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint coordinates from keypoints of shape [num_instances, num_keypoints, 2] to be relative to t...
66ecf2d6f22b9d6c14f374ab8e4e6e1a2e4df342
39,492
def build_dataloaders(args, random_state=None): """ Build dataloaders according to experiment args Parameters ---------- args : argparse.Namespace Experiment arguments random_state : np.random.RandomState, optional (default: None) Optional random state for reproducibility in tra...
c0daea5e4dfb37bee7691ff1c58e61c0d2fd67d4
39,493
import re from datetime import datetime def calc_cutoff_date(keep): """given a retention period, calculates the date before which files should be deleted""" keep_match = re.fullmatch(keep_re, keep) if keep_match is None: raise RuntimeError("KEEP must be in the format <number>[dw]") keep_ran...
40a11c37d358dabdb7b4a6fe14d82e029bafc57b
39,494
def traveling_salesperson(pos_list, restarts=100000, beam_search=True, k=4, nstart=None, verbose=False, ): """ Finds an approximate solution to the travelin...
df3c2d00b5378bad872bfad962d817a8e6a8e54e
39,495
import numpy def extract_pq_flags(array, flags=None, invert=None, check_zero=False, combine=False, quiet=True): """ Extracts pixel quality flags from the pixel quality bit array. :param array: A NumPy 2D or 3D array containing the PQ bit array. If array is 3D, then co...
2f40f6c0730ca6d4edcac6c582f7d3f83111c0a4
39,496
def readPatterns(sequence): """Read in the patterns to be matched. """ seqs = {} seqfile = open(sequence) for line in seqfile: toks = line.strip().split() if len(toks) != 2: print "Number of tokens on line is not 2. Kill!!!", line sys.exit(1) seqs[toks...
097df7957cfc9b3642a12510bb485659b3b0627d
39,497
def construct_parameters(**kwargs): """Translates data to a format suitable for Zabbix API Args: **kwargs: Arguments passed to the module. Returns: A dictionary of arguments in a format that is understandable by Zabbix API. """ if kwargs['mappings'] is None: return dict( ...
56b3805f1ea7b524a79107dd3c7df333a8c9026d
39,498
def _extreact_qml_file_info(file): """Returns file object in QML-ready format""" return { "name": file["name"], "path": file["path"], "isFile": file["is_file"], "isDir": file["is_dir"], "level": file["level"] }
4d28a0c1e440023ca887a693a2aea5dbd71d336b
39,499