content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional def get_uuid_for_error(**kwargs) -> Optional[str]: """ Return the uuid for the derived dataset if it exists, and of the parent dataset otherwise. """ rslt = get_dataset_uuid(**kwargs) if rslt is None: rslt = get_parent_dataset_uuid(**kwargs) return rslt
f3c6e4ec5f3189ef01fe9a8f9b5eac87b2e181b9
57,680
def mention_list_by_sentence_with_anaphora(a_obj, prev_obj, server): """ returns a list of lists of mentions, where the nth index of the list corresponds to the nth sentence in obj: [['Andrea', 'Dan'], ['Shane'], []] this includes mentions via anaphora. a_obj is the speechact to retrieve menti...
3f7090bc0769b9bc2c1c8bfe2c7e08c88077fca7
57,681
def collect_table_keys(data, exclude): """ Resolve used fields per table """ table_keys = {} for rule in data: t = rule[OF_RECORD_ITEM.table] for k in rule.keys(): if k not in exclude: keys = table_keys.setdefault(t, set()) keys.add(k) ...
acb6b9548734c15ead2e9f08e430da68cd0577d5
57,683
def cross_product_matrices(vectors): """Return corresponding cross product matrices for an array of vectors """ length = vectors.shape[0] result = np.tensordot(np.cross(vectors, unit_vectors(length, 3, 0)), np.array([1., 0., 0.]), axes=0) \ + np.tensordot(np.cross(vectors, unit_vectors(len...
d12b5dca424bc56809c0e85adf20c71e453be4fc
57,684
def format_docstring(usage: str, arg_list, kwarg_dict): """ Use argument lists to create Python docstring """ usage = usage.strip().strip("\"") docstring = f'{usage}\n\n' for arg in arg_list: if not arg['input']: continue docstring += f"\t:param {arg['name']} {arg['t...
a68c0d03aaf851ffb039b722affbdc60f7d05c1c
57,685
from pathlib import Path import shutil def temp_article_dir(temp_cwd: Path) -> Path: """Run the test from a temporary directory containing the "tests/data/article" dataset. """ article_source_dir = Path(__file__).parent / "data" / "article" for source_path in article_source_dir.iterdir(): ...
643b2c7f1183f19f263eaba0f3e930ac18fa6988
57,686
def load_states(): """Loads the shapefile for states in the United States. Returns -------- data : DataFrame DataFrame containing the shapefile for the United States. """ module_path = dirname(__file__) df = gpd.read_file(join(module_path, 'cb_2018_us_state_500k/cb_2018_us_state_500...
9f9fadb50781cfa3f783c07a3d9ea16bb3227203
57,687
def clamp_and_scale(img, bands, p, AOI): """ clip the upper range of an image based on percentile This function is similar to ee.Image().clip() and ee.Image().unitScale(), but operates on multiple bands with potentially different upper limits. Parameters: img (ee.Image): the image to modify bands (...
76081111644d4baa3ada4c93037d90ec21af1889
57,688
from typing import Union from typing import List import select from operator import and_ def get_resources_for(guild_id: int, resource_type="role", session=db.open_session()) -> Union[List[db.Settings], None]: """ Searches db for resource in a guild that matches the setting name :param guild_id: id of th...
af146ec17f71cd1c2cdefbb3beaad196ace80512
57,689
def rayleigh_k(x,k): """Rayleigh distribution parameterized by Fisher k parameter. """ return k*x * np.exp(-k*x**2/(2))
2dc84228eadb3dc1dc7d946335f02b4254530eda
57,690
def _packaging_type(f): """Returns the packaging type used by the file f.""" if f.basename.endswith(".aar"): return "aar" elif f.basename.endswith(".apk"): return "apk" elif f.basename.endswith(".jar"): return "jar" fail("Artifact has unknown packaging type: %s" % f.short_pat...
2b8cee53091672bb317ecdf29b869b8b8eb73f3f
57,691
def get_validator_keys(epoch, endpoint=_default_endpoint, timeout=_default_timeout) -> list: """ Get validator BLS keys in the committee for a particular epoch Parameters ---------- epoch: :obj:`int` epoch number endpoint: :obj:`str`, optional Endpoint to send request to tim...
d3f579c75f5cc394c106eefc876dc78074ba798f
57,692
from typing import Any import time import json def read_json_with_timeout(path: str) -> Any: """Repeatedly tries to read a json object from the given path, waiting until there is a trailing new line indicating that the write is complete Args: path (str): The path to read from Raises: ...
60f61da6e54fdba72f3a5f7300bcd6afd899b866
57,693
def create_model(model_name, pretrained=False, checkpoint_path=None, **kwargs): """Create a model Almost entirely taken from timm https://github.com/rwightman/pytorch-image-models Args: model_name (str): name of model to instantiate pretrained (bool): load pretrained ImageNet-1k weights if...
4f3fc75346ad3657891f1460e88bcc45d575ba01
57,694
from datetime import datetime def next_weekday(d, weekday): """ (datetime, string) -> datetime returns the first ocurrence of the given weekday after the initial datetime d """ days_ahead = weekday - d.weekday() if days_ahead <= 0: days_ahead += 7 return d + datetime.timedelta(days...
456e93f9332bc208e35080c05fcce8c31c329dd1
57,695
def get_compatibility_matrix(g: nx.Graph, attr_name: str): """ From Danai's heterophily paper :param g: :param attr_name: :return: """ values = set(nx.get_node_attributes(g, attr_name).values()) mapping = {val: i for i, val in enumerate(values)} print(mapping) C = nx.attribute_mi...
3f8a144278495191ffc861f1c431545255edc93f
57,696
def async_api(): """ 获取异步任务列表 get req: pass """ # q = {filters:[{}], order_by, single, limit, offset, group_by} query = Async.query.t_query pagin = gen_query(request.args.get('q', None), query, Async, db=db, per_page=settings.PER_PAGE, get_objects=True) objects = [] for o in...
1955bc0c3d27839a4d575779cede5807be110536
57,697
from operator import ne def project(fld_a, fld_b): """ project a along b (a dot b / magnitude(b)) """ # ax, ay, az = fld_a.component_views() # pylint: disable=W0612 # bx, by, bz = fld_b.component_views() # pylint: disable=W0612 # prod = ne.evaluate("(ax * bx) + (ay * by) + (az * bz)") # mag = ne...
5e6f0841896365ef41c180ec0239194e5bf4d632
57,699
def quote_dict(dct, tab): """ Recursively quotes dict values :param dct: :return: """ t = '\t' * tab # The middle arg here is a newline if value is another dict, otherwise it's a space dct_sring = '\n{0}'.format(t).join( [ '%s:%s%s' % ( camelize(k...
bef0627e4fae06ad8cce395c695e72b42da01eb7
57,700
import types def fit_state_preparation(create_u_func: types.FunctionType, vdagger: qiskit.QuantumCircuit, thetas: np.ndarray, num_steps: int, loss_func: types.FunctionType, optimizer: type...
ec02609b2f6bd7eb20b61a22114399efac5d1873
57,701
def get_provider_driver(provider=None, region=None): """ Gets the specified libcloud driver :param provider: Name of the driver :rtype: `libcloud.compute.base.NodeDriver` """ provider_driver = config.AVAILABLE_CLOUD_REGIONS.get(provider, {}).get(region, None) if not provider_driver: ...
d6260a86faa4c4f8d109418b5c95fb88bf2c27d6
57,702
def load_x_data_for_cnn(patient_name, keep_prob, input_x, sent_length, category_index, dropout_keep_prob): """Multiprocessing to fast speed""" pool = Pool(processes=HP.read_data_thread_num) generate_token_embedding_results = pool.map(generate_token_embedding, patient_name) pool.close() pool.join() ...
9c00d03f040851d39aad2c38db06e5aa3e1d6194
57,704
def reshape(a, newshape, order='C'): """ Gives a new shape to a tensor without changing its data. Parameters ---------- a : array_like Tensor to be reshaped. newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then t...
cbbb2c187a83afb8c1c5eea4c32dfbdd9ca59831
57,705
def generate_RIP_behavior_graph(records): """ :param records:list of tuples (process, RIP, API_called) :return: the graphs of API_calls of all subprocesses """ # Each subprocess is associated to one graph # LIC stands for Last I Checked forest_and_LIC = {} # forest_and_LIC = {subprocess : ...
1bf4a63cd8ab7d0b3d6e03b08cc4989b20c24aae
57,706
def render_mako_tostring_context(request, template_name, dictionary={}): """ Render mako tostring with RequestContext """ context_instance = get_context_processors_content(request) return render_mako_tostring(template_name, dictionary=dictionary, context_instance=context_instance)
0cad38e5e4c041014ff0675c607968af11beb3bf
57,707
def test_pointer_indexing(pointer_value, type_p): """ >>> a = np.array([1, 2, 3, 4], dtype=np.float32) >>> test_pointer_indexing(a.ctypes.data, float32.pointer()) (1.0, 2.0, 3.0, 4.0) >>> a = np.array([1, 2, 3, 4], dtype=np.int64) >>> test_pointer_indexing(a.ctypes.data, int64.pointer()) (1...
21f87a5ec840e3fd789c9e1ca9382d96f451e1e5
57,708
def _update_centroids(current_centroids, current_weights, new_cluster_sums, new_weights): """Computes a weighted combination of previous and new centroids. Args: current_centroids: A tensor whose rows represent the current centroids. current_weights: A tensor of integer weights associ...
09975fd6cd1bacdc51f50e910e3a5a6e6b83d07d
57,709
def bound_precision(y_actual: pd.Series, y_predicted: pd.Series, n_to_check=5): """ Accepts two pandas series, and an integer n_to_check Series are: + actual values + predicted values Sorts each series by value from high to low, and cuts off each series at n_to_check Determines how many hits...
15f78aa2d1ec4d54b1cef88632782f8dff40dc4e
57,710
import copy def reduce_parallelism(typ, roles, values,calc_set): """ calculation_set_yambo ={'resources': {"num_machines": 8,"num_mpiprocs_per_machine": 32}, 'max_wallclock_seconds': 200, 'max_memory_kb': 1*92*1000000 , 'custom_scheduler_commands': u"#PBS -A XXXX" , ' environme...
1b8893cdb0d1e949b8013ffd20fb3a5a8b893bd9
57,711
import re def clean_empty_sentences(df): """ Substitutes all the empty sentences with a customized sequence of characters """ return pd.DataFrame({ "sentence": df.sentence.apply(lambda x: re.sub("^ *$", "-", x)), "label": df.label })
a9f6d5a331e76ffacd324cc0b77170095e5a8f6e
57,712
def GetViewableStarredProjects( cnxn, services, viewed_user_id, effective_ids, logged_in_user): """Returns a list of viewable starred projects.""" starred_project_ids = services.project_star.LookupStarredItemIDs( cnxn, viewed_user_id) projects = list( services.project.GetProjects(cnxn, starred_pro...
2b0ddc93d27131a0d91833f470b03f2cdd7658f3
57,713
from .units_utils import convert_units def convert_g_per_liter_resin_to_cv(unitted_data, **kwargs): """ To convert to volume in CV, divide by the product concentration in g/L. """ if "concentration" not in kwargs: msg = "Trying to convert a volume in 'g per liter of resin' " \ "requ...
004cd3cf4769f6a982c6853a3367f04470f4c8c0
57,714
from typing import Union from typing import List from typing import Tuple def minimum_distances( left_arr: Union[np.ndarray, List], right_arr: Union[np.ndarray, List], return_indices: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: """ Finds the minimum distance betw...
e90ad3cd5989a6740cc087d1f813f8b1cbf660a7
57,715
import torch def manhattan_loss(X, mu_tilde): """ Computes the Manhattan loss. Arguments: X: array-like, shape=(batch_size, n_features) Input batch matrix. mu_tilde: array-like, shape=(batch_size, n_features) Matrix in which each row represents the assigned mean vec...
6a913bfdeb558b67684b66e1e1f067a198202474
57,716
import json import traceback def json_data_wrapper(method): """ Load JSON data from HTTP request bodies if possible """ if request.data: try: values = json.loads(request.data) if values: values.update(request.values.items()) request.values = values except: traceback.print_exc() pass retu...
f2253e40196c0310699fbbe2f11f0c200f5b42cd
57,717
import functools def forest_enabled(func): """ Decorator for validating that Forest is enabled for this study. """ @functools.wraps(func) def wrapped(*args, **kwargs): try: study = Study.objects.get(id=kwargs.get("study_id", None)) except Study.DoesNotExist: ...
0656ef67a0fd7bf4c927dae0a4199e15bc5a91e9
57,718
def test_run_command(): """ . """ # pylint: disable=too-few-public-methods,no-self-use class FakeSession: """ Fake session """ command = None def exec_command(self, command): """ . """ self.command = command ...
dd85e9cb3250c381ff7ff27c8ef64d714a50b561
57,719
def find_by_id(object_id, items): """ Find an object given its ID from a list of items """ for item in items: if object_id == item["id"]: return item raise Exception(f"Item with {object_id} not found")
822bf82ea68bd94d0bb1ed2dd5db754aee9b0cba
57,720
def spectral_analyze(dataset, timeindex = 0, bands = ['red', 'green','blue'], dims = ['x','y'], height = 500, width = 500, clims = None, norm = 'eq_hist', cmap=['black', 'white'], nodata = 1): """Interactivly visualize the spectral profile of single pixels in a multi-band xarray dataset Description -----...
0c1e6cf36cf8d9d4a42dc6b2dd2b92c2c22480e8
57,721
def common_modulus_attack(modulus, exp1, exp2, msg1, msg2): """ Perform RSA Common Modulus Attack, given the modulus, two exponents and two ciphertexts as integers. Returns the plaintext as an integer. """ g, s, t = gmpy2.gcdext(exp1, exp2) if g != 1: print("Error: GCD of the two exp...
1a4a20cc70f3f6bd1fa4c7ed8cf65ee31184b406
57,722
def big_h(u: np.array, v: np.array) -> np.array: """ The big h-function according to 139 of the specs. Args: u: v: Returns: np.array """ left = (u + v + np.exp(-u - v)) / 2 diff = np.abs(u - v) right = (diff + np.exp(-diff)) / 2 return left - right
6f6873d3c9e4e229a9b38910f529da01ad57cb15
57,723
import json def _get_results_table(df: pd.DataFrame, json_file: str = PATHWAY_NAMES): """Generate generic results table.""" with open(json_file) as f: pathway_id_name_dict = json.load(f) if 'pathway_id' in df: df['Pathway'] = df.pathway_id.map(pathway_id_name_dict) df['Database'] ...
a92baf686400e64fbad9ebcb253ea297fc373e50
57,724
def _getApplicationConfigObject(applicationname, createifneeded = True): """Return the application config object for the named application. Throws exception if the application is not found. Returns None if createifneeded is False and there isn't one yet.""" # Get the application deployment object for th...
aa2b9573913b9ed35ea7f74be02e3c6ef6961689
57,725
def getPixmap(page, matrix=None, colorspace=csRGB, clip=None, alpha=False, annots=True): """Create pixmap of page. Args: matrix: Matrix for transformation (default: Identity). colorspace: (str/Colorspace) cmyk, rgb, gray - case ignored, default csRGB. clip: (irect-like) restrict renderi...
0968ebb22349a40d67892a805a6277bafd36288f
57,726
def get_atom_int(atmstr: str) -> int: """ Get atom number from atom label """ atom = atmstr.strip().lower() atom = ATOM_LIST.index(atom) + 1 return atom
a3401776e543153599613101b47fe576bf11b612
57,727
import requests import json def create_snippet(data, baseurl, timeout, raw): """ Creates snippet with the given data on the haste server specified by the baseurl and returns URL of the created snippet. """ try: url = baseurl + "/documents" response = requests.post(url, data.encode(...
eb34861909b61749ef2f29da16450a82dcc8d83e
57,728
import json def timeline(): """Fake endpoint.""" with open('{}/examples/timeline3.json'.format(cwd), 'r') as timelinejson: return jsonify(json.load(timelinejson)) return jsonify({})
5b42c906be66c0bc602e6de86646999b35c41470
57,729
import numpy def apply_cnn_soundings_only( model_object, sounding_matrix, num_examples_per_batch=100, verbose=False, return_features=False, feature_layer_name=None): """Applies CNN to soundings only. :param model_object: See doc for `apply_2d_or_3d_cnn`. :param sounding_matrix: numpy arra...
7e0b0dcce45457ea7e0fe6b420d046406ffe1c69
57,730
import torch def fuse_epic_sliding_windows(maps_dict): """ Since different sliding windows have overlap, we desigin this function to fuse sliding windows. Args: maps_dict (dict): { "start_map": (tensor) "end_map": (tensor) "verb_map": (te...
205ac18633fcfddd9ba9af6f7b82d89345bf96c3
57,731
def get_or_create_permission(codename, name=camel_or_snake_to_title): """ Get a Permission object from a permission name. @:param codename: permission code name @:param name: human-readable permissions name (str) or callable that takes codename as argument and returns str """ u...
6c6105f1d82a0b889e15623f6391e9227e540b01
57,732
import re import copy def get_params(group, content): """ check content validity in {% %} and return params list token : eval(string) used to generate params.json orgin: local variable name to be tuned """ token_list, origin_list = list(), list() pattern = INIT + SCOPE + TAIL param_lis...
c154ea153291496f2181dbb1f5eefdbc33f19cfb
57,733
def server_interaction(client, hostname): """The server interaction function.""" prompt = 'fots@fotsies-ubuntu-testlab:~\$ ' # Start a client interaction using the paramiko-expect class interact = paramikoe.SSHClientInteraction(client, timeout=10, display=F...
7c69b3a1ebd76d4c82205609d2e2fdbb2046627b
57,736
import glob import fcntl import errno import time import csv def write_monitoring_ts(start_time, np_t, values, quantiles, datatype, fname, rewrite=False): """ writes time series of data Parameters ---------- start_time : datetime object or array of date time objects ...
693a3d4de4ff718c3b4e744f0e69eba3e7d8e896
57,737
def compile_deposit_script(payer_pubkey, payee_pubkey, spend_secret_hash, expire_time): """ Compile deposit transaction pay ot script. Args: payer_pubkey (str): Hex encoded public key in sec format. payee_pubkey (str): Hex encoded public key in sec format. spe...
4aeb66857f4e848620e3fd00bf91ef59f32762d1
57,738
def get_error_rate(predictions): """ Returns the erro 0-1 classification prediction Parameters ---------- predictions: pd df with columns 'pred_prob' and 'y' """ cutoff = 0.5 # get list of predicted probs and citaiton indicators y_act = predictions['is_edge'].tolist() y_pred = ...
a126436ed29a69b1cd9726f76024a11701e9d23b
57,739
import tokenize def build_model(): """Build a machine learning pipeline Args: None Returns: cv: gridsearchcv object. Gridsearchcv object that transforms the data, creates the model object and finds the optimal model parameters. """ pipeline = Pipeline([ ('vect', C...
3839bfea30f55bc812cce8d3a0b22915d9e339cd
57,740
from typing import Sequence def nan_calc_percentiles( arr: np.ndarray, percentiles: Sequence[float] = None, axis=-1, alpha=1.0, beta=1.0, copy=True, ) -> np.ndarray: """Convert the percentiles to quantiles and compute them using _nan_quantile.""" if percentiles is None: percent...
99db92753d33b87c88aac2beebda7fcb370615a4
57,741
def gaussian_tensor(x, axes, m, s, a, normalize=True): """Generally a 3-tensor where the axes represent the following: axis 1 is the x-axis grid, axis 2 is the number of total functions (i.e. training data) and axis 3 is the number of Gaussian functions one desires to sum and normalize (if at all). ...
156fc322d92535afff2a81dd82f7ee507d22d75d
57,743
def logmon(nav, t, sat, cs, iu=None): """ log variables for monitoring """ _, tow = gn.time2gpst(t) if iu is None: cpc = cs.cpc prc = cs.prc osr = cs.osr else: cpc = cs.cpc[iu, :] prc = cs.prc[iu, :] osr = cs.osr[iu, :] if nav.loglevel >= 2: n ...
3385f9b9dd519cee8e9116f960b1f98b92fce2e1
57,744
def run(config_path, paths): """ The worker function that process the tiles. Args: config_path (str) paths (Iterator) """ # load config config = load_config(config_path) # load model model = load_model(config) # update config path config["loaders"]["test"]["fi...
d9818b48586023b938bf834160aa2d61737f60e9
57,745
def remove_stale_connectivity_entries(): """ @rtype : boolean """ deletecursor = _db.cursor() connectivitycursor = _db.cursor() connectivitycursor.execute("SELECT StorageUUID FROM Connectivity") connectivityresults = connectivitycursor.fetchall() for connectivityrow in connectivityres...
47938669e20543e5e20e2d44b4159c06d9278e7d
57,746
def make_query_from_filter(sample_filter, require_meter=True): """Return a query dictionary based on the settings in the filter. :param filter: SampleFilter instance :param require_meter: If true and the filter does not have a meter, raise an error. """ q = {} if samp...
3ccea6e0253c159517f2f9d3379def00f97487e8
57,748
def wh_to_kwh(wh): """ Convert watt hours to kilowatt hours and round to two decimal places :param wh: integer or decimal value :return: two decimal spot kilowatt hours """ kw = float("{0:.2f}".format(wh / 1000.00)) return kw
19488960a9c7a4d2fc748f4d897d082cfdaee2b8
57,749
def _irafstarfind_objparams(imgcutouts, kernel, sky=None): """ Find the parameters for each source as defined by IRAF's ``starfind``. Parameters ---------- imgcutouts : list A list of ``findstars._ImgCutout`` objects containing the image cutout for each source. kernel : ``f...
c34a07f9141fcc325bc77962fd29b9cd4efa3e4b
57,750
def planck_energy_density(wavelength, temperature): """Spectral energy density according to Planck's law. Uses the SI unit system, so the wavelength must be in meters (m) and the temperature must be in Kelvin (K). Returns the spectral energy density form of the Planck's law in Joule per cubic meter per ...
758ee6ab7552e07ffc51eca436b433a2d11614ce
57,751
import random def get_background(dimensions: tuple[int, int], d_type: str = 'uint8', weights: tuple[int] = (1, 1, 1, 1, 1)) -> list: """ Generate a random background from one of 5 types Blank background. Random Color White Noise. Random picture of a grid or cityscape Procedurally generated li...
c4299dac551a0b8822934e25047efb7fa9344def
57,752
def unbox_numpy_null(d): """ Reverses box_numpy_null, replacing null_numpy_value with None. Recursively descends into a dictionary replacing None values. """ try: return {k: unbox_numpy_null(v) for k, v in d.items()} except Exception: return None if is_null_numpy_value(d) else d
84aa0bafc3df33819ec0a8a1d26d879ea9f21a42
57,753
def get_hms(): """ '2019-06-28 14:47:48' :return: """ hms = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') return str(hms)
02871fafb61bc1448cdf29ca4a77f16fb4740712
57,754
def v4_add(matrix1, matrix2): """Add corresponding numbers in given 2-D matrices. Removing the variable - row - altogether. """ combined = [] for row1, row2 in zip(matrix1, matrix2): combined.append([ n + m for n, m in zip(row1, row2) ]) return combined
9c5408deb245d86b2f92fd74971a6a8ef0380023
57,755
import hashlib import urllib def gravatar_url(email: str, default_image="mp", size=None) -> str: """Creates a gravatar URL from the given e-mail address.""" if email is None: return None email = email.lower().strip().encode("utf-8") url = "https://www.gravatar.com/avatar/" url += hashlib...
53aad42a55537736fd88377359b6ce09b20662de
57,756
def isnumber(x): """Returns True, if x is a number (i.e. can be converted to float).""" try: float(x) return True except ValueError: return False
3e115928d8458d0034f032a56259e18be6c3383b
57,757
from typing import Union from typing import List from typing import Tuple def get_block_saturation_perf( data: Union[pd.DataFrame, List], col_to_use: str = None, prev_sat_val: float = None, window_len: int = None, ) -> Tuple[float, int, int]: """Calculates the saturation value, experiences to satu...
f3c597addd0b2de803a0fa5c04cd7e06835f12b4
57,758
def read_football(edgelist, community): """ Only takes the vertices in the community list, since we don't know the ground truth not in the list """ # Two files concatenated with ',' # Create a iGraph with first file: Edge-list G = ig.Graph.Read_Ed...
b4089d6ea3421b32afcd5c08b19f3ffbd7e105b0
57,759
def eh_posicao_livre (maze, conj_posicoes, posicao): """Esta funcao indica se uma posicao (o terceiro argumento dado, validado \ como tal) se encontra livre ao ser indicado um labirinto e um conjunto de \ posicoes (os dois primeiros argumentos, validados como tal)""" if not (eh_posicao (posicao) and eh_labirint...
68a889ab5f5ebcf5545ddc734f4820e12d00ace1
57,760
def delete_trunk(module, switch, switch_port, peer_switch): """ Method to delete a conflicting trunk on a switch. :param module: The Ansible module to fetch input parameters. :param switch: Name of the local switch. :param switch_port: The l3-port which is part of conflicting trunk for l3. :para...
72dfc4a128f291fbaf0379c5dae2a76d22dda143
57,761
def julio (string, number): """ I like this program. """ alpha_cod = "" codificated = "" i = 0 position = 0 alpha = "ABCDEFGHIKLMNOPQRSTVX" while i < len(alpha): if i + number >= len(alpha) or i + number <= -1: alpha_cod = alpha_cod + alpha [(i + number) % len(al...
676b6f12ddf5897171cc809de2275ec4972fa4a0
57,762
def rgb_rendering_of_mask(pred_img, writing_path=None): """ Returns a segmentation mask in red and blue display :param pred_img: segmented image - 3-class mask :param save_mask: Boolean: whether or not to save the returned mask :param writing_path: string: path where to save the mask if save_mask=Tr...
d780af5d18921669daa67d4841faf1d99961280f
57,763
from typing import Iterable def iscontainer(*items): """ Checks whether all the provided items are containers (i.e of class list, dict, tuple, etc...) """ return all(isinstance(i, Iterable) and not isinstance(i, basestring) for i in items)
7e40d20bd32187a7bbd74a1635b27460f07e0ea2
57,765
def createGUI(): """Creates the, well, GUI!""" root = Tk() root.title("Xovich") root.geometry("500x325") xovich = Main(root) return xovich
55fa9e76b158a593d36eed21a39473de6433b617
57,766
import torch def recall_at_k_batch_torch(X_pred, heldout_batch, k=100): """ Recall@k for predictions [B, I] and ground-truth [B, I]. """ batch_users = X_pred.shape[0] _, topk_indices = torch.topk(X_pred, k, dim=1, sorted=False) # [B, K] X_pred_binary = torch.zeros_like(X_pred) if torch.cu...
580305c0ed43a22e8cf64bee23e3e207516e9e2a
57,767
def write_binary(path, contents): """Open file, write binary, and close. Args: path (str or py.path.Local): Path of file to write to contents (bytes): New contents Returns: py.path.local: `filename` as :class:`py.path.Local` """ p = py_path(path) p.write_binary(contents...
988b48d6a7c06567af83f3462df2060cf2c202b3
57,768
def move(action): """Takes the player's input and performs the transformation""" global climb #If the person asks for help they will be displayed a list of possible commands if action == "help" or action == "h": print("""A list of possible commands (not case sensitive): Cardinal Directions (...
f6852aa5f4e05ee14038691bd6b69ef0346a65ea
57,769
def core_version(): """Return the SODAR Core version""" return projectroles.__version__
19bd2fdeaf9066a47d4fa0759e3efcaa9f5b34f8
57,770
def api_error_generator(): """ API error dict generator for Flask-restful Some are just standard from werkzeug.exceptions, others are custom defined above. :return: """ api_errors = { "BadRequest": {"status": 400, "error": "Invalid syntax in request"}, "NoJSON": {"status": 400, ...
53dbb9afd3b2c412590a24b225eda58e72e98dd8
57,771
import math def angle(vec, units, vec2=[0,0,1]): """ Angle between vectors (with z by default) """ if units=='degrees': return math.acos( dot( unit(vec), unit(vec2) ) )*180.0/math.pi elif units=='radians': return math.acos( dot( unit(vec), unit(vec2) ) ) else: print('\nSpecify valid angle unit ("deg...
ce88b5d0fa20ad309f496620eb5956cd0efd19b8
57,772
import numbers def scale_tensor(tensor, scale): """ Safely scale a tensor without increasing its ``.size()``. """ if is_identically_zero(tensor) or is_identically_one(scale): return tensor result = tensor * scale if not isinstance(result, numbers.Number) and result.shape != tensor.shap...
a97734bb077234b21cb71eb74b4bec3f2c4d6835
57,773
def split_data(x, y, ratio, seed=10): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # generate random indices num_row = len(y) indices = np.random.permutation(num_row) index_split = int(np.floor(ratio * num_row)) index_tr = indices[: index_split] i...
229716e4cab06ecafdfbc685158f6f0bd4b1594d
57,775
def validate_with_model(model, type_checks=None, ignore=None, ignore_missing=None, disallow=None): """ Decorator which will check the contents of the of the json request against a model for: * missing fields which are required * values which don't match their type(s)...
352a2332ccb35f3193979225b5ebfe633a319012
57,776
def run_validators(): """ Run all test validators """ # First, add the validator direcotry to the python path to allow # modules to be loaded by pylint # We also add the jenkins/test directory so that github_helpers can be properly loaded. pypath = os.getenv("PYTHONPATH", "") tools_test_path = O...
d5ddecbcb5edee8a189c8dc178251995c42e752b
57,777
def widthHeightDividedBy(image, value): """Divides width and height of an image by a given value.""" w, h = image.shape[:2] return int(w/value), int(h/value)
78bbe60c43a1bbf362c98125bfddc080cf568861
57,778
import time import site def _get_hazard( ensemble: gm_data.Ensemble, station_name: str, im: IM, exceedance: float, ix: int, n_stations: int, ): """Computes the ensemble hazard curve for the specific station""" start_time = time.time() site_info = site.get_site_from_name(ensemble, s...
6c43223b52385d1d08157d6655c9655608027b63
57,779
def analytical_pulse_energy(q, ekev): """ Estimate of analytical_pulse_energy from electron bunch charge and radiation energy :param q: electron bunch charge [nC] :param ekev: radiation energy [keV] :return P: pulse energy [J] """ P = 19*q/ekev return P/1e3
d81ddafcc41e0e8619922dce0583bf19579112bc
57,782
def batch_parallel(map_fn, devices, **kwargs): """ Parallelize map_fn across devices. :param map_fn: function that takes kwargs and returns a tuple of tensors :param devices: A list of devices to parallelize over :param kwargs: kwargs of input to map, will be split along axis 0. :return: The ou...
0f0fb6da8553b73d8aeaebaec076b34af4571523
57,783
def plot_airfoil(air_df): """Plot an airfoil Parameters ----------- air_df : pd.Dataframe Pandas Dataframe containing x- and y-coordinates of airfoil data. """ line, = plt.plot(air_df.x, air_df.y) plt.axis('equal') return line
2b5c87acd54f8680a50a7e894b1a9658e631cecd
57,784
def get_file_date(tree): """ Get publication date from dta file xml tree. :param tree: the xml tree :return: int, the publication date """ date = tree.find("{http://www.dspin.de/data/metadata}MetaData/{http://www.dspin.de/data/metadata}source/{http://www.clarin.eu/cmd/}CMD/{http://www.clar...
64b0e43b9926d94f1cec066af5bf58ecc10d5044
57,785
import string import random def random_string(string_length=10): """ Generate a random string of fixed length :param string_length: :return: """ letters = string.ascii_lowercase data = "" for character in range(string_length): data += random.choice(letters) return data
54600929a4250612ac6dda904778950a767bd654
57,786
def format_version(version): """Converts a version specified as a list of integers to a string. e.g. [1, 2, 3] -> '1.2.3' Args: version: ([int, ...]) Version as a list of integers. Returns: (str) Stringified version. """ return '.'.join(str(x) for x in version)
fa85b122ce6fed4919ec87ad29847b0997493806
57,788
def find_keys_for_target(keys_left, keys_right, target): """ Finds a (left, right) pair of default rule keys in the respective keys dictionaries for the given target """ print("Searching for the specified build target...") print(target) target_pattern = '"' + target + '"' criteria = [ ...
35686f69e36da76d6514e138579a4ecb5f21d3d9
57,789
def padded_cross_entropy_loss(logits, labels, masks, smoothing=0.05, vocab_size=256): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] masks: Tensor of size [batch_size, length_...
c29ea2f99e6485cd052ea1fb8bc868908cb91908
57,791
def get_open_title(win, message_id, oms): """Build title for File Open / Save dialog """ what = get_text(win, message_id) if oms: what = ' - '.join((what, oms)) return what
52e33e1c1d583f0fcf0050c1795440faa3d8c40f
57,792