content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import platform def get_dataset_mrnet_args(parser, args=[]): """ Get all relevant parameters to handle the dataset -> here: MRNET """ # determine path if platform.system() == "Linux": path = "/home/biomech/Documents/OsteoData/MRNet-v1.0/" else: path = "C:/Users/Niko/Docume...
466cb843fca4a09f52a72603dcd2c4379ea1e54d
24,300
import base64 def convertImageToBase64(image): """ Convert image to base64 for transmission Args: image (obj): opencv image object Returns: (str): image encoded as base64 """ # im_arr: image in Numpy one-dim array format. _, im_arr = cv2.imencode('.jpg', image) im_bytes = im_arr.tobytes() ...
25f4ce7e9dce20ebb50fc55d31c52c77b0b7aa4b
24,301
def anchor_inside_flags(flat_anchors, valid_flags, tsize, allowed_border=0): """Check whether the anchors are inside the border. Args: flat_anchors (torch.Tensor): Flatten anchors, shape (n, 2). valid_flags (torch.Tensor): An existing valid flags of anchors. tsize (int): Temporal size o...
d7840ebb4e5fcb7735e27454c0367eb14cec6ff0
24,302
def args2command(*args): """ to convert positional arguments to string list """ try: assert None not in args assert "" not in args except: print("args:", args) raise(ValueError("None values not allowed in args!")) return [str(_).strip() for _ in args]
688fed2c2146583f05deb75a5c832aac6c971cbd
24,303
from typing import Tuple from typing import Optional from typing import List def parse_one(line: str) -> Tuple[Optional[str], List[str]]: """ Returns (first corruption char, remaining stack) """ stack = [] for c in line: if c in BRACKET_MAP.keys(): stack.append(c) c...
85c4479b743c5ff3de041bca23a01fec1294a6bd
24,304
def load_callable_dotted_path(dotted_path, raise_=True, reload=False): """ Like load_dotted_path but verifies the loaded object is a callable """ loaded_object = load_dotted_path(dotted_path=dotted_path, raise_=raise_, reload=relo...
e76cf024cfbc4700d224881a9929951a3b23e246
24,305
def get_engine(): """Helper method to grab engine.""" facade = _create_facade_lazily() return facade.get_engine()
1d430d2fbe7b79d6c6cb69a0a11fb811ade92b24
24,306
def generate_diagonals(): """ Cоздает словарь диагоналей на которые модет встать конь и массив с возможным количеством вариантов дойти в кажду точку этой диагонали :return: словарь - где ключ это число диагонали а значения, это список из возможных способов добраться до точек на этой диагонали ""...
cf5945a565197194c7844e8f59ff4a137cab1abf
24,307
from typing import Union def physical_rad_to_pix(im_prod: Union[Image, RateMap, ExpMap], physical_rad: Quantity, coord: Quantity, z: Union[float, int] = None, cosmo=None) -> Quantity: """ Another convenience function, this time to convert physical radii to pixels. It can deal with both...
4a26079610c882e40a31c7ba2ca64f7a0ccdd901
24,308
from functools import reduce def conversation_type_frequency_distribution(convo): """ Returns the type frequency (unigram) distribution for the convo. Parameters ---------- convo : Conversation Returns ------- collections.Counter """ return reduce(lambda x, y: x + y, map(post...
66da6bfea0f6a1df0657fba2c881f373acc7d69e
24,309
def _cleanup_legacy_namespace(input_string): """ At some point in time, the ttml namespace was TTML_NAMESPACE_URI_LEGACY, then it got changed to TTML_NAMESPACE_URI. There are tons of those floating around, including our pre-dmr dfxps and ttmls files. The backend (this lib) can deal with both namespa...
f5a291f02bf1df883e40b56526b8d500fd9bb810
24,310
import json def _err_to_json(key, *args): """Translate an error key to the full JSON error response""" assert (key in errors) code = errors[key][0] title = errors[key][1] detail = errors[key][2].format(*args) return json.dumps({ 'message': title, 'errors': [{ ...
00be9d9603f5a5e36bb0197dd60886afb4f1f989
24,311
def multiref_represent(opts, tablename, represent_string = "%(name)s"): """ Represent a list of references @param opt: the current value or list of values @param tablename: the referenced table @param represent_string: format string to represent the records """ if not opts:...
86cb90e04073ddb4ec5676de3d9c87417bed5740
24,312
def selected_cells(self): """Get the selected cells. Synchronous, so returns a list. Returns: A list of Cells. """ cells = [] generator = self.selected_cells_async() for chunk in generator: for value in chunk.cells: cells.append(value) return cells
523e77757acf8755b32ac0d283fd8864d6784ff1
24,313
import warnings def calc_annual_capital_addts_ferc1(steam_df, window=3): """ Calculate annual capital additions for FERC1 steam records. Convert the capex_total column into annual capital additons the `capex_total` column is the cumulative capital poured into the plant over time. This function ta...
3d1c07182f590f39f394a2e6ef78105b9ad2b745
24,314
import time import json async def async_upload_file(serialUID, filepath, upload_blockinfo): """异步上传文件""" ts = int(time.time() * 1000) # 计算分片CRC32 data, crc32 = get_block_crc32(filepath, upload_blockinfo["startOffset"], upload_blockinfo["endOffset"]) upload_blockinfo['dataCRC32'] = crc32 # 数据加...
08da476e3ce4b680b60124777972332a807137ce
24,315
def parse(parser_name=None, file_key=None, **kwargs): """Call the given parser and return parsed data It is possible to give file key instead of parser name. In that case the name of the parser will be read from the file list. TODO: This is the old style of running parsers, can be deleted when all par...
1a76add60f58e9830c669e3ed9547a3193e79a32
24,316
def create_cv_split(file_train, file_test, col_label='label', col_group=None, n_folds=5, splitter='skf', random_state=33): """ Parameters: splitter : str "kf", "skf", "gkf" Example: train_df, test_df = create_cv_split(os.path.join(args.data_dir, 'Train.csv'), ...
95a0ceb9c63c68a2cf322ccd72050cdf2708a59c
24,317
def get_scanner(hass, config): """Validate the configuration and return a Bbox scanner.""" scanner = BboxDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
2ce6e0e9e4b11885a2c3d9090ed31c0a3da9070d
24,318
def _trim_name(image): """Remove the slash at the end of the filename.""" return image[:-1] if image[-1] == '/' else image
823dd63920673352a18d73f83190853d5a234483
24,319
import os def check_for_pyd_so(file_path): """ Checks if a file with .pyd or .so extension exists """ return True if os.path.isfile(file_path+'.pyd') or os.path.isfile(file_path+'.so') else False
a060f2350c11a3d34b59054c9cd95acc594b781b
24,320
from sys import path def load_data(data_file): """Loads data CSV into input and target ndarrays of shape (n_samples, features). Args: data_file (str): Local or remote CSV file containing data to load. Returns: ndarray: Input data of shape (n_samples, in_features). ndarray: Ta...
1e6e69c98e29e6e26f6d0b65b6ed82e51bd69a89
24,321
from typing import Callable def sines_sum(parameters: ndarray) -> Callable: """ Construct a sum of sines for given parameters. Parameters ---------- parameters : ndarray y0, amplitude1, frequency1, phase1, amplitude2, frequency2, phase2, ... Returns ------- function f...
43cff5790ec098debc638a2cd66d3ac929a67ef6
24,322
def _divide_and_conquer_convex_hull(points): """ Notes: O(n * log(n)) Args: points: Returns: """ count = len(points) if count < 6: return Hull(_jarvis_convex_hull(points)) midpoint = count // 2 min_cloud, max_cloud = points[:midpoint], points[midpoint:] ...
46fc256c0efc08f978fe1049935d068a9a6b23de
24,323
from typing import Union def _parsed_method_to_method( parsed: Union[parse.UnderstoodMethod, parse.ImplementationSpecificMethod] ) -> Union[UnderstoodMethod, ImplementationSpecificMethod]: """Translate the parsed method into an intermediate representation.""" if isinstance(parsed, parse.ImplementationSpec...
061df4c074cd3fe5f0c5b8570bdefe8605527d46
24,324
def NS(namespace, tag): """ Generate a namespaced tag for use in creation of an XML file """ return '{' + XML_NS[namespace] + '}' + tag
32a6f1e8e351ca15f84391632f6773ee4c538dfd
24,325
import sys from sys import version def dump_requirements(nodes, strict=False): """Dump packages and their versions to a string. Format of the string is like a "requirements.txt":: # created with python-X.X package-1==1.2.3 package-2==2.3.4 :param nodes: List of ast nodes in a mo...
a9770800178e50234e96e648f16d821b3ea538be
24,326
def non_contradiction_instance_2(person_list, place_list, n, vi_function=vi, not_vi_function=not_vi, Everyone_str="Everyone", ...
068655c85b9bb5a4979a94a9c58b4297222db32e
24,327
def load_w2v_model(w2v_path): """ Loads pretrained w2v model :param w2v_path: :return: """ return gensim.models.Word2Vec.load(w2v_path)
f9e44290ae8d2e7069ed724b68c405f275d6b95b
24,328
import hmac def derive_keys(token, secret, strategy): """Derives keys for MAC and ENCRYPTION from the user-provided secret. The resulting keys should be passed to the protect and unprotect functions. As suggested by NIST Special Publication 800-108, this uses the first 128 bits from the sha384 KD...
1b7e53957f746f91df4b5e7545ac1a079a96ac94
24,329
from typing import Optional def bitinfo_holding_ts( track_addr: Optional[str] = None, track_coin: Optional[str] = None, timeframe: Optional[str] = "4h", sma: Optional[int] = 20, ): """Scrap the data from bitinfo and calculate the balance based on the resample frequency. track_addr (str): The a...
bf29a9f91c695a4424436522fd76b467e9e573e0
24,330
import logging def sharpe(p): """Sharpe ratio of the returns""" try: return p.mean()/p.std()*np.sqrt(252) except ZeroDivisionError: logging.error("Zero volatility, divide by zero in Sharpe ratio.") return np.inf
e2700f9dfdc5b1d405892bc7ee460a2930b860d4
24,331
from ase.lattice.cubic import FaceCenteredCubic from ase.lattice.cubic import BodyCenteredCubic import six def create_manual_slab_ase(lattice='fcc', miller=None, host_symbol='Fe', latticeconstant=4.0, size=(1, 1, 5), replacements=None, decimals=10, pop_last_layers...
47447a6f34b48865ab0bc4824f05c98e976b92be
24,332
def telephone(): """Generates random 10 digit phone numbers and returns them as a dictionary entry""" num = "" # for i in range(1, 11): num += str(rand.randint(0, 9)) if(i < 7 and i % 3 == 0): num += "-" return {"telephone":num}
436c6a04fbdff8162de39433ddd250a610333173
24,333
from datetime import datetime from typing import List import warnings import time def get_kline(symbol: str, end_date: [datetime, str], freq: str, start_date: [datetime, str] = None, count=None, fq: bool = False) -> List[RawBar]: """获取K线数据 :param symbol: 币安期货的交易对 BTCUSDT/ETHUSDT :param start...
5f6d9cdd82adf1a79dc9ed054de139170249ac13
24,334
def get_terms(properties, out_log, classname): """ Gets energy terms """ terms = properties.get('terms', dict()) if not terms or not isinstance(terms, list): fu.log(classname + ': No terms provided or incorrect format, exiting', out_log) raise SystemExit(classname + ': No terms provided or incorrect format') if...
b25c596fd65a68c4c3f7b99268ddbf39675ad592
24,335
from pathlib import Path import os def get_prefix(allow_base=False): """Get $CONDA_PREFIX as pathlib.Path object.""" confirm_active() prefix = Path(os.environ.get("CONDA_PREFIX")) if not allow_base and is_base_env(prefix): raise ImportError( "Base conda env detected, activate an ...
8c49675b96dbe0f2e51f980d3a89d2215bf10dab
24,336
import struct def _decomp_MAMFile(srcfile, destfile=''): """ Superfetch file이나 Prefetch file의 MAM 포맷의 압축을 푼다. """ f = open(srcfile, 'rb') data = f.read() f.close() # 압축된 파일인지 확인한다. """ MAX\x84 : Windows 8 이상 수퍼패치 파일 MAX\x04 : Windows 10 프리패치 파일 """ id = data[0:3].decode('utf8') ...
fd2687854a2918f5692d619b83bd8ca73d6c87aa
24,337
def cg(A, b, x=None, tol=1e-10, verbose=0, f=10, max_steps=None): """ Parameters ---------- A: A matrix, or a function capable of carrying out matrix-vector products. """ n = b.size b = b.reshape(n) if x is None: x = np.zeros(n) else: x = x.reshape(n) if isinstan...
8d2b6e332eee6ce21296a9f66621b1629cd56c33
24,338
def from_string(spec): """Construct a Device from a string. Args: spec: a string of the form /job:<name>/replica:<id>/task:<id>/device:CPU:<id> or /job:<name>/replica:<id>/task:<id>/device:GPU:<id> as cpu and gpu are mutually exclusive. All entries are optional. Returns: A Device. ...
c223ead53ee1677e5bbfd863aeaffb8aefc5e81f
24,339
from typing import OrderedDict def load_HDFS_data_timestamp_approach(input_path, time_delta_sec, timestamp_format, cached_workflow_path='data_df.csv', sep=',', encoding ='utf-8', cache_workflow=True): """ Downloads cached workflow data from csv file Args: input_path: path to cached wo...
b3e7dff820a666ee0060dc3349e91eb990a5c9ab
24,340
def pairwise_to_multiple(pwise, ref_seq, moltype, info=None): """ turns pairwise alignments to a reference into a multiple alignment Parameters ---------- pwise Series of pairwise alignments to ref_seq as [(non-refseq name, aligned pair), ...] ref_seq The sequence common...
36f8d63ba9a53aaa448bcf0c782f748edafc25fa
24,341
def get_dashboard(title: str): """Get a dashboard by title""" dashboards = sdk.search_dashboards(title=title) if not dashboards: print(f"dashboard {title} was not found") return None return dashboards[0]
3738557ef1ef2dee35382df7da86cf373908974c
24,342
import torch def translate_tensor(tensor, input_size=32, nt=2): """ Data augmentation function to enforce periodic boundary conditions. Inputs are arbitrarily translated in each dimension """ ndim = len(tensor[0,0, :].shape) t = input_size//nt t_vec = np.linspace(0, (nt-1)*t, nt).astype(in...
12280e33331adb6924b36eebc65c85a10f937d58
24,343
def _get_job_resources(args): """Extract job-global resources requirements from input args. Args: args: parsed command-line arguments Returns: Resources object containing the requested resources for the job """ logging = param_util.build_logging_param( args.logging) if args.logging else None ...
fbbf596c721369890a14581863d4dce0fb24eb42
24,344
import os import requests def am_api_post_json(api_path, data): """ POST json to the Archivematica API :param api_path: URL path to request (without hostname, e.g. /api/v2/location/) :param data: Dict of data to post :returns: dict of json data returned by request """ am_url = os.environ["...
94428a059e322246c35d38e690667f52bf842663
24,345
import os def collect_checkpoint_paths(checkpoint_dir): """ Generates a list of paths to each checkpoint file found in a folder. Note: - This function assumes, that checkpoint paths were written in relative. Arguments: checkpoint_dir (string): Path to the models checkpoin...
8c477535a77dc989b31b30d3a4487c7219efbfb3
24,346
import torch def cosine_distance(input1, input2): """Computes cosine distance. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. Returns: torch.Tensor: distance matrix. """ input1_normed = F.normalize(input1, p=2, dim=1) input...
e4aed2f8f0439797312977d674ccc0351a90402b
24,347
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post', truncating='post', value=0.): """ pad_sequences. Pad each sequence to the same length: the length of the longest sequence. If maxlen is provided, any sequence longer than maxlen is truncated to maxlen. Truncation...
f69c199861e17575185d0c40371f85b1fa5f2458
24,348
def get_regions(service_name, region_cls=None, connection_cls=None): """ Given a service name (like ``ec2``), returns a list of ``RegionInfo`` objects for that service. This leverages the ``endpoints.json`` file (+ optional user overrides) to configure/construct all the objects. :param service...
b63982d14c415d082c729595c85fee0833e75d8f
24,349
import math def sol_dec(day_of_year): """ Calculate solar declination from day of the year. Based on FAO equation 24 in Allen et al (1998). :param day_of_year: Day of year integer between 1 and 365 or 366). :return: solar declination [radians] :rtype: float """ _check_doy(day_of_year...
20c0c491a9ad99a324754c8bc2f6a32e6c6b1f51
24,350
import unittest def makeTestSuiteV201111(): """Set up test suite using v201111. Returns: TestSuite test suite using v201111. """ suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(NetworkServiceTestV201111)) return suite
39a7ecb94bce33e3edbbc52ae584e4fa36c95c42
24,351
def build_series(df): """ Return a series tuple where: the first element is a list of dates, the second element is the series of the daily-type variables, the third element is the series of the current-type variables, the fourth element is the series of the cum-type variables. :param df: pd....
d5ca0f87c46a6061544481ca01a88ad29def4c7e
24,352
def lnZ(df_mcmc): """ Compute log Z(1) from PTMCMC traces stored in DataFrame. Parameters ---------- df_mcmc : pandas DataFrame, as outputted from run_ptmcmc. DataFrame containing output of a parallel tempering MCMC run. Only need to contain columns pertinent to computing ln...
621d6db5a9126608d61688bd79ae09e03d25d114
24,353
def p2h(p, T=293., P0=1000., m=28.966, unit_p='mbar'): """ Returns an elevation from barometric pressure Parameters ---------- p: {float, array} barometric pressure in mbar or torr specified with unit_p T: float, optional Temperature in K P0: float, optional Pressure at ...
646eac27f7723116e9ea5cd9dcef226cc6c45cc5
24,354
from typing import Callable def upon_teardown(f: Callable): """ Use this decorator to mark you ploogin function as a handler to call upon teardown. """ return PlooginEventHandler(event=PlooginEvents.TEARDOWN, f=f)
289db179d427c9ebccd1ff408e4606d4f6e97bd5
24,355
def get_train_test_indices_drone(df, frac, seed=None): """ Split indices of a DataFrame with binary and balanced labels into balanced subindices Args: df (pd.DataFrame): {0,1}-labeled data frac (float): fraction of indicies in first subset random_seed (int): random seed used as random st...
f27f893f8cfcc48718d0ca5166e2eafdb57bbad2
24,356
import requests from bs4 import BeautifulSoup import re def get_subs(choice, chatid, obj): """Return subtitle download links.""" url = "https://yts-subs.com" + obj.get_url(chatid, int(choice)) try: reponse = requests.get(url, headers=headers) except Exception as e: print(e) rai...
60b19f1004771546cfe530be55fa793d24500df0
24,357
def get_shape(rhoa_range): """ Find anomaly `shape` from apparent resistivity values framed to the best points. :param rhoa_range: The apparent resistivity from selected anomaly bounds :attr:`~core.erp.ERP.anom_boundaries` :type rhoa_range: array_like or list ...
7de41fb432c733f434853e74e873ecac1542c877
24,358
def elslib_D2(*args): """ * For elementary surfaces from the gp package (cones, cylinders, spheres and tori), computes: - the point P of parameters (U, V), and - the first derivative vectors Vu and Vv at this point in the u and v parametric directions respectively, and - the second derivative vectors Vuu, Vvv and...
c99d089ba0aa95ed1134be53a491f690feb03edd
24,359
def readiness(): """Handle GET requests that are sent to /api/v1/readiness REST API endpoint.""" return flask.jsonify({}), 200
7c1edf3b965ad1f2b7356d634135a75846886b21
24,360
def camino_minimo(origen,dest,grafo,aeropuertos_por_ciudad,pesado=True): """Obtiene el camino minimo de un vertice a otro del grafo""" camino=[] costo=float("inf") for aeropuerto_i in aeropuertos_por_ciudad[origen]: for aeropuerto_j in aeropuertos_por_ciudad[dest]: if pesado: ...
a0ef06265ce754fa1a4289761139e86e241f14fc
24,361
def extract_name_from_uri_or_curie(item, schema=None): """Extract name from uri or curie :arg str item: an URI or curie :arg dict schema: a JSON-LD representation of schema """ # if schema is provided, look into the schema for the label if schema: name = [record["rdfs:label"] for record...
08125457496c9d563f96a4f2a54a560c56c01af8
24,362
import os def get_gcc_timeseries(site, roilist_id, nday=3): """ Read in CSV version of summary timeseries and return GCCTimeSeries object. """ # set cannonical dir for ROI Lists roidir = os.path.join(config.archive_dir, site, "ROI") # set cannonical filename gcc_tsfile = site + "_" +...
b800ffcbb90a6f3392c76ff388facae044d6265f
24,363
import tqdm def download_graph(coordinates, distances): """ Criação do grafo de ruas do OSM a partir das coordenadas solicitadas """ max_distance = max(distances) G = False print('Fetching street network') for coordinate in tqdm(coordinates, desc='Downloading'): if G: # "soma...
bf7dd26d18f798982e77aa7dfd8fc905cb97ea66
24,364
def external_forces(cod_obj): """actual cone position""" x_pos,y_pos,z_pos =cod_obj.pos_list[-1] """ Drift vector components Drift signal//all directions """ divx = forcep['divxp']([x_pos,y_pos,z_pos])[0] divy = forcep['divyp']([x_pos,y_pos,z_pos])[0] divz = forcep['divzp']([x_pos...
2dbd13b3e09b0eb7e09b10c0607a9e0e7a87c11a
24,365
def charis_font_spec_css(): """Font spec for using CharisSIL with Pisa (xhtml2pdf).""" return """ @font-face {{ font-family: 'charissil'; src: url('{0}/CharisSIL-R.ttf'); }} @font-face {{ font-family: 'charissil'; font-style: italic; src: url('{0}/CharisSIL-I....
a812b65da61d333031dac878ebfdf9e4afe4b448
24,366
def set_symbols(pcontracts, dt_start="1980-1-1", dt_end="2100-1-1", n=None, spec_date={}): # 'symbol':[,] """ Args: pcontracts (list): list of pcontracts(string) dt_start (datetime/str): start time of all pcontracts dt_end ...
9450e8355fa88d6794d58de7311992bb4bab357f
24,367
def estimate_vol_gBM(data1, data2, time_incr=0.1): """ Estimate vol and correlation of two geometric Brownian motion samples with time samples on a grid with mesh size time_incr using estimate_vol_2d_rv_incr, the drift parameter and mean rev paramters are set to 0. ---------- args: data1 data array...
4ecc5fb7f97c41db2f9b7347db43bda70d7b6c14
24,368
import logging import sys def check_quarantine(av_quarentine_file): """Check if the quarantine is over.""" in_quarantine = True try: with open(av_quarentine_file, 'r', encoding="utf-8") as ff_av: text = ff_av.readline() quar_str, av_run_str = text.split(':') quaranti...
2f2b6951f694de3b66b7aaa47829a31b5f09c87a
24,369
import requests def get_coin_total(credentials_file: str, coin: str) -> float: """ Get the current total amount of your coin Args: credentials_file: A JSON file containing Coinbase Pro credentials coin: The coin requested Returns: coin_total: The total amount of the coin you ...
cf71d211cf44e0b215af8ce219a12179c005f52a
24,370
from datetime import datetime def datetime_to_serial(dt): """ Converts the given datetime to the Excel serial format """ if dt.tzinfo: raise ValueError("Doesn't support datetimes with timezones") temp = datetime(1899, 12, 30) delta = dt - temp return delta.days + (float(delta.sec...
3142bfc9d33ddf782c0a6485898e6ed6bcc00418
24,371
from copy import deepcopy def compute_transitive_closure(graph): """Compute the transitive closure of a directed graph using Warshall's algorithm. :arg graph: A :class:`collections.abc.Mapping` representing a directed graph. The dictionary contains one key representing each node in the ...
62a7191759614f495f5297379544fa3cdf77fcfa
24,372
def A_intermediate(f1, f2, f3, v1, v2, v3, d1, d3): """Solves system of equations for intermediate amplitude matching""" Mat = np.array( [ [1.0, f1, f1 ** 2, f1 ** 3, f1 ** 4], [1.0, f2, f2 ** 2, f2 ** 3, f2 ** 4], [1.0, f3, f3 ** 2, f3 ** 3, f3 ** 4], [0....
484c17d0a176a1e666f2ebe447d74f3c83845918
24,373
def _evaluate_criterion(criterion, params, criterion_kwargs): """Evaluate the criterion function for the first time. The comparison_plot_data output is needed to initialize the database. The criterion value is stored in the general options for the tao pounders algorithm. Args: criterion (calla...
bbb0b2cdb4fb4e12d18b6e34c1878a3eaa40059a
24,374
def group_by(collection, callback=None): """Creates an object composed of keys generated from the results of running each element of a `collection` through the callback. Args: collection (list|dict): Collection to iterate over. callback (mixed, optional): Callback applied per iteration. ...
5ca9e3867a1e340da92c223b8ba60a2bdcf2bc0b
24,375
def lemmatize_verbs(words): """lemmatize verbs in tokenized word list""" lemmatizer = WordNetLemmatizer() lemmas = [] for word in words: lemma = lemmatizer.lemmatize(word, pos='v') lemmas.append(lemma) return lemmas
6d37cc6c4f52b062872586f56cb4d459d3fa5cb0
24,376
def loadfromensembl(homology, kingdom='fungi', sequence='cdna', additional='type=orthologues', saveonfiles=False, normalized=False, setnans=False, number=0, by="entropy", using="normal", getCAI=None): """ Load from ensembl the datas required in parameters ( look at PyCUB....
b7c3adee4ba4b61c0828b830b5f53578da75211c
24,377
def dereference(reference_buffer, groups): """ find a reference within a group """ if len(reference_buffer)>0: ref_number = int(''.join(reference_buffer))-1 return groups[ref_number % len(groups)] +' ' return ''
c76234051e81a16f44690de46435e9856996d677
24,378
def get_main_corpora_info(): """Create dict with the main corpora info saved in CORPORA_SOURCES :return: Dictionary with the corpora info to be shown :rtype: dict """ table = [] for corpus_info in CORPORA_SOURCES: corpus_id = CORPORA_SOURCES.index(corpus_info) + 1 props = corpus...
d0a642e98248eabdbaa018991774612f33caca8f
24,379
def start_compare_analysis(api_token, project_id, kind, url, username, password, target_branch, target_revision): """ Get the project identifier from the GraphQL API :param api_token: the access token to the GraphQL API :param project_id: identifier of the project to use as source :param kind: kind ...
10482ed334f5522894b271e9d69803b4c804cb09
24,380
def get_matrix_in_format(original_matrix, matrix_format): """Converts matrix to format Parameters ---------- original_matrix : np.matrix or scipy matrix or np.array of np. arrays matrix to convert matrix_format : string format Returns ------- matrix : scipy matrix ...
837b47ccb4d0bf608907dd13ed1bedd0cb780058
24,381
def get_haystack_response(res, debug=False, chatbot='QA'): """ Function that filters null answers from the haystack response. NOTE: The necessity of this suggests that Deepset's no_ans_boost default of 0 may not be functioning for FARMReader. :param res: :param chatbot: Type of chatbot to get respon...
abb74471c19cc8376cedda41fbf2badebcf0b385
24,382
def _convert_name(name, recurse=True, subs=None): """ From an absolute path returns the variable name and its owner component in a dict. Names are also formatted. Parameters ---------- name : str Connection absolute path and name recurse : bool If False, treat the top level ...
aa331f8616e3996d78a2bd278b10e2e806d56440
24,383
def _orthogonalize(constraints, X): """ Orthogonalize spline terms with respect to non spline terms. Parameters ---------- constraints: numpy array constraint matrix, non spline terms X: numpy array spline terms Returns ------- constrained_X: num...
01eb69ffa30d48c84c76915e33be39b201fda73e
24,384
import time import subprocess def get_shell_output(cmd,verbose=None): """Function to run a shell command and return returncode, stdout and stderr Currently (pyrpipe v 0.0.4) this function is called in getReturnStatus(), getProgramVersion(), find_files() Parameters ---------- cdm: li...
10b10c32ccbe0926d7778b3961d524b6680adc24
24,385
def tril(input, diagonal=0, name=None): """ This op returns the lower triangular part of a matrix (2-D tensor) or batch of matrices :attr:`input`, the other elements of the result tensor are set to 0. The lower triangular part of the matrix is defined as the elements on and below the diagonal. ...
62eb0c83cc633db655859160ea5df1fc0158086a
24,386
import csv def csv_to_objects(csvfile_path): """ Read a CSV file and convert it to a Python dictionary. Parameters ---------- csvfile_path : string The absolute or relative path to a valid CSV file. Returns ------- dict A dict containing a dict of show/episode entries and a dict of movie entrie...
87f28acf5b537a1206126f47a104c87564e76551
24,387
def rename_and_merge_columns_on_dict(data_encoded, rename_encoded_columns_dict, **kwargs): """ Parameters ---------- data_encoded: pandas.DataFrame with numerical columns rename_encoded_columns_dict: dict of columns to rename in data_encoded **kwargs inplace:bool, default=False decides ...
cb8767a102ad421674381182a2ea65468613abee
24,388
from typing import List def _get_public_props(obj) -> List[str]: """Return the list of public props from an object.""" return [prop for prop in dir(obj) if not prop.startswith('_')]
7b3be3e186bc009329ed417c6685fb2503a7c993
24,389
from typing import List def get_vd_html( voronoi_diagram: FortunesAlgorithm, limit_sites: List[SiteToUse], xlim: Limit, ylim: Limit, ) -> None: """Plot voronoi diagram.""" figure = get_vd_figure( voronoi_diagram, limit_sites, xlim, ylim, voronoi_diagram.SITE_CLASS ) html = get_...
1fbec3a3bf2c23d878e9c4b7d1779fb2526560e0
24,390
def sample_normal_mean_jeffreys(s1, ndata, prec): """Samples the mean of a normal distribution""" ## return rn.normal(s1 / ndata, 1 / np.sqrt(prec * ndata))
391cd72ea307903278e94bbc6b323f0997759f10
24,391
from distutils.dir_util import mkpath from distutils.dep_util import newer from distutils.errors import DistutilsFileError from distutils import log import os def copy_tree( src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0, condition=None): ...
ae786a6e207da24e060517a32e0dee99aa159f69
24,392
def pipeline_report_build(submission: Submission, stdout: str, passed: bool, **_): """ POSTed json should be of the shape: { "stdout": "build logs...", "passed": True } :param submission: :param stdout: :param passed: :return: """ if len(stdout) > MYSQL_TEXT_MAX_LE...
cbd07d2642b511f301a7e82581d71de3d04a66c6
24,393
import random def flatten(episode, context_length, include_labels=True, delimiter='\n'): """ Flatten the data into single example episodes. This is used to make conditional training easier and for a fair comparison of methods. """ context = deque(maxlen=context_length if context_length > 0 el...
37c44cb5e442e3d257230f151ce11a0012658ef5
24,394
def calc_binsize(num_bins, t_start, t_stop): """ Calculates the stop point from given parameter. Calculates the size of bins :attr:`binsize` from the three parameter :attr:`num_bins`, :attr:`t_start` and :attr`t_stop`. Parameters ---------- num_bins: int Number of bins t_start:...
0eb42e56aebfd29aa76190b4837171e5cfb94e82
24,395
def d_within(geom, gdf, distance): """Find the subset of a GeoDataFrame within some distance of a shapely geometry""" return _intersects(geom, gdf, distance)
463be3ff9c3eb7f002dc652047b96fbc15ba05b4
24,396
def make_params(args, nmax=None): """Format GET parameters for the API endpoint. In particular, the endpoint requires that parameters be sorted alphabetically by name, and that filtering is done only on one parameter when multiple filters are offered. """ if nmax and len(args) > nmax: ...
406d23a5090b901c20a4ac10dc182fbc3051e61e
24,397
def remap(value, oldMin, oldMax, newMin, newMax): """ Remaps the value to a new min and max value Args: value: value to remap oldMin: old min of range oldMax: old max of range newMin: new min of range newMax: new max of range Returns: The remapped value i...
c0e53ce2b2169b08d271f7077e552762c572cf1f
24,398
async def construct_unit_passport(unit: Unit) -> str: """construct own passport, dump it as .yaml file and return a path to it""" passport = _get_passport_dict(unit) path = f"unit-passports/unit-passport-{unit.uuid}.yaml" _save_passport(unit, passport, path) return path
e4f1e90bbe82b1cb425cf5834fafbd1f36258454
24,399