content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def euclidean3d(v1, v2): """Faster implementation of euclidean distance for the 3D case.""" if not len(v1) == 3 and len(v2) == 3: print("Vectors are not in 3D space. Returning None.") return None return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
89facc15567a7ed0138dee09ef1824ba40bb58a8
7,329
def blast_seqs(seqs, blast_constructor, blast_db=None, blast_mat_root=None, params={}, add_seq_names=True, out_filename=None, WorkingDir=None, SuppressStderr=None, Sup...
ce22f90fe3092a2c792478d7a4818d67fd13a753
7,330
def merge_dicts(dicts, handle_duplicate=None): """Merge a list of dictionaries. Invoke handle_duplicate(key, val1, val2) when two dicts maps the same key to different values val1 and val2, maybe logging the duplication. """ if not dicts: return {} if len(dicts) == 1: retur...
44c06ab30bb76920ff08b5978a6aa271abd3e449
7,331
from datetime import datetime def _timestamp(line: str) -> Timestamp: """Returns the report timestamp from the first line""" start = line.find("GUIDANCE") + 11 text = line[start : start + 16].strip() timestamp = datetime.strptime(text, r"%m/%d/%Y %H%M") return Timestamp(text, timestamp.replace(tz...
7e3083c6dec766fe681e82555daa59ba7f5166b5
7,332
def start_qpsworkers(languages, worker_hosts): """Starts QPS workers as background jobs.""" if not worker_hosts: # run two workers locally (for each language) workers=[(None, 10000), (None, 10010)] elif len(worker_hosts) == 1: # run two workers on the remote host (for each language) workers=[(work...
3b53693a292027fd82d808b6d609fb3276f1bc2a
7,333
def validate_frame_range(shots, start_time, end_time, sequence_time=False): """ Verify if the given frame range is overlapping existing shots timeline range. If it is overlapping any shot tail, it redefine the start frame at the end of it. If it is overlapping any shot head, it will push back all sh...
d287ad393c80b899cfba3bac92ea9717918aed4a
7,336
def sparse_add(sv1, sv2): """dict, dict -> dict Returns a new dictionary that is the sum of the other two. >>>sparse_add(sv1, sv2) {0: 5, 1: 6, 2: 9} """ newdict = {} keys = set(sv1.keys()) | set(sv2.keys()) for key in keys: x = sv1.get(key, 0) + sv2.get(key, 0) newdict...
ced3420a585084a246ad25f7686fb388f2c05542
7,337
def return_flagger(video_ID): """ In GET request - Returns the username of the user that flagged the video with the corresponding video ID from the FLAGS table. """ if request.method == 'GET': return str(db.get_flagger(video_ID))
c8ca346b60ffa322847b5444c39dcbc43c66701a
7,338
def get_all_hits(): """Retrieves all hits. """ hits = [ i for i in get_connection().get_all_hits()] pn = 1 total_pages = 1 while pn < total_pages: pn = pn + 1 print "Request hits page %i" % pn temp_hits = get_connection().get_all_hits(page_number=pn) hits.extend(temp_hits) return hits
23f4da652d9e89dd0401ac4d8ccf2aa4f2660a5e
7,339
import socket def create_socket( host: str = "", port: int = 14443, anidb_server: str = "", anidb_port: int = 0 ) -> socket.socket: """Create a socket to be use to communicate with the server. This function is called internally, so you only have to call it if you want to change the default parameters. ...
6b8cc3aa19af4582dbdf96d781d8ae64399165cf
7,340
def aten_eq(mapper, graph, node): """ 构造判断数值是否相等的PaddleLayer。 TorchScript示例: %125 : bool = aten::eq(%124, %123) 参数含义: %125 (bool): 对比后结果。 %124 (-): 需对比的输入1。 %123 (-): 需对比的输入2。 """ scope_name = mapper.normalize_scope_name(node) output_name = mapper._get_output...
c08fc3120130e949cbba4e147888fabca38c89e3
7,341
from typing import Tuple def _create_simple_tf1_conv_model( use_variable_for_filter=False) -> Tuple[core.Tensor, core.Tensor]: """Creates a basic convolution model. This is intended to be used for TF1 (graph mode) tests. Args: use_variable_for_filter: Setting this to `True` makes the filter for the ...
21deebe2de004554a5bdc6559ecf6319947f8109
7,342
def plot_diversity_bootstrapped(diversity_df): """Plots the result of bootstrapped diversity""" div_lines = ( alt.Chart() .mark_line() .encode( x="year:O", y=alt.Y("mean(score)", scale=alt.Scale(zero=False)), color="parametre_set", ) ) ...
8b91d1d6d1f7384dcbea6c398a9bde8dfb4aae39
7,343
def escape(s): """ Returns the given string with ampersands, quotes and carets encoded. >>> escape('<b>oh hai</b>') '&lt;b&gt;oh hai&lt;/b&gt;' >>> escape("Quote's Test") 'Quote&#39;s Test' """ mapping = ( ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), (...
2b4971c4e87e613cad457dde6d62806d299cdbcd
7,344
def _get_db_columns_for_model(model): """ Return list of columns names for passed model. """ return [field.column for field in model._meta._fields()]
181999f28ca659bf296bcb4dda7ac29ddfe61071
7,345
def get_UV(filename): """ Input: filename (including path) Output: (wave_leftedges, wav_rightedges, surface radiance) in units of (nm, nm, photons/cm2/sec/nm) """ wav_leftedges, wav_rightedges, wav, toa_intensity, surface_flux, SS,surface_intensity, surface_intensity_diffuse, surface_intensity_direct=np.genfromtx...
cd514ee29ba3ac17cdfcb95c53d4b5df4f4cad80
7,346
import json def load_chunks(chunk_file_location, chunk_ids): """Load patch paths from specified chunks in chunk file Parameters ---------- chunks : list of int The IDs of chunks to retrieve patch paths from Returns ------- list of str Patch paths from the chunks """ ...
c01ec6076141356ae6f3a1dc40add28638739359
7,347
def get_model_input(batch, input_id=None): """ Get model input from batch batch: batch of model input samples """ if isinstance(batch, dict) or isinstance(batch, list): assert input_id is not None return batch[input_id] else: return batch
1b12ee86257bfbd5ab23404251bed39c0021f461
7,349
def issym(b3): """test if a list has equal number of positive and negative values; zeros belong to both. """ npos = 0; nneg = 0 for item in b3: if (item >= 0): npos +=1 if (item <= 0): nneg +=1 if (npos==nneg): return True else: return False
e8cc57eec5bc9ef7f552ad32bd6518daa2882a3e
7,350
def predictOneVsAll(all_theta, X): """will return a vector of predictions for each example in the matrix X. Note that X contains the examples in rows. all_theta is a matrix where the i-th row is a trained logistic regression theta vector for the i-th class. You should set p to a vector of values fro...
32bf9d386ef84debe75781a52335588da360b269
7,351
from typing import Tuple from typing import List def lecture_produit(ligne : str) -> Tuple[str, int, float]: """Précondition : la ligne de texte décrit une commande de produit. Renvoie la commande produit (nom, quantité, prix unitaire). """ lmots : List[str] = decoupage_mots(ligne) nom_produit : s...
355721522b9711f9bc206f4ab63af6121ef9b3d0
7,352
def affinity_matrix(test_specs): """Generate a random user/item affinity matrix. By increasing the likehood of 0 elements we simulate a typical recommending situation where the input matrix is highly sparse. Args: users (int): number of users (rows). items (int): number of items (columns). ...
8e033d230cbc8c21d6058bcada14aca9fb1d7e68
7,353
def get_wm_desktop(window): """ Get the desktop index of the window. :param window: A window identifier. :return: The window's virtual desktop index. :rtype: util.PropertyCookieSingle (CARDINAL/32) """ return util.PropertyCookieSingle(util.get_property(window, ...
050fe4a97a69317ba875aa59b3bf4144b9e2f83c
7,354
def get_parents(tech_id, model_config): """ Returns the full inheritance tree from which ``tech`` descends, ending with its base technology group. To get the base technology group, use ``get_parents(...)[-1]``. Parameters ---------- tech : str model_config : AttrDict """ ...
7220a57b770232e335001a0dab74ca2d8197ddfa
7,355
import hashlib import urllib def profile_avatar(user, size=200): """Return a URL to the user's avatar.""" try: # This is mostly for tests. profile = user.profile except (Profile.DoesNotExist, AttributeError): avatar = settings.STATIC_URL + settings.DEFAULT_AVATAR profile = None ...
a810af7f7abb4a5436a2deed8c4e1069aa5d504c
7,358
import tqdm def union(graphs, use_tqdm: bool = False): """Take the union over a collection of graphs into a new graph. Assumes iterator is longer than 2, but not infinite. :param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite. :param use_tqdm: Should a progress bar be displaye...
8ea9bae0386c497a5fe31c8bd44099ee450b2b2a
7,360
def get_month_n_days_from_cumulative(monthly_cumulative_days): """ Transform consecutive number of days in monthly data to actual number of days. EnergyPlus monthly results report a total consecutive number of days for each day. Raw data reports table as 31, 59..., this function calculates and returns ...
5ede033023d357a60ba5eb7e9926325d24b986e8
7,361
def get_text(name): """Returns some text""" return "Hello " + name
bff30de2184c84f6ed1c4c1831ed9fd782f479c9
7,362
import re def apply_template(assets): """ Processes the template. Used for overwrite ``docutils.writers._html_base.Writer.apply_template`` method. ``apply_template(<assets>)`` ``assets`` (dictionary) Assets to add at the template, see ``ntdocutils.writer.Writer.assets``. returns ...
51042e25f701935d668d91a923155813ce60b381
7,363
def harvest(post): """ Filter the post data for just the funding allocation formset data. """ data = {k: post[k] for k in post if k.startswith("fundingallocation")} return data
67f400caf87f2accab30cb3c519e7014792c84d7
7,364
def model2(x, input_size, output_size): """! Fully connected model [InSize]x800x[OutSize] Implementation of a [InSize]x800x[OutSize] fully connected model. Parameters ---------- @param x : placeholder for input data @param input_size : size of input data @param output_size : size of output data Returns...
74a7f9129865e1d2b6cbfe767c7f218d53ee50e1
7,366
def cut_bin_depths( dataset: xr.Dataset, depth_range: tp.Union[int, float, list] = None ) -> xr.Dataset: """ Return dataset with cut bin depths if the depth_range are not outside the depth span. Parameters ---------- dataset : depth_range : min or (min, max) to be include...
ab4561711d118dc620100bec5e159dc4b7a29f92
7,367
def create_edgelist(file, df): """ creates an edgelist based on genre info """ # load edges from the (sub)genres themselves df1 = (pd .read_csv(file, dtype='str')) # get edges from the book descriptions df df2 = (df[['title', 'subclass']] ...
9cfba48eca977e8b2e3217078bd6d112c465ea23
7,368
def CodeRange(code1, code2): """ CodeRange(code1, code2) is an RE which matches any character with a code |c| in the range |code1| <= |c| < |code2|. """ if code1 <= nl_code < code2: return Alt(RawCodeRange(code1, nl_code), RawNewline, ...
c63213c63d96361451e441cf6923015238dae8f8
7,369
def sort_by_date(data): """ The sort_by_date function sorts the lists by their datetime object :param data: the list of lists containing parsed UA data :return: the sorted date list of lists """ # Supply the reverse option to sort by descending order return [x[0:6:4] for x in sorted(data, k...
f8d18b80404edcf141a56f47938ea09531d30df7
7,370
def get_menu_option(): """ Function to display menu options and asking the user to choose one. """ print("1. View their next 5 fixtures...") print("2. View their last 5 fixtures...") print("3. View their entire current season...") print("4. View their position in the table...") print("...
69e71555d9896d0c462b2e7b542ec87aea9213eb
7,371
def pdf(mu_no): """ the probability distribution function which the number of fibers per MU should follow """ return pdf_unscaled(mu_no) / scaling_factor_pdf
2d6fd461d12da6b00bbf20de7a7be7d61112014c
7,372
import requests def get_weather_by_key(key): """ Returns weather information for a given database key Args: key (string) -- database key for weather information Returns: None or Dict """ url = "%s/weather/%s.json" % (settings.FIREBASE_URL, key) r = requests.get(url) if r.sta...
8ab3bfa6b5924b726fef9a9c0b8bd9d47cf9dfc8
7,373
import warnings def source_receiver_midpoints(survey, **kwargs): """ Calculate source receiver midpoints. Input: :param SimPEG.electromagnetics.static.resistivity.Survey survey: DC survey object Output: :return numpy.ndarray midx: midpoints x location :return nump...
adec937949a4293d35c7a57aad7125f2e1113794
7,374
import copy def fix_source_scale( transformer, output_std: float = 1, n_samples: int = 1000, use_copy: bool = True, ) -> float: """ Adjust the scale for a data source to fix the output variance of a transformer. The transformer's data source must have a `scale` parameter. Parameters --------...
bf2dc0690732ce7677a484afee75fa7701b3d0e8
7,375
def samplePinDuringCapture(f, pin, clock): """\ Configure Arduino to enable sampling of a particular light sensor or audio signal input pin. Only enabled pins are read when capture() is subsequently called. :param f: file handle for the serial connection to the Arduino Due :param pin: The pin to en...
246dc76eb07b9240439befdffdc3f31376647a64
7,376
def year_filter(year = None): """ Determine whether the input year is single value or not Parameters ---------- year : The input year Returns ------- boolean whether the inputed year is a single value - True """ if year[0] == year[1]: single_year ...
35868a72196015c20517179dc89cd65b5601e969
7,377
def distance(p1, p2): """ Return the Euclidean distance between two QPointF objects. Euclidean distance function in 2D using Pythagoras Theorem and linear algebra objects. QPointF and QVector2D member functions. """ if not (isinstance(p1, QPointF) and isinstance(p2, QPointF)): ...
2e8b2d8fcbb05b24798c8507bef8a32b8b9468f3
7,378
import math import numpy def make_primarybeammap(gps, delays, frequency, model, extension='png', plottype='beamsky', figsize=14, directory=None, resolution=1000, zenithnorm=True, b_add_sources=False): """ """ print("Output beam file resolution = %d , output ...
371a29412b52b27c69193bed1e945eeed6a988d7
7,379
import json def view_page(request, content_id=None): """Displays the content in a more detailed way""" if request.method == "GET": if content_id: if content_id.isdigit(): try: # Get the contents details content_data = Content.objects.get(pk=int(content_id)) content_data.fire = int(conte...
11908d7d0f75377485022ab87a93e7f27b2b626d
7,380
def run_feat_model(fsf_file): """ runs FSL's feat_model which uses the fsf file to generate files necessary to run film_gls to fit design matrix to timeseries""" clean_fsf = fsf_file.strip('.fsf') cmd = 'feat_model %s'%(clean_fsf) out = CommandLine(cmd).run() if not out.runtime.returncode == 0: ...
4b033ff1aceb60cdf0c39ebfbefc0841dc4df507
7,381
def exportDSV(input, delimiter = ',', textQualifier = '"', quoteall = 0, newline = '\n'): """ PROTOTYPE: exportDSV(input, delimiter = ',', textQualifier = '\"', quoteall = 0) DESCRIPTION: Exports to DSV (delimiter-separated values) format. ARGUMENTS: - input is list of lists of data (a...
28075667459e872ec0713efb834a9c3aa1dc620e
7,382
def DatasetSplit(X, y): #Creating the test set and validation set. # separating the target """ To create the validation set, we need to make sure that the distribution of each class is similar in both training and validation sets. stratify = y (which is the class or tags of each frame) keeps ...
15c9d6acf51f6535bbd4396be83752b98c6a1fa0
7,383
def parse_children(root): """ :param root: root tags of .xml file """ attrib_list = set() for child in root: text = child.text if text: text = text.strip(' \n\t\r') attrib_list = attrib_list | get_words_with_point(text) attrib_list = attrib_list | pars...
5062b39775bdb1b788fa7b324de108367421f743
7,384
def load_data(ETF): """ Function to load the ETF data from a file, remove NaN values and set the Date column as index. ... Attributes ---------- ETF : filepath """ data = pd.read_csv(ETF, usecols=[0,4], parse_dates=[0], header=0) data.dropna(subset = ['Close', 'Date'...
84b4c20c7d74c7e028e62b0147662e9a54311148
7,385
def preprocess_LLIL_GOTO(bv, llil_instruction): """ Replaces integer addresses of llil instructions with hex addresses of assembly """ func = get_function_at(bv, llil_instruction.address) # We have to use the lifted IL since the LLIL ignores comparisons and tests lifted_instruction = list( [k fo...
656b6088816779395a84d32fe77e28866618b9ff
7,386
import json async def get_limited_f_result(request, task_id): """ This endpoint accepts the task_id and returns the result if ready. """ task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result ...
e459d1963e2de829802927e3265b41bbe4da6bfe
7,387
def process_addr(): """Process the bridge IP address/hostname.""" server_addr = request.form.get('server_addr') session['server_addr'] = server_addr try: leap_response = get_ca_cert(server_addr) session['leap_version'] = leap_response['Body'] \ ['PingRe...
109d3e0652caa5e06fe00702f43640304c30323d
7,388
import requests import json from datetime import datetime import time def get_bkk_list(request): """板块课(通识选修课)""" myconfig = Config.objects.all().first() year = (myconfig.nChoose)[0:4] term = (myconfig.nChoose)[4:] if term == "1": term = "3" elif term == "2": term = "12" if...
03010646ce1e83f644f9bf44b8dcb4e5b8355e52
7,389
import calendar def mkmonth(year, month, dates, groups): """Make an array of data for the year and month given. """ cal = calendar.monthcalendar(int(year), month) for row in cal: for index in range(len(row)): day = row[index] if day == 0: row[index] = N...
71298d60e852e6045b4ab5c45c2f371ae7049808
7,390
def is_extension(step_str): """Return true if step_str is an extension or Any. Args: step_str: the string to evaluate Returns: True if step_str is an extension Raises: ValueError: if step_str is not a valid step. """ if not is_valid_step(step_str): raise ValueError('Not a valid step in a p...
a3b30e238b3b8c42b645d18ae370dea501d1f389
7,391
def diff_list(first, second): """ Get difference of lists. """ second = set(second) return [item for item in first if item not in second]
19975990b5a05433266b3258cd541cca54ab83ac
7,392
from typing import Optional def validate_dissolution_statement_type(filing_json, legal_type) -> Optional[list]: """Validate dissolution statement type of the filing.""" msg = [] dissolution_stmt_type_path = '/filing/dissolution/dissolutionStatementType' dissolution_stmt_type = get_str(filing_json, dis...
868c9f0d6b229c303462a4dee7df16f27cd58898
7,393
from typing import List def weave(left: List[int], right: List[int]) -> List[List[int]]: """ Gives all possible combinations of left and right keeping the original order on left and right """ if not left or not right: return [left] if left else [right] left_result: List[List[int]] = weave_helper(left, right) ...
9a9717e43337802e6cef87a37b7d8d01493ebc8a
7,395
import torch def compute_rel_attn_value(p_attn, rel_mat, emb, ignore_zero=True): """ Compute a part of *attention weight application* and *query-value product* in generalized RPE. (See eq. (10) - (11) in the MuseBERT paper.) Specifically, - We use distributive law on eq. (11). The function com...
a39ca9d5933bc334648994fc5211355a496f8126
7,396
def mock_real_galaxy(): """Mock real galaxy.""" dm = np.loadtxt(TEST_DATA_REAL_PATH / "dark.dat") s = np.loadtxt(TEST_DATA_REAL_PATH / "star.dat") g = np.loadtxt(TEST_DATA_REAL_PATH / "gas_.dat") gal = core.Galaxy( m_s=s[:, 0] * 1e10 * u.M_sun, x_s=s[:, 1] * u.kpc, y_s=s[:, 2...
7dda66bccb5fcecbe55bd0f3ecb64171748947a6
7,398
def lend(request): """ Lend view. It receives the data from the lend form, process and validates it, and reloads the page if everything is OK Args: - request (HttpRequest): the request Returns: """ logged_user = get_logged_user(request) if logged_user is not None and logged_user.user_r...
59fdf04eafc1772b8ef880a1340af57739a71d25
7,399
def deprecated() -> None: """Run the command and print a deprecated notice.""" LOG.warning("c2cwsgiutils_coverage_report.py is deprecated; use c2cwsgiutils-coverage-report instead") return main()
ea3309fc308dd969872f7a4630c137e76a3659b0
7,400
def build_syscall_Linux(syscall, arg_list, arch_bits, constraint=None, assertion = None, clmax=SYSCALL_LMAX, optimizeLen=False): """ arch_bits = 32 or 64 :) """ # Check args if( syscall.nb_args() != len(arg_list)): error("Error. Expected {} arguments, got {}".format(len(syscall.arg_types), ...
1fc9e5eadb688e58f2e6ac3de4d678e3040a1086
7,401
def gamma(x): """Diffusion error (normalized)""" CFL = x[0] kh = x[1] return ( 1. / (-2) * ( 4. * CFL ** 2 / 3 - 7. * CFL / 3 + (-23. * CFL ** 2 / 12 + 35 * CFL / 12) * np.cos(kh) + (2. * CFL ** 2 / 3 - 2 * CFL / 3) * np.cos(2 * kh)...
c8689e1388338cc4d6b1b135f09db90f0e866346
7,402
import re def copylabel(original_name): """create names/labels with the sequence (Copy), (Copy 2), (Copy 3), etc.""" copylabel = pgettext_lazy("this is a copy", "Copy") copy_re = f"\\({copylabel}( [0-9]*)?\\)" match = re.search(copy_re, original_name) if match is None: label = f"{original_...
1f838c33faf347b4219ca23083b664bda01cb9ef
7,403
def load_opts_from_mrjob_confs(runner_alias, conf_paths=None): """Load a list of dictionaries representing the options in a given list of mrjob config files for a specific runner. Returns ``[(path, values), ...]``. If a path is not found, use ``(None, {})`` as its value. If *conf_paths* is ``None``...
6ef2acc7dce0de5e467456d376a52c8078336c55
7,404
def clut8_rgb888(i): """Reference CLUT for wasp-os. Technically speaking this is not a CLUT because the we lookup the colours algorithmically to avoid the cost of a genuine CLUT. The palette is designed to be fairly easy to generate algorithmically. The palette includes all 216 web-safe colours to...
ca95c95306f7f4762add01f2ffc113f348e29d3b
7,405
def get_file_from_rcsb(pdb_id,data_type='pdb'): """ (file_name) -> file_path fetch pdb or structure factor file for pdb_id from the RCSB website Args: file_name: a pdb file name data_type (str): 'pdb' -> pdb 'xray' -> structure factor Returns: a file path for the pdb file_name """ ...
19a557a0bf4f69ba132d6d4520a124aef931f816
7,406
def parse_events(fobj): """Parse a trace-events file into {event_num: (name, arg1, ...)}.""" def get_argnames(args): """Extract argument names from a parameter list.""" return tuple(arg.split()[-1].lstrip('*') for arg in args.split(',')) events = {dropped_event_id: ('dropped', 'count')} ...
af35deff9c5b76d4d46700a738186822032d4190
7,407
def enu2ECEF(phi, lam, x, y, z, t=0.0): """ Convert ENU local coordinates (East, North, Up) to Earth centered - Earth fixed (ECEF) Cartesian, correcting for Earth rotation if needed. ENU coordinates can be transformed to ECEF by two rotations: 1. A clockwise rotation over east-axis...
494078d7c3bf9933fcc5a1b8ac62e105233722b8
7,408
def get_login(discord_id): """Get login info for a specific user.""" discord_id_str = str(discord_id) logins = get_all_logins() if discord_id_str in logins: return logins[discord_id_str] return None
16b7690dd4f95df1647c7060200f3938b80993c0
7,410
import json from typing import OrderedDict def to_json_dict(json_data): """Given a dictionary or JSON string; return a dictionary. :param json_data: json_data(dict, str): Input JSON object. :return: A Python dictionary/OrderedDict with the contents of the JSON object. :raises TypeError: If the input ...
e1264d88a4424630f7348cbe7794ca072c057bdf
7,411
def get_keypoints(): """Get the COCO keypoints and their left/right flip coorespondence map.""" # Keypoints are not available in the COCO json for the test split, so we # provide them here. keypoints = [ 'nose', 'neck', 'right_shoulder', 'right_elbow', 'right_wris...
1bedcee8c5f38bdefcd00251dd95530966a41353
7,412
def has_mtu_mismatch(iface: CoreInterface) -> bool: """ Helper to detect MTU mismatch and add the appropriate OSPF mtu-ignore command. This is needed when e.g. a node is linked via a GreTap device. """ if iface.mtu != DEFAULT_MTU: return True if not iface.net: return False ...
a9415ed9fbcb276a53df8dac159f48aaac831744
7,413
def phrase_boxes_alignment(flatten_boxes, ori_phrases_boxes): """ align the bounding boxes with corresponding phrases. """ phrases_boxes = list() ori_pb_boxes_count = list() for ph_boxes in ori_phrases_boxes: ori_pb_boxes_count.append(len(ph_boxes)) strat_point = 0 for pb_boxes_num in ...
e961a90f61917f217ac6908263f5b6c74bc42b26
7,414
def dismiss_notification(request): """ Dismisses a notification ### Response * Status code 200 (When the notification is successsfully dismissed) { "success": <boolean: true> } * `success` - Whether the dismissal request succeeded or not * Status code...
97cbd560fd16da8ba0d081616e3e2504a2dbf8a0
7,416
def log_at_level(logger, message_level, verbose_level, msg): """ writes to log if message_level > verbose level Returns anything written in case we might want to drop down and output at a lower log level """ if message_level <= verbose_level: logger.info(msg) return True retu...
4b88ee137f7c2cb638b8a058b2dceb534329c0d9
7,417
def datafile(tmp_path_factory): """Make a temp HDF5 Ocat details file within 60 arcmin of 3c273 for obsids before 2021-Nov that persists for the testing session.""" datafile = str(tmp_path_factory.mktemp('ocat') / 'target_table.h5') update_ocat_local(datafile, target_name='3c273', resolve_name=True, rad...
16448a80385ab29ebbaef8e593f96ff0167c1fdb
7,418
def _collect_scalars(values): """Given a list containing scalars (float or int) collect scalars into a single prefactor. Input list is modified.""" prefactor = 1.0 for i in range(len(values)-1, -1, -1): if isinstance(values[i], (int, float)): prefactor *= values.pop(i) return p...
bea7e54eec16a9b29552439cd12ce29b9e82d40b
7,419
from pathlib import Path def create_output_directory(validated_cfg: ValidatedConfig) -> Path: """ Creates a top level download directory if it does not already exist, and returns the Path to the download directory. """ download_path = validated_cfg.output_directory / f"{validated_cfg.version}" ...
720f45885e177b55ddbdf492655b17275c4097f8
7,420
def presentation_logistique(regression,sig=False): """ Mise en forme des résultats de régression logistique Paramètres ---------- regression: modèle de régression de statsmodel sig: optionnel, booléen Retours ------- DataFrame : tableau de la régression logistique """ # Pa...
bef9e08f463c9bc0fbb1d737a412472ab792051e
7,421
def handle_colname_collisions(df: pd.DataFrame, mapper: dict, protected_cols: list) -> (pd.DataFrame, dict, dict): """ Description ----------- Identify mapper columns that match protected column names. When found, update the mapper and dataframe, and keep a dict of these changes to return to the...
56819ff256cc3c1bcd2062fab0cac29bce7a0c15
7,422
import codecs import json def process_file(filename): """Read a file from disk and parse it into a structured dict.""" try: with codecs.open(filename, encoding='utf-8', mode='r') as f: file_contents = f.read() except IOError as e: log.info('Unable to index file: %s, error :%s',...
864c04449cbd998394c07790858ccbdc2d4eea6d
7,423
def revive(grid: Grid, coord: Point) -> Grid: """Generates a set of all cells which can be revived near coord""" revives = set() for offset in NEIGHBOR_OFFSETS: possible_revive = addpos(coord, offset) if possible_revive in grid: continue active_count = live_around(grid, possible_revive) if active_count == ...
94e928ce9dff7015f2785e5a0186f06c4f754cda
7,424
def process_table_creation_surplus(region, exchanges_list): """Add docstring.""" ar = dict() ar["@type"] = "Process" ar["allocationFactors"] = "" ar["defaultAllocationMethod"] = "" ar["exchanges"] = exchanges_list ar["location"] = location(region) ar["parameters"] = "" ar["processDoc...
0669fce0363d807ee018b59125a13c95417294a7
7,425
import copy def makepath_coupled(model_hybrid,T,h,ode_method,sample_rate): """ Compute paths of coupled exact-hybrid model using CHV ode_method. """ voxel = 0 # make copy of model with exact dynamics model_exact = copy.deepcopy(model_hybrid) for e in model_exact.events: e.hybridType = SLOW...
95e26ec633b5c10797a040583cbc6ad6d6ad9127
7,427
import torch def process_image_keypoints(img, keypoints, input_res=224): """Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to...
e30e9c9b5de106c968d538a56062fefab7c1b3ee
7,428
from typing import Dict from typing import Iterable from typing import Union def _load_outputs(dict_: Dict) -> Iterable[Union[HtmlOutput, EbookConvertOutput]]: """Translates a dictionary into a list of output objects. The dictionary is assumed to have the following structure:: { 'outputs...
229eeb33ca34266a397dca56b13f004a8647e8e5
7,430
def _async_friendly_contextmanager(func): """ Equivalent to @contextmanager, except the resulting (non-async) context manager works correctly as a decorator on async functions. """ @wraps(func) def helper(*args, **kwargs): return _AsyncFriendlyGeneratorContextManager(func, args, kwargs) ...
453fb89ca52101e178e0bd2c5895804ca2cc54e6
7,431
import itertools def all_inputs(n): """ returns an iterator for all {-1,1}-vectors of length `n`. """ return itertools.product((-1, +1), repeat=n)
526dff9332cf606f56dcb0c31b5c16a0124478ed
7,432
def generate_winner_list(winners): """ Takes a list of winners, and combines them into a string. """ return ", ".join(winner.name for winner in winners)
2586292d4a96f63bf40c0d043111f5087c46f7a9
7,434
def stampify_url(): """The stampified version of the URL passed in args.""" url = request.args.get('url') max_pages = request.args.get('max_pages') enable_animations = bool(request.args.get('animations') == 'on') if not max_pages: max_pages = DEFAULT_MAX_PAGES _stampifier = Stampifier...
136d95adedeeddcdc4166a9bce20414e909fa21f
7,435
def init_time(p, **kwargs): """Initialize time data.""" time_data = { 'times': [p['parse']], 'slots': p['slots'], } time_data.update(**kwargs) return time_data
2aff3819d561f0dc9e0c9b49702b8f3fbb6e9252
7,438
def bsplslib_D0(*args): """ :param U: :type U: float :param V: :type V: float :param UIndex: :type UIndex: int :param VIndex: :type VIndex: int :param Poles: :type Poles: TColgp_Array2OfPnt :param Weights: :type Weights: TColStd_Array2OfReal & :param UKnots: :ty...
4c7a95448c116ef04fac36168c05a22597bc0684
7,440
def b_cross(self) -> tuple: """ Solve cross one piece at a time. Returns ------- tuple of (list of str, dict of {'CROSS': int}) Moves to solve cross, statistics (move count in ETM). Notes ----- The cube is rotated so that the white centre is facing down. The four white cro...
f0a82ea6b6634b78e4252ac264a537af87be0fc1
7,441
def retain_groundtruth(tensor_dict, valid_indices): """Retains groundtruth by valid indices. Args: tensor_dict: a dictionary of following groundtruth tensors - fields.InputDataFields.groundtruth_boxes fields.InputDataFields.groundtruth_classes fields.InputDataFields.groundtruth_confidences ...
a6681d8e6b3c8c44fa4fee9143ab57538eac2661
7,443
import json def cluster_list_node(realm, id): """ this function add a cluster node """ cluster = Cluster(ES) account = Account(ES) account_email = json.loads(request.cookies.get('account'))["email"] if account.is_active_realm_member(account_email, realm): return Response(json.dumps(cluste...
eebccc3c7c3c710fc2c26ee0dfba5481e2e2043a
7,444
def complete_json(input_data, ref_keys='minimal', input_root=None, output_fname=None, output_root=None): """ Parameters ---------- input_data : str or os.PathLike or list-of-dict Filepath to JSON with data or list of dictionaries with information about annotations r...
1a732c87670c890b406e935494ca2c51a0f0dc83
7,446
def BuildSystem(input_dir, info_dict, block_list=None): """Build the (sparse) system image and return the name of a temp file containing it.""" return CreateImage(input_dir, info_dict, "system", block_list=block_list)
4537da68b322e7d7714faa2c365ece1c67b255f2
7,447