content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def _get_array_uri(group_uri: str, array_name: str, is_virtual: bool) -> str: """Returns a URI for an array with name ``array_name`` inside a group at URI ``group_uri``. Parameters: group_uri: URI of the group containing the array array_name: name of the array is_vir...
0c3ae77e4f77d859df1bf19c563522c43887042f
624,421
def put_two_cross_lines(board, ai_mark, player_mark): """Check tow crossing outside lines, in these lines have to be placed AI mark in the middle of the line.""" if board[0][0] == "." and board[0][1] == player_mark and board[0][2] == "." and \ board[1][2] == player_mark and board[2][2] == ".": ...
cf82e0732916c293afe036b759c5cdbd73790033
624,422
def permdb(ind, beta=0.5): """Perm function D, BETA defined as: $$ f(x) = \sum_{i=1}^d (\sum_{j=1}^n (j^i+\beta) ((\frac{x_j}{j})^i - 1) )^2$$ with a search domain of $-n < x_i < n, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(1, 1/2, ..., 1/n) = 0. """ return sum(( \ ...
f8f776dd9a41a31be421b0b518d0ced5abd6adf3
624,423
def hashable(cls): """Makes sure the class is hashable. Needs a working __eq__ and __hash__ and will add a __ne__. """ # py2 assert "__hash__" in cls.__dict__ # py3 assert cls.__dict__["__hash__"] is not None assert "__eq__" in cls.__dict__ cls.__ne__ = lambda self, other: not sel...
77649d82d592eaf3e8a1acff15fff3402056d6b9
624,424
import os def destination_path(config, tile, product, root_override=None): """ Return path to tile data directory Tile data directory is constructed as follows: [root]/[collection name]/[tile name] Args: config (dict): Tilezilla configuration file information tile (Tile): Retrieve d...
5303e6862a8008b7a076070381736b6f07ef309a
624,425
def Fixer_tuple(xvar, th=None, nb=None, lb=None, ub=None): """ Somewhat self-documenting way to make a fixer tuple. For use in/by/for the so-called Reference Model. Args: xvar (Var): the Pyomo Var th (float): compared to sqrt(abs(xbar_sqared - xsquared_bar)) nb: (int) None means ...
78a84525ac0afacaaf67672a09adefe4744ee740
624,426
import random def random_tuple(k, n): """ Return a random tuple of k integers lower than n, all differents, uniformaly """ t = random.sample([x for x in range(n)], k) return tuple(t)
b568ff85cb67a76a6e14abb96e21b5913cbf4803
624,428
import argparse from re import VERBOSE def get_args(): """ To parse user parameters :return: """ parser = argparse.ArgumentParser(description='CNN Hate Speech Detection Experiment.') parser.add_argument('--seed', type=int, default=28) parser.add_argument('--num_epochs', type=int, default=1...
241b479f5f3e46a90b52551ea42cbed6f547b957
624,429
from typing import Dict from typing import Any def dict_get(prop: str, obj: Dict[str, Any]) -> Any: """ Get value of prop within obj. This simple function exists to facilitate a partial function defined :ref:`here<is_utterance>`. :param prop: A property within a :code:`dict`. :type prop: str ...
5589690676736f5744654822c261ad4692d2d9b6
624,430
def _create_sitelink_assets(client, customer_id, campaign_id): """Creates sitelink assets, which can be added to campaigns. Args: client: The Google Ads client. customer_id: The customer ID for which to add the keyword. campaign_id: The campaign to which sitelinks will be added. Re...
95e5e60f74dbab49570807076e66918ed365a708
624,431
import re def fix_value(value): """ A part of fixer() Format value of elements in desc-dict """ value = re.sub(r'\[\w*\d*\]|\s*\(\s*\w*\s*\)', '', value) value = re.sub(r'(\n)+', '\n', value).strip('\n') value = re.sub('\\xa0', ' ', value) return value
fbe8c2c5389d25bc93c43fb072d7f35996b9da48
624,433
def inexact(pa, pb, pc): """Direction from pa to pc, via pb, where returned value is as follows: left: + [ = ccw ] straight: 0. right: - [ = cw ] returns twice signed area under triangle pa, pb, pc """ detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]) detright = (pa[1] - pc[1]) * (pb[...
31b7643c5fc9c91294a7aef9c81acd6205a80b16
624,434
def see(m: list, x, y) -> int: """Return count of how many occupied seats can be seen when looking out from given seat position.""" seen = 0 # (dx, dy) is the current direction of gaze. for dx, dy in [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), ...
f5ff10e64d391a85e480fc337e5713a306ee0e84
624,435
def doc_filter(df, target): """ :param df: 要进行样本筛选的数据框 :param target: 符合要求的id列表 :return: 只保留符合要求id对应样本的数据框 """ for doc_id in df['id']: if doc_id not in target: df.drop(df[df['id'] == doc_id].index, inplace=True) return df
31e1daa21ecdaa3c8108a85fd4a340cd4540892e
624,436
import os def get_token_from_environment(): """get abeja platform jwt token from environment variables :return: dict { "auth_token": PLATFORM_AUTH_TOKEN } """ auth_token = os.environ.get('PLATFORM_AUTH_TOKEN') if not auth_token: return None return { "auth_token...
fe5c97c1b193c97b8d9bae3cf0406a66ac928522
624,437
import os def get_volume_paths(folder, extension_tuple=('.nrrd', '.tiff', '.tif', '.nii', '.bmp', 'jpg', 'mnc', 'vtk', 'bin'), pattern=None): """ Test whether input is a folder or a file. If a file or list, return it. If a dir, return all images within that directory. Optionally test for a pattern to ...
71b3d8f55a0ddb0a89528d9df0bfad4f1c18f92f
624,438
import types def is_module(obj): """Returns True if passed a module >>> import os >>> is_module(os) True """ return isinstance(obj, types.ModuleType)
c87a373bea3d72368b892f8c5233b75a5f6f3aa7
624,439
def validate2(recipe, bread, vegetable, other, protein, condiment): """ @param recipe is a list from the list of lists (CSammies, SSammies, HSammies), bread, vegetable, and protein are lists specific to these sandwiches @return whether this recipe is a SuperSammie """ # you need to have at least bread, prot...
6c44a0a16ae867822eaf03469bf1019fbb33ed33
624,440
import logging def LookupSpaceInfoByStorageType(storage_space_info, storage_type): """Looks up the storage space info for a given storage type. Note that this lookup can be ambiguous if storage space reporting for several units of the same storage type was requested. This function is only supposed to be used...
e083817d365f853e2f495d9057167c7aff741cee
624,441
import numpy def quatRotate(q,trans): """rotates a point by a 4-elt quaternion. Returns a 3 elt vector""" xx = q[1] * q[1] xy = q[1] * q[2] xz = q[1] * q[3] xw = q[1] * q[0] yy = q[2] * q[2] yz = q[2] * q[3] yw = q[2] * q[0] zz = q[3] * q[3] zw = q[3] * q[0] return 2*numpy....
01389df757453816db4a1f24350af677214b703e
624,442
from bs4 import BeautifulSoup def get_result_links(html): """ Extract urls to search result documents :param html: result page html :return: list of urls """ ret_val = [] soup = BeautifulSoup(html, 'html.parser') urls = soup.findAll("a", attrs={"ng-if": "item.uuid !== null"}) for...
65964dcf5dcf4f619314daec8ccc1f90d6521ae5
624,443
def var_name_by_j(j, n, s, start=1): """ args: j: (0-based) index of column n: number of primary decision variables s: number of slack variables start: start of subscript index for printing """ if j<n: return 'X%s' % (start+j,) if j<n+s: return 'S%s' % (start+j-n,) ...
61345097d86661e7649e61423b7a7d847b022227
624,444
def release_to_text(release): """ Translate this Release object into a text string that would trigger this plugin's matcher. In other words, translate the release into something that could match ReleaseTask.from_text(). :param release: txproductpages.release.Release object :returns: str, l...
7c74f5749089dbbe64028f17e93355bb9fe63c7c
624,445
import torch def collate_fn(batch): """ Specify batching for the torch Dataloader function :param batch: each batch of the JsonlDataset :return: text tensor, attention mask tensor, img tensor, modal start token, modal end token, label """ lens = [len(row["sentence"]) for row in batch] bsz...
6d2f9facac3fd0718eb5e9fdc78ff16eca2391a7
624,446
import getpass def ask_for_credentials(): """ Ask for credentials :return: (string) username, (string) password """ username = input("username : ") password = getpass.getpass("password : ") return username, password
2a6802afc222e472804d4cd6e3aa41a4fe4b7131
624,447
from bs4 import BeautifulSoup def create_soup(path): """ Reads a file and returns a lxml-xml BeautifulSoup object. """ with open(path, encoding="utf8") as f: return BeautifulSoup(f.read(), "lxml-xml")
de7d0978b875d0a77432fcdfe3326b6fff162456
624,448
def tail(array): """Return all but the first element of `array`. Args: array (list): List to process. Returns: list: Rest of the list. Example: >>> tail([1, 2, 3, 4]) [2, 3, 4] .. versionadded:: 1.0.0 .. versionchanged:: 4.0.0 Renamed from ``rest`` t...
8247b595defe671cd94d2f797ecf858e70bca537
624,449
def rt_range_overlaps(rt1, rt2): """ inputs: rt1: metatlas.datastructures.metatlas_objects.RtReference rt2: metatlas.datastructures.metatlas_objects.RtReference returns: True if there is overlap in the RT min-max regions of rt1 and and rt2 """ return ((rt2.rt_min <= rt1.rt_mi...
ae37524475114607f4ae5e5bf757a309e96506f0
624,450
def split_half(args): """ Split the given list into two parts (equal if possible, if not the right one gets one more) Arguments --------- args : list list to split Returns ------- list, list Args split in two parts """ split = int(len(args) // 2) return arg...
ed326308ab83f8f725585971fc951073f7bc1f4d
624,451
import os def path_rgba_byte_tif(data_dir): """Derived from RGB.byte.tif, this has an alpha band""" return os.path.join(data_dir, 'RGBA.byte.tif')
e84f3ceedd8784e496548e51a609273aa6f3414f
624,453
def is_list(query): """ Given a string return true if it is formatted as a list, and False otherwise """ try: return type(eval(query)) == list except: return False
00277e28cf9473463aeb1d2f37e094fb8e9c1e4b
624,454
def get_slurm_options_string(args): """ This function extracts the flags and options specified for slurm/sbatch options added with add_sbatch_options. Presumably, this is used in a high-level "process-all" script where we need to pass the slurm options to the "process-all" script. Args: ...
87b7190fae507152d84c3dec39727d2dde2079b7
624,455
def load_data(df, outputfile): """Collect data locally and write to CSV. :param df: DataFrame to print. :return: None """ (df .write .mode("overwrite") .csv(outputfile)) return None
ae63a44698723494592773aa9a83e89feff5a2a0
624,456
def get_fit(eq_individual): """Given an Equation object, it will return its fitness score.""" return eq_individual.get_fitness()
da50793b1aed9093516f6f1a4b2ca2d33afe71ea
624,457
def rubygems_homepage_url(name, version, repo='https://rubygems.org/gems'): """ Return a Rubygems.org homepage URL given a name, optional version and a base rubygems `repo` web interface URL. For instance: https://rubygems.org/gems/mocha/versions/1.7.0 or https://rubygems.org/gems/mocha """ ...
4ee2b9c80a6b5908ec755ad900009dd242316f5f
624,459
import importlib def import_class(what): """Import a class by given full name. Args: what (str): a string with full classname to import Return: (type): a class which has been imported """ modulename, classname = what.rsplit('.', 1) module = importlib.import_module(modulename) ...
d47665d1373d427de1858f629b39279529d6635f
624,460
def err(msg): """ : Add basic boilerplate around error message. """ return f"Error: {msg}. See `--help` for more information."
f428270b12c15bc16797bbe33a61379bc51a97c8
624,461
def node(session): """ :rtype: maya_mock.MockedNode """ return session.create_node("transform")
f17a49b6481086ae99a21c1463cbfad5457c5266
624,462
def untranslateName(s): """Undo Python conversion of CL parameter or variable name.""" s = s.replace('DOT', '.') s = s.replace('DOLLAR', '$') # delete 'PY' at start of name components if s[:2] == 'PY': s = s[2:] s = s.replace('.PY', '.') return s
cb79c202313282d528ae2beae63856ed50f055d6
624,463
import math def polysum(n, s): """ n: Number of sides s: Length of each side returns: sum of the area and square of the perimeter of the regular polygon """ area = (0.25*n*s*s)/math.tan(math.pi/n) perimeter = n*s sum = area + perimeter**2 return round(sum,4)
d2e7be6f8f02c7b5d481a08fed7f35aa8aa1c411
624,464
def dict_join(*dicts): """Join multiple dicts into one, updating duplicate keys from left-to-right manner. Thus the items from the rightmost dict will take precedence.""" rslt = {} for d in dicts: rslt.update(d) return rslt
4d4810cb4ad07676a0359b63eedf072e598d51f3
624,465
import random def create_verify_code(): """ 生成6位随机数字验证码 """ code = random.randint(100000,999999) return str(code)
c535fe89c526d65767760563de779c6ecf51ceb3
624,467
def parse_hour(hour, sep=':') -> tuple: """Returns a tuple of integer from an hour like '14:34'.""" if not isinstance(hour, str): return hour return tuple([int(x) for x in hour.split(sep)])
95a9dd6bfd80ed1ac2350a8e75d5a8dfa9892e7a
624,469
def valid_dictionary_word(word, words_list): """Function to check if the word is in the dictionary. Args: word (str): word to test words_list (list): the "dictionary" Returns: bool: wether or not the word is in the dictionary """ if word in words_list: return True ...
a74883830eed0c5c9af27168eb9b2b45c49b0437
624,470
import time def split_sources(srcs): """ :param srcs: sources :returns: a pair (split sources, split time) """ sources = [] split_time = {} # src_id -> dt for src in srcs: t0 = time.time() splits = list(src) split_time[src.source_id] = time.time() - t0 sour...
1112fce30de5815b8ba242e22b8b5deee16ec5a3
624,471
def bed_read_rows_into_dic(in_bed, exon_regions=False, id2exonc_dic=None, id2len_dic=None, two_ids_dic=False): """ Read in .bed file rows into dictionary. Mapping is region ID -> bed row. If exon_...
e00754dcd0f2ea3f3563091b38db163f4ece83e9
624,473
def varint_to_int(byte_str): """Returns the number(int/long) that was encoded in the Protobuf varint""" value = 0 size = 0 for current in byte_str: value |= (ord(current) & 0x7F) << (size * 7) size += 1 return value
a15097c19b9915b0a19977dabc27a6094a67f058
624,474
import os def get_file_path(filename, folder_path='data'): """ Constructs filepath. dataset is expected to be in the "data" folder :param filename: :return: """ dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file_path = os.path.join(dir_path, folder_path, filename) ...
16ae26ded0aa5a01b17bb771e7f0e98d6147898a
624,475
def find_node_down_via(G, edges, targets, visited_edges=None): """ find target nodes in targets connected from edges """ if visited_edges is None: visited_edges = set() for edge in edges: if edge in visited_edges: continue visited_edges.add(edge) if edge.to_node i...
4b011ac1f54fe2f3e3aac95216be3bbd44dcace1
624,476
def create_multidimensional_list(shape, element=None): """Creating a multidimensional list The recusion using list comprehension was obtained from create_empty_array_of_shape() at stackoverflow. Erko added element and the possibility to let element be a list. For example shape = [2...
5a619bbb658bf0ebc7657baeb6fb9ee91205c9e0
624,477
def rgb2hex(rgb): """Format an RGB color value into a hexadecimal color string. >>> rgb2hex((255, 0, 0)) '#ff0000' """ try: return '#%02x%02x%02x' % rgb except TypeError: raise ValueError(rgb)
8429e52c0eb0e4cf667d135292bb2b092fa66b1d
624,478
import random def _draw_random_seed(): """ Generate a 32-bit binary random seed""" return random.getrandbits(32)
b4171e9fd4f2b093f4932e5142c75e0b802edd61
624,480
def get_transfer_stats(client, pg_vol_snap_name): """ Returns a tuple of (started time, progress) """ transfer_stats = client.list_volumes(names=pg_vol_snap_name, snap=True, transfer=True)[0] return (transfer_stats["started"], transfer_stats["progress"])
09d9657ece762386b36e2a7ff5c49c550b346011
624,481
def _getsubnodetext(node, name): """Get an element from an XML node, raise an error otherwise. Parameters ---------- node: Element XML Element name: str Child element name Returns ------- test: str Text contents of the child nodes """ subnode = node.find...
123b089d6e615a972d15424255fca3ac4ad10def
624,482
import logging import shutil import tempfile def working_dir(request): """Temporary working directory. """ def fin(): """Tear down. """ logging.info('Deleting temporary test directory: "%s"', dirpath) shutil.rmtree(dirpath) request.addfinalizer(fin) dirpath = tempf...
8485e3f23189b570d0b896ebd53db347ed6602bb
624,483
import re def isNegative(phrase): """ Returns True if the input phrase has a negative sentiment. Arguments: phrase -- the input phrase to-be evaluated """ return bool(re.search(r'\b(no(t)?|don\'t|stop|end)\b', phrase, re.IGNORECASE))
ae7760d9200db664b8312d1eb8527099901e4469
624,485
def freq_at_bit(in_data: list, position: int) -> tuple: """Returns frequency of bit '0' and '1' in the position 'position' for input data (list of str) Args: in_data (list): list of str position (int): position to check the bit in Returns: tuple: (int, int) """ bits = [0, 0] ...
82be7bbde95ec66d332160b1c58e598ea8157ddd
624,486
def pixel_points(y1, y2, line): """ Converts the slope and intercept of each line into pixel points. Parameters: y1: y-value of the line's starting point. y2: y-value of the line's end point. line: The slope and intercept of the line. """ if line is None: ...
00c33c53fffb63ab52af74e4d4b77bf4b3756533
624,487
from typing import List def get_valid_package_keys_matching(all_keys: List, input_key: str) -> List[str]: """Return a list of keys of graph nodes that match a package input. For our use case (matching user input to package nodes), a valid key is one that ends with the ...
3faf693ceb1b0207f3479b3e9a5f97e0cd120c93
624,488
def divide_img_into_two_vertically(img, overlap_w): """ overlap_w: amount of overlap expressed as fraction of half the width of the image. or width of half a horizontally cut portion """ height, width = img.shape[:2] # Let's get the starting pixel coordiantes (top left of cropped top) start...
103910444dcfe3dc94340773508a3725f589cb7e
624,489
from typing import Optional from typing import List from typing import Tuple def dict_flatten( attrs: dict, delim: Optional[str] = None, indent_char: Optional[str] = None, bullet_char: Optional[str] = None, ) -> List[Tuple[str, str, str]]: """Recursively flattens dictionary to its atomic elements....
5bb7c49786b1a2e8ef169cf8b9b4be37c9352abe
624,490
def clear_empty(entry): """ Clear empty fields in entry """ gen = (field for field in entry.keys() if not entry[field]) for field in gen: del entry[field] return entry
a4f85f951887ac4846e0b2a564b6abd421f5ffa7
624,492
def find_lower_bound_index(pillar_vals,zero_index): """ Function that finds first non-sequential index in list of indices and pillar values """ zero_indices = zero_index[0] for i in range(len(zero_indices)-1): if zero_indices[i+1] != zero_indices[i]+1: if pillar_vals[zero_indices...
2b7b9a90ed6566fe58e21b4aa6fc40420af563e3
624,493
def resource_for_link(link, includes, resources=None, locale=None): """Returns the resource that matches the link""" if resources is not None: cache_key = "{0}:{1}:{2}".format( link['sys']['linkType'], link['sys']['id'], locale ) if cache_key in resou...
7c65b1ea1a7cbf5be897799a9aad7d633b9f0409
624,494
def get_givenl(l, osc, osckey): """ Returns frequencies, radial orders, and inertias or uncertainties of a given angular degree l. Parameters ---------- l : int Angular degree between l=0 and l=2 osc : array An array containing the individual frequencies in [0,:] and the ...
a4fd5ebb25c404fa8164016801af189f0a9088de
624,496
import os def _RunCommand(dut_ip, cmd): """Runs command on the DUT. Args: dut_ip: IP of the DUT. If it's None, runs command locally. cmd: The command to run. """ if dut_ip: # Commands via ssh shall be double-quoted to escape special characters. cmd = '"%s"' % cmd return os.system('ssh roo...
13e9cd677e6b572539e8d017d06394ed5d99b17e
624,497
def external_document(title: str, location: str, publish=True) -> dict: """ ``` { 'title': title, 'location': location, 'publish': publish, } ``` """ return { 'title': title, 'location': location, 'publish': publish, }
cce1c2a2fa80b8d3e03f232ffe5aa6e32491816b
624,498
def isintlike(value): """ Checks if an object can be converted to an integer. @param value: {object} @return {bool} """ try: int(value) return True except (TypeError, ValueError): return False
43c98f6bf7bf7a20a83a64356e0b3fb3c6ce6a4b
624,499
import re def isint(word): """ONLY matches integers! If you have a decimal point? None shall pass! @param[in] word String (for instance, '123', '153.0', '2.', '-354') @return answer Boolean which specifies whether the string is an integer (only +/- sign followed by digits) """ try: word ...
fedcc93d03f2d41e1fe743d07452399f4a123edd
624,501
def get_vocab(dataset="mscoco"): """ return the vocab of dataset """ vocab = getattr(eval(dataset), "get_vocab") return vocab
93f4e8d6416a4fe1dede7e41ba503c4e37835b5e
624,502
import re import os def _truncate_pwd(): """ Truncate path if it is more than 4 directories :return: """ _pwd = os.getcwd() _home = os.path.expanduser('~') _pwd = re.sub(_home, "~", _pwd) _paths = _pwd.split('/') if len(_paths) > 4: _pwd = "%s/%s/.../%s/%s" % (_paths[0], _...
33762e5834360b00013d8317661a91c3e0624e6d
624,503
def map_outputs(building_name, outputs, mapping): """ Maps outputs from EnergyPlus to OPC tags Inputs: building_name- The name of the building outputs- List of values from EnergyPlus Outputs: [(OPC_tag, value)]- List of tuples of tags and values """ output_tags = mapping[building_name]["Outputs"] ret = [] ...
5b858205d5ecc80dafb7c74443b5bfa219a1e3d3
624,504
def slack_escape(text: str) -> str: """ Escape special control characters in text formatted for Slack's markup. This applies escaping rules as documented on https://api.slack.com/reference/surfaces/formatting#escaping """ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;...
46dd7c138e117a45b4b567d9b63a15de8b4332a0
624,505
import functools def coroutine(func): """ @param func: @return: """ @functools.wraps(func) def primer(*args, **kwargs): gen = func(*args, **kwargs) next(gen) return gen return primer
cfe7b07bc2dd60c754cfdfc92d8ed88265e76e9c
624,506
def strip_none(none_list): """ Given a list that might contain None items, this returns a list with no None items. :params list none_list: A list that may contain None items. :returns: A list stripped of None items. """ if none_list is None: return [] results = [x for x in none...
7529f2f559defb57f7e935c0ad869b40116274b4
624,507
def coding_problem_49(arr): """ Given an array of numbers, find the maximum sum of any contiguous subarray of the array. For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximum su...
9cf09e1813e0315f45939e097986ac782309fb52
624,508
import typing import re def get_package_namespace(package: str, namespaces: typing.Dict[typing.Union[str, None], str]) -> typing.Tuple[str, str]: """ Get the prefix and URI for the namespace of an SBML package Args: package (:obj:`str`): SBML package id (e.g., ``fbc``, ``qual``) namespaces (:...
f4b5339fc2f7eaab0081e787a60bca2621d586dd
624,509
import math def atan_norm(value): """The arctan function grows more and more slowly as its input increases, so it is applied in hope of reducing the influence of possible outliers. Args: value (int): Byte frequency of a byte integer between 0-255. Returns: float: arctan nor...
1e7dacd497fd572aa7f8e0c9ac4b9ce22cca4074
624,510
import os def datafile(filename): """Generate path of the file Args: filename: file name Returns: the file path """ DATA_DIR = os.path.join(os.path.dirname(__file__), "data") return os.path.join(DATA_DIR, filename)
c557fe8a08d18264c03fdfe818cd4ed7ff757cc1
624,512
def _edgeness(hxx, hyy, hxy): """Compute edgeness (eq. 18 of Otero et. al. IPOL paper)""" trace = hxx + hyy determinant = hxx * hyy - hxy * hxy return (trace * trace) / determinant
eca87ae8ecee269fbbdaa84a3070a0eb86f6a47d
624,513
def str2gb(args): """ :参数 args: :返回: GB2312编码 """ return str(args).encode('gb2312')
f31f638ba6ed39bbad08c67bab8845b747c4d344
624,514
def parse_wgac_alignment(wgac_alignment): """ Parses a WGAC alignment from a list into a tuple of tuples for each sequence in the alignment. """ wgac_alignment[1:3] = map(int, wgac_alignment[1:3]) wgac_alignment[5:7] = map(int, wgac_alignment[5:7]) return ( tuple(wgac_alignment[:4]),...
41f8130604e54bac8510b785d33ca9c672de69c1
624,516
import re def get_individual_words(concept): """extracts the individual words from a concept """ clean_concepts = re.sub(r"\/c\/[a-z]{2}\/|\/.*", "", concept) return clean_concepts.strip().split("_")
8c7ec7c78277bf3004c51d02db31ebdca7c9d0b6
624,517
def format_taxon(taxonomy): """ Format the taxonomy string. """ genus = taxonomy.split(';')[-2] organism = taxonomy.split(';')[-1] return [genus, organism]
de0e83cf7d4fa6fe381597b40a117ccc80ac4814
624,520
def b32(val): """ convert to 32 bit binary """ return bin(val)[2:].zfill(32)
3aabae78a4c026dc373ac4ce59549b99cba89f6c
624,521
import torch import math def matern_spectrum( w: torch.Tensor, amplitudes: torch.Tensor, lengthscales: torch.Tensor, nu: float = 1.5, ) -> torch.Tensor: """Evaluate the Matern 5/2 power spectrum element-wise at ``w``. Args: w: The (dimensionless) frequencies at which to evaluate the p...
cda62315cb017a2cf4ced7d4240bb5e9d4f97635
624,523
import os def _get_pred_path(params, exp_dir): # pylint: disable=unused-argument """Gets path to predictions.""" return os.path.join(exp_dir, 'pred')
85f7946488ca97a9e76bd8c98f355f55e1da5d13
624,524
import os import sys def add_mistune_path(path=None): """\ Add a directory for the mistune Markdown parser to sys.path, the search path for Python module import, depending on the parameter value: - If path is None, adds one of the following to sys.path: - The value of the MISTUNE environment variable, if...
c3435bb9971045ba43049564e72e1e43225d1413
624,525
import io def function_definition(decorated): """ A decorator gadget that generates a C function declaration. The function decorated by this gadget should generate the function's body. Usage: properties.name = "my_function" properties.return_type = "uint64_t" properties.args =...
38fe70c81ddef365267b9501c47f6379253351e6
624,526
def is_in_list(item, list_, kind): """Check whether an item is in a list; kind is just a string.""" if item not in list_: raise KeyError(f"Specify {kind} from {list_}: got {item}") return True
25887a0b22061149777d2f6b5a2f792c6bcfc1a7
624,527
def none_bool(x): """Implementation of `none_bool`.""" return False
efd1f31f6daf029c237ff27632a0a743ed4e7d96
624,528
def validate_management_key_id_against_chain_id(key_id, chain_id): """ Checks if the chain in the key_id matches the value supplied in chain_id. Parameters ---------- key_id: bytes or str The partial or full key identifier chain_id: str The chain ID Raises ------ Un...
da02214f46528298f1c3ca336ffef2df3529b638
624,529
def get_lomb_amplitude(lomb_model, i, j): """ Get the amplitude of the jth harmonic of the ith frequency from a fitted Lomb-Scargle model. """ return lomb_model['freq_fits'][i-1]['amplitude'][j-1]
e4d0da88d90e53d8be1a0dab540c14db89918ba7
624,530
def _can_create(model): """Returns True if the given model has implemented the autocomplete_create method to allow new instances to be creates from a single string value. """ return callable(getattr( model, 'autocomplete_create', None, ))
b8d81da32bc4f69373996617aef7cd2dd06ff3b6
624,532
def selection_sort(t_input): """ Selection Sort Algorithm Simple, stable algorithm with in-place sorting http://en.wikipedia.org/wiki/Selection_sort Best case performance: O(n^2) Worst case performance: O(n^2) Worst Case Auxiliary Space Complexity: O(n) :param t_input: [list] of numbers ...
e50c3d6ab420eeccf674dbb7a5b68f2cbdba1eac
624,533
def isQualified(name): """ Check if a property name is qualified """ return name.find(':') != -1
e01cbbd4219542b830f9ce8070e9761d7a3b03c2
624,534
import subprocess import os def sort_fastqs(r_umitagged_unsorted_file, sort_opts, read_out): """ sort by query name. https://edwards.sdsu.edu/research/sorting-fastq-files-by-their-sequence-identifiers/ """ cmd = 'cat {0} | paste - - - - | sort -k1,1 {1} | tr "\t" "\n" > {2}; rm {0}'.format(r_umita...
5d06ebcdefce3ed78075383caa2bcdca8feb64d9
624,535
import torch def rotate_coords(coords, i): """ giving cartesian coordinates, a selected central residue C, rotate the system to the internal ref. internal ref: C is at origin; A, B are the previous two residues. C-B along negative x. C-B-A in x-y plane. :param coords: :return: """ coords =...
cf397ac0038567cf3ff7206acc3424fffd77add2
624,536
import re def is_hex(s): """ Check whether a string is actually a hex color code. Args: s (str): A string and possibly a hex color code. Returns: (bool): True if the input is a valid hex color code and False if it is not. """ match = re.search(r"^#(?:[0-9a-fA-F]{3}){1...
0b9fe14447dd3f3ce23445bd649ba2b65ab8baf4
624,537
def remove_markers(text): """ strip out asterics and hashes from the file""" markers = "*#" for char in markers: text = text.replace(char, "") return text
e8b166ecc34d0a050f62c17525e86cfc3d3c0b71
624,538