content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def first_alpha(s): """ Returns the length of the shortest substring of the input that contains an alpha character. """ for i, c in enumerate(s): if c.isalpha(): return i + 1 raise Exception("No alpha characters in string: {}".format(s))
7cccb3a5721323f8084731a587c6718bbe2dd368
667,774
import os import torch def load_checkpoint(model, save_dir): """Load the model and training parameters. Args: model (nn.Module): Model to import. save_dir (str): Path to the model. Returns: Model stored in the checkpoint. """ assert os.path.isfile(save_dir) assert save_dir.split('.')[1] == 'pth' ch...
ad07df9172b65f4d933409cee379ce90ab6ac442
667,776
def vswr_to_gama(vswr): """Calculate Gama (Reflection Coefficient) from VSWR""" gama = (vswr-1)/(vswr+1) return gama
cf3416b7dab6856606b764226ea359386dcafb80
667,777
import argparse def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Self Correction for Human Parsing") parser.add_argument("--dataset", type=str, default='lip', choices=['lip', 'atr', '...
2b11ecc9a4ff8d64c4546518909ad42f4d1b65f6
667,778
def lerp(a, b, pos) -> float: """### Basic linear interpolation. This method returns a value between the given `a`->`b` values.\n When `pos=0` the return value will be `a`.\n When `pos=1` the turn value will be the value of `b`. `pos=0.5` would be\ half-way between `a` and `b`. """ lerp...
52039693bd702d4b41c219ac4667ebc2832b407e
667,779
def __get_codeclimate_severity(cpio_severity: str) -> str: """Get Code Climate severity, from CppCheck severity string CodeQuality: info, minor, major, critical, blocker """ map_severity_to_severity = { "high": "critical", "medium" : "major", "low" : "minor" } return map...
07b86d9a696eaf486dce4051a12c046a8087c85d
667,780
def category_data(c3): """Test data to make changes for validation or customization (testing).""" return {"name": "CMS development", "parent": c3}
1e6f206882b9ee96a719b1fb482c1e62f742c0cf
667,781
def fmt_given_desc(desc): """Additional formatting for a web UI with the base description.""" # Ensure always ends with period. if not desc.endswith('.'): desc += '.' # Capitalize first letter. desc = '{}{}'.format(desc[0].upper(), desc[1:]) return desc
4c3fb2f155e8465dd6fa9af879a1cd7f7908a002
667,782
def muodostaPaivamaara(rivi): """Funktion lue apufunktio, joka parsii yhden rivin päivämäärän oikeaan muotoon.""" rivi = rivi[0:16].replace('-',' ') #Otetaan päivämäärä sarake talteen ja muutetaan erotin väliksi. rivi = rivi.split(" ") #Nyt splitillä saa järkevästi jaettua päivämäärä sarakkeen tiedot, kun s...
5ae19a083bcf87ca75b63cb7803e6f20f04d955a
667,783
import torch def padding_all(vec, max_len): """ vec: [n, len, feat] """ n = vec.shape[0] vec_len = vec.shape[1] padded = torch.cat([vec, torch.zeros((n,max_len-vec_len,20), dtype=torch.double)], dim=1).data return padded
21b2347f6d5b010c939d541022d60b9db85b3a70
667,784
def change_parameter_unit( parameter_dict: dict, multiplier: float ) -> dict: """ Currently only used to adapt the latency parameters from the earlier functions according to whether they are needed as by year rather than by day. Could be more generally applicable. Args: parameter_dict:...
e3138e7c017e967f94f2c23b7c1937ee1a78a2d6
667,785
def all_annotations(num, test) -> None: """All arguments require annotations >>> no_annotations(1, "a") None """ return None
b7f710c6b0ec29b373a86bea48b2aec4296bfe86
667,786
def is_in(elements, value): """ Determines if a value is in a list. It also handles degenerate cases when instead of a list, elements is True, False or None """ if not elements: return False elif elements is True: return True else: return value in elements
7d1c44966bd7eeaa8c4919d3d835ed13c6466ce7
667,787
def flip(x, axis=0): """ 按axis指定的轴翻转,轴可正索引,可负索引。超出范围将忽略 """ if isinstance(axis, int): axis = [axis] axis = [ax if 0 <= ax else ax+x.ndim for ax in axis] return x[[slice(-1, -1-x.shape[dim], -1) if dim in axis else slice(None, None, None) for dim in range(x.ndim)]]
0104b63947914c46dd3b87cf71537eed10534072
667,788
def Region(main): """This function creates the region and set the boundaries to the machine analysis by FEM. Args: main (Dic): Main Dictionary than contain the necessary information. Returns: Dic: unmodified main dictionary. """ oEditor = main['ANSYS']['oEditor'] oDesign...
24e414f1664d3d57ac1552fa6d2e820e67334faf
667,789
def parse_endpoint(endpoint): """ Parse endpoint into (blueprint, endpoint). blueprint can be :const:`None` """ if '.' in endpoint: return endpoint.split('.', 1) return None, endpoint
ad1960367d1cd768641fd46dc4a8ef8886340d5e
667,791
def dict_swap(d): """ Swap dictionary keys and values. :type d: dict """ done = {} for k, v in d.items(): done[v] = k return done
4c050534fc0d3b4e5d6fcbf45ea51b43ae70cfb4
667,792
def combine_args(supported_args, *arg_sets): """ Combine args with priority from first in the list to last in the list """ base_dict = arg_sets[0] sup_arg_dict = {arg['name']: arg['arg_params'] for arg in supported_args} for i in range(1,len(arg_sets)): this_dict = arg_sets[i] if this_di...
8203b2e82b46ff2608b626fa7fb2aceaae15ae35
667,793
def internal_visibility_allowlist(): """Returns a list of the packages that can depend on internal targets.""" return []
6c4d8345d40c1794448b10e5cd32bbe0b793f1c3
667,794
def derp(term): """this does something Returns: [str] -- [a dumb string] """ if term == "poop": return "gross" elif term == "hotdog": return "yum" else: return None
4d09b5eded7b04ddd0eef07efeddee16c1a1c561
667,795
import copy def merge_dict(bot, top): """Helper function for merging dict fields over another dict. Merge top dict onto bot dict, so that the returned new dict has the updated top vals.""" new = copy.deepcopy(bot) for k, v in top.items(): new[k] = v return new
e52acd0bf1864cf8adb47b8ce85179fb74c25269
667,796
def add_2_nums(first_list, second_list): """ Ex : input: first_list = [2, 4, 3] second_list = [5, 6, 4] output: third_list = [7, 0, 8] :intype first_list: List[int] :intype second_list: List[int] :rtype List[int] """ res = [] first_num = int("".join(map(s...
f156157165a088f4a28297ce643cbb6feb8d1d84
667,797
def get_gene_capacity(genes_df, database, col='GeneID'): """Get gene capcaity from the stored metadata""" capacity = (database.groupby('geneid').capacity.mean() .to_frame(name='GeneCapacity')) genes_df = genes_df.merge(capacity, how='left', left_on='GeneID', right_index=True) return gene...
f2091adedea143e46df3a6c18822bdbbc8e27f7f
667,798
def valid_parentheses(string): """.""" stack = [] for i in string: if i == '(': stack.append(0) elif i == ')': if stack == []: return False else: stack.pop() return stack == []
695648a4383ea528359ea2bb213f54a19d90e8da
667,800
import json def get_model_id_list(redis): """ Get the list of model ids """ ids = redis.get("m:ids") or "{}" return json.loads(ids)
65ef7d7884b0d93d4ce84f3fdb37feaae642d537
667,801
def min_max_mormalization_1(x): """[0 1]""" return [(float(i) - min(x)) / float(max(x) - min(x)) for i in x]
e04dd8bc6999b030840e57e7157de18fe58eb572
667,802
import random def get_random_string(characters, length=8): """ Returns a string of the requested length consisting of random combinations of the given sequence of string characters. """ return ''.join(random.choice(characters) for _ in range(length))
f0df5cc9b40f331ddead3cb05930b9dd4066101f
667,804
def graph_list_to_features(graphs): """Get a TFRecord feature dictionary from a list of graphs. The features from each graph is prepended with a prefix and all added to the final dictionary at the same level. Parameters ---------- graphs : [Graph] Returns ------- features : dict (...
97728caa1e5aedbb9e404b39fb6174361dd2b0cd
667,805
def mkdir_cmd(path): """Return mkdir command""" return " ".join(["/bin/mkdir", "-p", path])
7172eaab58c15541394fa3f3a67d21cdb9d5e04a
667,806
def vsbyfmt(val): """Tricky formatting of vis""" val = round(val, 3) if val == 0: return 0 if val <= 0.125: return "1/8" if val <= 0.25: return "1/4" if val <= 0.375: return "3/8" if val <= 0.5: return "1/2" if val <= 1.1: return "1" if...
0a9d0bc2ae097844c82e03862beba5a4dbec7532
667,807
def deck_measurer(decklist, lda): """ Given a decklist and a trained tomotopy LDAModel(), returns the likelihood that the given deck is associated with the model's topics. Parameters: decklist: list of str A single decklist represented as a list of card names (strings). l...
de24a2d6fd98d4dfbb386f7c76a6e142660eb166
667,808
def transform_region_to_coordinates(x_coord, y_coord, prefix_len, image_bit_level=10): """Transforms (x,y)-bit region into a square for a final level. This method converts a leaf on some level `prefix_le...
7ac371e69279e45ee11d6cd97a289f0d530d9960
667,809
from typing import Optional def join_address_and_port(address: Optional[str], port: int) -> str: """ Join address and port using format "{address}:{port}". :param address: The address. If not given, "localhost" is used. :param port: The port number. :return: Joined address and port. """ r...
3243875396292d2b6528f5475f43055f7515f973
667,810
def capitalize(text): """<string> -- Capitalizes <string>. :type text: str """ return ". ".join([sentence.capitalize() for sentence in text.split(". ")])
e38eee5d51ffcb8c8a148979de24dc00df6a0a42
667,811
def home(): """List all available api routes.""" return"""<html> <h1>List of all available Honolulu, HI API routes</h1> <ul> <br> <li> Return a list of precipitations from last year: <br> <a href="/api/v1.0/precipitation">/api/v1.0/precipitation</a> </li> <br> <li> Re...
ad19400e9b157fa356c896097ce02c305ebb95de
667,812
def today(): """ Return today's schedule from the user's calendar. This path operation will: * return a map of events """ return {"Today is a great day!"}
fd0efbdb3242204671330febed015cb4f991846f
667,813
def merge_st(S1, S2): """Merge two sorted Python Lists S1 and S2 into properly sized list S""" i = j = 0 S = S1+S2 while i+j < len(S): if j == len(S2) or (i < len(S1) and S1[i] < S2[j]): S[i+j] = S1[i] i = i+1 else: S[i+j] = S2[j] j = j+1 ...
5d8f202d30af988971c6e797313f2d82bd08c285
667,815
import re def format_prefix(data): """ pipe and backslash in header must be escaped. escape group with backslash Arguments: data {string}: data Returns: string -- backslash escape string """ # pipe and backslash in header must be escaped # escape group with backslash return...
7a038ecadc071d3b543cda4853de6aef0251ff22
667,816
def deny(blacklist): """ Decorates a handler to filter out a blacklist of commands. The decorated handler will not be called if message.command is in the blacklist: @deny(['A', 'B']) def handle_everything_except_a_and_b(client, message): pass Single-item blacklists may...
bd195f9345487f14129d27f487b8708c6b7ffc6c
667,817
import time def get_time_stamp(): """获取毫秒级的时间""" ct = time.time() local_time = time.localtime(ct) data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time) data_secs = (ct - int(ct)) * 1000 time_stamp = "%s.%03d" % (data_head, data_secs) return time_stamp
e93d2814c82369436f3662580293a31d9e915c4f
667,818
import time def prime_out(num): """prime_out: A user-friendly tool to evaluate whether or not a number is prime. Args: num (int): Number to be evaluated as prime Returns: Prints whether or not the number is prime and how long it took to evaluate. """ t1_start = time.perf_counter() ...
402198e9ed88e1433334707ed8c448987629836f
667,819
import re def sanatize_text(text): """ Replace non alphanumeric characters in text with '_' Parameters ---------- text : str text to sanatize Returns ------- text the sanatized text """ if text is None: return text return re.sub('[^a-zA-Z0-9]', '_', text...
1158929bc909fbc0791ea2057d01f8750ba7c822
667,820
import torch def metrics(preds, y, th=0.5): """ Params: preds: torch tensor, [batch_size, output_dim] y: torch tensor, [batch_size] Yields: A dictionary of accuracy, f1 score, recall, precision and specificity """ # y_preds = preds.argmax(d...
4e7e2ac1599916e266e7bbb265b3bf5faaa0cc70
667,821
import base64 def encode2b64(source): """ encode source twice base64 """ code = base64.b64encode(base64.b64encode(source)) return code
6b2443d5465877c9be61eee7b7dfea203acc05d2
667,822
def first_key(d): """get the first key of a dict""" return list(d.keys())[0]
e8e6dd99872e02fb6c563a91607cc0393db19549
667,823
def lat_lon_to_float(v): """ convert strings from HNC to float locations """ #the following is the test for conversion of lat long if(v[-1] =="S") or (v[-1] == "W"): multiplier = -1 else: multiplier = 1 return float(v[:-1])* multiplier
2651d981a8f437c7ed82018791cc0fb2e4454794
667,825
import numpy def labels_nan_removal(raw_y, non_nan_values, n_timesteps): """ removing nans in y""" print(raw_y.shape) y_without_nans_1D = raw_y[~numpy.isnan(raw_y)] y_without_nans_3D = numpy.reshape( y_without_nans_1D, (non_nan_values, n_timesteps, raw_y.shape[-1]), ) # To mu...
7202f7c524c92e7a9228f61eadd2c8fc73d689be
667,826
def fixture_input_dict(): """ A test dictionary """ return { "one": "two", "three": "four", "five": "six", "seven": "eight", "nine": "ten", }
a30c07006c14ac669703f9273803d9260b4cdafc
667,827
def is_unauthorized_response(resp): """Check if is unauthorized.""" return (resp.status_code == 401 or "<ResponseCode>401</ResponseCode>" in resp.text)
d1db355ea69fed26fecc4d2bc290d5b509efe7ba
667,828
def split_flat_pair_dict(the_dict): """Combine a pair of file dictionaries Parameters ---------- the_dict : `dict` A dictionary of data_ids or filenames keyed by raft, slot, filetype Returns ------- out_dict : `dict` A dictionary of data_ids or filenames keyed by raft, slot...
96ebf3a2934400f56dee703df545dc468139db30
667,829
import sys import gzip def finftypes(filepath): """ filepath can be stdin, normal txt, and gz file """ if(filepath == 'stdin'): fin = sys.stdin elif(filepath[-3:] == '.gz'): fin = gzip.open(filepath) else: fin = open(filepath) return fin
1e2dd722aebd3236cb334244aeba9e253d805499
667,830
def n_coeffs_from_ell_max(ell_max): """Returns the number of coefficients for an SWSFT with max degree ell_max.""" return (ell_max + 1)**2
2c173b7f0c2365ddde5136fa3d3984468e0339bf
667,831
def declare_temp(var_type, var_name): """Create a declaration of the form (declare (temporary) <var_type> <var_name) """ return [['declare', ['temporary'], var_type, var_name]]
0df399f269e8f5372fea81b60cd5ed008ba1d806
667,832
def get_depths_to_prune(node_name, node_list): """Return non-minimum depth values given a (duplicate) node name""" depth_list = [node[node_name] for node in node_list] depth_list.remove(min(depth_list)) return depth_list
3619f65ec754c92e6f501359296b742cb82fb6b9
667,833
def _iteritems(d): """Like d.iteritems, but accepts any collections.Mapping.""" return d.iteritems() if hasattr(d, "iteritems") else d.items()
06a4cd4a0817b37f19cf89604112b3f9f9af26c4
667,834
def file_session_to_import_file(file_session): """Get the import file of its session.""" return file_session.file
05fc886ec02e15743b58c22758ccbd33e65e3937
667,835
def timestr_to_int(time_str): """ Parse the test time set in the yaml configuration file and convert it to int type """ # time_int = 0 if isinstance(time_str, int) or time_str.isdigit(): time_int = int(time_str) elif time_str.endswith("s"): time_int = int(time_str.split("s")[0]) elif...
90a8b42c683645e31ae5e7db4276503ec7adea94
667,836
def get_project_id_from_service_account_email(service_account_email: str) -> str: """ Get GCP project id from service_account_email >>> get_project_id_from_service_account_email('cromwell-test@tob-wgs.iam.gserviceaccount.com') 'tob-wgs' """ # quick and dirty return service_account_email.spl...
8761823c940b447813e1e476c6aad2588fd95b79
667,837
def tnuc_region_in_exon(np, beg, end): """ region in tnuc positions """ if beg.tpos != 0: return False if end.tpos != 0: return False for i in range(beg.pos, end.pos-1): if abs(np[i] - np[i+1]) != 1: return False return True
db30888a3debd9a30037e14fbf3ee9eba2957afc
667,838
def _filter_slabs(provisional, max_size): """ Filters the repeat slabs from the list of all the zero dipole slabs. Creates lists of large and repeat slabs if any are present for the warnings Args: provisional (`list`): All zero dipole slabs generated with SlabGenerator max_size (`int...
4993bc6d89e0d09840c30ce54119cc54e9ca42f2
667,839
import curses def resolve_capability(term, attr): """ Resolve a raw terminal capability using :func:`tigetstr`. :arg Terminal term: :class:`~.Terminal` instance. :arg str attr: terminal capability name. :returns: string of the given terminal capability named by ``attr``, which may be empty...
763f75987fde643382fb89a06cd0d7f7225183fc
667,840
def prettify_format(format): """ Return the date format in a more human readable form. """ f = format.replate('%Y', 'yyyy') f = f.replace('%m', 'mm') f = f.replace('%d', 'dd') return f
190f9beb7b05f888f2ea58c7ae83a768dff04525
667,841
import copy def merge_left_with_defaults(defaults, loaded_config): """ Merge two configurations, with one of them overriding the other. Args: defaults (dict): A configuration of defaults loaded_config (dict): A configuration, as loaded from disk. Returns (dict): A merged confi...
630db012b0705e7c0ab12c9cd4e7df07b3ab56f0
667,842
def get_version_name(lang: str, major: int, minor: int, patch: int): """Return the package name associated with the lang ``name`` and version (``major``, ``minor``, ``patch``)""" return f"{lang}_{major}_{minor}_{patch}"
62a07e3d66a10acb398687a0ba76d9e09d7407bf
667,845
def dict_rm_none(data): """将字典中值为 None 的键值对剔除""" for key in list(data.keys()): if data.get(key) is None: del data[key] return data
abba9360b5309d2fc6a6886a1317439e3f31cfbb
667,846
import subprocess def get_num_lines(filename, ignore_comments=True): """count number of lines in filename. Arguments --------- filename : string Name of the file to be opened. ignore_comments : bool If true, ignore lines starting with ``#``. Returns ------- int T...
f7b2083c78717c130a3cb5453339a7cda526fc3d
667,847
def only_logged_user(): """Decorator to specify the action must only be called by logger users""" def real_decorator(function): function.pi_api_only_logged_user = True return function return real_decorator
f8cd336ff3dbc4b3753bd9579c0f68f1cd567dc9
667,848
def isLDAPUrl(s): """ Returns 1 if s is a LDAP URL, 0 else """ s_lower = s.lower() return \ s_lower.startswith('ldap://') or \ s_lower.startswith('ldaps://') or \ s_lower.startswith('ldapi://')
943f6185391d2b1d36938f915947e164bd32a698
667,849
def _environment_intersection(run, caseversion): """Intersection of run/caseversion environment IDs.""" run_env_ids = set( run.environments.values_list("id", flat=True)) case_env_ids = set( caseversion.environments.values_list("id", flat=True)) return run_env_ids.intersection(case_env_id...
ee6f5c302667532820af0b1e89cfdeaa2c825cf1
667,851
def _rebase_path(api, file_path): """Attempts to make an absolute path for the command. We want to pass to runtest.py an absolute path if possible. """ if (file_path.startswith('src/') or file_path.startswith('./src/')): return api.m.path['checkout'].join( *file_path.split('src', 1)[1].split('/')[1...
3ea7a601d25387718c9beb80a474146d52d5d197
667,852
import tempfile def wrap_in_tempfile(data): """Return SpooledTemporaryFile with given data as content, ready to read eg. as a subprocess input. """ wrapped = tempfile.SpooledTemporaryFile() wrapped.write(data) wrapped.flush() wrapped.seek(0) return wrapped
803df030888ab379cca12aae904e76451c1dc739
667,853
def memory_game(numbers: list, abort: int) -> int: """Play the North Pole memory game.""" memory = {number: idx for idx, number in enumerate(numbers[:-1])} current = numbers[-1] turn = len(numbers) - 1 while turn < abort - 1: if current in memory.keys(): tmp = current ...
41eff558b3f012057d94195dc362870363eb294d
667,854
def number_of_internal_nodes(tree): """Return the number of internal nodes of tree.""" if tree.is_empty(): return 0 elif tree.left_child().is_empty() and tree.right_child().is_empty(): return 0 else: return 1\ + number_of_internal_nodes(tree.left_child())\ ...
5ec45205cfa41cde8146b47d51bb198cc2dd6bb0
667,855
import random def generate_gender() -> bool: """Returns a random gender. True is male and False is female. Returns: bool: A gender represented by a bool. """ return bool(random.getrandbits(1))
2012bb100ad7f63125c95a552f9b0671d2658df3
667,856
def compute_optimum(groups, elements): """Compute the number of elements per group and the remainder. :param elements: total number of elements :param groups: total number of groups """ return elements // groups, elements % groups
cf973952358d5ccb940b149a8bb5717302009b4a
667,857
def half_to_full(ins): """把字符串半角转全角""" outs = "" for c in ins: code = ord(c) if code < 0x0020 or code > 0x007E: outs += c else: if code == 0x0020: code == 0x3000 else: code += 0xFEE0 outs += chr(code) ...
b1f42b19c0d5ea1d399af4864ce7772406b2f909
667,859
def get_eta_C_i(f_C_i, etr_d_i): """開口部の冷房期の日射熱取得率 (-) (4) Args: f_C_i(float): 開口部の冷房期の取得日射熱補正係数 (-) etr_d_i(float): 開口部の垂直面日射熱出得率 ((W/m2)/(W/m2)) Returns: 開口部の冷房期の日射熱取得率((W/m2)/(W/m2)) """ return f_C_i * etr_d_i
c2a735dd60fa07846bbd2dd7d39720c36acecdfa
667,860
import argparse def get_argparse(): """ A function to parse all the input arguments """ parser = argparse.ArgumentParser(description='A python workflow to run active learning for Electronic Coarse Graining') parser.add_argument('-json','--jsonfilename', type=str,required=True,help='Input JSON con...
05f19a0bb3a0b821f424a397b870c53de3724002
667,861
def do_join(d=u''): """ Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define ith with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{...
52400f7f9448c31472ff1af910875941303d0214
667,862
import math import random def create_spiral_galaxy(system_count=100, spirals=2): """ Creates a spiral galaxy with given spirals (arms) and system count. The galaxy is unlinked and just creates the galaxy shape """ sep = 2*math.pi/spirals spiral_list = [] for x in range(spirals): ...
c64507d5819d285f019b6093d19aee9c74458c04
667,864
def valid_filename_from_query(query): """ Generates a filename from a query. This just gets the descriptor string from the query and replaces any spaces with hyphens. (At the time of writing, descriptors can't contain spaces, but in the future they will be able to.) """ return query.dnode.t...
84bcb62a73a13f10aafea59772d2186013e2fe0b
667,865
import re def trim_offset(name): """_trim_offset(name: str) -> str Remove address offset from name. Example: some_function+0x42beef -> some_function """ return re.sub(r'\+0x[0-9a-fA-F]+$', '', name)
9151d13dca9c7888dd0dd8bcc3d042a37043cd15
667,866
def normalizar_nombre_propio(name): """ str -> str Función que transforma un texto a las normas del español de forma correcta para un nombre propio. >>>>normalizar_nombre_propio(" rigoberto villalta ") 'Rigoberto Vilalta' >>>>normalizar_nombre_propio("Rigoberto villalta ") 'Rigobe...
1c352aa13f2e24583d0775ee1f4e3033017c32b4
667,867
def color_hex_to_color_hex(color_hex): """ >>> color_hex_to_color_hex('#3af') '#33aaff' >>> color_hex_to_color_hex('#09bd') '#0099bbdd' >>> color_hex_to_color_hex('#00ff1080') '#00ff1080' """ n = len(color_hex) assert n > 0 and color_hex[0] == '#', "color hex code should start wi...
1b532d6f9403e91cc6015c064d3bb7cb13fb3826
667,868
def get_ngrams( s, n): """ Returns a list with the possible concatenation of words with a size of n """ min_n = 2*n - 1 s_lw = s.lower() tokens_list = [token for token in s_lw.split(" ") if token.strip() != ""] ngrams = zip(*[tokens_list[i:] for i in range(n)]) ngrams = [ gram for gram in ngrams if len(''.join(g...
1f3ba4ac1b37e596e278ed611ba494237e3ab9ea
667,869
import random def choose_false_edges(non_edges, K): """ Randomly choose a fixed number of non-existing edges :param non_edges: Edges that are not in the graph :param K: Fixed number of edges to choose :return: A list of K false edges """ indexes = random.sample(range(1, len(non_edges)), K)...
9b77228ac29a9d9f28f52af8c4352526171de0f9
667,870
def factorial(num): """ Replacement of ``scipy.misc.factorial()``. First, it avoids requiring scipy; second, it returns integer instead of float (which gives more precision for subsequent calculations). """ res = 1 for i in range(2, num + 1): res *= i return res
3f63f62ec3d7d7d83e4a0e1e37f3b92c86191b3c
667,871
def caption() -> str: """Caption to be displayed at the end. Returns: str: Message for the users. """ return 'Thank you for using crypto-candlesticks\ Consider supporting your developers\ ETH: 0x06Acb31587a96808158BdEd07e53668d8ce94cFE\ '
0a8f70ea04899208d2d714225e23d9d8c6ac4194
667,872
def _gen_eos_args(state_i, eos_pars): """ Generate a dict that we can pass to EosInterface """ pars = dict( list(state_i.items()) + list(eos_pars.items())) for key in ['u_s', 'u_2']: if key in pars: del pars[key] return pars
742998359b1350af0c4077fd73356c7ac40dc12c
667,873
import math def get_approx_flame_length(head_fire_intensity: float): """ Returns an approximation of flame length (in meters). Formula used is a field-use approximation of L = (I / 300)^(1/2), where L is flame length in m and I is Fire Intensity in kW/m """ return math.sqrt(head_fire_intensity / 3...
5728ba488c8535ea27df31526b9e67fd9d01c6aa
667,874
def indicator_function_ei(X_i, M, X_nk_n): """Returns 1 if M is smaller or equal than X_nk_n and if X_nk_n is smaller than X_i, and 0 otherwise.""" return 1*(M <= X_nk_n < X_i)
35312d20272289de6c6deaeb6c1398066e75773a
667,875
def remove_http_https_prefix(endpoint): """remove http:// or https:// prefix if presented in endpoint""" endpoint = endpoint.replace("https://", "") endpoint = endpoint.replace("http://", "") return endpoint
3ec56da4eae83fa7637fee2fe08b47d61513b30e
667,876
def timedelta_as_string(td): """Formatted 'HH:MM:SS' representation of a timedelta object""" hours, remainder = divmod(td.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) return "{:02d}:{:02d}:{:02d}".format(*map(int, (hours, minutes, seconds)))
80fc9d59a74869c32b841cbebedd8878d2fe22f9
667,877
def Kabsch(A, B): """ Returns Kabsch-rotated matrices resulting from aligning A into B. Adapted from: https://github.com/charnley/rmsd/ * Inputs: * A,B are (3 x N) * backend: one of ["numpy", "torch", "auto"] for backend choice * Outputs: tensor/array of shap...
a3359c71c43ac39c0c17fa80839651a34772a8b4
667,878
import pathlib def remove_name_prefix(path: pathlib.Path, prefix: str) -> pathlib.Path: """Remove prefix from path name. Does nothing if prefix is not part of path name. Args: path: File system path to edit. prefix: String prefix to remove from path name. Returns: Path witho...
2b505dc4694d9677c3f22a0d237a86c2486c2d7a
667,879
def cmp(x, y): """Compare the two objects x and y and return an integer according to the outcome.""" return (x > y) - (x < y)
c635e85c57394ad7cc6999c5cd3fc13f18eedcba
667,880
import re def _path2module(path): """相对路径转换为类模块路径""" return re.sub(r'.py', '', re.sub('/', '.', path))
86550d7d1ca9d1ba0977361385784b8b90ac6207
667,881
from typing import Any def is_multi_agg_with_relabel(**kwargs: Any) -> bool: """ Check whether the kwargs pass to .agg look like multi-agg with relabling. Parameters ---------- **kwargs : dict Returns ------- bool Examples -------- >>> is_multi_agg_with_relabel(a='max') ...
ab692e293de43d2d1d9c45235b9be819f790db14
667,882
import numpy as np def readStationData(datasets,years): """ Read in station-based data sets for T2M """ ### Import modules ### Define directories directorydata = '/home/zlabe/Documents/Projects/IceVarFigs/Data/' ### Set time yearall = np.arange(1900,2019+1,1) ### Re...
7c4581490d7950bc50e3af2c8b2772af011f4d0e
667,883
def pull_tag_dict(data): """This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values. """ # If there are tags, set them to a normal dict, vs. a list o...
1bd4ad8cecb26796798c29aee0d4ecb01ee42923
667,884