content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def Activate(line): """Checks if we are reading nodes, elements, or something else Parameters ---------- line : string The line to check for activation Returns ------- active : string 'nodes' if we are going to read nodes, 'elems' if we are going to read ...
323fa110c6a8004008f21dd8ad57170e5e2d59ab
647,428
import json def prettydump(pdu_obj): """Unpack PDU dictionary and dump it as a JSON formatted string""" return json.dumps(pdu_obj, indent=4, sort_keys=True)
e9f53b4213f02613eb581992e0295b40795f5c6c
647,430
def allof(*items): """ allof(*items) → Return the result of “all(…)” on all non-`None` arguments """ return all(item for item in items if item is not None)
2343fded5ad33e65faccdd13f215ddc0dce2d0df
647,431
def negative_dice_parse(dice: str) -> str: """ :param dice: Formatted string, where each line is blank or matches t: [(t, )*t] t = (0|D|2T|FT|2F|F|T) (note: T stands for Threat here) :return: Formatted string matching above, except tokens are r...
473eda79fdf761dc552c4afe193b288f9eb77075
647,432
def bridge_h_1(current_state, goal_state): """ adds up the amount of time remaining on the left side :param current_state: :param goal_state: :return: """ h = 0 for x in current_state.state[0].values(): h += x return h
fbf54a78ffc4c7c5a6b74f662e8216e054c05b96
647,434
from typing import OrderedDict def merge_list(col1, col2): """ Given two sequences col1 and col2, returns a list of the items in them, in order, omitting any from col2 that are also in col1. """ cs = OrderedDict() for c in col1: cs[c] = 0.0 for c in col2: cs[c] = 0.0 ...
b7070f916c75acc627689d6adc56eea316080816
647,435
def show_seconds(value, show_units): """Return nicely formatted seconds.""" if value is None: return "unknown" if show_units: return f"{value} s" return value
24aed8018571c233aaf94079aeee6cff34f63e26
647,436
def calculate_n50(contigs, assembly_size): """Calculate the n50 of the assembly.""" n50_stats = {'n50': 0, 'l50': 0} total_length = 0 total_contigs = 0 for length in contigs: total_length += length total_contigs += 1 if total_length >= assembly_size//2: n50_stats[...
ee0aaf0f51a0a519fa0bcf954a4e364c7d22f275
647,439
def write_iter_in_file(path_to_file_write, iterable, fun_prepline=None, mode="w"): """ Write a iterable as text line in file >>> mi_iterable = ["line1", "line2", "line3"] >>> write_iter_in_file("file.txt", mi_iterable) 3 :param path_to_file_write: path file where write :param iterable: Ite...
108f6948c657b1f2dda913f427732b62d75dadd1
647,443
from typing import List from typing import DefaultDict def __distinct_elems(mols: List[DefaultDict[str, int]]) -> List[str]: """Get the distinct elements that form the molecules.""" elems = set() for mol in mols: for key in mol: elems.add(key) return list(elems)
f96f4be0768d33253b30fb9278a616126f96720b
647,445
import random def delay_exponential(base, growth_factor, attempts): """Calculate time to sleep based on exponential function. The format is:: base * growth_factor ^ (attempts - 1) If ``base`` is set to 'rand' then a random number between 0 and 1 will be used as the base. Base must be gr...
15cea06599ac26f03fd1b89c9d2c56342fb8dc96
647,447
def implies(a: bool, b: bool) -> bool: """Implication (IF...THEN)""" return (not a) or b
378a01b5c857346488355a2ba71d0ea9b02126dd
647,453
def _get_acq_time(start, default_value=-1): """Private helper function to extract the heuristic count time The SPEC-style plans inject a heuristic 'count_time' (which has different meanings in different contexts) as a top-level key in the RunStart document. Parameters ---------- start : Do...
ad5bdffb0951abe30873c847f6611d37310651db
647,456
def _DictToTuple(to_sort): """Converts a dictionary into a tuple of keys sorted by values. Args: to_sort: A dictionary like object that has a callable items method. Returns: A tuple containing the dictionary keys, sorted by value. """ items = to_sort.items() items.sort(key=lambda pair: pair[1]) ...
4fccdfcd7a8e4f03e7b12de05aa87ad0a9bfe96f
647,457
def file_contains_doctests(path): """Scan a python source file to determine if it contains any doctest examples. Parameters ---------- path : str Path to the module source file. Returns ------- flag : bool True if the module source code contains doctest examples. """ ...
6ebeecaa96278be103db1ea577accf6ee63f2442
647,460
def parse_hex_color(color): """Parses a hex format color string, i.e. #ccc or #12ab34, into an (r, g, b) tuple.""" color = color.strip('#') if len(color) == 3: color = ''.join(ch*2 for ch in color) if len(color) == 6: r = int(color[0:2], base=16) / 255 g = int(color[2:4], base=16...
95398d933dd29f8654d4ad5dd6b49e9e7f59ae11
647,461
def cal_intersection(points): """ Calculate the intersection of diagonals. x=[(x3-x1)(x4-x2)(y2-y1)+x1(y3-y1)(x4-x2)-x2(y4-y2)(x3-x1)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)] y=(y3-y1)[(x4-x2)(y2-y1)+(x1-x2)(y4-y2)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]+y1 :param points: (x1, y1), (x2, y2), (x3, y3), (x4, y4). ...
6e4902136b516aa7930c96985b27b5cf3bb1ba1c
647,462
def alignValue(value, align): """ Align a value to next 'align' multiple. >>> alignValue(31, 4) 32 >>> alignValue(32, 4) 32 >>> alignValue(33, 4) 36 Note: alignValue(value, align) == (value + paddingSize(value, align)) """ if value % align != 0: return value + alig...
f0331e6e8a363fdc41af863d86ce0903f2fd47a5
647,464
def make_list(value): """Return a list of items from a comma-separated string. Surrounding whitespace will be stripped from the list items. If the provided string is empty, an empty list will be returned. This function will also accept the value None and return an empty list. """ if value is No...
e7ceb8e49c1ab6fa4618065c3b25d1a31f6ccb2e
647,466
def nestedmap(f, args, type=list): """ Map `f` over `args`, which contains elements or nested lists """ result = [] for arg in args: if isinstance(arg, type): result.append(list(map(f, arg))) else: result.append(f(arg)) return result
ed286a1d1f529042c2dd3df21f112b1afd3d7262
647,470
import math def part_1(memory_loc): """Get the manhattan distance from a location to the centre of a (1-indexed) spiral array Arguments --------- memory_loc : int, the location of the starting point. Locations are numbered anticlockwise from the centre, and head right first, e.g. ...
05d9490c7695b5635ba936352a32985009533cad
647,473
def parserDateToString(date): """Funkcja zmieniająca obiekt datetime.date na string postaci YYYYMMDD""" date = str(date) date = date.replace('-','') return date
8d115683e90b4ed98cf4cf586a64878399e69ac3
647,475
def rgb_to_hex(rgb): """Converts an rgb tuple to hex string for web. >>> rgb_to_hex((204, 0, 0)) 'CC0000' """ return ''.join(["%0.2X" % c for c in rgb])
40e325c766b486f8f55148f094fd6776f8d53e76
647,477
import pytz def tz_aware(dt, tz): """ Ensures that a datetime object is time zone aware. Only makes changes to naive datetime objects. :param dt: datetime -- any valid datetime object :param tz: string in IANA time zone database format -- the timezone to attach to the object :returns: datetim...
b055e1442badab7f8cc9ebb980f05704a1edf455
647,478
def poly_desc(W, b): """Creates a string description of a polynomial.""" result = 'y = ' for i, w in enumerate(W): result += '{:+.2f} x^{} '.format(w, len(W) - i) result += '{:+.2f}'.format(b[0]) return result
ef2a870916581f2da48aed7010a81adf3af823f1
647,481
def get_prefix(network): """Convert network type to prefix of address :param network: testnet or mainnet :type network: str :returns: tbnb or bnb """ return 'tbnb' if network == 'testnet' else 'bnb'
ba4af04093f5486be68c70df20d87733d4f146fa
647,486
def __insert_color_custom(txt, s, c): """insert HTML span style into txt. The span will change the color of the text located between s[0] and s[1]: txt: txt to be modified s: span of where to insert tag c: color to set the span to""" return txt[:s[0]] + '<span style="font-weight: bold;color: {0}...
60e7177b588c48c20a5146a92e49f99ad232eb5a
647,489
def normURLPath(path): """ Normalise the URL path by resolving segments of '.' and '..'. """ segs = [] pathSegs = path.split('/') for seg in pathSegs: if seg == '.': pass elif seg == '..': if segs: segs.pop() else: seg...
78abcc6c1cce17e5678baac10af96db508b3d57a
647,490
def compose1(f, g): """Return a function that composes f and g. f, g -- functions of a single argument """ def h(x): return f(g(x)) return h
8d4829a787b78826f1c03d5e9621fb7d6a6ea56c
647,491
def get_messages_per_weekday(msgs): """Gets lists of messages for each day of the week (7 lists in a dictionary total). Args: msgs (list of MyMessage objects): Messages. Returns: A dictionary such as: { day_of_the_week (int 0-6): list off all messages sent on th...
aaa509db067a0b42a3d6af0ff5bdbe4128cde9f5
647,494
def aq(string): """ Add the quotes " characters around a string if they are not already there. Parameters ---------- string : str just a string to be formatted Returns ------- str a string with " character at the beginning and the end """ tmp = string if n...
c255361e546703eb35cc88af6745001dfee62327
647,495
def _is_valid_back_ref(index): """ Helper method used to ensure that we do not use back-reference values that would produce illegal byte sequences (ones with byte 0xFE or 0xFF). Note that we do not try to avoid null byte (0x00) by default, although it would be technically possible as well. :param in...
ea8c62d7a0676c8b68116317515e9b2a89fdfb88
647,496
import torch def edge_loss(disp, img): """Computes the smoothness loss for a disparity image The color image is used for edge-aware smoothness """ grad_disp_x = torch.abs(disp[:, :, :, :-1] - disp[:, :, :, 1:]) grad_disp_y = torch.abs(disp[:, :, :-1, :] - disp[:, :, 1:, :]) grad_img_x = torch...
cee22a18da59f873afb58a29d193a62b0fcdea73
647,498
def event_split(string, event_type): """Return a list of event type and event action. Args: string (str): The supplied string that will be splitted. event_type (str): The event type (execute, log, set, etc). Returns: list: A list of the splitted string Examples: >>> is...
f5193878ebba6344b343fb57c58c6032e5bab41e
647,505
def format_time( seconds ): """ Formats the time, in seconds, to a nice format. Unfortunately, the :py:class:`datetime <datetime.datetime>` class is too unwieldy for this type of formatting. This code is copied from :py:meth:`deluge's format_time <deluge.ui.console.utils.format_utils.format_time>`. :param ...
dba02e146b363b5a468a2a5939d9ab96dafaf838
647,506
from typing import Any from pydantic import BaseModel # noqa: E0611 import importlib def build_model(model: Any, backend: str) -> BaseModel: """ Build a correct model wrapper given the backend :param model: any neural network models, see backend folder for more details :param backen...
a6e74545e31dab479ab9bbf7532ace3e88d9b90e
647,509
import re def version_greater_or_equal_than(version_str, other_version_str): """ Checks if a version number is >= than another version number Version numbers are passed as strings and must be of type "N.M.Rarb" where N, M, R are non negative decimal numbers < 1000 and arb is an arbitrary string. For ...
94d5232851f63ac5b6c2d0d2a2ad5df68729c1db
647,528
from typing import List def fixture_family_tag_names(vcf_tag_name: str, family_tag_name: str) -> List[str]: """Return a list of the family tag names""" return [vcf_tag_name, family_tag_name]
def503a86ea26f989cfd46a2b98af1379d5ddf47
647,531
import math def Percentile(values, percentile): """Returns a percentile of an iterable of values. C = 1/2 The closest ranks are interpolated as in "C = 1/2" in: https://en.wikipedia.org/wiki/Percentile """ values = sorted(values) index = len(values) * percentile - 0.5 floor = max(math.floor(index), 0...
1ab78b82d41422ecb566f2e325d28bcecd0f9380
647,535
import math def distance(p0, p1): """ returns distance between two pubg points in meters :param p0: point 1 :param p1: point 2 :return: """ return math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2 + (p0[2] - p1[2]) ** 2) / 100
82cdac882b58ccbe4f7190b260e13518494f5b02
647,539
def ask_for_continuation(iteration: int) -> bool: """ Ask the user if we can proceed to execute the sandbox. :param iteration: the iteration number. :return: True if the user decided to continue the execution, False otherwise. """ try: answer = input( "Would you like to proc...
93f007c7ac40bf618eee04dea01e25c2a85cc005
647,540
import requests def get_ipam_roles(url, headers): """ Get dictionary of existing IPAM roles """ api_url = f"{url}/api/ipam/roles/" response = requests.request("GET", api_url, headers=headers) all_roles = response.json()["results"] roles = [] for role in all_roles: role_info = d...
d912691e86812bb8adf478fc4cd0329e4b1ce86c
647,542
def node_bounds(*nodes): """Get the min and max for the x- and y-coordinates for an iterable of `daft.Node`s.""" xs = list(n.x for n in nodes) ys = list(n.y for n in nodes) return (min(xs), max(xs)), (min(ys), max(ys))
4248961bbbc3ca0c6618d9a255bae41c8b904d81
647,543
def cert_get_serial(cert): """ Fetch the serial number from the certificate. :param cert: :return: serial number """ return cert.serial
2051b04277543bafe68c10146f8920e9d9d2fcc5
647,550
from typing import Optional from typing import Union from typing import List from typing import Tuple def normalize_to_list( value: Optional[Union[str, List[str], Tuple[str, ...]]] ) -> List[str]: """ Takes the different formats of options containing multiple values and returns the value as a list obj...
a85a8dd102ffad99ecec8bd3695e09342c99a9a6
647,552
import hashlib def _hash_gene(gene, length=6): """Get the first letters of the SHA-1 digest of the gene.""" encoded = sum( v * 4 ** i for i, v in enumerate(gene) ).to_bytes(13, byteorder='big') digest = hashlib.sha1(encoded).hexdigest() return digest[0:length]
981722aeafeef4899a858da9998fe95046207218
647,560
def _tags_to_dict(s): """ "k1=v1,k2=v2" --> { "k1": "v1", "k2": "v2" } """ return dict(map(lambda kv: kv.split('='), s.split(",")))
62387274b9cf033909e4d37dbd804b714afb8c2e
647,562
def formatStyle(a): """Format an inline style attribute from a dictionary""" return ";".join([att+":"+str(val) for att,val in a.iteritems()])
e7c615c2c3ed24014b1f2922aac8cf9789826929
647,566
import re def _get_log_fname(mtz_fname): """ convert an mtz filename to the corresponding main log filename """ regex = re.compile(r'(.*)_all.mtz$') hit = regex.search(mtz_fname) assert hit is not None assert len(hit.groups()) == 1 return hit.groups()[0] + '_main.log'
ba70819f29d983535808f23c805814a1a74850df
647,567
def create_connectivity_list(shape, element_offset=0): """Use the element indices for each shape to create the connectivity list""" num_points = len(shape.points) num_parts = len(shape.parts) elements = [] for i in range(num_parts): # parts[] returns the point index at the start of each par...
7febca3aba0cd6a83ef7ee3370ee57b99e50615c
647,568
def month_difference(from_date, to_date): """ gets the number of months between from_date and to_date could be negative or zero example usage: >>> month_difference(datetime(2010,10,1), datetime(2010,11,1)) 1 """ return (to_date.year - from_date.year) * 12 + (to_date.month - from_...
f0dd16b71e97a280e8ec0c0bd557cee45e70b76f
647,569
def dt_str(dt_object, format_='%Y-%m-%dT%H:%M:%S') -> str: """ Converts python datetime object into datetime string """ return dt_object.strftime(format_)
0f4588df718aade8a4850b2f3c04ac161aa44d54
647,571
def generateFilename(photoInfo, photoNum): """Creates a file system file name for a photo. The file name will be in the format date-taken_title.extension. For example, 20180521203625_My_Flickr_Picture.jpg. The date taken will be a numeric string which means the pictures on the file system will sort i...
0bd1711078dac94fcbf068789b4358a97b05f93f
647,572
def getNestedValue(dictionary, keyString, default=None): """ Returns the value from a nested dictionary where '.' is the delimiter """ keys = keyString.split('.') currentValue = dictionary for key in keys: if not isinstance(currentValue, dict): return default curr...
b5193cf1d29a9877737c4a208f972d566e6214f4
647,573
def remove_ticks(ax, x=False, y=False): """ Remove ticks from axis. Parameters: ax: axes to work on x: if True, remove xticks. Default False. y: if True, remove yticks. Default False. Examples: removeticks(ax, x=True) removeticks(ax, x=True, y=True) """ if x: ax...
6f2b9d5b2f76a648ee0f2d4eac45213a83dac7d2
647,576
import torch def normalize_tensor_one_minone( pp: torch.Tensor, ) -> torch.Tensor: """ Receives a tensor and retrieves a normalized version of it between [-1, ..., 1]. We achieve this by normalizing within [0, 2] and subtracting 1 from the result. """ pp_norm = pp.float() pp_max = pp_norm....
0b013cc324f782c9989848de438abf81339e8077
647,577
from typing import Optional def get_description(description: Optional[str]) -> str: """Filter. Get the description of a property or an empty string""" return description or ""
9d56b2312d8ec45a3321dcfcd7584d5504547839
647,579
def Hex2Alpha(ch): """Convert a hexadecimal digit from 0-9 / a-f to a-p. Args: ch: a character in 0-9 / a-f. Returns: A character in a-p. """ if ch >= '0' and ch <= '9': return chr(ord(ch) - ord('0') + ord('a')) else: return chr(ord(ch) + 10)
86917deb9d0f4af8426b880fe8f28ea637747fff
647,585
def _crypt_audio_packet(packet: bytes, key: bytes) -> bytes: """Encrypt/decrypt a plaintext/encrypted audios stream payload. Skips encryption/decryption if packet is less than or equal to 0x140 bytes. """ data = bytearray(packet) if len(data) > 0x140: for i in range(0x140, len(data)): ...
1bc1e84e459a9a41d1c8b3b73448579be39c3a34
647,586
import json def json_encode(data, *args, **kwargs): """Encodes a dictionary into a JSON string Arguments: data {dict} -- Dictionary to encoded Returns: str -- JSON encoded string """ return json.dumps(data, *args, separators=(',', ':'), **kwargs)
9ba19524250e79ea0830016f04a281ffddbb35bc
647,588
import re def remove_URL(text: str)-> str: """ Removes URL patterns from text. Args: `text`: A string, word/sentence Returns: Text without url patterns. """ url = re.compile('https?://\S+|www\.\S+') text = url.sub('',text) return text
2b992490591030e2c2be29d0df9ab38d1bd66ddb
647,589
def split_by_bar(abc_string): """ Takes a string of full ABC notation and splits it into lists representing individual bars """ result = abc_string.split('|') return [x for x in result if x != '']
f6a44d9fce478c491a4072f0c27998a31d169a65
647,591
import math def convert_bytes(size): """Make a human readable size.""" label = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') try: i = int(math.floor(math.log(size, 1024))) except ValueError: i = 0 p = math.pow(1024, i) readable_size = round(size/p, 2) return '{}{}'....
b4b070e85d31c0c607422667aa7f79bc0c21bcfc
647,594
def objtag(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: objtag(tagkey) objtag(tagkey, category) Only true if accessed_obj has the specified tag and optional category. """ if hasattr(accessed_obj, "obj"): accessed_obj = accessed_obj.obj tagkey = args[0] i...
7c730527b292fdd4dc8f0e26680a2c78fae0f551
647,595
def rec_replace(l, d): """ Recursively replace list l with values of dictionary d ARGUMENTS: l - list or list of lists d - dictionary where if an element in l matches d['key'], it is replaced by the value OUTPUT: l - list with elements updated """ ...
8b4bb40238d8304f5da8c5b5408541a2742b7ea1
647,596
def _map(args): """Mapping helper function for mp_list_map.""" lst, fnc, kwargs = args return fnc(list(lst), **kwargs)
18326e23549216bd16f80057d50935bf4b52f914
647,601
def read_file(name): """ Reads the content of a text file specified by the user. """ file = open(name, 'r', encoding="UTF-8") return file.read()
364ca6419dfd8bb56f35616ce2db0cc3265aafe5
647,603
import math def is_prime(n): """Return True if n is a prime number, else False.""" return n >= 2 and not any( n % p == 0 for p in range(2, int(math.sqrt(n)) + 1))
9f85a0e67cf3420cbf07c3f915af7eeb9e931f48
647,604
def get_block_id(color, id_tag="00"): """Get block identifier based on color Args: color (string): string representation of color id_tag (string, optional): prefix for the object. Defaults to "00". Returns: string: block identifier as string """ return "%s_block_%s"...
52ad52a24f5719f51cc976b464c4e74ef51cab33
647,607
def findStartOfLine(text,offset,lineLength=None): """Searches backwards through the given text from the given offset, until it finds the offset that is the start of the line. With out a set line length, it searches for new line / cariage return characters, with a set line length it simply moves back to sit on a multip...
c1b8b055ef91a53a618b8bddf4915c47e7bef631
647,610
def dodo_existing(tmpdir): """ Set up a project with a DODO file """ prjdir = tmpdir.join('projdir') prjdir.ensure(dir=True) prjdir.join('.project').ensure() dofile = prjdir.join('DODO') dofile.write("\n - this is a task\n") return (prjdir, dofile)
66bf3a3162091b957adfcac0d7f6d78690632477
647,611
def get_theta_bounds(priors): """ Returns the state vector parameters bounds. Parameters ---------- priors : list of instantiated Prior objects :class:`Prior` vector Returns ------- bounds : list List of (min, max) tuples """ return [prior.get_bounds() for prior...
440348e552027ebb51f92962fea5d537c7c4916f
647,615
def title(snake_case: str): """Format snake case string as title.""" return snake_case.replace("_", " ").strip().title()
362161e7cbfc2451bd3cb3bcb60ef4cfa2eaf415
647,616
def merge_duplicate(merged_streams_in_island_list): """ Merge lists that have at least one common element into one list. :param merged_streams_in_island_list: list of lists to test and merge :type merged_streams_in_island_list: list of lists :return: list of merged lists :rtype: list o...
f461121f3310a007a1058a4ac64a5e71415428b4
647,617
from pathlib import Path from datetime import datetime def most_recent_run(outputs_path, fmts=["%Y-%m-%d", "%H-%M-%S"]): """Get the most recent Hydra run folder. Parameters ---------- outputs_path : pathlib.Path or str The root Hydra outputs directory fmts : list Optional list of ...
4440f95390550997f2b88b1454d6095d4f2860d0
647,618
def b_overlap_a(a, b, alab='a', blab='b', verb=False): """Check if there is any value in `b` inside the range of the values in `a`. Only checks if there is overlap, but not how (e.g. do not tell if all values of b inside a, or just from one side). Examples -------- a: ' |---| ' b: '|--...
1fd137cf4ff3bf13440e5543fa574b15472ca091
647,622
def Artifact(file_path, view_url=None, fetch_url=None, content_type='application/octet-stream'): """Build an Artifact dict. Args: file_path: A string with the absolute path where the artifact is stored. view_url: An optional string with a URL where the artifact has been uploaded to as a ...
605c865b92090906aa91d89d7782d377826ed3cb
647,624
def careful_update(adict, bdict): """ Carefully updates a dictionary with another dictionary, raising a ValueError if keys are shared. """ if not set(adict.keys()).isdisjoint(set(bdict.keys())): raise ValueError('adict shares keys with bdict') else: adict.update(bdict) ...
ed5eca1a867fe3bc0aac60886c457b58f5997e9d
647,626
def update_dict_key(dict_value, key_map): """将字典中的key进行修改 Args: dict_value:原始字典 key_map: key映射dict类型 Returns: 返回修改后的字典 举例: dict_value = {'a':1,'b':2} key_map = {'a':'c'} 返回值new_val = {'c':1, 'b':2} """ new_val = dict_value.copy() for k, v in ke...
bf4d78798514144ac5c1396f67558480c3f7affd
647,635
def create_lookup_tables(unique_words): """ Create lookup tables for word_to_id and id_to_word Args: unique_words: dictionary of words in training set Return: word_to_id: dict with words as keys and corresponding ids as values id_to_word: dict with ids as keys and corr...
44a99e615c5be147039a2c030e8a45a8c01080b2
647,636
import urllib3 def read_pdbid(pdbid): """ Read a pdb file from the PDB. Need an internet connection. Parameters ---------- pdbid: Name of the pdb file. (ex: 1dpx or 1dpx.pdb) Return ------ The content of the pdb file """ # URL of the PDB url = 'http://files.rcsb.org/downl...
b4eb2f0d4b20be877faa0e2f4df0a4a2825841ae
647,640
def single_structure_property_predicted(body): """ Method for make message as dict with data which would be send to rabbitmq ml single structure property predicted queue :param body: body of message received from RabbitMQ queue :type body: dict :return: single structure property predicted messa...
a18eef6efe28a5e7f8f65637ec3d42fd34e88f93
647,643
def word_splitter(df): """ This function takes pandas dataframe as input, split the sentence into a list of separate words and returns a modified dataframe Example Input: Tweets Date @IamGladstone @CityPowerJhb @HermanMashaba The... 2019-11-29 11...
aa11ba70a2c6de89fd048ad100c88b5056876c98
647,644
from typing import Awaitable from typing import Dict from typing import Any import aiohttp import json async def download_data(url) -> Awaitable[Dict[str, Any]]: """The download_data method downloads json data from the `url`. Args: url (str): the url that the user wants to download Returns: ...
ee27b08a61dc008fdcfd2d4f80316d259fe0fd5c
647,645
def xeval(sexpr): """ >>> xeval('') 0 >>> xeval('1234567') 1234567 >>> xeval('+1234567') 1234567 >>> xeval('-1234567') -1234567 >>> xeval('2+3') 5 >>> xeval('2-3') -1 >>> xeval('2-23+4') -17 >>> xeval('2-01+3-1') 3 >>> xeval('1-2-3-4-5') -13 ...
9e7f8120b9f546fdc94c08ab0ee9978d528309f2
647,646
from pathlib import Path from typing import Dict import re def parse_debian_control(cwd: Path) -> Dict[str, str]: """ Extract fields from debian/control :param cwd: Path to debian source package :return: Dict object with fields as keys """ field_re = re.compile(r"^([\w-]+)\s*:\s*(.+)") co...
4788719a9322703807f0e87ee431e1a160f98fac
647,650
def _get_cover_address(metadata): """Returns cover address. Returns ------- int cover address """ if 'COVER_1' in metadata.footer: address = int(metadata.footer['COVER_1']) else: address = 0 return address
20fa5cda7b26034835900d60bafcf1894596cef7
647,651
def end_ea(obj): """ Return end ea for supplied object. :param obj: Object to retrieve end ea. :return: end ea. """ if not obj: return None try: return obj.endEA except AttributeError: return obj.end_ea
8960419bc65833813e131358e3b12b90d036930f
647,654
def chunk(array, num_memory_steps): """Chunk an array into size of N steps. The array of size N x k_1 x ... k_n will be reshaped to be of size Batch x num_memory_steps x k_1 x ... k_n. Parameters ---------- array: Array. Array to reshape. num_memory_steps: int. Number of st...
90ae3e049e95aa38a8eb35f06c80875874160315
647,663
def compute_CdS_from_drop_test( terminal_velocity, rocket_mass, air_density=1.225, gravity=9.80665 ): """Returns the parachute's CdS calculated through its final speed, air density in the landing point, the rocket's mass and the force of gravity in the landing point. Parameters ---------- t...
17d56bf6fb35f363eeb2ba398cf17a4e3b988435
647,664
def cvars(occs): """ Return a single representative occurrence for each variable. """ names = [] canonicals = [] for occ in occs: if occ.name in names: continue canonicals.append(occ) return canonicals
939490076d20ba686f6547a36914452500b15af8
647,665
def convert_to_babylonian_time(seconds): ############################################################################### """ Convert time value to seconds to HH:MM:SS >>> convert_to_babylonian_time(3661) '01:01:01' """ hours = int(seconds / 3600) seconds %= 3600 minutes = int(seconds / ...
da785fe6f76dc4e22c96a741fd50749b46da125b
647,666
import yaml def load_yaml_file(file_name): """Load YAML file. Parameters ---------- file_name: str or pathlib.Path YAML file name. Returns -------- dict_data: dict YAML contents. """ with open(file_name, 'r') as f: dict_data = yaml.load(f, L...
7f2ac99700a80bc4eb99752f14ca1e67da41665c
647,668
def within(self, index): """ Like between() but takes a pandas index object. :param pandas.Index index: pandas index :returns self: result of between() with start/end as the ends of the index. """ try: start = index.min().start_time end = index.max().end_time except Attribut...
d09c662b9e3d743d14535d3d99c6d4d53cd5a205
647,672
def read_transcripts(transcript_file): """Return a dict containing transcript data with UCSC ID as key""" transcripts = dict() f_in = open(transcript_file) for line in f_in: data = line.rstrip('\n').split() transcript_data = { 'chrom': data[2], 'start': int(da...
cf00783e91667dc7516a68bcf700195b792f254c
647,674
import torch def batch_rotate_p4(batch, k, device=None): """Rotates by k*90 degrees each sample in a batch. Args: batch (Tensor): the batch to rotate, format is (N, C, H, W). k (list of int): the rotations to perform for each sample k[i]*90 degrees. device (str): the device to allocate...
e6d3365c5ba3c073cb7d63d97b1208b5584a947e
647,675
def lin_sum(x, lr, y): """Returns linear sum.""" return x + lr * (y - x)
6a7996e82ee7c0a8f611e8995c5537939e680564
647,677
def select_tags(tag_list, key_list): """ Return selected tags from a list of many tags given a tag key """ select_list = [] # select tags by keys in key_list for tag in tag_list: for key in key_list: if key == tag['Key']: select_list.append(tag) # ensure o...
66dd34b06a06c7dd26b59368522a1a33fb5fab08
647,678
import random import string def get_random_str(length): """ Returns a random string of length characters. """ return ''.join(random.choice(string.ascii_letters) for _ in range(length))
978dcb0a7a6d6cff87a1ce18a3474325e3fce941
647,681
def huber(x, y, scaling=0.1): """ A helper function for evaluating the smooth L1 (huber) loss between the rendered silhouettes and colors. """ diff_sq = (x - y) ** 2 loss = ((1 + diff_sq / (scaling**2)).clamp(1e-4).sqrt() - 1) * float(scaling) return loss
fe9ba23d60ddd6effbeec9c9b49634a443ba1ae9
647,682