content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def add_arguments(parser, create_group=True): """A helper function to add standard command-line options to make an API instance. This adds the following command-line options: --btn_cache_path: The path to the BTN cache. Args: parser: An argparse.ArgumentParser. create_group: Wh...
a6fb6e5a2b2e4ac9a5d1313da9876722fa026014
680,804
def import_object(module_name, attribute_name): """Import an object from its absolute path. Example: >>> import_object('datetime', 'datetime') <type 'datetime.datetime'> """ module = __import__(module_name, {}, {}, [attribute_name], 0) return getattr(module, attribute_name)
daa127b60089a815f1ac887662755a88e8f54f23
680,805
import re def get_prefix(curie): """Get prefix from CURIE.""" match = re.fullmatch(r'([a-zA-Z.]+):\w+', curie) if match is None: raise ValueError(f'{curie} is not a valid CURIE') return match[1]
84e295bcb764a83cc2fb0432caef220589ab94c9
680,806
import os def make_directories(partition_n,target_train_size,output_dir="../model_output/"): """ Creates model output directories and returns path """ if not os.path.exists(output_dir): os.mkdir(output_dir) output_dir = output_dir+"n{}_p{}/".format(target_train_size,partition_n) # folder to st...
6c2b2ab93fe8522cd405e2c653c56f39fca20b59
680,807
def cross(v1, v2): """ Returns the cross product of the given two vectors using the formulaic definition """ i = v1[1] * v2[2] - v2[1] * v1[2] j = v1[0] * v2[2] - v2[0] * v1[2] k = v1[0] * v2[1] - v2[0] * v1[1] return [i, -j, k]
dc74c72b7a36716721b427a08d57d0927a761bc6
680,808
import os import sys def exit_if_all_absent(env_vars): """Check if any of environment variable is present. Args: env_vars: Names of environment variable. Returns: Returns True if any of env variable exists, False otherwise. """ for env_var in env_vars: if os.environ.get(...
0b0de59acd7ce794f3dcc1a515b26669dd206d84
680,809
def iterable(item): """If item is iterable, returns item. Otherwise, returns [item]. Useful for guaranteeing a result that can be iterated over. """ try: iter(item) return item except TypeError: return [item]
e9ba90fa3b5818e72d40cb7486ae8c8863e6bd16
680,810
def xy_to_uv76(x, y): # CIE1931 to CIE1976 """ convert CIE1931 xy to CIE1976 u'v' coordinates :param x: x value (CIE1931) :param y: y value (CIE1931) :return: CIE1976 u', v' """ denominator = ((-2 * x) + (12 * y) + 3) if denominator == 0.0: u76, v76 = 0.0, 0.0 else: ...
9aed4b49adc2e6379489009454a642f2a2fdbd92
680,811
def parent(n: int) -> int: """Return the index of the parent of the node with a positive index n.""" return (n - 1) // 2
b2b9451d00124665fd7443b6fe663f24ba6d7fc7
680,812
import collections def value_to_gdb_native(value): """Translates Python value into native GDB syntax string.""" mapping = collections.OrderedDict() mapping[bool] = lambda value: 'on' if value else 'off' for k, v in mapping.items(): if isinstance(value, k): return v(value) retu...
d53fa435c7273b6771445f0ee11e9ef70bea0232
680,813
import collections import itertools def find_repeat(data): """You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice. >>> find_repeat([+1, -1]) 0 >>> find_repeat([+3, +3, +4, -2, -4]) ...
65f46e40d434994f49ab7520ae852de1ca209da6
680,814
def _next_power_of_two(value): """Return the first power of 2 greater than or equal to the input.""" power = 1 while power < value: power *= 2 return power
3b3574e8c5fb5c051dec9d722d02e0e0e5506d09
680,815
def get_release_command_pattern(): """Returns regex pattern for matching a release command (used with git commit messages)""" return r'\(\s*release\s*(((bump)\s*(major|minor|patch))|((set)\s*v?(([0-9]+)\.([0-9]+)\.([0-9]+))))\s*\)'
65730d5dd3ad094971ef0390cb9d9e2fdb904163
680,816
import math def Tan(num): """Return the tangent of a value""" return math.tan(float(num))
0c7854800d144d68009ffd7ad7fc51d4b513186d
680,817
def make_decorator(foreign_decorator): """ Returns a copy of foreignDecorator, which is identical in every way(*), except also appends a .decorator property to the callable it spits out. """ def new_decorator(func): """wrapper to create the new decorated func""" decorator_result...
3ade3fc44c1ee6e2128a7001af34c375997f9663
680,818
def _read_file(path): """Default read() function for use with hash_files().""" with open(path,"rb") as f: return f.read()
c65dfdccdb011d4871e6d2bfaf02164e14d0e828
680,820
def expand_dict_lists(d): """Neat little function that expands every list in a dict. So instead of having one dict with a list of 5 things + a list of 3 things, you get a list of 5x3=15 dicts with each dict representing each possible permutation of things. :param d: Dictionary that can contain some...
d232db4bbc17bac728e922cd523c5d401366757a
680,821
def val(default=None): """Return the entire data value. This is the info-version of 'id'. """ def f(data): if data is None: return default else: return data return f
6ff969517174b31770dc001fe78e1008b00bbed8
680,822
import numpy def get_class_labels(y): """ Get the class labels :param y: list of labels, ex. ['positive', 'negative', 'positive', 'neutral', 'positive', ...] :return: sorted unique class labels """ return numpy.unique(y)
8096d2a8491319e0d973ef171182a3d152783c5d
680,823
def string_is_comment(a_string): """Is it a comment starting with a #.""" return a_string[0] == "#"
b605c73f12d6791fc3d78177805e2bed02aabe20
680,824
import numpy def distance_logdet(A, B): """Return the Log-det distance between two covariance matrices A and B : .. math:: d = \sqrt{\log(\det(\\frac{\mathbf{A}+\mathbf{B}}{2}))} - 0.5 \\times \log(\det(\mathbf{A} \\times \mathbf{B})) :param A: First covariance matrix :param B: Seco...
a930748c12e0a3e5a115b502e5c368e4eb53e0a6
680,825
def wrap(item): """Wrap a string with `` characters for SQL queries.""" return '`' + str(item) + '`'
bd25264ad8c3ffda41b57ba6b263105e31343b9b
680,826
def filterTags(attrs): """ Convert some ShapeVIS attributes to OSM. """ result = {} if 'HAALPLTSMN' in attrs: result['name'] = attrs['HAALPLTSMN'] result['bus'] = 'yes' # Default result['public_transport'] = 'stop_position' if 'station' in result['name'].lower() and...
0f5f9727519142b480003491996dc285be6c359b
680,827
def isSquare(mat): """ :param mat: a matrix of any dimension :return: if the matrix is true, it returns true, else returns false """ return all(len(row) == len(mat) for row in mat)
98749d5062a30f0ce15ee370111ad8bff032a5bd
680,828
import numpy as np def create_probabilities(duration=600, VT1=320, VT2=460): """Creates the probabilities of being in different intensity domains These probabilities are then sent to the CPET generator and they are used ot generate CPET vars that can replicate those probabilities Parameters: dur...
987bd6f6c4f8b172272fa5b92b2bc47e1c646ea9
680,829
def recvn(sock, n): """ Read n bytes from a socket Parameters ---------- sock - socket.socket The socket to read from n - int The number of bytes to read """ ret = b'' read_length = 0 while read_length < n: tmp = sock.recv(n - read_length) ...
07e854ea13d2bf0c74dbbea0348bf6ee15ac1a0c
680,830
def m_to_str(seq): """ :param seq: :return: """ res = [] if isinstance(seq, list): for i in seq: res.append(str(i)) return res return str(seq)
83b10082c3e7623a2321c50f47016ed883a7e49a
680,831
def is_palindrome(n): """Returns True if integer n is a palindrome, otherwise False""" if str(n) == str(n)[::-1]: return True else: return False
c297288e0af7d458b8c7c4917b1feaa558d760ab
680,832
import textwrap def prepare_description(report): """Constructs a description from a test report.""" raw = report['description'] # Wrap to at most 80 characters. wrapped = textwrap.wrap(raw, 80) description = wrapped[0] if len(wrapped) > 1: # If the text is longer than one line, add a...
999fd532dfc08aa5e9cc0ef240cb47cc0fbc817e
680,833
def read_ext(request): """ Valid extensions for reading Excel files. """ return request.param
f98eac53dc9e9063c4e5ea28dfc58932745e7302
680,834
import os def get_connection_url(user=os.environ.get('PGUSER', 'postgres'), dbname=os.environ.get('PGDATABASE', 'postgres'), port=int(os.environ.get('PGPORT', '5432')), host=os.environ.get('PGHOST', 'localhost'), password=os.environ.get('PGPASSWORD'...
236428090595a4b3f3e2e04b157324253d6cd6de
680,835
import torch def select_nms_index(scores: torch.Tensor, boxes: torch.Tensor, nms_index: torch.Tensor, batch_size: int, keep_top_k: int = -1): """Transform NMS output. Args: scores (Tensor): The detection scores of sha...
e7c34d757216f863f0b28fdada43f8f4ef096075
680,836
def all_none(centre_list): """ :param centre_list: :return: checks if all positions in a list are None """ none_yes = 1 for element in centre_list: if element is None: none_yes = none_yes*1 else: none_yes = none_yes * 0 return bool(none_yes)
333b9597ffe14352a551e622c4c95fe66e3cc53d
680,837
import os import sys def read_MAG_taxonomy(args): """[Read GTDB-TK taxonomy of MAGs] Args: args ([type]): [description] Returns: [dict]: [Dictionary with MAG taxonomic lineage] """ #gtdb_file = os.path.join(args.b,'nc_gtdbtk_MQNC/gtdbtk.bac120.summary.tsv') gtdb_file = '07_b...
221481491d73de5dbd6dd59e053704e26abaf8bf
680,838
def dict_from_cursor(cursor): """ Convert all rows from a cursor of results as a list of dicts :param cursor: database results cursor :return: list of dicts containing field_name:value """ columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for r...
88d640d78c761be8474965f1a6cce8151a2217ef
680,839
def parse_rmc_status(output, lpar_id): """ Parses the output from the get_rmc_status() command to return the RMC state for the given lpar_id. :param output: Output from IVM command from get_rmc_status() :param lpar_id: LPAR ID to find the RMC status of. :returns status: RMC status for the given...
bcb47653045ce6f08e60f70eed02477b4ff27cdc
680,840
def miles_to_kilometers(miles): """Convert miles to kilometers PARAMETERS ---------- miles : float A distance in miles RETURNS ------- distance : float """ # apply formula return miles*1.609344
65700f378a65161266a5229596765a89e6556367
680,841
def _fix_name(name): """Clean up descriptive names""" return name.strip('_ ')
656d018909e013ef34c924ee912b6f107b44d971
680,842
def compute_phi(mu: float, var: float, beta: float): """ Compute Phi ------------------------ Compute the Dispersion parameter. """ return var / (mu ** (2-beta))
e48503b4fc071543f44368f47612fc4771ccdff2
680,843
import os def get_filenames(directory): """Return a list of all the pdf files in a given directory.""" if not os.path.isdir(directory): print(f'Folder {directory} does not exist.\n' 'Using current directory instead.\n') directory = os.getcwd() pdf_files = [] for filename ...
3a587c661b5fb6b4a0711253f20e19545515c10d
680,844
from pathlib import Path def _get_timestamped_path( parent_path: Path, middle_path, child_path='', timestamp='', create=True, ): """ Creates a path to a directory by the following pattern: parent_path / middle_path / [child_path] / [timestamp] :param parent_pat...
59f39cb79cfc815aaff44db734d9cb0018e12f23
680,845
from typing import Any def empty_page_format(_, __, entry: Any) -> Any: """This is for Code Block ListPageSource and for help Cog ListPageSource""" return entry
8d8fadba1037760c55fe2be2a3802f3e1ae07017
680,846
def node2code(nodes, with_first_prefix=False): """ convert a node or a list of nodes to code str, e.g. " import paddle" -> return "import paddle" " import paddle" -> return "import paddle" """ if not isinstance(nodes, list): nodes = [nodes] code = '' is_first_leaf =...
331570be3a57f0cd3a37a6c68c515a50e9e33c74
680,847
def is_int(int_string: str): """ Checks if string is convertible to int. """ try: int(int_string) return True except ValueError: return False
4d40ee83e4c5869e569226b842188aa152154472
680,848
def _get_course_marketing_url(config, course): """ Get the url for a course if any Args: config (OpenEdxConfiguration): configuration for the openedx backend course (dict): the data for the course Returns: str: The url for the course if any """ for course_run in course....
5a45d320b3805535e3cd6018a987df6d255827b8
680,849
def get_speciesList(speciesType): """ given speciesType return a list of all species """ if speciesType == "dmel_dpse_dvir_ERCC": return(["dmel","dpse","dvir","ERCC", "uncate"]) if speciesType == "dmel_dmoj_dper_ERCC": return(["dmel","dmoj","dper","ERCC", "uncate"]) if speciesType == "dw...
126746ff7ad3e40be0e86853acf3187d646cce14
680,850
def try_get_value(obj, name, default): """ Try to get a value that may not exist. If `obj.name` doesn't have a value, `default` is returned. """ try: return getattr(obj, name) except LookupError: return default
694180b8aad2bff8288838e1cdab784c0df23864
680,851
def _get_top_menus(top_menus): """ top_menus = {"Forum": "http://localhost:8080/feed?num=1", "Contact": "http://localhost:8080/feed?num=2", "Test": "http://localhost:8080/feed?num=3"} """ return " | ".join(['<a href="{1}">{0}</a>'.format(k, v) for k, v in top_menus.iter...
cfae027b98a5736ef1e822d08110f4dab514a112
680,852
def getById(sql, conn): """ return a single row """ # execute it with conn.cursor() as cursor: cursor.execute(sql) result = cursor.fetchone() return result
9f3b14ef89a7a8a4878d0962deefb3fa38f752e4
680,853
def count_null_urls(conn): """ Queries the sqlite3 table unpaywall and finds the number of Nones in pdf_url""" cur = conn.cursor() query = """ SELECT count(*) FROM unpaywall WHERE pdf_url IS NOT NULL """ cur.execute(query) return cur.fetchone()[0]
14d88993e1310eaf0e3a5dc234f48e8f62f41cf3
680,854
def getNoMappedReadsStrCheck(inFile, outFiles): """File from map-reduce steps may carry no data. This is indicated by the string 'no_mapped_reads. This must be caught within the wrappers to know when not to exit the algorithm required by the wrapper and sebsequently exit gracefully. Given and input and ...
76c022cc59ec6a28ea3b802b354880ff9669e644
680,855
def f(x): """ THis is the doc of f(x) :param x: :return: """ return 5 + x
7dafca06c984d53067a59bd12d3096a4e73ddb2e
680,856
def check_win(secret_word, old_letters_guessed): """ this function checks whether the player was able to guess the secret word and thus won the game :param secret_word: the word the player has to guess :param old_letters_guessed: all the characters the player has already guessed :type secret_word:...
007cb0fdfc47011943f4b9cd9bdf69ba785ab51e
680,857
def get_hostname(pod, node): """ This puts together the hostname in a way that is consistent """ if pod and node: return "pod-{}-node-{}".format(pod, node) else: return None
eff342b6f49a3740d5cc9174eb578545eea241b3
680,858
import hashlib def md5_encryption(string: str) -> str: """ 对字符串进行md5加密 :param string: 加密目标字符串 :return: """ m = hashlib.md5() m.update(string.encode("utf-8")) return m.hexdigest()
6bd0eccb4ad8f35f4339c62e902a019dd9486aeb
680,859
def Axes_Set_Breakaxis(bottom_ax,top_ax,h,v,direction='v'): """ Remove the spines for between the two break axes (either in vertical or horizontal direction) and draw the "small break lines" between them. Parameters: ----------- direction: the direction of the two break axes, could ...
04eab5126aa35a85ead516979738578d8257d24e
680,860
def grad_norm(grad): """ :param grad: numpy array :return: """ grad_2d = grad.sum(axis=0) grad_max = max(grad_2d.max(), abs(grad_2d.min())) grad_norm = grad_2d / grad_max return grad_norm
bcc6c5e1fed28176e7fe8efc2bc4a0f173b1ad21
680,861
def islistoflists(arg): """Return True if item is a list of lists. """ claim = False if isinstance(arg, list): if isinstance(arg[0], list): claim = True return claim
753162d40c52fb15494c1f097e85d326f30497e3
680,863
def _extract_output(outputs): """Extract text part of ouput of a notebook cell. Parasmeters ----------- outputs : list list of output Returns ------- ret : str Concatenation of all text output contents """ ret = '' for dic...
6b3e752b027884dd335fbc15a6e57407b7032ccd
680,864
def until(upper_bound, filter_func, value): """ Similarly, a sequence of values can have a simple, recursive definition. We compare a given value against the upper bound. If the value reaches the upper bound, the resulting list must be empty. This is the base case for the given recursion. There are...
2c98e81073d8dbd5187eff4e7e40fa39107b9c2f
680,865
def generate_additional_table_header(header_length, min_year): """ On génère l'entête des tableaux complementaires pour l'utiliser dans toutes les tableaux qui seront générés :param header_length: Longueur de la :param min_year: Première année du tableau :return: Liste de string qui represente l'ent...
95ba3e43c96ffc5bb98cfbac2a8d44757523b405
680,866
def date_to_str(ts): """ Convert timestamps into strings with format '%Y-%m-%d %H:%M:%S'. Parameters ---------- ts : pd.timestamp Timestamp. Returns ------- str Strings with format '%Y-%m-%d %H:%M:%S'. """ return ts.strftime('%Y-%m-%d %H:%M:%S')
95d3ff658068394530790ae6df23759729d2596a
680,867
def list_to_tuple(x): """ Make tuples out of lists and sets to allow hashing """ if isinstance(x, list) or isinstance(x, set): return tuple(x) else: return x
044f94e94fa0220a278bffc0d1a4975fe75be8d5
680,868
def sum_digits(): """ sums, prints, and returns the digits of the number that the user inserts. the functionality can be viewed on repl.it website using the following links https://repl.it/@abdelkha/sum-digits?embed=1&output=1#main.py""" sum_ = 0 while True: try: digits = input(...
5d3a4705be42259f217a1a3bdc92964e009445f2
680,869
def stageoutPolicyReport(fileToStage, pnn, command, stageOutType, stageOutExit): """ Prepare Dashboard report about stageout policies This dashboard report will be used for reporting to dashboard and visualize local/fallback/direct stageout related issues for prod/analysis jobs. """ tempDict = {...
5315a9b5e258b6d24f0e8fc014085f91c2594c0c
680,870
import gzip import pickle import logging def load_obj(filename): """ Load saved object from file :param filename: The file to load :return: the loaded object """ try: with gzip.GzipFile(filename, 'rb') as f: return pickle.load(f) except OSError: logging.getLogge...
e7317cde84c88f4e39a57a04ce26c5d04185a33a
680,871
import os def layerapi2_label_to_plugin_home(plugins_base_dir, label): """Find the plugin home corresponding to the given layerapi2 label. We search in plugins_base_dir for a directory (not recursively) with the corresponding label value. If we found nothing, None is returned. Args: plu...
94afd2f8dba3e1c16de6f9fc882b540622a4ad83
680,872
from sympy.sets import FiniteSet, Union from sympy.geometry import Point def intersection_sets(self, o): # noqa:F811 """ Returns a sympy.sets.Set of intersection objects, if possible. """ try: # if o is a FiniteSet, find the intersection directly # to avoid infinite recursion if ...
f838b14e61db122580cd9611435e76c4f49cdbe2
680,873
import torch def scale_intrinsics(intrinsics, sy, sx): """ scale intrinsics wrong for non-diagonal intrinsics ? """ return intrinsics * torch.tensor([ [sx, 1.0, sx], [0.0, sy, sy], [0.0, 0.0, 1.0] ], dtype=torch.float32)
586c8ee8643da263d9c0e965de874164409a3fe8
680,874
def egenskaptype2qgis( egenskaptype): """ Omsetter en enkelt NVDB datakatalog egenskapdefinisjon til QGIS lagdefinisjon-streng Kan raffineres til flere datatyper. Noen aktuelle varianter #Tekst - Eksempel: Strindheimtunnelen #Tall - Eksempel: 86 #Flyttall - Eksempel: 86.0 #Kortdato - ...
6635a8d5e047829691e1dfeaeb224a8fb7ce80ff
680,875
import copy def bigger_price(limit, data): """ TOP most expensive goods """ products = [] dataset = copy.copy(data) for _ in range(limit): biggestItem = max(dataset, key=(lambda x: x['price'])) products.append(biggestItem) dataset.remove(biggestItem) return pr...
e7f16dfcb38817241a3e2716bc75c96e14e6127e
680,876
import base64 def b64urlencode(message): """ This function performs url safe base64 encoding. :param message: Message to encode, :return: Encoded string. """ return base64.urlsafe_b64encode(message)
a46a946b18041f6c9d76cb741a7b12bb0ef1b390
680,877
def lesser(tup,value): """ Returns the number of elements in tup strictly less than value Examples: lesser((5, 9, 1, 7), 6) returns 2 lesser((1, 2, 3), -1) returns 0 Parameter tup: the tuple to check Precondition: tup is a non-empty tuple of ints Parameter value: the value to...
199895708250e993b80c63669c3b68806a5aaec1
680,878
def dequote(name): """ dequote if need be """ if name[0] == '"' and name[-1] == '"': return name[1:-1] return name
752db8f14bd91460354e5357164d6da9fb22cd9d
680,879
def problem_19_1(x, y): """ Write a function to swap a number in place without temporary variables. """ # Bit-wise operations. #x = x ^ y #y = x ^ y #x = x ^ y #return (x, y) # Arithmetic operations. x = x - y y = y + x x = y - x return (x, y)
89902c1210f1b79869eef826cecd89bbba204c69
680,880
def _call_callables(d): """ Helper to realize lazy scrubbers, like Faker, or global field-type scrubbers """ return {k.name: (callable(v) and v(k) or v) for k, v in d.items()}
f424581aadcdffe26301ed604c061da521751e7c
680,881
import argparse import json def get_args(): """Argument parser. Returns: Dictionary of arguments. """ parser = argparse.ArgumentParser() parser.add_argument( '--parameterDictionary', '-paramdict', type=json.loads, required=True, action='append', help='a json string containing paramet...
ed2c1ec075b86c149a8c43b7fa3a52e385a41b6e
680,883
def generate_bs_pointers(bs_lengths, bs_size): """ It generates the pointers (i.e. time indexes) of each modified sax word into the original time-series data :param bs_lengths: list of modified sax words :type bs_lengths: list of str :param bs_size: window size (in the original time-series) of a si...
8d4c6b3369d2fcb7bb59ab73b2e75aed8c7f87db
680,884
def upper_first(text: str) -> str: """ Capitalizes the first letter of the text. >>> upper_first(text='some text') 'Some text' >>> upper_first(text='Some text') 'Some text' >>> upper_first(text='') '' >>> upper_first(text='_some text') '_some text' :param text: to be cap...
62670f7348c1384b939f25eec7df5846b0e866f1
680,885
def add_msg_to_states(states, msgs): """ Concate respective states with msgs """ new_states = [] for state, msg in zip(states, msgs): state_arr = list(state) + [msg] new_states.append(tuple(state_arr)) return new_states
2864189e50fa463376e44f4f02b03b962d2ff516
680,886
def _pathDecode(pathString): """decodes a unicode string to a dart sequence (see _pathString)""" result = [] for d in pathString: d = ord(d) if d > 0x080000: d -= 0x100000 result.append(d) return result
b6d591090f86c90ee2d07985ae11ba78e150e8cc
680,887
def parse(line): """Parses HH:MM:SS text -> (time,text)""" parts = line.strip().split(" ") return (parts[0], " ".join(parts[1:]) )
c57e1d06a702e5933610d321c13681343fe05d85
680,888
def last(mention): """ Compute the last token of a mention. Args: mention (Mention): A mention. Returns: The tuple ('last', TOKEN), where TOKEN is the (lowercased) last token of the mention. """ return "last", mention.attributes["tokens"][-1].lower()
0b252eb5a9b84806828e1866eb52b7a3381bf0ad
680,890
from typing import Any from typing import Iterable def elem(n: Any, it: Iterable[Any]) -> bool: """ Determine if iterable object contains the given element Args: n: Value to validate it: Iterable object Examples: >>> fpsm.elem(2, range(10)) True >>> fpsm.elem(...
595ce3e21bf5a6cf2c77d1417404950de6fc845f
680,891
def to_camel(string): """Convert a snake_case string to CamelCase""" return "".join(word.capitalize() for word in string.split("_"))
2962e613dbe018148126fa69649d8a9a18150081
680,892
import re def compressAlignment(alignment, gap_character="-", ignore_beginning=0): """compress an alignment string. Lower-case characters at the beginning are ignored if so wished. --xxabBCDEfgHI becomes: -6+4 This was necessary for radar output (e.g., 46497) """ # subsitute all init...
5b10735a304c5bf530eb9a11e59af14d626edead
680,893
def get_association_options(defaults=None): """Adding arguments for the association subcommand """ if defaults is None: defaults = {} options = { # Input fields to include in the cluster. '--association-fields': { "action": 'store', "dest": 'association...
29b821b60c5b7ce72a92440b0edd8de13c98b1a4
680,894
def get_temperature_number(temp_str): """ Given a temperature string of the form "48.8 °C", return the first number (in this example, 48). Also handles strings of the form "48,8 °C" that apparently can exist (at least when reading the response from a file) :param temp_str: Temperature string ...
30b9985a1d2ff4471ad4286903b035f2d1c6d589
680,895
import re def format_timestamp(timestamp): """ Format timestamp xx:xx.xxx as xx:xx.xx :param timestamp: timestamp :type timestamp: str :return: formatted timestamp :rtype: str """ if len(re.findall('\d+:\d+\.\d\d\d', timestamp)) != 0: timestamp = re.findall('\d+:\d+\.\d\d\d', ...
5317c2bb865a90e18cf2800d3240b9f1df05e969
680,896
import argparse def parameter_parser(): """ A method to parse up command line parameters. The default hyperparameters give a high performance model without grid search. """ parser = argparse.ArgumentParser(description="Run SimGNN.") parser.add_argument( "--dataset", nargs="?",...
c27faabeff309217a0a54c0cd2bdba2e291ede77
680,898
def __convert_input(val): """ Interpret and user input from weeks to days. val - input specified by end-user. Must be a str with a number followed by either "w", "d", or nothing. 'w' stands for weeks, "d" stands for days. If there is no identifier, we the end user s...
c1e52671311e077efca49e68bb26ea417c8b0648
680,899
import re def squish(text): """Turn any run of whitespace into one space.""" return re.sub(r"\s+", " ", text)
631cdf496e95cab9062156de4fcd7bf353844a50
680,900
def convert_pinyin(pinyin, pinyin_word_table, word_word_table): """ Convert pinyin to Chinese sentence. Args: pinyin: A string, a sentence of pinyin separated by space. pinyin_word_table: pinyin-word table, a dict, key->pinyin, value->[[word, log(probability)]. word_word_table: word...
5705c4f49db745e07fa2dd0c47305f6470ade48b
680,901
def compute_union_of_regions( regions ): """Compute a non-overlapping set of regions covering the same position as the input regions. Input is a list of lists or tuples [ [a1,b1], ... ] Output is a similar list. All regions are assumed to be closed i.e. to contain their endpoints""" result = [] reg...
6a5efa05a29bc9455eef8e3062c1f242262c55bc
680,902
def get_grid_coupling_list(width, height, directed=True): """Returns a coupling list for nearest neighbor (rectilinear grid) architecture. Qubits are numbered in row-major order with 0 at the top left and (width*height - 1) at the bottom right. If directed is True, the coupling list includes both [a, b...
1a34f1ea643561126073992f583fc0aee6dc902e
680,903
from datetime import datetime def get_month_number(month): """ Get the month in numeric format or 'all' Parameters ---------- month : int or str Returns ------- n_month : int or 'all' Month in numeric format, or string 'all' """ if isinstance(month, str): if ...
f3741dc80914609666da7b123109900e1ed0f11a
680,904
import fnmatch def lookup_labels(file, PDB_files, labels, verbose = True): """ returns the label for a given file or set of files file is a string that is contained within a single file, or a set of files (ex. '720.199000', or '0.850_15') """ indices=[f for f in range(len(PDB_files)) if fnmatc...
df79920c5d90b08533861cfc7a0df5d953a94aa1
680,905
def name_matches(texnode, names): """ Returns True if `texnode`'s name is on one of the names in `names`. """ if hasattr(texnode, 'name') and texnode.name in names: return True else: return False
554a24d05cc6ef93645ef6877bcae2e671cd1bed
680,906
def quote_string(prop): """Wrap given prop with quotes in case prop is a string. RedisGraph strings must be quoted. """ if not isinstance(prop, str): return prop if prop[0] != '"': prop = '"' + prop if prop[-1] != '"': prop = prop + '"' return prop
d33200564c62ce2853778f60bed7de36ac526f1f
680,907
async def absent( hub, ctx, name, zone_name, resource_group, record_type, connection_auth=None, **kwargs, ): """ .. versionadded:: 1.0.0 Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name ...
3aa18778b0fa46a393d31bedae89a1ff3f2b16c2
680,908