content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Dict import torch from typing import List def collect_flow_outputs_by_suffix( output_dict: Dict[str, torch.Tensor], suffix: str ) -> List[torch.Tensor]: """Return output_dict outputs specified by suffix, ordered by sorted flow_name.""" return [ output_dict[flow_name] for...
5706a1645ca4d2e9cd263f699a21ed00d140de94
679,585
from typing import Counter def _counterSubset(list1, list2): """ Check if all the elements of list1 are contained in list2. It counts the quantity of each element (i.e. 3-letter amino acid code) in the list1 (e.g. two 'HIS' and one 'ASP') and checks if the list2 contains at least that quant...
a1420117f259351cdc86182f278e2b285efc56a1
679,586
def clean_url(address): """Remove unwanted data and provide a default value (127.0.0.1)""" if address == "": return '127.0.0.1' address = address.replace("http://", "") address = address.replace("https://", "") address = address.split(":")[0] return address
94cd8067f4142d4e97e5ad5119a7ac3a8447e786
679,587
import numpy def isnan(x): """Check if nan. :param x: The value to be checked. :type x: int or float :return: Whether nan or not. :rtype: bool """ return numpy.isnan(x)
14dd77bd1fa23a84a4ba656a82864d6070e920fc
679,588
from typing import OrderedDict def pivot(data=None, data_row_label=None, row_list=None, row_label=None, column_list=None): """Pivot a processed data structure. Keyword Arguments: data: The already processed dataset. Should be a list of dicts data_row_label: Accessor for the current row label ...
c078af0854d36dc5e7abf516a67c797dd9d08fa8
679,589
def string_encode(key): """Encodes ``key`` with UTF-8 encoding.""" if isinstance(key, str): return key.encode("UTF-8") else: return key
e143e32135c17a066dbacc4e1ce21461c1c2ceae
679,590
def hasanno(node, key, field_name='__anno'): """Returns whether AST node has an annotation.""" return hasattr(node, field_name) and key in getattr(node, field_name)
257f8fb3b2295ab0dbe112fe9379b9b713a36931
679,591
def readlink(path): """Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using ``os.path.join(os.path.dirname(path), result)``.""" return ""
a900531d33bf0c7bfa4756abbac299729b528baf
679,592
import os def GetCSnakeUserFolder(): """ Get the csnake folder. """ # csnake user folder userFolder = os.path.expanduser("~") + "/.csnake" # create it if it does not exist if not os.path.exists(userFolder): os.mkdir(userFolder) return userFolder
7846889747c3134cbc78fd361d084a97382c1cf6
679,593
def create_iam_policies(context): """Creates a list of IAM policies for the new project. Arguments: context: the DM context object. Returns: A list of policy resource definitions. """ policies = [] # First, we pre-fill the policy list with Firecloud-wide role grants. These # include roles g...
76bc31959df27ebd9f470ac2abf3c7a4640a3e80
679,594
def checkPath(path_type_in): """ function: Check the path: the path must be composed of letters, numbers, underscores, slashes, hyphen, and spaces input : path_type_in output: NA """ pathLen = len(path_type_in) i = 0 a_ascii = ord('a') z_ascii = ord('z') ...
d2c3a826d26b267772ad697be271764b61bd1fd5
679,595
def scale_reader_decrease(provision_decrease_scale, current_value): """ :type provision_decrease_scale: dict :param provision_decrease_scale: dictionary with key being the scaling threshold and value being scaling amount :type current_value: float :param current_value: the current consumed ...
255af14433efdecfa257df5df4c545b0e476c9d8
679,596
import logging def compareFuzzies(known_fuzz, comparison_fuzz): """ The compareFuzzies function compares Fuzzy Hashes :param known_fuzz: list of hashes from the known file :param comparison_fuzz: list of hashes from the comparison file :return: dictionary of formatted results for output """ ...
0421a10c70e3cc89022619b07d1621d93efaa4c8
679,597
import typing def _rounded(d: typing.SupportsFloat) -> float: """Rounds argument to 2 decimal places""" return round(float(d), 2)
88f85627c447a568c792059ac31c0efa29b9cb5a
679,598
def ping_parser(line): """When Twitch pings, the server ,ust pong back or be dropped.""" if line == 'PING :tmi.twitch.tv': return 'PONG :tmi.twitch.tv' return None
59221051bfb84fab841fb18b561ab259b5b1fd52
679,599
def _in_matched_range(start_idx, end_idx, matched_ranges): """Return True if provided indices overlap any spans in matched_ranges.""" for range_start_idx, range_end_idx in matched_ranges: if not (end_idx <= range_start_idx or start_idx >= range_end_idx): return True return False
6419a3039d251ae1e23cf8f6414e60b9710f584e
679,600
def _tf2idxf(tf_d, tidx_d): """ _tf2idxf(): Don't use it directly, use tf2idxf instead. This function is getting a TF dictionary representing the TF Vector, and a TF-Index. It returns a Index-Frequency dictionary where each term of the TF dictionary has been replaced with the Index number of...
460aeba0a89aed4287d9c80f71de1f3ec79d9c88
679,601
def get_facts(device): """ Gathers facts from the <file-list/> RPC. """ home = None rsp = device.rpc.file_list(normalize=True, path="~") if rsp.tag == "directory-list": dir_list_element = rsp else: dir_list_element = rsp.find(".//directory-list") if dir_list_element is no...
42a7387a9eb4e5b5a95820438b676345e53df3a2
679,602
def isSubList(largerList, smallerList): """returns 1 if smallerList is a sub list of largerList >>> isSubList([1,2,4,3,2,3], [2,3]) 1 >>> isSubList([1,2,3,2,2,2,2], [2]) 1 >>> isSubList([1,2,3,2], [2,4]) """ if not smallerList: raise ValueError("isSubList: smallerList is empty: %s"% smallerList) ...
533fe07e3b3b3687cf7d708dcc6b0d7c3677d262
679,603
def merge_sort(arr): """ Merge sort repeatedly divides the arr then recombines the parts in sorted order """ l = len(arr) if l > 1: mid = l//2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < le...
0db88996a16e2d7a40604395a43a18b5bc985a02
679,604
def add(a,b): """这是一个用来进行加法的函数""" c=a+b; return c
c47eb6e420eb5948a164fae601881f65582bdf45
679,605
import torch def mls_similarity_deformation(vy, vx, p, q, alpha=1.0, eps=1e-8): """ Similarity deformation Parameters ---------- vx, vy: torch.Tensor coordinate grid, generated by torch.meshgrid(gridX, gridY) p: torch.Tensor an array with size [n, 2], original control points, ...
440ddee891d7065fbdf059e3b4029804a7aef4ec
679,606
import os import json def animals_page_two(): """Returns data for Animal category Page 2""" path = os.path.join(os.path.dirname(__file__), "data", "animals_page_two.json") with open(path) as fp: data = json.load(fp) return data
72ceff5695adc6407b85c25e496f4d192487db93
679,609
def valid_parentheses(parens): """Are the parentheses validly balanced? >>> valid_parentheses("()") True >>> valid_parentheses("()()") True >>> valid_parentheses("(()())") True >>> valid_parentheses(")()") False >>> valid_parentheses("())") ...
ce241f7fdd337424a17d04fee51e814eaea382aa
679,610
def getLastRun(): """(Integration only) Retrieves the LastRun object :return: LastRun object :rtype: ``dict`` """ return {"lastRun": "2018-10-24T14:13:20+00:00"}
32369a465fc376e601d8f583fd194d554e673be7
679,611
import re def is_file_pattern(text): """ >>> is_file_pattern('file.java') True >>> is_file_pattern('.gitignore') True >>> is_file_pattern('file') False >>> is_file_pattern('java') False >>> is_file_pattern('*.java') True >>> is_file_pattern('docs/Makefile') True ...
8b7592ebb58cbb57b793dcbed41f71980ad0e887
679,612
def gc_percent(seq): """ Calculate fraction of GC bases within sequence. Args: seq (str): Nucleotide sequence Examples: >>> sequtils.gc_percent('AGGATAAG') 0.375 """ counts = [seq.upper().count(i) for i in 'ACGTN'] total = sum(counts) if total == 0: retu...
c74fe809ca74952456b815f345c13a5f52ca51a5
679,613
def build_superblock(chanjo_db, block_group): """Create a new superblock and add it to the current session. Args: chanjo_db (Store): Chanjo store connected to an existing database block_group (list): group of related database blocks Returns: object: new database block """ superblock_id, some_blo...
6f06c99a971e944ec23e3205e6bc1108a05e1acf
679,614
def post_authorizable_keystore(intermediate_path, authorizable_id, operation=None, current_password=None, new_password=None, re_password=None, key_password=None, key_store_pass=None, alias=None, new_alias=None, remove_alias=None, cert_chain=None, pk=None, key_store=None): # noqa: E501 """post_authorizable_keystore...
78cc4ba2bae1ab9db3eadf4497b59c8af37c4a96
679,615
import glob import os def get_last_chkpt_path(logdir): """Returns the last checkpoint file name in the given log dir path.""" checkpoints = glob.glob(os.path.join(logdir, '*.pth')) checkpoints.sort() if len(checkpoints) == 0: return None return checkpoints[-1]
438471961f868577acd076ca9ab625b9fdb75b9a
679,616
def prune_small_terms(hpo_counts, min_samples): """ Drop HPO terms with too few samples """ filtered_counts = {} for term, count in hpo_counts.items(): if count >= min_samples: filtered_counts[term] = count return filtered_counts
53edbe05ef91aa7b63aa5dade2ae48c721821956
679,618
import jinja2 def get_jinja_parser(path): """ Create the jinja2 parser """ return jinja2.Environment(loader=jinja2.FileSystemLoader(path))
18f0a673035592f26690c50e28426221aee0925c
679,619
def debian_number(major='0', minor='0', patch='0', build='0'): """Generate a Debian package version number from components.""" return "{}.{}.{}-{}".format(major, minor, patch, build)
2aa9471d0ebed91d8ab45ed8db4208e4220f94c5
679,620
import logging def get_request_data(request): """ Retrieve request data from the request object. Parameters ---------- request: object the request object instance Returns ------- Dictionary the request data from the request object. Raises ------ Exception: ...
90fb5c4be02e975ec27162b4033d14f839dc2c30
679,621
def get_prospective_location(location, velocity, time): """Calculate the final location and velocity based on the one at time 0""" return [l + v * time for l, v in zip(location, velocity)]
1c67fe7c81edb440727b4d41f1ae15a5d961fd67
679,623
import json def pretty_jsonify(data): """Returns a prettier JSON output for an object than Flask's default tojson filter""" return json.dumps(data, indent=2)
b36d2579b16c622f4b050ab86cf7cf1a153877d1
679,624
def get_id_by_binary_ip_mask(binary_ip, binary_mask): """ Метод проходит по октетам в обратном порядке и выполняет пересечение маски и ip Если октет маски != 00000000, то двоичные элементы ip адреса над не нулевыми элементами маски - искомый id Пример 00000000 10000110 00000101 - ip 00001111 ...
b40deb64fa884704c2dffecb511d4387f3eda36d
679,625
def sum(arr): """递归求和,但是这种实现方式是mutable的,即会改变传入的数组 Arguments: arr {[list]} -- [待求和的list] Returns: [int] -- [和] """ item = arr.pop(0) if len(arr): item += sum(arr) return item
ba512966ae0cba04f65590f44279fe1c9fdfd32b
679,626
def depth_link(endpoint, exchange, instrument, starttime): """ starttime: YYYY-mm-dd """ base_url = f"/market-depth/{exchange}/{instrument}?startTime={starttime}" return endpoint + base_url
f7129cd73fa1c11a55aa54b15d94505922c44fe0
679,628
def _check_pixel(tup): """Check if a pixel is black, supports RGBA""" return tup[0] == 0 and tup[1] == 0 and tup[2] == 0
a12b1a8ce51a59e37326ef8f7bc80a5e5a907a1a
679,629
def deprecated_argument_lookup(new_name, new_value, old_name, old_value): """Looks up deprecated argument name and ensures both are not used. Args: new_name: new name of argument new_value: value of new argument (or None if not used) old_name: old name of argument old_value: value of old argument (...
5702e58179daf18bca5504fc3fffdab73e993b44
679,630
import math def estimate_site_upgrades(region, strategy, total_sites_required, country_parameters): """ Estimate the number of greenfield sites and brownfield upgrades for the single network being modeled. Parameters ---------- region : dict Contains all regional data. strateg...
6858a3d4eeacb68626f3ec4adc7059e950c5e970
679,631
from typing import Tuple def float_to_hm(fraction: float) -> Tuple[int, int]: """Convert fraction of a day into hours and minutes :type fraction: float :rtype: float """ if not (0 <= fraction < 1): raise ValueError("Incorrect time") time = fraction * 24 hours = int(time) min...
d32f3b9029d152367b6c25abac04530ec19168b9
679,632
import torch def total_variation(x): """ Total Variation Loss. """ return torch.sum(torch.abs(x[:, :, :, :-1] - x[:, :, :, 1:]) ) + torch.sum(torch.abs(x[:, :, :-1, :] - x[:, :, 1:, :]))
057e2635ea9c7c78d89b8c0de134044140f2ee5a
679,633
def match_asset(asset_name, goos, goarch): """ Compate asset name with GOOS and GOARCH. Return True if matched. """ asset_name = asset_name.lower() goarch = { "386": ["386"], "amd64": ["amd64", "x86_64"] }[goarch] match_goos = goos in asset_name match_goarch = any([wo...
1d058237e0c903f7a8542975b862165f98e75f46
679,634
def basic_color(code): """ 16 colors supported """ def inner(text, rl=False): """ Every raw_input with color sequences should be called with rl=True to avoid readline messed up the length calculation """ c = code if rl: return "\001\033[%sm\002%s\001\0...
d310431d7bb6a8bae8fc2f78bf26779c5ef03783
679,635
def process_input_dict(input_dict, set_permissions=False): """ Turn string values from checkboxes into booleans :param input_dict: :param set_permissions: whether or not to insert missing permissions :return: """ # if we get a list (which is valid JSON), expand the list if isinstance(inp...
01f41722afb3fb6fa7292771e932f42837baac8d
679,638
def create_fill_row_string(slot1: str, slot2: str, gap_space: int): """ creates a gap with variable spaces according to the length of the slot string """ return '|' + slot1 + (' ' * (gap_space-(2 + len(slot1) + len(slot2)))) + slot2 + '|'
04e3b394fc7351e209f3ddac8ed67479b0173853
679,639
import numpy def get_minimum_tags(bad, section, tags, vector_distance, verbose=False): """return the minimum edit distance in the pairwise comparison of all sequence tags. if verbose, return all tags compared that are at the minimum edit distance""" bad[section]['minimum'] = 10000 bad[section]['ta...
5eba4ba9e3d4b7fc835d208993fa508baad48ea2
679,640
from typing import List from typing import Any def list_union(a: List[Any], b: List[Any]) -> List[Any]: """Return union of two lists maintaining order of the first list.""" return a + [x for x in b if x not in a]
f2c085a42276bdc4c11f1df172a997db2c87916c
679,641
import torch def kl_diag_gauss_with_standard_gauss(mean, logvar): """Compute the KL divergence between an arbitrary diagonal Gaussian distributions and a Gaussian with zero mean and unit variance. Args: mean: Mean tensors of the distribution (see argument `mean` of method :func:`sampl...
94e4fb3c372b27adb1c7084889bd330faa50e4c5
679,642
def read_taxids(filename): """ read masked list of taxids from file """ with open(filename, 'r') as fh: taxids = fh.read().splitlines() return taxids
e17d3aa31bef72a03121966edab8aec951972ba9
679,643
def selected_conflicts(conflict_gdf, **kwargs): """Creates a plotting instance of the best casualties estimates of the selected conflicts. Args: conflict_gdf (geo-dataframe): geo-dataframe containing the selected conflicts. Kwargs: Geopandas-supported keyword arguments. Returns: ...
d9a49887070709ccb455c1a4c490caa34227d3df
679,644
def event_handler(event_name): """ Decorator for designating a handler for an event type. ``event_name`` must be a string representing the name of the event type. The decorated function must accept a parameter: the body of the received event, which will be a Python object that can be encoded as a J...
55906894c2b0dd2b62b76a29a827bd238f3bb703
679,645
def _get_boot_time(): """Return system boot time (epoch in seconds)""" f = open('/proc/stat', 'r') for line in f: if line.startswith('btime'): f.close() return float(line.strip().split()[1])
dc2397dd476d1d58d7a9cbbb5e72f308ca5b500d
679,646
import functools import time def slow_down(_func=None, *, rate=1): """Sleep given amount of seconds before calling the function *, : means all floowing parameters are keyword only function to decorate is only passed in directly if the decorator is called without arguments """ def decorator_slo...
8e78cf7bad9d72ceed1ff297c3b6d31c504d7f73
679,647
def sum_two(num_1, num_2): """ This function returns the sum of two numbers """ return num_1 + num_2
7af9e7abe366441c8e6e25686b81124e5967bddf
679,648
def equation_quad(x, a, b, c, d=0, e=0): """Equation form for quad """ return a + b*x + c*x*x
a51ac7aef82026e2cb2de73d62dc99357c860652
679,649
def fix_config_list(config_list): """ transforms a list of the form ['a, b'] to ['a', 'b'] """ if not config_list: return [] t = config_list item = t[0] list_items = item.split(',') return [nr.strip() for nr in list_items]
a514302578b9edebbdc929836eaef08046f8a69c
679,650
def collabel_2_index(label): """Convert a column label into a column index (based at 0), e.g., 'A'-> 1, 'B' -> 2, ..., 'AA' -> 27, etc. Returns -1 if the given labe is not composed only of upper case letters A-Z. Parameters ---------- label : string Column label (expected to be composed...
929d4b26dc9ec58bc55f397c2e67158ed0176a1d
679,651
def calculate_total_votes(poll): """Calculate the total number of votes of a poll.""" total = 0 for vote in poll.votes: total += vote.vote_count return total
4a6314a0a4ffb1a80c8e5a927631ceb5fa646a4b
679,652
def __none_mult(x, y): """PRIVATE FUNCTION, If x or y is None return None, else return x * y""" if x is not None and y is not None: return x * y return None
88cd9fca1fbb3f2ab10dec22a73e792201b20578
679,653
def get_rescale_ratio(image, target): """Gets the required ratio to rescale an image to a target resolution :param image: An image to resize. :param target: The target resolution to resize to. :type image: Image :type target: int :return: The min of the ratio between the target resolution and t...
d3a27b9cfb787bc586a0a97a58578e593ad1d66e
679,654
from typing import Dict def load_config() -> Dict: """ 导入配置信息 :return: """ config = {} with open('./http_request/config.txt', 'r') as f: lines = f.read().strip().split('\n') for line in lines: line = line.strip().split(',') config[line[0]] = line[1] ...
f94a5a4f2a269cc91fa8f7eb275a11ba87c75be1
679,655
def option_name(path, delimiter="--"): """ Returns a cli option name from attribute path **Arguments** - path (`list`): attribute path - delimiter (`str`): delimiter for nested attributes **Returns** cli option name (`str`) """ return "--{}".format(delimiter.join(path).replace("...
0beab1b60f5ec479e70a4e12af799ca5efe0230a
679,656
import os def pathjoin(*path): """ Copy of ``os.path.join`` to make the function name shorter. :param: path: Path to file :type: path: str """ return os.path.join(*path)
32fdc07107a9511b9520a7b094c2eb15dcf905b0
679,657
def showp1rev(context, mapping): """Integer. The repository-local revision number of the changeset's first parent, or -1 if the changeset has no parents.""" ctx = context.resource(mapping, 'ctx') return ctx.p1().rev()
9be762e9c12f1271be289614d9c570775a7397af
679,658
def ledaLines(lines): """Filter sequence of lines to keep only the relevant ones for LEDA.GRAPH""" def relevant(line): return line and not line.startswith('#') return filter(relevant, lines)
1b1e67f59f6fb262795dc9f550e3bcc5d32f5de2
679,659
import random def generate_bootstrap_batch(seed, data_set_size): """Generate the IDs for the bootstap""" random.seed(seed) ids = [random.randint(0, data_set_size-1) for j in range(int(data_set_size*0.8))] return ids
c21fb30ae203a83ed6c73dcd1c7fd0cbd48d4d8e
679,660
import colorsys def rgb_to_hls(r, g ,b): """Convert R(0-255) G(0-255) B(0-255) to H(0-360) L(0-255) S(0-255). """ rgb = [x / 255.0 for x in (r, g, b)] h, s, v = colorsys.rgb_to_hls(*rgb) return (h * 360, s * 255, v * 255)
4f20041e55e0d9bdb7f4200afaa3e609cd300169
679,661
def int_or_float(x): """Return `x` as `int` if possible, or as `float` otherwise.""" x = float(x) if x.is_integer(): return int(x) return x
eacef4f2f88351f0d0a8832afcbebb12be305b26
679,662
def is_single_color_image(image): """ Checks if the `image` contains only one color. Returns ``False`` if it contains more than one color, else the color-tuple of the single color. """ result = image.getcolors(1) # returns a list of (count, color), limit to one if result is None: ...
d81d2a6f0eb697ffd87713c750a5c0b6867de44f
679,663
def aggregate_group(df, aggregate_me, name="aggregated_group"): """ Aggregates several rows into one row. df: str aggregate_me: list. One or more values from the new_var column may be given as a list. This function takes those values (rows), aggregates them, and returns one ro...
e819dea3b2903256ac5c430a6d8c07b1c5265daf
679,664
def convert_ahref_to_extlink(xml_etree): """ This methods receives an etree node and replace all "a href" elements to a valid ext-link jats compliant format. """ for ahref in xml_etree.findall('.//a'): uri = ahref.get('href', '') if len(uri) == 0 or not uri.strip().startswi...
f7d788a5517bde4ed0fabefda683399abf0e8ac4
679,665
def is_youtube(raw_song): """Check if the input song is a YouTube link.""" status = len(raw_song) == 11 and raw_song.replace(" ", "%20") == raw_song status = status and not raw_song.lower() == raw_song status = status or 'youtube.com/watch?v=' in raw_song return status
32583391962e23f2b1409b506a316f9d0df34ed3
679,666
def get_rickroll_text(): """ Returns: string with the entire lyrics of Rick astley's "never gonna give you up" """ return """We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell ...
92e47f92c91674c0135230c4b5c29658524abbaf
679,667
import re def remove_relative_imports(source) -> str: """ Remove all the relative imports from the source code :param source: :return: """ return re.sub(r"^#include \"(.+)\"$", "", source, flags=re.MULTILINE)
06c126b7fe3fe347256d75f2241893f2fb88b926
679,668
def build_node_types(meta_node, outfile): """build_node_types""" nt_ori2new = {} with open(outfile, 'w') as writer: offset = 0 for node_type, num_nodes in meta_node.items(): ori_id2new_id = {} for i in range(num_nodes): writer.write("%d\t%s\n" % (offse...
d147d98aefd72c0a6e94ee3d42d2b4193afdc07f
679,669
def get_table_names(connection): """ Gets all table names in the specified database file. :param connection: Connection to the DB file. :return: List of table names """ connection.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = [] for table in connection.fetchall(...
0be8aff053b4aef6d4d7deef2ea965471b081f01
679,671
import os def is_processed(xml_file, df): """ For a given xml_file, use the file name to check whether the file has a corresponding entry in the input dataframe. """ file_name_id = os.path.splitext(xml_file)[0] is_processed = df.isin([file_name_id]).any().values[0] return is_processed
943b9b5dfb638b175cf8683712bcceacb27a1de3
679,673
def get_breadcrumb(cat3): """包装面包屑导航数据""" # 包装面包屑导航数据 breadcrumb = {} breadcrumb['cat3'] = cat3 breadcrumb['cat2'] = cat3.parent cat1 = cat3.parent.parent cat1.url = cat1.goodschannel_set.all()[0].url breadcrumb['cat1'] = cat1 return breadcrumb
411845a23616deefb4f424abe75b765b95e30770
679,674
import itertools def binary_cartesian_product(nb_bits: int): """ Compute binary possibilities of an nb_bits variable. """ ranges = [range(0, 2) for i in range(nb_bits)] # In possibilities, we compute the nb_bits cartesian product of set([0, 1]} possibilities = list() for xs in itertools.pr...
21333911eb19550c2cf8de895e27619c8ebdcf15
679,675
def prompt_txt_file_name(): """Prompts user for desired name of .txt file. Currently does not check for other file types. :return: The name of a .txt file :rtype: str """ while True: # if necessary, add extensions to list and check containment extension = ".txt" file_na...
1ae766708f9d1b7d3b1b71abdcec158a5d6c7ac4
679,677
import argparse def initialize_arguments(args): """ initilize arguments """ parser = argparse.ArgumentParser( description = 'Find match map between RTL Names & Gate-Level Names') parser.add_argument('--match', type=str, required=True, help="""match output file (RTL name -> Gate-level name)""") parser...
64a8a1a918cb935b9d234938fa7c3c342db5ce19
679,678
import torch def RotBox2Polys_torch(dboxes): """ :param dboxes: :return: """ cs = torch.cos(dboxes[:, 4]) ss = torch.sin(dboxes[:, 4]) w = dboxes[:, 2] - 1 h = dboxes[:, 3] - 1 x_ctr = dboxes[:, 0] y_ctr = dboxes[:, 1] x1 = x_ctr + cs * (w / 2.0) - ss * (-h / 2.0) x2 ...
8683b6022610c1480e7bb74966fcdafb1c52d3be
679,679
from typing import List def brute_force(num_lst: List[int], pivot: int) -> List[int]: """ Given a list and a pivot, sort so that all elements to the left of the pivot(s) are less than the pivot and all elements to the right of the pivot(s) are greater than the pivot. Runs in O(3n) but not constant storage...
b11fdc8ef5e5a10b3756380881daecdcdfba05b2
679,680
def set_session_value(key_string, value_list, prefix='', rconn=None): """Return True on success, False on failure Given a key_string, saves a value_list with an expirey time of 7200 seconds (2 hours) The items are saved as strings. empty values are stored as '_'""" if not key_strin...
5cca5d8c425ba31af7703ba908cebf12c244a6d9
679,681
import pandas as pd def load_all_db(FOLDER): """ Args: FOLDER (str): path to network folder. Returns: stops_file (pandas.dataframe): dataframe with stop details. trips_file (pandas.dataframe): dataframe with trip details. stop_times_file (pandas.dataframe): dataframe with s...
4eccc3f84c35d0d3e55bc33850361c0232052982
679,682
def Circle(name, rad=1.): """ Create a hostobject of type 2d circle. @type name: string @param name: name of the circle @type rad: float @param rad: the radius of the cylinder (default = 1.) @rtype: hostObject @return: the created circle """ #put the apropriate...
872a9c7f0df06ad7411cf58990783b55f0124a87
679,683
def degree(a): """ returns the degree of the atom """ return a.GetDegree()
778f15474582f9a2673b5d91ef9e1123ad986a60
679,684
import decimal def format_value(value): """Returns the given value rounded to one decimal place if it is a decimal, or integer if it is an integer. """ value = decimal.Decimal(str(value)) if int(value) == value: return int(value) # On Python 3, an explicit cast to float is required ...
cfc3bb57897d4004afd9f7c6d95efdb0ba1e6d33
679,686
import copy def exclude_meta(src_obj): """return copy of src_obj, without path, img, full_path, and objects keys""" obj = copy.copy(src_obj) for key in ['path', 'img', 'full_path', 'objects']: if key in obj: del obj[key] return obj
ca4ad46a6cf7cf0385ed8b33ce971f7841632fcc
679,687
def part1(input_lines): """ The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list. For example: - 1122 produces...
dfc5387d08f146a71c2dbe72ec4d074de331c6bd
679,689
import importlib def import_and_get_task(task_path): """ Given a modular path to a function, import that module and return the function. """ module, function = task_path.rsplit(".", 1) app_module = importlib.import_module(module) app_function = getattr(app_module, function) return app_...
6e628eb0d24a94aafa22107b2ac70ece355f17d9
679,690
from PIL import Image def getImageSizes(fname): """calculate actual and relative dimensions of image""" sizes = dict() im=Image.open(fname) (sizes["width"], sizes["height"]) = im.size if sizes["width"] >= sizes["height"]: sizes["rel_width"] = 600 try: sizes["rel_height"...
d4948357fd317b7521686359063336a70ac69b27
679,691
def MDD(series): """Maximum Drawdown (MDD) is an indicator of downside risk over a specified time period. MDD = (TroughValue – PeakValue) ÷ PeakValue """ trough = min(series) peak = max(series) mdd = (peak - trough) / peak return round(mdd, 3)
71ef94e58345b24c3a64311f3652b24c8f1eeafc
679,692
def named_value(dictionary): """ Gets the name and value of a dict with a single key (for example SenzaInfo parameters or Senza Components) """ return next(iter(dictionary.items()))
30ed1c6bcf6b0178b0705492b795646257a62fbd
679,693
from typing import Set import os def get_aws_cred_files_from_env() -> Set[str]: """Extract credential file paths from environment variables.""" return { os.environ[env_var] for env_var in ( 'AWS_CONFIG_FILE', 'AWS_CREDENTIAL_FILE', 'AWS_SHARED_CREDENTIALS_FILE', 'BOTO_C...
d2811ec0efaf04cf34ce09f57dbb3bfe96cc1afa
679,695
def _get_conjuncts(tok): """ Return conjunct dependents of the leftmost conjunct in a coordinated phrase, e.g. "Burton, [Dan], and [Josh] ...". """ return [right for right in tok.rights if right.dep_ == 'conj']
8962050ab17d2c9991e6af7bf0d73cb178698a08
679,696
def is_parent_cmnode(n1, n2): """Check if n1 is a parent node of n2. There are two types of nodes: 1) task 2) output """ if n1.type not in ('task', 'output') or n2.type not in ('task', 'output'): raise ValueError('Unsupported CMNode type: {}.'.format(n1.type)) if n1.type == 'task' a...
ba3b2dee9c140ba331e531fc3014ddf3e1dbe8eb
679,697