content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def get_test_files(package='test'): """ Load all test_XX.py module names from the test dir. """ try: files = [s for s in os.listdir(package) if s.startswith('test_')] except EnvironmentError as ex: raise EnvironmentError( 'Unable to list "test" dir: {}'.format(os.getc...
d1e0a3be0a77f3a11efd2eb0af9250c120539cb8
686,317
def add_titles_to_keys(idx_file, n): """ :param idx_file: path to idx file :param res_keys: current keys extracted from dictionnary :param n: number of titles to add """ titles = set() with open(idx_file, 'r') as fd: for line in fd: for word in line.split(' '): ...
f2fbd506b10c7817676e2640b287537c00c14b43
686,318
import calendar def decimal_year(test_date): """ Convert given test date to the decimal year representation. Repurposed from CSEP1 Author: Masha Liukis Args: test_date (datetime.datetime) """ if test_date is None: return None # This implementation is based on the Ma...
99ee10f9a2a27b1ff05d57152169e288718ca040
686,319
def get_longest_substring(a, b): """ This fuction is used to get the longest substring of two strings Args: a & b Return: c: longest substring """ a_len, b_len = len(a), len(b) dy_map = [[0 for j in range(b_len + 1)] for i in range(a_len + 1)] longest = 0 for idx, ite...
9647d0d3806313249414307835ba9fec5b1bd25a
686,320
def read_scores_into_list(scores_file): """ Read in scores file, where scores are stored in 2nd column. """ scores_list = [] with open(scores_file) as f: for line in f: cols = line.strip().split("\t") scores_list.append(float(cols[1])) f.closed assert scores_...
3b972bef937293aa12101205ae2a4979bc2161f6
686,321
def serialize_person_link(person_link): """Serialize PersonLink to JSON-like object.""" data = {'email': person_link.person.email, 'name': person_link.display_full_name, 'fullName': person_link.display_full_name, 'firstName': person_link.first_name, 'familyName': ...
36f3c1a15738ddb4a9594fad3a72e40cc81f88de
686,322
def fields(cursor): """ Given a DB API 2.0 cursor object that has been executed, returns a dictionary that maps each field name to a column index, 0 and up. """ results = {} for column, desc in enumerate(cursor.description): results[desc[0]] = column return results
2ee53896033dd05f88394605850b34be87e719d4
686,323
import random def eval_iter(source, batch_size): """ A iterator for evaluation, it gives a list of batches to be iterate through -Args: @source (during evaluation) @batch_size: int -Returns: @batches: generator giving list of batches """ batches = [] dataset_size = len(source) start = -1 * batch_size o...
eea2600152cd53ef62011ce64da948e3095573df
686,324
def introspection_email(request): """Returns the email to be returned by the introspection endpoint.""" return request.param if hasattr(request, 'param') else None
a2cf38e02fe16571e0971142528ee4a7a001564b
686,325
def submat(M,i,j): """ return a copy of matrix `M` whitout row `i` and column `j` """ N = M.copy() N.row_del(i) N.col_del(j) return N
cb3de622a554645b4600f801e607d1e66a225a8e
686,326
import json def parse_data_file(data_path): """ Parse data file with benchmark run results. """ with open(data_path, "r") as fp: content = fp.read() data = json.loads(content) return data
87e337d1b5a7809382aa2749881894df791e4c9f
686,327
import re def splitTypeName(name): """ Split the vendor from the name. splitTypeName('FooTypeEXT') => ('FooType', 'EXT'). """ suffixMatch = re.search(r'[A-Z][A-Z]+$', name) prefix = name suffix = '' if suffixMatch: suffix = suffixMatch.group() prefix = name[:-len(suffix)] ret...
1a7013b82e554fe6ff6ebff1b84d7d96ae3481db
686,328
from typing import Dict def stream_error(e: BaseException, line: str) -> Dict: """ Return an error `_jc_meta` field. """ return { '_jc_meta': { 'success': False, 'error': f'{e.__class__.__name__}: {e}', 'line': line.strip() ...
d7c9364103d03dc4ca00c3ca447f9ae8a0b20f08
686,329
def import_object(name): """Function that returns a class in a module given its dot import statement.""" name_module, name_class = name.rsplit('.', 1) module = __import__(name_module, fromlist=[name_class]) return getattr(module, name_class)
da49ca7198f53fb6540b8179d7ba481fa09ff9fb
686,331
import requests def target_link_data(qID, kind): """ :param qID: Pharos ID for the gene target :param kind: link of interest :return: """ url = "https://pharos.nih.gov/idg/api/v1/targets/{}/links(kind={})".format(qID, kind) info = requests.get(url).json() return info
335f473323134eed810d17c6c5f474a1a632969c
686,332
def is_numeric(value): """ check whether a value is numeric (could be float, int, or numpy numeric type) """ return hasattr(value, "__sub__") and hasattr(value, "__mul__")
dd4320dcaaf51a39589f812b5d2ec5ca20976b24
686,333
def process(apikey, session, subject): """ perform actual lookup, apikey = API key, s = Requests session """ did = str(subject) url = "https://cnam.bulkCNAM.com/?id=" + apikey + "&did=" + did # print(url) result = session.get(url) status = result.status_code if status != 200: prin...
3833e0a920f69d1f6d8bed0e8e13e8a09630a813
686,334
def to_sets(arr): """ make sets out of the entries of arr for easier comparison """ list_of_sets = [set(e) for e in list(arr)] for s in list_of_sets: if -1 in s: s.remove(-1) return list_of_sets
64c485718b477f50d44035eb3b2e16498aee1c18
686,335
def has_extension(filepath, extensions): """Check if file extension is in given extensions.""" return any(filepath.endswith(ext) for ext in extensions)
9ad2f3692185340ecf170b5befef69df4e4fc4b8
686,337
def to_basestring(s): """Converts a string argument to a byte string. If the argument is already a byte string, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(s, bytes): return s return s.encode('utf-8')
58cb048fbbbb73d34a8b88ab0555da2a99cd74c5
686,338
def dont_check_me(x): """Ensure unit_test=False works""" return x
45a8b4393ecb8bfb5a11095e53cbbe755b0c7e07
686,339
def get_content_zip_path(content_path): """ Returns the content path inside zip archive """ content_path = content_path.replace('/./', '/') if content_path.startswith('/'): content_path = content_path[1:] if content_path == '': return 'content.xml' return '{}/content.xml'.for...
e367a422f652756b6f5f4d3671e90c0fe4c63bdd
686,341
from pathlib import Path def read_numbers(path: Path, cast=int) -> list[int]: """Read numeric data from a text file.""" if cast not in (int, float): raise ValueError("Can only cast values to int or float") data = [] with open(path, "r") as file: for line in file.readlines(): ...
4439cce93a8866cba78551fbb0f507ec0f467a95
686,342
def cross(str_a, str_b): """Cross product (concatenation) of two strings A and B.""" return [a + b for a in str_a for b in str_b]
c6e026e19bbde0749272adec8baa3ebf7b19d32e
686,343
def getKeyNamePath(kms_client, project_id, location, key_ring, key_name): """ Args: kms_client: Client instantiation project_id: str - location: str - key_ring: str - key_name: str - Returns: key_name: str - 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/keyR...
059e30a69aba64e641f9c8aaecab0b575322e877
686,344
def _extract_mime_types(registry): """ Parse out MIME types from a defined registry (e.g. "application", "audio", etc). """ mime_types = [] records = registry.get("record", {}) reg_name = registry.get("@id") for rec in records: mime = rec.get("file", {}).get("#text") if m...
d071be57ddf99e401a037a505fe31241c2f6d080
686,345
def num_pos(y_test): """ Gets number of positive labels in test set. :param y_test: Labels of test set :type nb_points: `np.array` :return: number of positive labels :rtype: `int` """ if y_test == []: return 0 else: return sum(y_test)
5cdb04d6b15e38e26310ceb545fea33c992540d1
686,346
def location(C,s,k): """ Computes the location corresponding to the k-value along a segment of a polyline Parameters ---------- C : [(x,y),...] list of tuples The coordinates of the polyline. s : int The index of a segment on polyline C. Must be within [0,n-2] k : float ...
7e7ae7cb89f2ee73a916bd6bc923d3f62438fb41
686,347
import os def _get_git_path(): """Get the path to the local git repo.""" package_dir = os.path.dirname(__file__) root_dir = os.path.normpath(os.path.join(package_dir, os.pardir)) return os.path.join(root_dir, '.git')
fefd47dca9b317d6835117cd8e3664a2c3a09652
686,348
def _create(wlk, root, api): """ Implementation detail. """ api.set_ns_prefix('VSO', 'http://virtualsolar.org/VSO/VSOi') value = api.get_type('VSO:QueryRequestBlock')() wlk.apply(root, api, value) return [value]
ea319d5effbd385f0c1ddbc6ef8b67fad1628570
686,349
import re def matchLettersAndNumbersOnly(value): """Match strings of letters and numbers.""" if re.match('^[a-zA-Z0-9]+$', value): return True return False
c15cc90c6db57411373f5446abdd1ea7d66664bf
686,350
def transform(timescale, dt): """ Transform timescale to omega Parameters ---------- timescale : float or array dt : float Returns ------- float """ return 0.5 * (dt / timescale) ** 2
bc79d9208406647ab8d084aa5570e925e7143693
686,351
import math def haversine_distance(origin, destination): """ Haversine formula to calculate the distance between two lat/long points on a sphere """ radius = 6371.0 # FAA approved globe radius in km dlat = math.radians(destination[0]-origin[0]) dlon = math.radians(destination[1]-origin[1]) a = math.sin(dl...
f9e9591ba20d8a024e8d06d78a0872cefe1b5d25
686,352
from pathlib import Path from typing import Union import hashlib import re def insert_hash(path: Path, content: Union[str, bytes], *, hash_length=7, hash_algorithm=hashlib.md5): """ Insert a hash based on the content into the path after the first dot. hash_length 7 matches git commit short references ...
65854fcefe34bb36c4036465a26cddbd5b3efedb
686,353
import codecs import random def true_rand_choice(seq, file_rand='randorg.txt'): """даёт истинно случайный выбор из листа, используя файл с истинно случайными числами randorg.txt""" file = codecs.open(file_rand,"r","utf-8") file_lines = file.read() true_rand_list = file_lines.split(', ') t_r = ...
1a9862ae06796662f171aa73f298f47b2dec3cf2
686,355
def compute_edge_nzis(nzis): """ Function that retrives the non-zero indices of a shape located on the border of that shape. """ edge_nzis = nzis[:] for dx, dy in nzis: inner_nzi = ((dx, dy + 1) in nzis and (dx, dy - 1) in nzis and (dx + 1, dy) ...
d0b43645d8b3aec1c17a0f9bce7dc0a623531619
686,356
def build_dataservices_by_publisher_query() -> str: """Build query to count dataservices grouped by publisher.""" return """ PREFIX dct: <http://purl.org/dc/terms/> PREFIX dcat: <http://www.w3.org/ns/dcat#> SELECT ?organizationNumber (COUNT(DISTINCT ?service) AS ?count) FROM <https://dataservices.fellesdatakata...
59922406f0b2d73ad2e552039b12acc60a36893b
686,357
import time def keep_time(func): """Decorator function to print time elapsed.""" def wrapper(*args, **kwargs): t0 = time.time() func(*args, **kwargs) time_elapsed = time.time() - t0 print("Time elapsed is %.2f seconds" % time_elapsed) return wrapper
21ec7d848db9d649f77da60bc8724aa4332bc8ca
686,358
def ffilter(fct, gen): """ Filters out elements from a generator. @param fct function @param gen generator @return generator .. exref:: :title: filter :tag: progfonc .. runpython:: :showcode: from sparkouille.fctmr...
4ea9f2a244b7d3eaf40fdfe827d04767a8670aa8
686,359
async def get_action(game_state, message: str, possible_actions: list) -> int: """ Helper function used to get action from player for current state of game. :param game_state: GameState object with all game data inside :param message: string with message for player :param possible_actions: list with...
ab7dfc57909289f217098612eac05edf67139812
686,360
def simplify_title(title: str): """ Takes in an anime title and returns a simple version. """ return ''.join( i for i in title if i.isalpha() or i==' ' ).lower().strip()
1783722e7df262d2254f70525fc3fc8b090c109c
686,361
import socket import logging def get_ip(): """Tries to detect default route IP Address""" s = socket.socket(type=socket.SOCK_DGRAM) try: s.connect(("8.8.8.8", 1)) ip = s.getsockname()[0] except Exception as e: logging.exception(e) ip = "127.0.0.1" finally: s...
48b706582b7d9b850e4d1e3b227bd0bb1630172e
686,362
def human_file_size(bytes_): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = float(bytes_) except (TypeError, ValueError, UnicodeDecodeError): return '0 bytes' def filesize_number_format(value): return ...
fc5761f3403acc502c96d049f7d2dbbce900ea32
686,363
import subprocess def restart_server(): """Restart worker server""" log = subprocess.check_output(['shutdown', '-r', 'now']) return log
c88ac3cb08868629cc25644a005a92b003b347a6
686,364
def motif_finder(sequence, motif): """ Given a sequence and a motif, it returns a dictionary= {position: sequence} """ offset = 0 listindex = [] i = sequence.find(motif, offset) while i >= 0: listindex.append(i) i = sequence.find(motif, i + 1) return listindex
fb251408151c5d27f04de27031f1100881def0c5
686,365
def square(file_index, rank_index): """Gets a square number by file and rank index.""" return rank_index * 8 + file_index
374e98e5ac0ff86cf0e1eded12a537ca3b48e2fb
686,366
import copy import json def copy_array_and_replace_key_values_in_dict(json_array, replacement_dictionary): """ Function to copy an array of JSON files loaded as text, do a replacement from a dictionary (replacing the keys for the values) and loading it back as an JSON Object """ NEW_JSON_ARRAY = [] ...
c22f8d280b0557a2b9fbb1d109203a8b634f83b6
686,367
from typing import Tuple def file_name_to_parts(image_file_name) -> Tuple[str, str, int]: """ Given the `file_name` field in an iMerit annotation, return the dataset name, sequence id and frame number. """ parts = image_file_name.split('.') dataset_name = parts[0] seq_id = parts[1].split('...
61861a8ff1d5b49e656ab61f5179e627e717f3ff
686,368
import collections def trainval_log_statistic(trainval_log): """ Args: trainval_log (dict): output of function: read_trainval_log_file :return: e.g.: >>> result = { >>> 'total_epoch': 100, >>> 'last_top-1_val_accuracy': 0.87, >>> 'last_top-2_val_accuracy': 0.95, ...
ec29b5f7a6099f6d9991a2d3e62e61c76590469c
686,369
import hashlib from sys import stderr def verify(data, given_hash): """verify: Ensure that hash of data and given hash match up. Currently, only a warning is emmitted if they do not. :param data: byte-like object :param given_hash: string """ if hashlib.sha1(data).hexdigest() != given_hash...
c1c0719ae0845ca5f00f4c4514a52b8b66c1902e
686,370
import hashlib def sha256_encode(text): """ Returns the digest of SHA-256 of the text """ _hash = hashlib.sha256 if type(text) is str: return _hash(text.encode('utf8')).digest() elif type(text) is bytes: return _hash(text).digest() elif not text: # Generally for cal...
88a39fb82beefa4f89abda7f995347ca16573d28
686,371
def is_current_or_ancestor(page, current_page): """Returns True if the given page is the current page or is an ancestor of the current page.""" return current_page.is_current_or_ancestor(page)
c2377e5898cb0152e4e6434c486bd500b4c54b2b
686,372
import subprocess import json def get_all_pods(kubectl: str = "kubectl"): """ get all the pods """ out = subprocess.run([kubectl, 'get', 'pods', '-o', 'json'], check=True, text=True, capture_output=True) out = json.loads(out.stdout) return out['items']
1f0694582c8f4121cfdd131fd99b3abbfb0a1712
686,373
def luhn(n): """Check a PAN against LUHN algorithm""" try: r = [int(ch) for ch in str(n)][::-1] return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0 # Returns true if the algorithm checks out except ValueError: return False
d5b7cacb1e3643a086b0fe55b83c0b23d69d1254
686,374
def prepare_chart_data(contributors, month, request): """ Prepare charts data for index page and /raw/ page. Keyword arguments: contributors -- the contributors for the month month -- the current month we want to process request -- current client request """ chart_data = [] patch_...
528ecf40979a570b7201d5bad91b8fed24f44342
686,375
def buildVecWithFunction(da, func, extra_args=()): """ Construct a vector using a function applied on each point of the mesh. Parameters ========== da : petsc.DMDA The mesh structure. func: function Function to apply on each point. extra_args: tuple extra para...
4330c4f132370ac69f5303a4a257adb05fa44976
686,376
import torch def pairwise_orthogonalization_torch(v1, v2, center:bool=False): """ Orthogonalizes columns of v2 off of the columns of v1 and returns the orthogonalized v1 and the explained variance ratio of v2 off of v1. v1: y_true, v2: y_pred Since it's just pairwise, there should not be any...
3835c2665e58d0d25ff3d447f6d638277f191fda
686,377
def _clean_sambam_id(inputname: str) -> str: """Sometimes there are additional characters in the fast5 names added on by albacore or MinKnow. They have variable length, so this attempts to clean the name to match what is stored by the fast5 files. There are 5 fields. The first has a variable length. ...
f8c641a42144fcabcfb422f406e5c1c0ab2316b1
686,378
def MS(record): """ "Maximise Severity": any alarm state on the linked record is propagated to the linking record. When propagated, the alarm status will become `LINK_ALARM`. Example (Python source) ----------------------- `my_record.INP = MS(other_record)` Example (Generated DB) -----...
7e3619e7bb0c94a7c50391a075f499498841aec7
686,380
import json def validate_invoking_event(event): """Verify the invoking event has all the necessary data fields.""" if 'invokingEvent' in event: invoking_event = json.loads(event['invokingEvent']) else: raise Exception('Error, invokingEvent not found in event, aborting.') if 'resultToke...
8c4780ddaea1e72e5c7883be75cf32333abcc47b
686,381
def check_image_png_or_webp(image_string): """Checks if the image is in png or webp format only. Args: image_string: str. Image url in base64 format. Returns: bool. Returns true if image is in WebP format. """ return image_string.startswith(('data:image/png', 'data:image/webp'))
51197cdc8fa4ff76af4906c5042433ce3f3ea14b
686,382
import math def get_oversized(length): """ The oddeven network requires a power-of-2 length. This method computes the next power-of-2 from the *length* if *length* is not a power-of-2 value. """ return 2 ** math.ceil(math.log2(length))
ac76471a535d22f1e1ff28424f368a9df3711c82
686,383
def is_set(obj) -> bool: """Checks if the given object is either a set or a frozenset.""" return isinstance(obj, (set, frozenset))
6c968f282439aafe09e4bab4dbda4b3a475a2b81
686,384
import numpy def _msa_f_op( primary_veg_smooth, primary_veg_mask_nodata, msa_f_table, msa_nodata): """Calculate msa fragmentation. Bin ffqi values based on rules defined in msa_parameters.csv. Parameters: primary_veg_smooth (array): float values representing ffqi. primary...
7bd78576321341b8ca5c5e8d1d99ffa0ad850538
686,385
def _csv_dict_row(user, mode, **kwargs): """ Convenience method to create dicts to pass to csv_import """ csv_dict_row = dict(kwargs) csv_dict_row['user'] = user csv_dict_row['mode'] = mode return csv_dict_row
b6d47f9df34b8889233ea6037f1a19c5570c392c
686,386
def divide(a, b): """Divide two numbers and return the quotient""" #Perform the division if the denominator is not zero if b != 0: quotient = round(a/b, 4) print("The quotient of " + str(a) + " and " + str(b) + " is " + str(quotient) + ".") return str(a) + " / " + str(b) + " = " + st...
c316182818ddad2b0bb5f8a455d07a4af78e7f90
686,389
import math def Euclidean_distance(x,y): """ Given two vectors, calculate the euclidean distance between them. Input: Two vectors Output: Distance """ D = math.sqrt(sum([(a-b)**2 for a,b in zip(x,y)])) return D
07bde8ae91bb2a5ceeb303e515965af320083f6a
686,392
import os def dir_last_updated(folder): """ Returns the timestamp of the last time the static folder was updated to avoid the browser caching an outdated openapi.yaml file """ return str(max(os.path.getmtime(os.path.join(root_path, f)) for root_path, dirs, files in os.walk(folder) ...
0fdb444d3c76215296c460581cc07ec704b75965
686,393
import os def load_master_txt(): """Load file containing text parts to be used in tweet""" if(os.environ.get('DEV_ENV', '') is "1"): txt_file = open("../master.txt", "r") else: txt_file = open("/txts/master/master.txt", "r") txt = txt_file.read() txt_parts = txt.split('--') sp...
da2764925b99aa6190d9ca96fc10a0a7a49b6da7
686,394
from typing import Tuple def neighbors(depths: list[list[int]], x: int, y: int) -> list[Tuple[int, int]]: """Generate the list of neighboring points for the given point""" max_x = len(depths[0]) max_y = len(depths) result = [] for _x, _y in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: ...
97776164b229edfa12cf4dfa19b9409f33e07921
686,395
import argparse from sys import version def parse_args(args=None): """Parse commandline""" parser = argparse.ArgumentParser( usage="%(prog)s [OPTIONS] [--] COMMAND [ARGS...]", description="Entrypoint and init for containers: configure via " "environment variables and YAML file; render ...
5a35ad9c3172ba6ab31bc0ab45e02b39a836e63e
686,396
import re def capitalise_chi(value): """CHI at the start of shelfmarks should always be capitalised.""" return re.sub(r'(?i)^chi\.', 'CHI.', value)
30850eae926d9b808808787367bbce1379792881
686,397
def copy_doc(source): """Copy the docstring from another function (decorator). The docstring of the source function is prepepended to the docstring of the function wrapped by this decorator. This is useful when inheriting from a class and overloading a method. This decorator can be used to copy th...
dd914e0ee648509aafeee509cb0c2175ad8ce39f
686,398
import string def ishex(hexstr): """Checks if string is hexidecimal""" return all(char in string.hexdigits for char in hexstr)
9b3c96ddb1783263f07a00493161f4315947156c
686,399
def center(self, decimals=2): """Return the geographic center point of this dataset/ dataarray.""" if self._center is None: # we can use a cache on our accessor objects, because accessors # themselves are cached on instances that access them. lon = self._obj.lon lat = self._obj.l...
47c55efb327d2eb531027684462b9ca3430a1ef9
686,400
def build_ig_bio(part_of_day, sky_cond, sky_emoji, temp_feel): """Builds IG bio.""" return f"Back page of the internet.\n\nI look up this {part_of_day} and the Toronto sky looks like {sky_cond}{sky_emoji}.\nKinda feels like {temp_feel}\u00b0C."
7b9d075f81045a4464545dc0b4548d50d2546845
686,401
def reorganize_entries(entries_native): """ Reorganize entries by organism """ entries_org = {} for entry in entries_native: taxid = str(list(entry.org_taxid)[0]) if taxid not in entries_org: entries_org[taxid] = [entry] else: entries_org[taxid].append(en...
c070ae2c2525c7d2ccc27031bbb74f78b144b4fb
686,402
def usage(): """ display the usage for this tool Returns a command line usage string for all options available by the sphinx-build-confluence extension. Returns: the usage string """ return ("""sphinx-build-confluence [action] <options> (actions) <builder> specify a b...
a7b3736f2f206914e1e3177e9d287d1dce280dd3
686,403
import six def camel_case_to_underscore_naming(source): """ 将驼峰形式字符串转为下划线形式 :param source: :return: """ if not isinstance(source, six.string_types): return source result = '' for i, s in enumerate(source): if i == 0: result += s.lower() else: ...
fccb9c8413575ad6f3965106730fe18e1d61d646
686,404
def two_fer(name="you"): """ :param name:str name of the person :return str message. """ return f"One for {name}, one for me."
cbeb6ea10bd913968f307cae4fb47adda5100ecc
686,405
def split_epiweek(epiweek): """ return a (year, week) pair from this epiweek """ return (epiweek // 100, epiweek % 100)
5627d75a36ae64b83c6a2ceacaf58725f6d81818
686,406
def _get_num_to_fold(stretch: float, ngates: int) -> int: """Returns the number of gates to fold to achieve the desired (approximate) stretch factor. Args: stretch: Floating point value to stretch the circuit by. ngates: Number of gates in the circuit to stretch. """ return int(roun...
71322e13f72111ba5af93c0011ef732ae5894771
686,407
def retrieve_options(args, env): """ Retrieve PlopRotTemp options from input arguments """ options = [] if args.core != -1: options.extend(["--core {}".format(args.core)]) if args.mtor != 4: options.extend(["--mtor {}".format(args.mtor)]) if args.n != 1000: options.e...
9a79ee77dc07d28f33c39e0147e896de4eb4fb59
686,409
import re def lreplace(pattern, sub, string): """ Replaces 'pattern' in 'string' with 'sub' if 'pattern' starts 'string'. """ return re.sub('^%s' % pattern, sub, string)
60364bc5aaabb0da7971b6d09f9dc5f5807ce613
686,410
import math def normal(x1: float, y1: float, x2: float, y2: float) -> tuple[float, float]: """ Compute the normal vector given two points """ phi = math.atan2(y2 - y1, x2 - x1) + math.pi/2 return (math.cos(phi), math.sin(phi))
31cc8728e21d00f24b79140cf258956c0b52e353
686,411
def test_banjo_player_name() -> str: """This function test banjo player name and format message.""" name = input('Are you playing banjo? Enter your name: ') if not name: exit("error: you doesn't entered name!") if name[0] == 'R' or name[0] == 'r': msg = ' plays banjo' else: ...
0a3802fdc5d9f7eb235c90b81173a9824b233e1a
686,412
def motifScoreCmp(motifOcc1, motifOcc2): """Compares two motif occurences according to their pval.""" if (motifOcc1.getPval() < motifOcc2.getPval()): return -1 elif (motifOcc1.getPval() == motifOcc2.getPval()): return 0 else: assert (motifOcc1.getPval() > motifOcc2.getPval()) ...
dce8e3e79c5a49230b3ca1aa85c2dad0d4101ed5
686,414
import uuid def valid_report_data(): """Produce valid data for making a report.""" return dict( id=str(uuid.uuid4()), status='OK', report=dict(key1='value1', key2='value2'), )
45de0e04832308c63dd02209adb2b01f67401c46
686,415
from typing import List def get_requirements() -> List[str]: """Returns all requirements for this package.""" with open('requirements.txt') as f: requirements = f.read().splitlines() return requirements
fc49b661c07c40ecf1c8d51fb90eb56ee6049a56
686,416
import os def translate_docker_path(path): """Translate docker volumes to host path. A path in docker may represent a different path on the host machine. Translate a path inside docker to a path on the host. """ with open("/proc/self/mountinfo", 'r') as mountinfo: for mount in mountinfo: host_dir...
59e1d281e64506c2fcff0edf2e81d17a3cd9553d
686,417
from typing import List import os def filter_deleted_files(input: List[str]) -> List[str]: """ Filter the list of files which no longer exist. """ return list(filter(lambda f: os.path.exists(f), input))
afd026f88ef35559f0bd1d5b5896cbeabfcb15ae
686,419
def _proto_dataset_info(dataset): """Return information about proto dataset as a dict.""" # Analogous to dtool_info.inventory._dataset_info info = {} info['type'] = 'dtool-proto' info['uri'] = dataset.uri info['uuid'] = dataset.uuid info["size_int"] = None info["size_str"] = 'unknown...
6072f5f9222f88ea1e33971036bd13d65754f39a
686,420
def escape_cell(cell): """ Escape table cell contents. :param cell: Table cell (as unicode string). :return: Escaped cell (as unicode string). """ cell = cell.replace(u'\\', u'\\\\') cell = cell.replace(u'\n', u'\\n') cell = cell.replace(u'|', u'\\|') return cell
679a47ac662f3eb61020015eb082833e2cefb16e
686,422
def get_vm_ips(nm_client, resource_group, vm_name): """ Get the private and public IP addresses for a given virtual machine. If a virtual machine has the more than one IP address of each type, then only the first one (as determined by the Azure SDK) is returned. This function returns the following ...
fb32b4b16e1c70f268f42abe15fef02398d8e06d
686,423
import torch def direct_predict(model, data): """ Method to handle direct model prediction. :param model: trained model :param data: data to be passed into model """ with torch.no_grad(): output = model(torch.tensor(data, dtype=torch.float32)) return output.numpy()
b76e1c7636f9cd8825a7768aea046baf188690b5
686,424
def interpolate_group(group, classes, params, group_names): """ In the dict returned by get_nm_group, replace class and parameter IDs, and other group IDs, with their appropriate string or dict representations. :param group: the Group dict returned by get_nm_group() :type group: dict :param...
e0fa803da2bc3f897cb2e27b282ee59dd9341512
686,425
def format_datetime(dt): """Format a datetime for use in HealthVault requests. :param dt: The datetime to format :type dt: datetime.datetime :returns: time in `HealthVault dateTime format <http://msdn.microsoft.com/en-us/library/ms256220.aspx>`_ (CCYY-MM-DDThh:mm:ss) :rtype: string """ ...
f5173c09f34d18a77ad83ec16ecc4bf7ff8bd878
686,426
from typing import Dict from typing import Any def get_allocation_goal(**attributes: Dict[str, Any]) -> Dict[str, Any]: """Retrieve the reliability goal for the hardware item. Used to select the goal for the parent hardware item prior to calling the do_allocate_reliability() method. :param attribute...
c63b0a91a90035c72090e4b526d2c45c9d721890
686,427
def make_header(lines): """returns one header line from multiple header lines""" lengths = list(map(len, lines)) max_length = max(lengths) for index, line in enumerate(lines): if lengths[index] != max_length: for i in range(lengths[index], max_length): line.append("")...
c30ab9f172c1131ff2fda3521a700a1ed838cff5
686,429
def iterize(obj): """ Converts into or wraps in an iterator. If `obj` is an iterable object other than a `str`, returns an iterator. Otherwise, returns a one-element iterable of `obj`. >>> list(iterize((1, 2, 3))) [1, 2, 3] >>> list(iterize("Hello!")) ['Hello!'] >>> list...
83964bb497339a9aa73def3911a25bf743b0b29e
686,430