content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy def _are_equal(a, b) -> bool: """Compare two statedicts and return if they are equal. This is required because of annoying numpy array comparisons and such. """ try: numpy.testing.assert_equal(a, b) return True except AssertionError: return False
85ed69bf38b1632f9e3bb208da7678aa9e4d3204
655,197
def threads(): """max parallel threads""" return 5
ffdf416706d215150a8a6238a9a5148c9624764a
655,198
def highlight_single_token(token): """Highlight a single token with ^.""" return {token.start_row: " " * token.start_col + "^" * len(token.string)}
d2c0287d423bbb41731d3847e211f3eee8233ee7
655,199
def replace_data(obj: object) -> object: """登録・更新用データの置換処理 空文字はNoneに置換 """ if isinstance(obj, dict): for key, value in obj.items(): obj[key] = replace_data(value) elif isinstance(obj, list): [replace_data(element) for element in obj] elif obj == '': obj = None...
986ec99872660ceb0e4d3c6776b8b9fd069c886f
655,200
def _esc_var(name): """Returns a valid and unique Python identifier derived from name. Just returns name with the "_" appended. This is enough to ensure there's no collisions with any keyword or built-in or import. Args: name (string): The name to escape. Returns: string: A name w...
4bc3d6c75f183e399845402da6e80723c0bb9db3
655,201
import os def mkdir_p(sftp, remote_directory): """Change to this directory, recursively making new folders if needed. Returns True if any folders were created.""" if remote_directory == '/': # absolute path so change directory to root sftp.chdir('/') return if remote_di...
7346c8ced4d6a7181f40db8b9f2909052809faa4
655,202
def voter_notification_settings_update_doc_template_values(url_root): """ Show documentation about voterNotificationSettingsUpdate """ required_query_parameter_list = [ { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # b...
ad2fda6cfb0d2d228b6fc6ae6b18d71026728157
655,203
import re def parse_gitmodules(input_text): """Parse a .gitmodules file and return a list of all the git submodules defined inside of it. Each list item is 2-tuple with: - submodule name (string) - submodule variables (dictionary with variables as keys and their values) The input should be a ...
0c0f1dda715f1f0db4418c0762137b40842a74ab
655,204
def is_clockwise(vertices): """ Returns whether a list of points describing a polygon are clockwise or counterclockwise. is_clockwise(Point list) -> bool Parameters ---------- vertices : a list of points that form a single ring Examples -------- >>> is_clockwise([Point((0, 0)), Point...
643ff81227c7c0a958fba4867cd80b7d33d9588c
655,205
import string def solution(W, H): """ Retorna la solucion del sliding puzzle para las dimensiones dadas """ return tuple(string.ascii_uppercase[0:(W*H) - 1] + "-")
0fb994f92d8f4183c740694ee2bbfc1392fae5b3
655,206
import yaml def yaml_from_dict(dictionary): """convert a Python dictionary to YAML""" return yaml.dump(dictionary)
c33ebdd7c64ca4862618cd65134df772e67386e4
655,207
def leaf_distance(node1, node2, weighted): """Calculates the minimal distance between two leaves. Args: node1 (`Node`): The 1st leaf. node2 (`Node`): The 2nd leaf. weighted (boolean): True if the weighted distance should be calculated; False if all edges have a weight of 1. Returns: float: The leaf distan...
4cda52ef52ac6b67dd2a115af45850789b3274d8
655,210
def Soil(temp, inf, ep, sm_old, uz_old, tm, fc, beta, e_corr, lp, c_flux): """ ============================================================ Soil(fc, beta, temp, tm, e_corr, lp, c_flux, inf, ep, sm_old, uz_old) ============================================================ Soil routine of the ...
daf897bd6e47023f4e1deaa48abd1f6da398d15a
655,213
def _GetOrAddArgGroup(parser, help_text): """Create a new arg group or return existing group with given help text.""" for arg in parser.arguments: if arg.is_group and arg.help == help_text: return arg return parser.add_argument_group(help_text)
b66d2c36b08d1676161f48dfd30254efa70fc942
655,214
import re def parse_show_arp(raw_result): """ Parse the 'show arp' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show arp command in a \ dictionary of the form. Returns None if no arp found or \ empty dictionary: ...
bdba95d2dbb5d742b629f2c5b43c58295c4017f4
655,215
def quote(s: str) -> str: """ Quotes the '"' and '\' characters in a string and surrounds with "..." """ return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
c852970bdc6aee2068e3c064dd476d8ebc9c9cfe
655,216
import re def remove_structure_definitions(data): """ Remove lines of code that aren't representative of LLVM-IR "language" and shouldn't be used for training the embeddings :param data: input data as a list of files where each file is a list of strings :return: input data with non-representative ...
c88074e1470bad0229e31292d4e309b75eba415c
655,218
import pickle def serialize(name, obj): """Returns True if serialized.""" try: pickle_out = open(name, 'wb') pickle.dump(obj, pickle_out) pickle_out.close() return True except Exception as e: print(str(e)) return False
0290c56fe3768fb70e3d7cdc87d5160993524855
655,220
def normalise_list( l: list, d: int, f: int = 1, ) -> list: """Normalise a list according to a given displacement Parameters ---------- l : list The list of values n : int, optional The displacement, by default 0 Returns ------- list The normalis...
a8a16073a52c48aed03108e9d7f47524003fbf92
655,221
def _format_timestamp(timestamp) -> str: """Returns the timestamp in human readable format.""" return timestamp.ToDatetime().isoformat(' ', timespec='seconds')
6d8705c4959c2f3d3db45e3c055cecfd63410745
655,222
def assert_time_of_flight_is_positive(tof): """ Checks if time of flight is positive. Parameters ---------- tof: float Time of flight. """ if tof <= 0: raise ValueError("Time of flight must be positive!") else: return True
54f85189ca8b25f0447ccbca60179a2eff41b018
655,223
def int2mac(integer, upper=False): """ Convert a integer value into a mac address :param integer: Integer value of potential mac address :param upper: True if you want get address with uppercase :return: String mac address in format AA:BB:CC:DD:EE:FF """ def format_int(): return zip...
e5d020c2f1151f1235a8700606a3edb369dc3afd
655,224
def filter_phrases(input_str, filter_list): """ Filters out phrases/words from the input string :param input_str: String to be processed. :return: string with phrases from filter_list removed. """ for phrase in filter_list: input_str = input_str.replace(phrase,'') return input_str
1e5ee006a665f6b9660e17e2f9d0dff187023b49
655,225
def build_mpi_call_str(task_specs,common_options,format_opts=None,runner='mpiexec'): """Summary Args: task_specs (list): List of strings, each containing an MPI task description, eg e.g: ['-n {nrunners} python3 awrams.module.example {pickle_file}'] common_options ...
a63ed5c05e31d51b42913157f8a3f448477ef80d
655,226
import glob def read_files(): """ Reads all files in "Islendingasogur" folder :return: A string containing content of all text files in the folder. """ all_sagas = '' for single_file in glob.glob('Islendingasogur/*'): all_sagas += open(file = single_file, encoding='UTF-8').read() ...
0142dad1532b770963dd1bbd654c340d438a5b6c
655,227
def get_channel_dim(input_tensor, data_format='INVALID'): """Returns the number of channels in the input tensor.""" shape = input_tensor.get_shape().as_list() assert data_format != 'INVALID' assert len(shape) == 4 if data_format == 'NHWC': return int(shape[3]) elif data_format == 'NCHW': return int(...
cdd2dfd7e270395566527742042050c922b48b94
655,228
import re def minify_dtd(src): """Returns a minified version of the given DTD source string.""" src = "".join(ln.strip() for ln in src.split("\n")) src = re.sub(r"<!--.*?-->", "", src) return src
1fc3137af661b8646025731995a05b51ff464268
655,230
def xor_strings(s, t): """xor two strings together""" if isinstance(s, str): # Text strings contain single characters return "".join(chr(ord(a) ^ ord(b)) for a, b in zip(s, t)) else: # Python 3 bytes objects contain integer values in the range 0-255 return bytes([a ^ b for a,...
dc33b569eda2dfad92f6e64f19b321f3b05d4e63
655,232
def rle_encode(byte_arr): """Use run length encoding on a byte string. :param byte_arr: byte generator. :return: byte string of encoded data. """ output = b"" streak = 1 try: prev = next(byte_arr) except StopIteration: return b"" while True: try: c...
e7b0a645236166355155893c639e7b2e1e55ea13
655,233
def index_of_square(square): """ Index of square Args: square (String): Square in chess notation e.g. f7 Returns: Int: Index of square in bitboard """ line = ord(square[0].lower()) - ord('a') row = int(square[1]) idx = 8 * (row - 1) + line return idx
e48d344168254828e4b6fdff2c18f2f472db89f2
655,234
def _check_attribute(obj, attr, typ, allow_none=False): """Check that a given attribute attr exists in the object obj and is of type typ. Optionally, allow the attribute to be None. """ if not hasattr(obj, attr): return False val = getattr(obj, attr) return isinstance(val, typ) or (allo...
7925e92ce5b7b68660e9a5519d7de993e393afa5
655,235
def patch_stanza(struc, diff): """Applies the diff stanza ``diff`` to the structure ``struc`` as a patch. Note that this function modifies ``struc`` in-place into the target of ``diff``. If ``struc`` is a tuple, you get a new tuple with the appropriate modification made: >>> patch_stanza((17,...
dbfad02fb2fa411e850a6ef9e4b45dc6fe427080
655,236
def join(func): """Decorator that joins characters of a returned sequence into a string.""" return lambda *args: ''.join(func(*args))
c561a9167da83c88355cb3e8458df7b5c80453c7
655,237
def divide(value, divisor): """ Divide value by divisor """ v = float(value) d = float(divisor) return v / d
2c251cf80842c3c0222fa612eaf7c2520c6913d8
655,238
import torch def numpy2tensor(numpy): """ convert numpy_array in cpu to tensor in gpu :param numpy: :return: torch.from_numpy(numpy).cuda() """ return torch.from_numpy(numpy).cuda()
02a7321e7df88c073d4dbc0dae04a3193ed360da
655,239
import warnings def datastream_does_not_exist_warning(sensor_type, operation): """Warn about not existing datastreams.""" message = 'The datastream "{}" does not exist for the current session.\ The performed operation "{}" will have not effect'.format( sensor_type, operation ) return warn...
d635f1978c6ee84561a4193920a0c9863c8fde03
655,240
import requests from bs4 import BeautifulSoup def Extract_With_CSSselecter(URL,CSSselecter): """スクレイピングしてCSSセレクタを条件に抽出""" session = requests.session() r = session.get(URL).content soup = BeautifulSoup(r,"html.parser") tags = soup.select(CSSselecter) return tags
b44322ca317263f292d591997575e82ca9bad72f
655,241
def getWAMP(rawEMGSignal, threshold): """ Wilson or Willison amplitude is a measure of frequency information. It is a number of time resulting from difference between the EMG signal of two adjoining segments, that exceed a threshold.:: WAMP = sum( f(|x[i] - x[i+1]|)) for n = 1 --> n-1 ...
3e47e63d09c6d4ae1db2fe5e7fafa028c238dcf5
655,242
def fileGroupName(filePath): """ Get the group file name. foo.0080 would return foo """ return filePath.split('.')[0]
be43b8ce497b46ad79b153e686c1ed3b78ea6509
655,243
import subprocess def types_valid(file_name): # type: (str) -> bool """ Run Mypy check on the given file, return TRUE if Mypy check passes """ mypy_exit_code = subprocess.call(('mypy %s' % file_name), shell=True) return not bool(mypy_exit_code)
ba695dc6cab5db14335ffbb6df9a1d1c454bc7f7
655,244
def _min_filter(path_data, min_genes, min_transcripts): """ Return `True` is path_data has more than min_genes and min_transcripts. """ if min_genes > 1: if len(path_data.Genes) < min_genes: return False if min_transcripts > 1: if len(path_data.Transcripts) < min_transcri...
dcb1bc496b1a22fd8dc6394dd2d7119db7e7e09d
655,246
import os def get_config_root_path(): """ Path to configs for unit tests """ cur_file_dir = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) ret = os.path.dirname(os.path.dirname(cur_file_dir)) ret = os.path.join(ret, "configs") return ret
936900bb427c21e4b6c7be8b8e8aba3e02d560f1
655,247
import subprocess def get_modified_files(): """Returns a list of all modified files.""" c = subprocess.Popen( ["git", "diff-index", "--cached", "--name-only", "HEAD"], stdout=subprocess.PIPE ) return c.communicate()[0].splitlines()
b1920886f627acdd61e144b18b04873275019a40
655,248
def get_session_cpu_path(): """Returns the path of the CPU cgroup hierarchy for this session, which is writable by the impalad processes. The cgroup hierarchy is specified as an absolute path under the CPU controller root. """ PROC_SELF_CGROUP = '/proc/self/cgroup' cgroup_paths = open(PROC_SELF_CGROUP...
3a1060e464d2efab163aa7e16c6c7af2eb718f84
655,249
def InvertDictionary(origin_dict): """Invert the key value mapping in the origin_dict. Given an origin_dict {'key1': {'val1', 'val2'}, 'key2': {'val1', 'val3'}, 'key3': {'val3'}}, the returned inverted dict will be {'val1': {'key1', 'key2'}, 'val2': {'key1'}, 'val3': {'key2', 'key3'}} Args: origin_dict:...
1fa11a1a9843ffe7bf97a3cf0c57775f7d26b584
655,250
import hashlib def get_hash_from_str(text): """Функция возвращает хеш от строки в виде HEX чисел, используя алгоритм sha1.""" alg = hashlib.sha1() alg.update(text.encode()) return alg.hexdigest().upper()
5b6c20cd3860746334774110e9ac8f3dc261542f
655,251
from typing import List import re def split(sentence: str) -> List[str]: """ Split a string by groups of letters, groups of digits, and groups of punctuation. Spaces are not returned. """ return re.findall(r"[\d]+|[^\W\d_]+|[^\w\s]+", sentence)
d8e8e3ac0a0b00c4346eedef29693a5d66a7f3a4
655,252
import typing def splitdec(G: typing.Sequence[str], neg: str) -> float: """ accounts for variable width by hinging at decimal point """ dec = G[0].split(".") dd = float(dec[0][:-2]) + float(dec[0][-2:]) / 60.0 if G[1] == neg: dd = -dd return dd
cd1a55afd48bf83321a316a156027b7524b82a94
655,253
def get_user_name(email: str) -> str: """Returns username part of email, if valid email is provided.""" if "@" in email: return email.split("@")[0] return email
8dfbed701a7e4c2f87f5d1e8bc481e44494de955
655,254
import argparse def parse_command_line(): """ Parse command-line. Returns: Namespace with members for all parsed arguments. """ parser = argparse.ArgumentParser(description='Run evaluation on COCO dataset.', formatter_class=argparse.ArgumentDefaultsHel...
cc562c91784225cac084097ed1aeee1ff7197743
655,255
def curve(vx=0.5, vy=0.5, wz=1.6, t=16): """Generate a curved trajectory""" time_points = range(t) speed_points = ( # One side (vx, vy, 0, 0), (vx, vy, 0, 0), (vx, vy, 0, 0), (vx, vy, 0, 0), (vx, vy, 0, 0), (vx, vy, 0, 0), (vx, vy, 0, 0), ...
0e0615ed9b492d04e0704e968cf6adfce2ad7fd1
655,256
from typing import List def rotate_right(sequence: List[int]) -> List[int]: """ Shifts the elements in the sequence to the right, so that the last element of the sequence becomes the first. >>> rotate_right([1,2,3,4,5]) [5, 1, 2, 3, 4] >>> rotate_right([1]) [1] >>> rotate_right([]) []...
a936fd2ed35b03c0a67738d457ff2748d46a52cc
655,257
def clone_model(model, **kwargs): """Based on https://stackoverflow.com/a/55991358""" # will raise AttributeError if data not loaded try: model.sequence_id # taskmanager doesn't have an 'id' column except AttributeError: model.id # pylint: disable=pointless-statement table = model...
b55ec327d2fd82345000e726f0c5f19642496b54
655,258
import itertools def get_all_combinations(elements): """ get all combinations for a venn diagram from a list of elements""" result = [] n = len(elements) for i in range(n): idx = n - i result.append(list(set(itertools.combinations(elements, idx)))) return result
d6423d46fe8104fdb0f338446c8f91c655e89062
655,259
import numpy def allclose2(p, q): """Determines if `p` and `q` match to two digits.""" return numpy.allclose(p, q, rtol=0.01, atol=0.01)
658dca32484afa85016535d91a79ace5d1c45f31
655,260
def calc_theta_int_inc(theta_int_ini, delta_theta_int_inc): """ Eq. (1) in [prEN 15316-2:2014] :param theta_int_ini: temperature [C] :type theta_int_ini: double :param delta_theta_int_inc: temperature [C] :type delta_theta_int_inc: double :return: sum of temperatures [C] :rtyp...
35ee8827750bb4e74b534c9577d216bc0dc79150
655,261
from typing import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial f(x) at specified point x and return the value. Arguments: poly -- the coeffiecients of a polynomial as an iterable in order of ascending degree x -- the point at which to eva...
deaff8810fccb4b75d4c18316ec19e70e15ed8c3
655,262
def _swift_sanitizer_flags(features): """Returns sanitizer flags.""" sanitizer_features_to_flags = { "asan": ["-sanitize=address"], } sanitizer_flags = [] for (feature, flags) in sanitizer_features_to_flags.items(): if feature in features: sanitizer_flags.extend(flags) return sanitizer_fla...
b780488890afc802ec81c37ed78a10c3b6c1da82
655,264
def isen_nozzle_ratios(M_E, gamma_var): """ Calculates ratio between stagnation and exit pressure and temperature in and isentropic nozzle. Input variables: M_E : Mach number at exit gamma_var : ratio of specific heats """ T_ratio = 1 / (1 + (((gamma_var - 1) / 2)...
fc6fe22f8793a5ac093d37b4de53dade237dbcbc
655,265
from datetime import datetime def generateDateTime(s): """生成时间""" dt, _ = s.split("+") dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S.%f") time = str(dt.time()) date = str(dt.date().strftime("%Y%m%d")) return date, time
12b56a86be5a350343b150d6677a37542bc53d19
655,266
def menu_toggle(n_clicks: int) -> dict: """ Args: n_clicks: Returns: """ if n_clicks and n_clicks % 2 == 1: return {"display": "block"} return {"display": "none"}
38cec15649bcec1b84e4e375099647bcc4ddf4a6
655,267
def accept_mode(): """ This function accepts the string for mode of analysis from the user and check if the entered mode is valid or not. If the entered mode is not valid, then the user is instructed to enter another valid string until the entered string is found to be valid. the valid string is c...
09f8c68e337de121715e4e3f2e8461b0c189bd05
655,268
from typing import Optional import html def unescape_string(value: Optional[str]) -> Optional[str]: """Perform HTML unescape on value.""" if value is None: return value return html.unescape(str(value))
d3bbb43fa7677bb87e5b45f2678d4f0e2a4ee21e
655,269
def normal_name(dot_str, mode="both"): """字符串首尾去掉逗号""" if not dot_str: return "" if dot_str[0] == ",": dot_str = dot_str[1:] if dot_str[-1] == ",": dot_str = dot_str[0:-1] return dot_str
f5914a0aa13d6884870deb0c14194b2c6f200818
655,270
import os def _get_file_metadata_key(request_or_response_id, filepath, is_update): """ See upload.utils.get_upload_key Since this key is being stored in upload_redis, a pipe is used instead of an underscore to avoid any key conflicts. """ return '|'.join((str(request_or_response_id), ...
7fe63f5aee1223263c777dfb0538936a7d2d48c5
655,272
import torch def sinkhorn(a: torch.Tensor, b: torch.Tensor, M: torch.Tensor, eps: float, max_iters: int = 100, stop_thresh: float = 1e-3): """ Compute the Sinkhorn divergence between two sum of dirac delta distributions, U, and V. This implementation is numerically stable with float32. :p...
c8a488b1f0a624fc16d63eb24dea432ef0cab895
655,273
import argparse from datetime import datetime import os def build_parser() -> argparse.ArgumentParser: """Create a command-line argument parser.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "-d", "--num-download-tasks", type=int, default=100...
f6d72f41d0289ccd09b4c3896ab067ca37085947
655,275
def find_Chinese_term(content: str): """ Find the Chinese Term from the contents :param content: The contents of the website :return Chi_term: The found Chinese Term :return content: The contents that cut the Chinese term part """ if '中文名称' not in content: Chi_term = '' else: ...
c90d1f51ac5537b1a6c491b9a503e2865e91f1f3
655,276
def split(target_name): """Split a target name. Returns a tuple "(build_module, name)". The split is on the first `:`. Extra `:` are considered part of the name. """ return target_name.split(':', 1)
3f0da32429be382cc736b591b1b8aa1c72060628
655,277
def validate(config): """ Validate the beacon configuration """ # Configuration for aix_account beacon should be a dictionary if not isinstance(config, dict): return False, "Configuration for aix_account beacon must be a dict." if "user" not in config: return ( False,...
a18e90904646a90c5ec1d1e11533eeeb25c49e25
655,279
def process_invalid(api_dict): """ 输入:{'value': 'xfjc@zb', 'lx': "xfxs_cfxfbz", 'xfxs': "invalid"} 输出:{'value': 'xfjc@zb', 'lx': "xfxs_cfxfbz"} """ # 处理invalid: return 200, "success", {k: v for k, v in api_dict.items() if v not in ["invalid", "Pinvalid"]}
ff1e5cbbc586cc75521c277a806baafe1e26a777
655,280
def calc_closest_point_w_linestr(point, linestr): """ Calculate closest point between shapely LineString and Point. Parameters ---------- point : object Shapely point object linestr : object Shapely LineString object Returns ------- closest_point : object Sh...
4df35993dddba1185ac984a79245a1692a537e57
655,281
def _compute_time(index, align_type, timings): """Compute start and end time of utterance. Adapted from https://github.com/lumaku/ctc-segmentation Args: index: frame index value align_type: one of ["begin", "end"] Return: start/end time of utterance in seconds """ mid...
d2efc4768d4779e8452afdc2015fffbd30d14ffe
655,282
import math def lcc_simp(seq): """Local Composition Complexity (LCC) for a sequence. seq - an unambiguous DNA sequence (a string or Seq object) Returns the Local Composition Complexity (LCC) value for the entire sequence (as a float). Reference: Andrzej K Konopka (2005) Sequence Complexity ...
3eb7765d991fbd8bcad06275cfa9487fdd1920f7
655,283
from typing import List def right(lst: List[int], idx: int) -> int: """Return right heap child.""" right_idx = idx * 2 + 2 if right_idx < len(lst): return right_idx else: return -1
b69301c7326eaa3fa00a9635fed8424942470e48
655,284
def unique_regions(R): """removed duplicated regions""" return list(set(R))
ee53d49c2de97fba3dfdbcd43657a93cf8f509ad
655,285
import os def CatTextInFiles(filelst): """ Cancatinate text in files :param lst filelst: file name list, [filename1,filename2,...] """ text='' if len(filelst) <= 0: return text for file in filelst: if not os.path.exists(file): text=text+'#### Not found file='+file ...
8c71030f861032c017892ff99074dcfcb55cb7c2
655,286
def get_study_range_dates(config_file): """ Gets the start date and end date :param config_file: :return: """ start_date = config_file['StudyInfo']['StudyDates']['StartDate'] end_date = config_file['StudyInfo']['StudyDates']['EndDate'] if not start_date: start_date = 19700101 ...
91315207b467c6715a7cc9a679c9cfcaf8fb18ec
655,287
def get_temp_dir(app_name): """Get the temporary directory for storing fab deploy artifacts. Args: app_name: a string representing the app name Returns: a string representing path to tmp dir """ return '/tmp/.fab-deploy-{}'.format(app_name)
3c4ff6725c2fafb02ecb74ae21e8e2fff3f84ab2
655,288
import csv from io import StringIO def success_sample_data(customer, customer_2): """Enough to break the minimum funding goal""" data = """ Address,Payment at,Tx hash,Tx index,Invested ETH,Received tokens {},2017-04-13T16:01:46+00:00,0xf88780859cfde239e5898d036b685f5358d4b0a0f82e8cce26403c782f8a2e52,1,0.505,5...
351ebd848643f850bfd32f52239b9c8b4f8397ba
655,289
def command( *args ): """ Returns the command as a string joining the given arguments. Arguments with embedded spaces are double quoted, as are empty arguments. """ cmd = '' for s in args: if cmd: cmd += ' ' if not s or ' ' in s: cmd += '"'+s+'"' else: ...
3412deb9c2b8ca842a2ddec587b4e4a3d1862eb9
655,290
def PVT(df): """价量趋势指数""" df["pvt"] = ((df["close"] - df["close"].shift(1)) / df["close"].shift(1) * df["volume"]).cumsum() return df
4fc4949b75ca143b8e6c65f46d0d0d0d726ddfb6
655,291
def find_nearest(dataframes, x, npoints=5): """ Function that will take a list of dataframes, and return slices of the dataframes containing a specified number of closest points. """ nearest = [ df.loc[(df["Frequency"] - x).abs().argsort()[:npoints]] for df in dataframes ...
a46d117602952720db77a5de5aacbeb5335c012b
655,292
from typing import List def gamess_list() -> List: """Return an array of GAMESS methods with energies. Appended to procedures['energy']. """ val = [] val.append("gamess") val.append("gms-scf") val.append("gms-hf") val.append("gms-mp2") val.append("gms-cisd") val.append("gms-lcc...
599409bb17a10d4672e931d9cba23c4fe0a8a6e0
655,293
def threept_center(x1, x2, x3, y1, y2, y3): """ Calculates center coordinate of a circle circumscribing three points Parameters -------------- x1: `double` First x-coordinate x2: `double` Second x-coordinate x3: `double` Third y-coordinate y1: `double` ...
ddb71ed0c380105daeb13c681057f099a7195c2e
655,295
def get_theme_labels(themes: list): """Devuelve un string con los labels de themes del dataset separados por comas""" labels = [] for theme in themes: labels.append(theme['label']) return ','.join(labels)
24804fc1cf7a0403ba7cad8057264981857c756f
655,296
import re def massive_sub(infos, doc): """ :param infos: Dict, 表示被替换内容对应的正则表达式及替换对象 :param doc: 表示正文 :return: 返回一个完成替换的文本 """ for v, k in infos: doc = re.sub(v, k, doc) return doc
aa7015f226233f30fa74a3954af7f2e93e023a1d
655,297
import os def get_helper_filepath(parameters, filename): """ Return the absolute file of the 'filename' helper file :param filename: file name :return: """ filename = os.path.join(parameters["dataset"]["helper_filepath"], parameters["dataset"][filename]) print(...
a14714cc9c0ed52d8b4a788cea6cd04933c75a3d
655,298
def read_hierified(f): """Read a markdown table in ‘hierified’ format.""" line = f.readline() header = tuple((s.strip() for s in line.split('|')[1:-1])) _ = f.readline() # The line under the header. rows = [] for line in f: line = line.strip() if not line: break ...
356e3d2e1e4eda9cc474c538433440d548fff878
655,299
def _clean_name(name): """Strip surrounding whitespace.""" return name.strip()
ba2aa25fb57ac76de43475b56e587222f38f63c7
655,300
import calendar def short_month(i, zero_based=False): """ Looks up the short name of a month with an index. :param i: Index of the month to lookup. :param zero_based: Indicates whether the index starts from 0. :returns: The short name of the month for example Jan. >>> from dautils import ts ...
98667ffff6b70eec23662bc8b87b55614ee52766
655,301
def delete_double_undervotes(tally): """ Delete all double undervotes from a ballot dictionary tally If a double undervote occurs, delete it and all subsequent positions from ballot. Args: dictionary {tally}: dictionary mapping ballots to nonnegative reals Returns: dictionary ...
984a474ba76881bcb1234022d3614df05b5be524
655,302
def basic(x_old, r=3.9): """Logmap update dynamics (1 step) :param float x_old: current value :param float r: parameter :return: next value """ x_new = r * x_old * (1.0 - x_old) return x_new
0a4fdc766e77c1678527f3213b77a85d13bf4216
655,303
from typing import List def parse_timeseries( timeseries_str, time_input_unit="minute", time_output_unit="second" ) -> List[List[float]]: """Create a list of 2-list [timestep (seconds), value (mm/hour)].""" if not timeseries_str: return [[]] output = [] for line in timeseries_str.split(): ...
90c498650adf5764a6e7e4fedc1bcf7da454f192
655,305
def get_labels(filename, logger=None): """Returns a dictionary of alternative sequence labels, or None - filename - path to file containing tab-separated table of labels Input files should be formatted as <key>\t<label>, one pair per line. """ labeldict = {} if filename is not None: if...
a94a15b7a7cea31adb064695c9b8a5d37d3ac6cd
655,306
def formatting_time(float_time): """ Computes the estimated time as a formatted string as well """ if float_time > 3600: time_str = '{:.2f}h'.format(float_time / 3600); elif float_time > 60: time_str = '{:.2f}m'.format(float_time / 60); else: time_str = '{:.2f}s'.format(float_time); return...
5eee3d8aacc097f99039399e60ef4a27f7f6aa64
655,307
def get_method_identifier(identify): """ This function provides a dot notated reference to a bound function """ return u'{}.{}.{}'.format( identify.im_self._meta.app_label, identify.im_self.__name__, identify.im_func.__name__ )
87382e91e26798f8229e6fa7a232160bb2003185
655,308
def authz_query(authz, field='collection_id'): """Generate a search query filter from an authz object.""" # Hot-wire authorization entirely for admins. if authz.is_admin: return {'match_all': {}} collections = authz.collections(authz.READ) if not len(collections): return {'match_none...
d45612fa67e7a9ae687264f287f505078131f27d
655,309
import re def has_covid(text): """ returns 1 or 0 if text has \'COVID\' in it """ if re.search('COVID',text.upper()): return 1 else: return 0
a0028d4fc84ef46fc2d30b1b1a0452093f3dd81d
655,310
def _file_name_get(project, row): """ forma el nombre de cada fichero de gráfico input project: es el tag project del proyecto seleccionado en fichero XYplus_parameters.f_xml -en XYplus_main.py- row: es la fila de un punto que devuelve la select select_master del fic...
21569ad0ce6e4e8d42ab7bc13cb7e67e501ff45d
655,311