content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def collaspe_fclusters(data=None, t=None, row_labels=None, col_labels=None, linkage='average', pdist='euclidean', standardize=3, log=False): """a function to collaspe flat clusters by averaging the vectors within each flat clusters achieved from hierarchical clustering""" ## preprocess data if log: data = np.l...
879ba2e9469831b096f716dbbb38047580d76844
19,968
from typing import Union def iapproximate_add_fourier_state(self, lhs: Union[int, QuantumRegister], rhs: QRegisterPhaseLE, qcirc: QuantumCircuit, approximation: int = None) -> Ap...
3e1ccb2576e8babdb589c60aec51f585001bdd9a
19,969
import itertools def _get_indices(A): """Gets the index for each element in the array.""" dim_ranges = [range(size) for size in A.shape] if len(dim_ranges) == 1: return dim_ranges[0] return itertools.product(*dim_ranges)
dc2e77c010a6cfd7dbc7b7169f4bd0d8da62b891
19,970
def calculateOriginalVega(f, k, r, t, v, cp): """计算原始vega值""" price1 = calculatePrice(f, k, r, t, v*STEP_UP, cp) price2 = calculatePrice(f, k, r, t, v*STEP_DOWN, cp) vega = (price1 - price2) / (v * STEP_DIFF) return vega
7b90662003231b50c4d758c3a7beb122b90c05e7
19,971
def to_numpy(tensor): """ Converts a PyTorch Tensor to a Numpy array""" if isinstance(tensor, np.ndarray): return tensor if hasattr(tensor, 'is_cuda'): if tensor.is_cuda: return tensor.cpu().detach().numpy() if hasattr(tensor, 'detach'): return tensor.detach().numpy()...
c5186918fe7a07054607df500d61b32ae1b0037f
19,973
def _maybe_to_dense(obj): """ try to convert to dense """ if hasattr(obj, 'to_dense'): return obj.to_dense() return obj
a2f18aec19bd0bad58a35e772180b94d649262e1
19,976
def update_visit_counter(visit_counter_matrix, observation, action): """Update the visit counter Counting how many times a state-action pair has been visited. This information can be used during the update. @param visit_counter_matrix a matrix initialised with zeros @param observation the state...
418097d34f194c81e38e3d6b122ae743c7b73452
19,977
from datetime import datetime def pandas_time_safe(series): """Pandas check time safe""" return (series.map(dt_seconds) if isinstance(series.iloc[0], datetime.time) else series)
f802d7ad4cd9c9dbf426b2c1436c41402b24da0b
19,978
def binary_cross_entropy_loss(predicted_y, true_y): """Compute the binary cross entropy loss between a vector of labels of size N and a vector of probabilities of same size Parameters ---------- predicted_y : numpy array of shape (N, 1) The predicted probabilities true_y : numpy array o...
ba72db9051976a9d07355a1b246a22faea43b2b1
19,979
def money_flow_index(high, low, close, volume, n=14, fillna=False): """Money Flow Index (MFI) Uses both price and volume to measure buying and selling pressure. It is positive when the typical price rises (buying pressure) and negative when the typical price declines (selling pressure). A ratio of posi...
bd2cbb7b18c7be8d5c0ec0a984c4f3cadf295eec
19,980
def parse_args(args=[], doc=False): """ Handle parsing of arguments and flags. Generates docs using help from `ArgParser` Args: args (list): argv passed to the binary doc (bool): If the function should generate and return manpage Returns: Processed args and a copy of the `ArgPa...
355d8e8722171ab64ebdc02d1fe39db7521a497b
19,981
def gaussian_kernel_dx_i_dx_j(x, y, sigma=1.): """ Matrix of \frac{\partial k}{\partial x_i \partial x_j}""" assert(len(x.shape) == 1) assert(len(y.shape) == 1) d = x.size pairwise_dist = np.outer(y-x, y-x) x_2d = x[np.newaxis,:] y_2d = y[np.newaxis,:] k = gaussian_kernel(x_2d, y_2d, ...
626f38a5a5e1e7c7dd98c92636a424c74fc7146b
19,982
from pathlib import Path import tarfile def clone_compressed_repository(base_path, name): """Decompress and clone a repository.""" compressed_repo_path = Path(__file__).parent / "tests" / "fixtures" / f"{name}.tar.gz" working_dir = base_path / name bare_base_path = working_dir / "bare" with tarf...
bbd733b079ebedb91687597180b0f98825f6ed6c
19,983
def slices(series, length): """ Given a string of digits, output all the contiguous substrings of length n in that string in the order that they appear. :param series string - string of digits. :param length int - the length of the series to find. :return list - List of substrings of specif...
ea2d1caf26a3fc2e2a57858a7364b4ebe67297d6
19,984
from where.models.delay import gnss_range # Local import to avoid cyclical import def get_flight_time(dset): """Get flight time of GNSS signal between satellite and receiver Args: dset(Dataset): Model data Return: numpy.ndarray: Flight time of GNSS signal between satellite and rec...
503bfb55fc10bef9f610291aa0f35e0530c8b0f2
19,985
def textToTuple(text, defaultTuple): """This will convert the text representation of a tuple into a real tuple. No checking for type or number of elements is done. See textToTypeTuple for that. """ # first make sure that the text starts and ends with brackets text = text.strip() if t...
89fed32bff39ad9e69513d7e743eb05a3bf7141a
19,986
def m2m_bi2uni(m2m_list): """ Splits a bigram word model into a unique unigram word model i=11, j=3 i=10, j=3 i=9,10,11,12, j=3,4,5,6 ###leilatem### ###leilatem### ###leilatem### ###temum### ###temum### ###temum### ^ ...
37f1644dc16bc0e4dd47acd7a69f1c2d6fbfc6d5
19,987
import time def time_func(func): """Times how long a function takes to run. It doesn't do anything clever to avoid the various pitfalls of timing a function's runtime. (Interestingly, the timeit module doesn't supply a straightforward interface to run a particular function.) """ def timed(*a...
3506ad28c424434402f3223a43daff4eb51b7763
19,988
def GetPhiPsiChainsAndResiduesInfo(MoleculeName, Categorize = True): """Get phi and psi torsion angle information for residues across chains in a molecule containing amino acids. The phi and psi angles are optionally categorized into the following groups corresponding to four types of Ramachandran plo...
07295d99f3f2150e4a9e0782bf376ac1aa22a499
19,989
def generate_data(n_samples=30): """Generate synthetic dataset. Returns `data_train`, `data_test`, `target_train`.""" x_min, x_max = -3, 3 x = rng.uniform(x_min, x_max, size=n_samples) noise = 4.0 * rng.randn(n_samples) y = x ** 3 - 0.5 * (x + 1) ** 2 + noise y /= y.std() data_train = p...
f7d2f5637327119d5f08fe2ccbfe2d4f41a34c5c
19,990
def get_element_event(element_key): """ Get object's event. """ model = apps.get_model(settings.WORLD_DATA_APP, "event_data") return model.objects.filter(trigger_obj=element_key)
bd177573035209e97110a2213cbe98b3b2eadafb
19,991
import operator def get_seller_price(sellers,seller_id,core_request): """ sellers is a list of list where each list contains follwing item in order 1. Seller Name 2. Number of available cores 3. Price of each core 4. List of lists where length of main list is equal to number of cores. Length of minor list will ...
a1103b05409cdab20dd1982f5839a712939c3c3f
19,992
def create_affiliation_ttl(noun_uri: str, noun_text: str, affiliated_text: str, affiliated_type: str) -> list: """ Creates the Turtle for an Affiliation. @param noun_uri: String holding the entity/URI to be affiliated @param noun_text: String holding the sentence text for the entity @param affiliat...
d641a5aa77860dad48c605b3486bc83c0250d551
19,993
from typing import Tuple def get_subpixel_indices(col_num: int) -> Tuple[int, int, int]: """Return a 3-tuple of 1-indexed column indices representing subpixels of a single pixel.""" offset = (col_num - 1) * 2 red_index = col_num + offset green_index = col_num + offset + 1 blue_index = col_num + of...
cb4a1b9a4d27c3a1dad0760267e6732fe2d0a0da
19,994
def sigmoid(x): """ This function computes the sigmoid of x for NeuralNetwork""" return NN.sigmoid(x)
534391dc7b39aede21e6a66692bc1ca2ea1ce8b6
19,995
def extractTranslatingSloth(item): """ 'Translating Sloth' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None tagmap = [ ('娘子我才是娃的爹', 'Wife, I Am the Baby\'s Father', 'translated'), ...
0ed9f5d4ae4c69fae2dc46e0260e29d1c97225af
19,996
def human(number: int, suffix='B') -> str: """Return a human readable memory size in a string. Initially written by Fred Cirera, modified and shared by Sridhar Ratnakumar (https://stackoverflow.com/a/1094933/6167478), edited by Victor Domingos. """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z'...
b41e9014ee7afbacb40115f85223ae89b08094a8
19,997
def _get_field_names(field: str, aliases: dict): """ Override this method to customize how :param field: :param aliases: :return: """ trimmed = field.lstrip("-") alias = aliases.get(trimmed, trimmed) return alias.split(",")
cb732c07018c33a546bf42ab1bf3516d2bd6c824
19,998
def get_answer(question_with_context): """ Get answer for question and context. """ # Create pipeline question_answering_pipeline = pipeline('question-answering') # Get answer answer = question_answering_pipeline(question_with_context) # Return answer return answer
ba560ecf5aa07a59b697465e0c34c8b32ddf64e6
19,999
import numpy def undiskify(z): """Maps SL(2)/U(1) poincare disk coord to Lie algebra generator-factor.""" # Conventions match (2.13) in https://arxiv.org/abs/1909.10969 return 2* numpy.arctanh(abs(z)) * numpy.exp(1j * numpy.angle(z))
9ac4cd521ca64decd082a34e35e0d080d3190e13
20,000
def mean_vertex_normals(vertex_count, faces, face_normals, **kwargs): """ Find vertex normals from the mean of the faces that contain that vertex. Parameters ----------- vertex_count : int The number of vertices faces...
767214b5c2ba701de5288009ee4ebfb90378446c
20,001
def get_beam_jobs(): """Returns the list of all registered Apache Beam jobs. Returns: list(BeamJob). The list of registered Apache Beam jobs. """ return [beam_job_domain.BeamJob(j) for j in jobs_registry.get_all_jobs()]
24e22d487fdbdb02917011e94a6d5b985de67640
20,002
def z_norm(dataset, max_seq_len=50): """Normalize data in the dataset.""" processed = {} text = dataset['text'][:, :max_seq_len, :] vision = dataset['vision'][:, :max_seq_len, :] audio = dataset['audio'][:, :max_seq_len, :] for ind in range(dataset["text"].shape[0]): vision[ind] = np.nan...
8cf40069b2a8c042d357fab3b1e3aaf13c15c69e
20,003
def days_upto(year): """ Return the number of days from the beginning of the test period to the beginning of the year specified """ return sum([days_in_year(y) for y in range(2000,year)])
f87295a53d839e2ce895ef5fe5490b77377d28eb
20,004
def choose_field_size(): """a function that crafts a field""" while True: print('Пожалуйста, задайте размер поля (число от 3 до 5):') try: field_size = int(input()) except ValueError: continue if field_size == 3: print('\nПоле для игры:\n') ...
ed370aca1f13a9f93bb96e483885c67e1bd30317
20,006
def delete_submission_change(id): """Delete a post. Ensures that the post exists and that the logged in user is the author of the post. """ db = get_db() db.execute('DELETE FROM submission_change WHERE id = ?', (id,)) db.commit() return jsonify(status='ok')
a886dfd89939ca10d95877bd16bda313ccb9353d
20,007
from datetime import datetime def get_search_response(db, search_term): """Method to get search result from db or google api. Args: db: The database object. search_term: The search term. Returns: String: List of relevant links separated by line break. """ # Find if the s...
11180ad1ee57d2a778439fd260d5201d3723cfe7
20,008
def lattice_2d_rescale_wave_profile(kfit, X, dT, Z_C, Y_C, v, dx=1.): """ Fit the wave profile (X, dT) to the ODE solution (X_C, dT_C) """ # recenter the profile around 0 k0 = np.argmax(dT) x0 = X[k0] Z = kfit*(X.copy()-x0) # retain a window corresponding to the input ODE solution z...
8caea59a092efd9632e4b705400f40aa0ebbec44
20,009
def extent_switch_ijk_kji( extent_in: npt.NDArray[np.int_]) -> npt.NDArray[np.int_]: # reverse order of elements in extent """Returns equivalent grid extent switched either way between simulator and python protocols.""" dims = extent_in.size result = np.zeros(dims, dtype = 'int') for d in range...
c960591fa1f3b31bd0877fd75845a17fff8eff50
20,010
def create_data(f, x_vals): """Assumes f is a function of one argument x_vals is an array of suitable arguments for f Returns array containing results of applying f to the elements of x_vals""" y_vals = [] for i in x_vals: y_vals.append(f(x_vals[i])) return ...
5f74402586c3f7d02c8d6146d5256dbccdf49e81
20,011
def register(): """注册""" req_dict = request.get_json() phone = req_dict.get("phone") password = req_dict.get("password") password2 = req_dict.get("password2") sms_code = req_dict.get("sms_code") phone = str(phone) sms_code = str(sms_code) # 校验参数 if not all([phone, password, pass...
f9e6bc8dc30cb967843d0f47fada1b4b62c6b130
20,012
def cpp_flag(compiler): """Return the -std=c++[11/14/17] compiler flag. The newer version is prefered over c++11 (when it is available). """ flags = ["-std=c++17", "-std=c++14", "-std=c++11"] for flag in flags: if has_flag(compiler, flag): return flag raise RuntimeError( ...
a21a0a8efcad62cc26ff033877c366d7d6acf09d
20,013
def to_null(string): """ Usage:: {{ string|to_null}} """ return 'null' if string is None else string
1868ca2c7474a8134f2dbb0b0e542ca659bf4940
20,014
import warnings def get_mtime(path, mustExist=True): """ Get mtime of a path, even if it is inside a zipfile """ warnings.warn("Don't use this function", DeprecationWarning) try: return zipio.getmtime(path) except IOError: if not mustExist: return -1 raise
6c661fb5d7a874a8173ec509b07401e2120da95b
20,015
def get_table_8(): """表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数 Args: Returns: list: 表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数 """ table_8 = [ (0.9, 1.0), (0.9, 1.0), (1.0, 1.0) ] return table_8
89470f0242982755104dbb2afe0198e2f5afa5f4
20,016
import requests import warnings def query_epmc(query): """ Parameters ---------- query : Returns ------- """ url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=" page_term = "&pageSize=999" ## Usual limit is 25 request_url = url + query + page_term r =...
a8da1ee3253d51738f1d556548f6bccf17b32b53
20,017
def is_default_array_type(f, type_map=TYPE_MAP): """ Check whether the field is an array and is made up of default types, e.g. u8 or s16. """ return f.type_id == 'array' and type_map.get(f.options['fill'].value, None)
ec0e7a26261cc72e473d2c365bc452b2eeab396f
20,018
def delete_police_station_collection(): """ Helper function to delete station collection in db. """ result = PoliceStation.objects().delete() return result
7b3cc89269695fa494eb12a7b904fabd1974f3d8
20,019
def compute_asvspoof_tDCF( asv_target_scores, asv_nontarget_scores, asv_spoof_scores, cm_bonafide_scores, cm_spoof_scores, cost_model, ): """ Compute t-DCF curve as in ASVSpoof2019 competition: Fix ASV threshold to EER point and compute t-DCF curve over thresholds in CM. ...
27819737d7a1a84db10d78cce4c5edd16548e774
20,020
def all_divisor(n, includeN=True): """ >>> all_divisor(28) [1, 2, 4, 7, 14, 28] >>> all_divisor(28, includeN=False) [1, 2, 4, 7, 14] Derived from https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56 """ lower_divisors, upper_divisors = [], [] i = 1 while i * i <= n: i...
2fa0eb58eac30030cfbbfdcce62bc91cb36f218e
20,021
def isTrue(value, noneIsFalse=True): """ Returns True if <value> is one of the valid string representations for True. By default, None is considered False. """ if not value: if noneIsFalse: return False else: return None else: return value.lower() in TRUE_STRINGS
16e69dc43ef2034d210803e8cc3ebf2ae13e13b2
20,022
import pickle def read_doc_labels(input_dir): """ :param input_dir: :return: doc labels """ with open(input_dir + "doc_labels.pkl", 'rb') as fin: labels = pickle.load(fin) return labels
c0246f8e09441782a7437177877cc1e4d83ecb40
20,023
def search(catalog_number): """ A top level `catalog_number` search that returns a list of result dicts. Usually catalog numbers are unique but not always hence the returned list. """ results = query(catalog_number) result_list = [] for result in results: dict_result = vars(result)["...
2a8ce325250cbaa5a9f307ef707c74c5101d84d3
20,025
def calculate_mean_probas(time_ser, model): """Calculate the metric to evaluate based on average probabilities Args: time_ser (np.ndarray): dynophore time series model (HMM): Fitted HMM Returns: np.float: Probability of prediting the given time series based on the fitted model ...
b8320a24c01e56c89b5d706630190a118d803ffa
20,027
def compute_t(i, automata_list, target_events): """ Compute alphabet needed for processing L{automata_list}[i-1] in the sequential abstraction procedure. @param i: Number of the automaton in the L{automata_list} @type i: C{int} in range(1, len(automata_list)+1) @param automata_list: List of a...
88fc64aaf917d23a29e9400cf29705e6b20665c3
20,028
def cal_min_sim(y): """Calculate the minimal value given multiple trajectories from different isomers""" y = y.copy() if len(y.shape) == 2: # add one more dimension if only two provided y = y[np.newaxis, :] n_sim, nT, nP = y.shape y_min_sim = np.min(y, axis = 0) return y_min_...
efbee1f3d8a88ac447609019a431d3ac6469f2cf
20,029
async def create_rsa_key( hub, ctx, name, vault_url, key_ops=None, enabled=None, expires_on=None, not_before=None, tags=None, **kwargs, ): """ .. versionadded:: 2.0.0 Create a new RSA key or, if name is already in use, create a new version of the key. Requires the ke...
f22a520bc82bed0447440a80639a1f6ef575e718
20,030
import re def _parse_size_string(size): """ Parse a capacity string. Takes a string representing a capacity and returns the size in bytes, as an integer. Accepts strings such as "5", "5B", "5g", "5GB", " 5 GiB ", etc. Case insensitive. See `man virsh` for more details. :param size: The size...
6ad10ba10380eaa7a8acd6bbeb52b537fdcf3864
20,031
def get_exp_lr(base_lr, xs, power=4e-10): """Get learning rates for each step.""" ys = [] for x in xs: ys.append(base_lr / np.exp(power*x**2)) return ys
58486de08742d2467a4178d1ac0544c0d1f2055c
20,033
import time def dashboard(): """ Main dashboard function. Run stats across all accounts. """ start = time.time() instance_count = 0 user_count = 0 sg_count = 0 elb_count = 0 aws_accounts = AwsAccounts() accounts = aws_accounts.all() pool = Pool(10) results = pool.map(get_acco...
e5138d8527ecb5712db6205757432d31efde8f2b
20,034
def strip_new_line(str_json): """ Strip \n new line :param str_json: string :return: string """ str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings return str_json
f2faaa80dca000586a32a37cdf3dff793c0a2d9b
20,035
def fromAtoB(x1, y1, x2, y2, color='k', connectionstyle="arc3,rad=-0.4", shrinkA=10, shrinkB=10, arrowstyle="fancy", ax=None): """ Draws an arrow from point A=(x1,y1) to point B=(x2,y2) on the (optional) axis ``ax``. .. note:: See matplotlib documentation. """ if ax is No...
a7b14ae62d26f203da0fb3f26c7aa7652fb9a345
20,036
import torch def exp(input_): """Wrapper of `torch.exp`. Parameters ---------- input_ : DTensor Input dense tensor. """ return torch.exp(input_._data)
01449c87486a7145b26d313de7254cb784d94a7b
20,037
from datetime import datetime def get_lat_lon(fp, fs=FS): """ get lat lon values for concat dataset """ logger.info(f"{str(datetime.datetime.now())} : Retrieving lat lon") with xr.open_dataset(fs.open(fp)) as ds: lat, lon = ds["latitude"].values, ds["longitude"].values logger.info(f"{s...
a99614463121edb99c290ddea8d6bb7b298498f1
20,039
def one_hot_encode(vec, vals=10): """ For use to one-hot encode the 10- possible labels """ n = len(vec) out = np.zeros((n, vals)) out[range(n), vec] = 1 return out
079c4c505464659248631b3e5c3d1345557d922b
20,040
def COUNTA(*args) -> Function: """ Returns a count of the number of values in a dataset. Learn more: https//support.google.com/docs/answer/3093991 """ return Function("COUNTA", args)
c8e876e80a0414eab915b6eb0efc9917b12edb19
20,041
import json def decode_url_json_string(json_string): """ Load a string representing serialised json into :param json_string: :return: """ strings = json.loads(h.unescape(json_string), object_pairs_hook=parse_json_pairs) return strings
6f616e5e6037024ebdab6e63aa90c13c60fca40c
20,042
def svn_wc_merge2(*args): """ svn_wc_merge2(enum svn_wc_merge_outcome_t merge_outcome, char left, char right, char merge_target, svn_wc_adm_access_t adm_access, char left_label, char right_label, char target_label, svn_boolean_t dry_run, char diff3_cmd, apr_array_header_t merge...
271e596810b7ee604532f34612e349ae30b108c5
20,044
import torch def test_finetuning_callback_warning(tmpdir): """Test finetuning callbacks works as expected.""" seed_everything(42) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.backbone = nn.Linear(32, 2, bias=False) self...
c7bec2c256ece471b0f3d9f56a74dcb2c7ad186a
20,045
from contextlib import suppress def idempotent(function): """Shallows 304 errors, making actions repeatable.""" @wraps(function) def decorator(*args, **kwargs): with suppress(GitlabCreateError): return function(*args, **kwargs) return decorator
4012ce715a8344a7a9eb7e27a7d96f0e3b9c8f6d
20,046
def newline_formatter(func): """ Wrap a formatter function so a newline is appended if needed to the output """ def __wrapped_func(*args, **kwargs): """ Wrapper function that appends a newline to result of original function """ result = func(*args, **kwargs) # Th...
71af6af25aa93e0e8f80958b5caf5266f598c878
20,047
from typing import List from typing import Tuple def sigma_splitter(float_arr: List[float]) -> Tuple[List[List[int]], List[List[int]], List[List[int]]]: """ separates the NCOF score into the 1-3 sigma outliers for the NCOF input @param float_arr: List[float] @return: inliers , pos_outliers , neg_outli...
824c3d11ffa1fb81763cdf815de3e37a7b8aa335
20,048
import torch def cosine_beta_schedule(timesteps, s = 0.008, thres = 0.999): """ cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ """ steps = timesteps + 1 x = torch.linspace(0, timesteps, steps, dtype = torch.float64) alphas_cumprod = torch.cos(((x / timesteps) + s...
a1969deafdb282955a53b15978a055d15f0678a0
20,049
from typing import Callable from re import T from typing import Optional from typing import Dict from typing import Any import yaml def construct_from_yaml( constructor: Callable[..., T], yaml_dict: Optional[Dict[str, Any]] = None, ) -> T: """Build ``constructor`` from ``yaml_dict`` Args: con...
5cb92f8af0b0ab49069e88b74b7b10fdf2cc797d
20,050
import tokenize def text_to_document(text, language="en"): """ Returns string text as list of Sentences """ splitter = _sentence_splitters[language] utext = unicode(text, 'utf-8') if isinstance(text, str) else text sentences = splitter.tokenize(utext) return [tokenize(text, language) for text in s...
2f196c51a979a2f9a849ebd6f89203c907406789
20,051
def get_top_playlists_route(type): """ An endpoint to retrieve the "top" of a certain demographic of playlists or albums. This endpoint is useful in generating views like: - Top playlists - Top Albums - Top playlists of a certain mood - Top playlists of a certain mood from pe...
2012e95073291669a6bb881afa853961922160c5
20,052
import urllib def parse_host(incomplete_uri: str) -> str: """Get netloc/host from incomplete uri.""" # without // it is interpreted as relative return urllib.parse.urlparse(f"//{incomplete_uri}").netloc
099284e970756055f2616d484014db210cb04a76
20,053
import functools import operator def inner_by_delta(vec1: Vec, vec2: Vec): """Compute the inner product of two vectors by delta. The two vectors are assumed to be from the same base and have the same number of indices, or ValueError will be raised. """ indices1 = vec1.indices indices2 = vec2...
660f7d73e6d73cd4dfdf73d532e90e5a29f38481
20,054
def remove_mapping(rxn_smi: str, keep_reagents: bool = False) -> str: """ Removes all atom mapping from the reaction SMILES string Parameters ---------- rxn_smi : str The reaction SMILES string whose atom mapping is to be removed keep_reagents : bool (Default = False) whether to...
fb16648fee136359bc8ef96684824319221a3359
20,055
def generate_bot_master_get_results_message(message_id, receiving_host, receiving_port): """ :rtype : fortrace.net.proto.genericmessage_pb2.GenericMessage :type receiving_port: int :type receiving_host: str :type message_id: long :param message_id: the id of this message :param receiving_ho...
4c46a9c1bf69022092b7df4b48e302a87d2d7b90
20,056
import fileinput from datetime import datetime def readLogData(username,level,root='.'): """ Extracts key events from a log """ filename = getFilename(username,level,extension='log',root=root) log = [] start = None for line in fileinput.input(filename): elements = line.split() ...
f94c3e715d021b206ef46766fdc0e6051784615e
20,057
def get_type1(pkmn): """get_type1(pkmn) returns Type 1 of the Pokémon with the name 'pkmn' """ return __pokemon__[pkmn]['Type 1']
c4290f695160f2f1962f1dca158359e250a4803a
20,058
def load_json(fname): """ Load a JSON file containing a riptide object (or list/dict/composition thereof) """ with open(fname, 'r') as f: return from_json(f.read())
93f771ae0ba31974b564e1520412fab5719b08be
20,059
def get_stock_data(symbol, start_date, end_date, source="phisix", format="c"): """Returns pricing data for a specified stock and source. Parameters ---------- symbol : str Symbol of the stock in the PSE or Yahoo. You can refer to these links: PHISIX: https://www.pesobility.com/...
94171c950198f0975c4232f232ec9be93bd3f2a3
20,060
def extract_borderless(result) -> list: """ extracts borderless masks from result Args: result: Returns: a list of the borderless tables. Each array describes a borderless table bounding box. the two coordinates in the array are the top right and bottom left coordinates of the bounding box. ...
e81844a5deb553bf8d7380ebec8a76fec219ee72
20,061
import itertools def get_frequent_length_k_itemsets(transactions, min_support=0.2, k=1, frequent_sub_itemsets=None): """Returns all the length-k itemsets, from the transactions, that satisfy min_support. Parameters ---------- transactions : list of list min_support : float, optional F...
a293b48c62ebbafda7fa89abb6792f04c4ff1371
20,062
import types def create_news_markup(): """ Метод, создающий клавиатуру для новостей кино :return: telebot.types.ReplyKeyboardMarkup """ news_markup = types.ReplyKeyboardMarkup() news_markup.row(Commands.GET_BACK_COMMAND) return news_markup
654ec227d07fe914c795931f48ce634e0a4a6fc3
20,063
def _generate_description_from(command, name, description): """ Generates description from the command and it's optionally given description. If both `description` and `command.__doc__` is missing, defaults to `name`. Parameters ---------- command : `None` or `callable` The command's fu...
e2f782f7e74635b3c50273b36b837e48d7999f4f
20,065
def uses_na_format(station: str) -> bool: """ Returns True if the station uses the North American format, False if the International format """ if station[0] in NA_REGIONS: return True elif station[0] in IN_REGIONS: return False elif station[:2] in M_NA_REGIONS: retur...
b3158a85ae9b1ba45ebeb3de27491650d7f4c4c8
20,066
def openFile(prompt,key = "r",defaulttype = None, defaultname = None): """ Method to open a text file with sanity checking, optional defaults and reprompt on failure. This is the main used callable function to open files. :param prompt: the prompt to be displayed :type prompt: str :param key: ...
e9985872c0beb15eaa5bafa543eefb01f5fd8413
20,067
def dsphere(n=100, d=2, r=1, noise=None, ambient=None): """ Sample `n` data points on a d-sphere. Parameters ----------- n : int Number of data points in shape. r : float Radius of sphere. ambient : int, default=None Embed the sphere into a space with ambient dimensi...
8957a328c2025fbdb3741b004f2fb3825f19e4d9
20,068
def topological_sort_by_down(start_nodes=None, all_nodes=None): """ Topological sort method by down stream direction. 'start_nodes' and 'all_nodes' only one needs to be given. Args: start_nodes (list[NodeGraphQt.BaseNode]): (Optional) the start update nodes of the graph. all...
22a36d4f8225ae2978459796f115059e2bbb8d62
20,069
from datetime import datetime def parseYear(year, patterns): """"This function returns a string representing a year based on the input and a list of possible patterns. >>> parseYear('2021', ['%Y']) '2021' >>> parseYear('2021', ['(%Y)', '%Y']) '2021' >>> parseYear('(2021)', ['%Y', '(%Y)']) '2021' """ ...
743378c868a2439f721e428f676092f9da0a2e7a
20,072
def fit_oxy_nii(target_row, velocity_column = None, data_column = None, IP = "center", **kwargs): """ Fits oxygen bright line to spectrum for future subtraction Parameters ---------- target_row: `SkySurvey` row ...
1251bf102abaec690fc97117c2409e2f5e89f35b
20,073
def image_reproject_from_healpix_to_file(source_image_hdu, target_image_hdu_header, filepath=None): """ reproject from healpix image to normal wcs image :param source_image_hdu: the HDU object of source image (healpix) :param target_image_hdu_header: the HDU object of target image (wcs) :param f...
b261663f18ccdf095c0b6e20c02d2ebc0282b713
20,075
def flux_reddening_wl(wl, flux_wl, ebv, Rv=None, law=LawFitz, mode=ReddeningLaw.MW): """ Apply extinction curves to flux(lambda) values :param wl: [A] :param flux_wl: [ergs s^-1 cm^-2 A^-1] :param ebv: E(B-V) :param Rv: R_V :param law: the variant of extinction curves :param mode: type...
668d1824d988989a3411c798614aeb1bc6a63cb6
20,076
import string def genRandomString( size: int = 5, upper: bool = False, lower: bool = False, mix: bool = False, numbers: bool = True) -> str: """ Generates a random string of the given size and content. :param numbers: Numbers are included in the string. Default True. :param upper: Uppercase only. Default False. ...
a63a2be76675bbb42da2a4cd0ae20db8be723ee3
20,077
def process_whole_image(model, images, num_crops=4, receptive_field=61, padding=None): """Slice images into num_crops * num_crops pieces, and use the model to process each small image. Args: model: model that will process each small image images: numpy array that is too big for model.predic...
3e9ab9485662f9bae40217c60837d8d8cba020d3
20,078
def compute_covariance(model, xy, XY=None): """Returns the covariance matrix for a given set of data""" if xy.size == 1: dist = 0 elif XY is None: dist = squareform(pdist(xy)) else: dist = cdist(xy, XY) C = model(dist) return C
b898ef57155898c75797033e057c6cab4e2487bc
20,079
import sqlite3 def prob1(cur: sqlite3.Cursor) -> pd.DataFrame: """List how many stops are in the database. Parameters ---------- cur (sqlite3.Cursor) : The cursor for the database we're accessing. Returns ------- (pd.DataFrame) : Table with the solution. """ cur.execu...
ed6a3a316e89177a6224fd7513ca5c098940e312
20,080