content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def Interp(theta, intervals): """ This just turns the 7 points into 90 points linearly spaced in joint space """ long_theta = [] parts = np.zeros((6,intervals-1)) for i in range(int(len(theta)-1)): delta = (theta[i+1]-theta[i])/intervals parts[i] = np.linspace(theta[i],the...
e0461aae4c0e3e70ab9e538b45792453003fd36d
65,300
import os import pickle def load_face_encodings(image_path, encodings_path): """Load face encodings from cache or from files.""" face_id = 0 # checking for cache if encodings_path in os.listdir(): print('load encodings from cache') with open(encodings_path, 'rb') as f: tm...
b08bb14c81576be8d312db99180eb793450121fe
65,301
def _makeScriptOrder(gpos): """ Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front. """ scripts = [] for scriptRecord in gpos.ScriptList.ScriptRecord: scripts.append(scriptRecord.ScriptTag) if "DFLT" in scripts: ...
6c67698c3d084c8e8f038e05a8d8e53811220a15
65,302
from typing import Union def tiny(url: str) -> Union[str, None]: """ :param url: url :return: short url :rtype: Union[str,None] """ try: return Shortener().tinyurl.short(url) except: raise tinyUrlError
16d34a0984a30fbcf2fa0a0239b8c9c01b247d55
65,303
import math def axisRotation(axis,angle): """Compute rotation matrix. From TDL. @param axis: The axis of rotation; must be unit length. @type axis: vec3, vec4, or list of at least three scalars @type angle: scalar @param angle: Angle, in radians @rtype: mat4 """ #axis=normalize(axis) ...
c8626374d428057d7279859f479065032b8f9b60
65,304
import importlib def get_metarig_module(metarig_name): """ Fetches a rig module by name, and returns it. """ name = "rigify.legacy.%s.%s" % (METARIG_DIR, metarig_name) submod = importlib.import_module(name, package=MODULE_NAME) importlib.reload(submod) return submod
79c16e2ab040286b4a4dda9cf0578bb04d41f7f9
65,305
import torch from typing import Tuple from typing import List def concat_enc_outs( input: torch.LongTensor, enc_out: torch.Tensor, mask: torch.BoolTensor, embedding_size: int, padding_idx: int, ) -> Tuple[torch.Tensor, torch.BoolTensor]: """ Concatenate Encoder Outputs. Does the whole...
6b1794966229a8f7658afcb70a5e91a652e6b1c5
65,306
import re def insert_tags(tags, session): """Inserts a list of tag dictionaries into the database Args: tags (list): A list of tags, where each tag is a dict with a 'tag' key and a 'tagged_card' key session (sqlalchemy session): a session with the database Returns: li...
f9f80a421f64540edaa2562d459a26b8b142a6d2
65,307
def task_zip_release() -> DoitTask: """Zip up important information in the releases directory. Returns: DoitTask: doit task """ return debug_task(_zip_release())
63df07052174893705cfffa8bcc2cdcc67760eae
65,308
import typing import os import tqdm def get_metadata_from_files_in_folder( folder_path: str, hash_flag: bool, relative_paths_from_ia_metadata: typing.Optional[typing.List[str]] = None, ) -> typing.Dict[str, str]: """Return dict of file paths and metadata of files at a directory (and its subdirectories...
af034c9e210b249133284cab8fb5094a84235545
65,309
def windowed_mean(a, w, mode='reflect', axis=0): """ Perform rolling window average (smoothing). Args: a: array w: window length mode: see jnp.pad axis: axis to smooth down Returns: Array the same size as `a` """ if w is None: return jnp.broadcast_to(jnp...
7d4fed029ba7f523b8b44361784aef4b857b4cee
65,310
import re def _reg_name_regex(): """Compile regular expression for RFC3986_ reg-name production _RFC3986: https://www.ietf.org/rfc/rfc3986 """ # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" unreserved = r"[A-Za-z0-9-._~]" # pct-encoded = "%" HEXDIG HEXDIG pct_encoded = r"%[0-9A-...
9af962094a9d52c49942f472506c37770da2156e
65,311
import requests def is_retryable_exception(exception: Exception) -> bool: """ Helper method to catch HTTP errors that are likely safe to retry. Args: exception: exception raised from ApiClientSession.api_request instance """ for ex in [requests.exceptions.ConnectionError, requests.exceptions.T...
97025db6c5a6bb74a8e3e70b89f5ebd49b9bba31
65,312
def _filter_codesign_output(codesign_output): """Filters the codesign output which can be extra verbose.""" filtered_lines = [] for line in codesign_output.split("\n"): if line and not _BENIGN_CODESIGN_OUTPUT_REGEX.search(line): filtered_lines.append(line) return "\n".join(filtered_lines)
9fd429c870a14401386a88dd35c99e12e5a3b395
65,313
def setup( epochs: int ) -> tuple: """ Setup for running neural network experiments :param epochs: int, number of epochs to run :return: tuple, inputs for function to run neural network """ ccfd_data = get_data() train_data, train_target, val_data, val_target, test_data, test_target...
11254e12ed1ef8497196b0536dc4db7748a81d2b
65,314
def api(tac): """TAC API endpoint.""" if len(tac) != 8: abort(400, 'Bad TAC format') try: int(tac) except ValueError: abort(400, 'Bad TAC format') with get_db_connection() as db_conn, db_conn.cursor() as cursor: cursor.execute('SELECT * FROM gsma_data WHERE tac = %s...
ec4a84e5e480948efbe0e892546e4ceca7d07712
65,315
def get_global_default_branding(branding_type): """ Args: branding_type (unicode) Returns: DefaultBranding """ return DefaultBranding.default_key(branding_type).get()
3d65a39130ad9ede30168fa137df47a13d1dcd89
65,316
import logging def _run_binomial_test(contingency_table, verbose): """Runs one-sided binomial test using contingency_table. The null hypothesis is that both models have the same error rate. The alternative hypothesis is that model 1 has a higher error rate. See: https://en.wikipedia.org/wiki/Sign_test Ar...
88bfa0ec5d3c9db07fc1e567adaaee78d817e3ff
65,317
def translate_address(PARAMETER): """ Translates address for use in HBN chain [PARAMETER] is required and can be any crypto address. """ d = urllib2.urlopen(blockexplorer('translate_address') + '/' + str(PARAMETER)) return d.read()
f32da642448781d6d8102cf423d8fa0b86738318
65,318
def _pressure_conditions(pressure: reaction_pb2.PressureConditions) -> str: """Generates a text description of pressure conditions. Args: pressure: PressureConditions message. Returns: String description of the pressure conditions. """ txt = "" if pressure.atmosphere.type != pr...
8dfce7a6b402f48ad5612fe736ca8260a3429739
65,319
def max_future_level(station, poly, shift, start, days): """This function returns the maximum relative level predicted for the next day by the best-fit polynomial curve.""" start = date2num(start) # Array of times from present moment to one day later x = np.linspace(start, start+days, 100) # Array of p...
05ddf0323ff3521d260b3496e86440dbbbe7b38d
65,320
def config_top_path_get(path): """Get entry in config top-level For anything not in the modules section. """ config = read_config() path = path.split("/") success, end_node = _traverse_module(config, path) if not success: return end_node ret = {"value": end_node} return js...
ec08e3c08e2344a41ba92ccbde374b9e62a925bf
65,321
import logging def prepare(): """ 应该只有修改需要prepare+commit, 所以在客户端层应该已经判定了是读还是写了. :return: """ data = request.json print(request.data) logging.debug(f"receive data: {data}") id = FileNoSQL().record_log(data["key"], data["value"]) if id > 0: return {"code": 0, "msg": "succeed ...
e40cb87506d172d7cc560d36ade5f727053891ba
65,322
def circuit_identity_phasepoly() -> Circuit: """Returns a 4-qubit circuit that is equal to the identity, provable by phase polynomial reductions.""" c = Circuit(4) c.add_gate("ParityPhase",Fraction(1,4),0,1,2,3) for i in range(4): c.add_gate("ZPhase",i, Fraction(3,4)) for j in range(i+1,...
a9ed41cdc8462af8efb797ecf1cfe7e96fc3c9c7
65,323
def build_U (base=None, min_rooms=0, rooms=2, rooms_wide=2, placement=None, outer=None, inner=None, room_height=None): """ Modifies the results of base_builder() to result in an U-shaped layout. :``base``: The base shape collection. If None, a new base will be built from base_builder. *Defau...
c88944b95bfe73680ec3dc8eed64d54e13e2c7e8
65,324
def kmp(main, pattern): """ kmp字符串匹配 :param main: :param pattern: :return: """ assert type(main) is str and type(pattern) is str n, m = len(main), len(pattern) if m == 0: return 0 if n <= m: return 0 if main == pattern else -1 # 求解next数组 next = get_next...
747379be5fcc52150a82c7ceb3d4343a0934169b
65,325
def make_sentiment_dashboard(topic): """ Make a sentiment analysis dashboard for a given topic. """ data = load_topic_comprehend(topic) sent_res = general_sentiment(data) gauge1 = make_sentiment_gauge( 'Positive Sentiment', sent_res['mean_pos_sent']) gauge2 = make_sentiment_gauge( ...
6acf7c3a77788d1e229744dfc7778ebe2c08b92d
65,326
import copy def GetPackageMap(target): """Compiles a package map for the given target from the constants. Uses a cache in target_version_map, that is dynamically filled in as needed, since here everything is static data and the structuring is for ease of configurability only. Args: target: The target ...
c37c47bf0832b878debe53a1afa4868507936490
65,327
def generate_launch_description(): """launch grasshopper camera node.""" flir_dir = get_package_share_directory('flir_spinnaker_ros2') config_dir = get_package_share_directory('flir_spinnaker_ros2') + '/config/' launch_arg = LaunchArg('camera_name', default_value='grasshopper', ...
78d0425b1c793ff4a7dbaa07a3ad00dc36f119a1
65,328
import pickle def deliver(conn, localobj): """delivers (recreates) a local object on the other party. the object is moved by *value*, so changes made to it will not reflect on the local object. returns a proxy to the remote object""" return conn.modules.cPickle.loads(pickle.dumps(localobj))
5587d08d9ed984a919bdd1fc51e0f3b1e69d5896
65,329
def calc_all_energies(n, k, params): """Calculate all the energies for the 2^n or 3^n states in model. Parameters ---------- n : int Number of spins. k : int Number of distinct states. params : ndarray (h,J) vector Returns ------- E : ndarray Ene...
d9279ce6b59a1148270b69be6c2fefc8c203cebf
65,330
def proximity(geoname_id): """ Get cities closest to the specified one. :param geoname_id: int - ID associated with a city :returns: Flask response """ extra_query_params = [key for key in flask.request.args if key not in {'k', 'countryCode'}] if extra_query_params...
81a4db6da43662421bf64c6666297a9927eacc95
65,331
def prepare_abe_connectivity_problem_response(): """ Generates a response to send to AVS indicating there was a problem talking to ABE. :return {dict}: a response to be sent back to AVS """ return prepare_response('There was a problem speaking to ABE. Please contact your Library Overlord.')
661277db7f20af7b625c0abf2b965702d280aa76
65,332
import io def create_taxon_distribution(taxonkey): """returns a distribution matrix for given taxon taxon by applying filters""" logger.info("working on taxon {}".format(taxonkey)) _filters = ( filters.polygon, filters.fao, filters.latitude, filters.depth, filters...
c0c9eb5d058f3166edee086687f38ed0511bd953
65,333
def obtener_cantidad_por_ciudades_mensualmente_y_anualmente(PaisOrigen, AnioInicio, AnioFin): """ Obtener cantidad de vuelos salientes totales en todas las ciudad de un pais durante un rango de años separando por meses Obtiene la cantidad de vuelos salientes en todas las ciudades de un pais durante un rango...
94b2f4d8c4ee39d7ba61b999880727ca28fc7bbd
65,334
import ctypes def device_array_from_ptr(ptr, nelem, dtype=np.float, finalizer=None): """ device_array_from_ptr(ptr, size, dtype=np.float, stream=0) Create a Numba device array from a ptr, size, and dtype. """ # Handle Datetime Column if dtype == np.datetime64: dtype = np.dtype("datetim...
069243086b6aa32218d1252dfba5fca4502ca4b0
65,335
import math def poids_attirance(p, dist): """ Calcule le poids d'attraction d'une neurone vers une ville. """ d = p[0] * p[0] + p[1] * p[1] d = math.sqrt(d) d = dist / (d + dist) return d
4a997566d19dc7e436a3a1704be7b5ac74424266
65,336
def computeSamplePvalue(distribution: list, statistic_value: float) -> float: """ Compute sample p-value given null distribution and statistic value """ N_equal_more_extreme = len( np.where(np.array(distribution) >= statistic_value)[0] ) N_total = len(distribution) return N_equal...
d25444b18cadfc766874829813afe3b45779777c
65,337
from typing import Union from typing import Tuple def compute_stats(tris: Union[Triangle64, Triangle32], mass: Real) -> Tuple[np.ndarray, float, float, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ Compute statistics on a shape...
640ecd625aa55fef475f1d16c54e196fff9e9a39
65,338
import math def check_path(flow, G, routing_policy=default_routing_policy, debug=False): """ Check the path of a given flow in the topology. Args: flow: The flow spec to check. G: The topology object. Returns: the AS-PATH length of the route. nan - no route in...
cff8c1bbf4a8b354ea09eb613640d640f90b7ef9
65,339
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the con...
94cf2bfb3b8fe9817628932544b00efe560ebfda
65,340
def save_route(route): """ Save route information into database. """ u_id = current_user.get_id() db.session.add(Route(u_id, route)) db.session.commit() flash('Your route has been saved.') return redirect('/')
9e05664e6204175e783fe492ab3362d98323ac1c
65,341
def dedup(records): """Remove any identical records from the list. Args: records (list(dict)): the list of dicts to be filtered. Returns: list(dict): the list of records with any duplicates removed. The list returned contains records in the same order as the original list. """ ...
f3aadddf1458a08d36331a74722e12057d8ab8f9
65,342
import inspect def is_functional_member(member): """ Check whether a class member from the __dict__ attribute is a method. This can be true in two ways: - It is literally a Python function - It is a method descriptor (wrapping a function) Args: member (object): An object in t...
268068600689a7935c9a8b26aa14ca09f9679228
65,343
def read_mask(img_gt_path): """" Thay đổi ảnh mask trong grayscale về 0, 1, 2(background/non-neoplastic/neoplastic). @param: img_gt_path(path to folder contains gt) @return: img_gt sau khi quy về mask 0, 1, 2 """ img_gt = cv2.imread(img_gt_path, 0) img_gt[img_gt < 10] = 0 img_gt[(img_gt...
d4ca70c4f4f9f90f2a5a89d625997f11f0b8c7fc
65,344
import time def algo_graph_iht( x_mat, y_tr, max_epochs, lr, x0, tol_algo, edges, costs, s, g=1, root=-1, gamma=0.1, proj_max_num_iter=50, verbose=0): """ Graph Iterative Hard Thresholding proposed in [4] and projection operator is proposed in [2]. :param x_mat: the design ma...
6e7f66a07b30d360c46217246b1cd598df158aae
65,345
def restore_reply(request, id): """Restore reply""" reply = get_object_or_404(Reply, pk=id) if reply.status == '6deleted' or reply.status == '5hidden': reply.status = '1normal' reply.save() else: return error_page(request) referer = get_referer(request) return redirect(r...
c8a26f26605ad8b6ca7731c6e12bddff91e47cb3
65,346
from datetime import datetime import math def format_unixtime_ms(unixtime): """ Format a unix timestamp in ms to a human readable string """ if unixtime: return str(datetime.datetime.fromtimestamp(math.floor(unixtime / 1000)).strftime("%x %X %Z")) else: return ""
e17aa14612686ca5156862352c424c1bdcb3a519
65,347
def convert_x1y1x2y2_to_XcYcWH(box): """ Convert box from dictionary of {"x1":,"y1":,"x2":,"y2"} to {"x_centre":,"y_centre":,"width":,"height":} Assumption 1: point 1 is the top left and point 2 is the bottom right hand corner """ assert box["x1"] <= box["x2"] assert box["y1"] <= box["y2...
e7da7353b64b969b4c51dc7ece06729b05bad31e
65,348
import numpy def _plot_panel(ax, ds, fieldName, scale, lower, upper, cmap, normType): """ Plot a single panel for a given model in a movie frame """ ax.set_adjustable('box') ds = ds.where(ds[fieldName].notnull(), drop=True) field = ds[fieldName].values x = 1e-3*ds['xGL'].values y = ...
d64d46358fb512d17f41b7315a3f1ca53d4ac820
65,349
def cms_cancel(request, context): """show menu""" if context.get('edit_mode'): url = context.get('coop_cms_cancel_url', None) if url: return make_link( url, _('Cancel'), 'times', classes=['alert_on_click', 'icon'] )
772f6e601fd4f361438861c1f56afdc269029f77
65,350
def convert_to_onehot( xs: ArrayLike, n_classes: int = 0, ) -> np.ndarray: """Convert an integer-valued ordinal array to one-hot representation. Also supports converting binary probabilities to categorical ones, via the mapping p -> [1-p, p]. If `n_classes == 0`, then it is inf...
0cd86216beca7ab3d1a4bd80e1184e34574c4a5f
65,351
def get_decoded_token(token, secret_key='aws-saas-factory'): """ Decodes token using PyJWT library :param token: :param secret_key='aws-saas-factory': """ return jwt.decode(jwt=token, key=secret_key, algorithm='HS256')
3ccbd0f27debfa213d17dd455e95d8609eecc234
65,352
def format_date_pretty(date_to_format: str) -> str: """ Format a date that is in the format YYYY-MM-DD into: 'Name_Of_Month Day, Year' :param date_to_format: The date to convert. :return: An easier to read format of the date_to_format. """ date_array = date_to_format.split("-") day = date_a...
02f8c872057b5b601b83dee9bf34f2174c03340e
65,353
def get_unbounded_params(params): """Retrieve unbounded version of model parameters used to fit concentration history. Parameters ---------- params : sequence Values of the model parameters. Values should respect the parameter bounds. Returns ------- u_params : sequence Val...
f39f4d1edeac8745962472c302cb1d25ed9bb267
65,354
def read_dictionary(): """ This function reads file "dictionary.txt" stored in FILE and appends words in each line into a Python list """ lst = [] with open(FILE, 'r') as f: for word in f: lst.append(word.strip()) return lst
99a71ba31de68686348e06f4c6f1e34cb9785861
65,355
import json def get_word_vec_top_sentences(block_vec,wiki_fpath,num_output=10): """ Takes in a sentence and returns the most similar sentences within the wikipedia corpus. args: block_vec (np.array): shape(300,), average word embeddings for a block of text wiki_fpath (str): path to the wikiped...
b83c1c05a56c1d55968e25562bed6237c6455b4b
65,356
def resnet_v2(input_shape, depth, num_classes=10): """ResNet Version 2 Model builder [b] Stacks of (1 x 1)-(3 x 3)-(1 x 1) BN-ReLU-Conv2D or also known as bottleneck layer First shortcut connection per layer is 1 x 1 Conv2D. Second and onwards shortcut connection is identity. At the beginning of...
370146c54b5c11f59a7a2519fad036180103b953
65,357
from typing import Union def get_quantize_parent_for_dequantize_node( quantized_model: ModelProto, dequantize_node: NodeProto ) -> Union[NodeProto, None]: """ Returns the first quantize node found by traversing the first node input of the given de-quantize node's ancestors. All inputs to de-quantize n...
90589484e31db357fe416216f98dd3c6200fd3b4
65,358
import six def colormap_to_rgba(colormap): """ Convert color ma to rgba colors. """ if 'continuous' in colormap: return {k: hex_to_rgba(v) if isinstance(v, (six.string_types, int)) and k in ['from', 'to', 'over'] else v for k, v in colormap.items()} else: return {k: hex_to_rgba(v) ...
5d54173f4b93876c7050377218206343e688fd03
65,359
def align(a, b, d=-5, s=lambda x,y: x==y, key=lambda x: x, gap=None): """Find the globally optimal alignment between the two sequences a and b using gap penalty d and similarity function s, and return the aligned sequences. The similarity function is applied to the result of key(x) and key(y) for each x...
f02b37fedfe8aefec215bbce98902efc59318ff6
65,360
import importlib def find_dataset_using_name(dataset_mode): """ Get the dataset of certain mode """ dataset_filename = "datasets." + dataset_mode + "_dataset" datasetlib = importlib.import_module(dataset_filename) # Instantiate the dataset class dataset = None # Change the name format...
665f0a7510f60f6b1455b778dca0969393e3e47f
65,361
import argparse def update_namespace(args, dictionary, overwrite=True, rest=False): """update Namespace with given dictionary Args: args (Namespace): Namespace to be updated dictionary (dict): dictionary overwrite (bool, optional): If True, All Namespace value will overwritten by dict...
e75e933b2e174353c2db8ce595fa07232f2e5c1d
65,362
def ParseOneFile(f, iwyu_record): """Given a file object, read and classify the lines of the file. For each file that iwyu_output mentions, we return a list of LineInfo objects, which is a parsed version of each line, including not only its content but its 'type', its 'key', etc. Arguments: f: an iterab...
2bf1a17d846be95fd595f68bc4dccec181c07c20
65,363
def get_warcraft_logs_url(zone_id, character_name, wcl_token, realm): """ Returns the warcraft logs url for the player with the given character name and the given zone id. Returns None if warcraft logs could not be found for the given character. """ parse_url = f'https://classic.warcraftlogs....
84a0ea83f2f77f630573a9a851ab382a3a5c2ee2
65,364
def svn_repos_verify_fs3(*args): """svn_repos_verify_fs3(svn_repos_t * repos, svn_revnum_t start_rev, svn_revnum_t end_rev, svn_boolean_t check_normalization, svn_boolean_t metadata_only, svn_repos_notify_func_t notify_func, void * notify_baton, svn_repos_verify_callback_t verify_callback, void * verify_baton, svn_...
e4022ac5bb22c3918e9f603842d457d79ba9c321
65,365
def sigma(find="sigma", printEqs=True, **kwargs): """ Stress Where: sigma = stress P = load A0 = original cross-sectional area """ eq = list() eq.append("Eq(sigma, P / A)") return solveEqs(eq, find=find, printEq=printEqs, **kwargs)
67ff64a1692dee0f6b2d6f21a3cae4734ebeae2a
65,366
def check_authentication(func): """ 检测是否登录成功过,不成功则跳转到登录页面 :param flask_app: :return: """ def __check_authentication(*args, **kwargs): if "ok" in session and session["ok"]: return func(*args, **kwargs) else: return jsonify(status=403, message="未能授权成功", d...
ba659418c6261e2a4c7a998e58cf94abced59a88
65,367
def polynomial_3_integral_from_zero(x, a, b, c, d): """Integral of polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3. Integral(f(x)) 0 -> x = a * x + b * x**2 / 2 + c * x**3 / 3 + d * x**4 / 4 """ return x * (a + x * (b / 2.0 + x * (c / 3.0 + x * d / 4.0)))
50e7d899e2f509bef0d15cef4fffca6d4af44934
65,368
def get_event_signature_with_args(hex_signature, args): """ Requests the event signature from the CSV file based on the hex_signature including ongoing names for the parameters Args: hex_signature: the 32-byte signature of the event as hex value args: the names of the parameters of the even...
7cc8f3cc8742ef364aab5aac573980a38fdfd48f
65,369
import logging def convert_label_map_to_categories(label_map, max_num_classes, use_display_name=True): """Loads label map proto and returns categories list compatible with eval. This function loads a label map and returns a list of dicts, ea...
3dd504f90e129986378a6a7e4130953e89c50bd1
65,370
def RPL_ENDOFUSERS(sender, receipient, message): """ Reply Code 394 """ return "<" + sender + ">: " + message
3591d9bf24060ae3baf443824a5bd16ecf1309be
65,371
def pancake(N=500, band=0, seed=42): """ Sample of the :func:`pancake_field <skgstat.data.pancake_field>`. By default, the Red band is sampled at 500 random location without replacement. Parameters ---------- N : int Number of sample points to use. band : int can be 0 (R...
618a819f02d55cb146a3273a2c14ddd52715825a
65,372
def get_dataset_url(hit): """Select dataset url.""" ret_url = None for url in hit["_source"].get("urls", []): if url.startswith("http"): ret_url = url if url.startswith("http") and "amazonaws.com" in url: ret_url = url if url.startswith("http") and "googleapi...
1d78757dda61d762008a78e4b9463c7248978f56
65,373
def test_dag(): """Creates a test DAG with a few operators to test on.""" def f(task_id): return f"OP:{task_id}" with DAG(dag_id="test_xcom_dag", default_args=DEFAULT_ARGS) as dag: operators = [PythonOperator(python_callable=f, task_id="test_op_%i" % i) for i in range(4)] return da...
9acd944fd57a13baa525141d768c8740237a1f04
65,374
def flip(x: tf.Tensor) -> tf.Tensor: """Flip augmentation Args: x: Image to flip Returns: Augmented image """ x = tf.image.random_flip_left_right(x) x = tf.image.random_flip_up_down(x) return x
949defcc6a76866273aaebc4e9da108996efb72f
65,375
def n_dyts_by_count(cnt, dytmat): """ Used to "triangle" dytmats, return the dyt_i for the last of a given count. """ # Concat an extra False on to this list because argmin of a uniform # array has the annoying property of returning -1. # argmin([True, True, True]) == -1 but I want it to return ...
f19816a2261bbee9590beeb3722c018b7e46fc5b
65,376
def peak_slicer(peaks_dirs, peaks_values=None, mask=None, affine=None, colors=(1, 0, 0), opacity=1, linewidth=1, lod=False, lod_points=10 ** 4, lod_points_size=3): """ Visualize peak directions as given from ``peaks_from_model`` Parameters ---------- peaks_dirs : ndarray...
84b1ea9de050ebfc4d45f088ecd698e94a5fb6ea
65,377
from typing import Optional import os def get_data_loader(data_config: dict, mode: str) -> Optional[DataLoader]: """ Return the corresponding data loader. Can't be placed in the same file of loader interfaces as it causes import cycle. :param data_config: a dictionary containing configuration for data...
3c208880e9e370823c79987e9b0663cef37670b4
65,378
from typing import List def create_path_from_se2(states: List[StateSE2]) -> InterpolatedPath: """ Constructs an InterpolatedPath from a list of StateSE2. :param states: Waypoints to construct an InterpolatedPath. :return: InterpolatedPath. """ progress_list = calculate_progress(states) # ...
7368e3a35a9443c64a44d8079c19cdeb1ce45e85
65,379
def col(name=None, dtype=None): """Return a symbolic column variable (ndim=2, broadcastable=[False,True]). Parameters ---------- dtype : numeric None means to use aesara.config.floatX. name A name to attach to this variable. """ if dtype is None: dtype = config.floa...
0b16ba2e2766fc0039c83b2ba52b3ec1b4e8dfd3
65,380
def _needed_for_ringsdb(card): """ Check whether a card is needed for RingsDB or not. """ card_type = ('Treasure' if card.get(CARD_SPHERE) == 'Boon' else card.get(CARD_TYPE)) return (card_type in CARD_TYPES_PLAYER and card.get(CARD_ADVENTURE) != 'Promo')
7a0efa91d97d85730a2c94c7332684c3c0320337
65,381
def AMOC_max(AMOC): """ AMOC maximum at 26 deg N, 1000 m """ lats = approx_lats('ocn') tdepths = create_tdepth('ocn') j26 = find_array_idx(lats, 26) # 1451 z1000 = find_array_idx(tdepths, 1000) # 21 return AMOC.isel({'z_t':z1000, 'nlat':j26})
913df758a6ed03a9e6065ee484f8fbf9782f26fe
65,382
import random def list_all_derivations(): """ >>> list_all_derivations() """ trace_id = str(random.randint(1000000, 9999999)) logger.info("[trace page start " + trace_id + "]") dat = clib.read_db(path_to_db) if request.method == "POST": logger.debug("request.form = %s", request.fo...
08fb34f7375aa2b0c861e93e50bfc3542732d6e6
65,383
import os def get_script_module(script_name): """Load a script module.""" return read_json(os.path.join(file_location, script_name))
4897503d9cd35d8be1ed9a3682f8c4482971bff1
65,384
import tqdm import torch import os import pickle def encode_corpus(corpus, seq_len, min_token_len=1, max_sections_per_email=3, save_new_corpus=True, file_path=None): """ Tokenizes, filters and converts text corpus into sequences of token indices. Generates input and output tensors. :para...
2978b7d0ab3c64e82413291a65901738c904beb5
65,385
def all_true_like(arr: pa.Array) -> pa.Array: """Return a boolean array with all-True with the same size as the input and the same valid bitmap.""" valid_buffer = arr.buffers()[0] if valid_buffer: valid_buffer = valid_buffer.slice(arr.offset // 8) output_offset = arr.offset % 8 output_lengt...
d7f6b94e5e7e244377f1389d938c4daa06edecd9
65,386
def phrase_prob(lang1p, lang2p, transfrom=2, transto=1, db="sqlite:///:memory:", init_val=1.0e-10): """ """ engine = create_engine(db) Session = sessionmaker(bind=engine) session = Session() # search query = session.query(TransP...
bf2dc8cb62395890fcfa84d77c379bccff1f60d4
65,387
from typing import Optional from typing import Union from typing import List from typing import Dict from pathlib import Path def NekoTrainer( logger: Optional[str], checkpoint_callback: Union[bool, Callback] = True, callbacks: Optional[Union[List[Callback], Callback]] = None, default_root_dir: Option...
d066f42d9e23c8b33050caba692642c383a84a30
65,388
import scipy def doLogLikelihoodTest( complex_ll, complex_np, simple_ll, simple_np, significance_threshold = 0.05): """perform log-likelihood test between model1 and model2. """ assert complex_ll >= simple_ll, "log likelihood of complex model smaller than...
0d5858de204366e19c41704a83a37c2c9b04a45c
65,389
def get_num_from_user(str_info, lower, upper): """Ask and returns a integer inputted by the user from a set range. :param str_info: Text shown to the user :param lower: Inferior range limit :param upper: Superior range limit :return: Integer from the user """ flag_finish = False aux_inp...
cd5d30f4dfa3b340c92580e8d40fe9eca62efc1d
65,390
def _import_resource(fixture_name, editor_group=None): """ Imports the XML resource description with the given file name. The new resource is published and returned. """ result = test_utils.import_xml('{0}/repository/fixtures/{1}' .format(ROOT_PATH, fixture_n...
2640f38337e3cfd17e55f8b8c471577719188824
65,391
def edit_distance(s1: str, s2: str) -> int: """The minimum number of edits required to make s1 equal to s2. This is also known as the Levenshtein distance. An edit is the addition, deletion, or replacement of a character. """ if not s1: return len(s2) if not s2: return len(s1) M = [[0 for _ in...
bd433f8b52dd9826032ced7ece0fb7df8b5ad8cc
65,392
def parse_seed(secret): """Your Stream secret is a seed from which the true private key can be derived. The ``Seed.parse_json()`` method of stm-lib supports different ways of specifying the seed, including a 32-byte hex value. We just support the regular base-encoded secret format given to you by t...
d91b182f4db7ee2399cd15e1297a13385d489489
65,393
import requests def suggest_username(query: str) -> list: """ Function suggest the username for the Instagram Accounts by Instagram """ with requests.session() as s: response = s.get(home_url) token = response.cookies["csrftoken"] headers["x-csrftoken"] = token dat...
194339ade1afcc65999d9242ac8a0264cc0c062c
65,394
def removeTags(text): """ """ # {} wrapper generates a set instead of list to deal with repeated tags tags = {tag.strip('#') for tag in text.split() if tag.startswith("#")} text = text.replace('#', '') return (text, tags)
30e267e22da210d48b3271a2e57562b6bff92820
65,395
import os import tqdm def download_file(url, local_filename): """ Simple wrapper around urlretrieve that uses tqdm to display a progress bar of download progress """ local_filename = os.path.abspath(local_filename) path = os.path.dirname(local_filename) if not os.path.isdir(path): os.maked...
7d68fefe6ad21dc242c10afb363688bb51646c8a
65,396
import os def commit_for_dir(dir): """Returns a tuple of commit and workspace status. Raises NoCommit if a commit is not available. """ dir = os.path.abspath(dir) for scheme in SCHEMES: commit = _apply_scheme( dir, scheme.commit_cmd, scheme.commit_patte...
43fd514a756d9e0f168a54bdfe94a24cc1e052ad
65,397
def _remap_cortex_out(cortex_out, region, out_file): """Remap coordinates in local cortex variant calls to the original global region. """ def _remap_vcf_line(line, contig, start): parts = line.split("\t") if parts[0] == "" or parts[1] == "": return None parts[0] = contig...
03357f276c6733508f17197a3300f1d55271e486
65,398
def to_base(base: t.Literal[2, 8, 16], number: int) -> str: """Convert any passed integer into given base as string.""" if base == 2: return bin(number).replace("0b", "") elif base == 8: return oct(number).replace("0o", "") elif base == 16: return hex(number).replace("0x", "")
478a1fdda832601c5f17aecdd1f4e716bf50d793
65,399