content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _lennard_jones_force(dist, point, ref, params): """ Compute the Lennard-Jones force between two particles given their interaction parameters, the distance, and distance vector. Parameters: ----------- dist: float the distance between particles vect: np.ndarray(3) the...
8516533385caaa4222bf4d04a17475cbbc844c2c
571,576
import math def absolute_humidity(t, rh): """ Gives you the mass of water vapor in volume of dry air. Units in g/m^3 See [SensIntroHum]_ Different pressure seem to affect absolute humidity slightly. For a more accurate calculation that uses pressure, see [PlanetAbsHum]_. :param t: Temperature in...
b0fff00073e44a115468ade9f30f714cff7af5f0
571,585
def code_to_coord(c): """ Utility function to decode encoded coordinates """ i_x = c / 1000 i_y = c % 1000 return i_x, i_y
ecf963aadef3e9e2e4646979763ab44e523746e3
571,587
def _distance_between_nodes(node_1, node_2): """calculate the euclidean distance of two points using pythagoras""" x1, y1 = node_1 x2, y2 = node_2 return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
856f552aba24ac40931c31d83c7a71b6c427e56e
571,589
def decode(tokenizer, ids): """ Decode integer representation to string based on tokenizer vocab. Parameters ----------- ids: List[int] Returns -------- result: str """ return tokenizer.decode([i for i in ids if i > 0])
23765339eba45b65e6a150568a66e56dc5928419
571,592
import math def log(x): """This function returns log of base 10""" return math.log(x,10)
63d00c9a771040f501a2b4091705ef37bb8d19ce
571,593
def PyLong_FromUnsignedLongLong(space, val): """Return a new PyLongObject object from a C unsigned long long, or NULL on failure.""" return space.newlong_from_rarith_int(val)
33e6b25c148741ba86a7fa7b9ad68730be9056cd
571,594
import math def generic(zeff: float, radius: float, rpow: float = 1, apow: float = 1) -> float: """ Calculate the electronegativity from a general formula Args: zeff: effective nuclear charge radius: radius value for the element rpow: power to raise the radius to (see equation bel...
e56ebb34c84434041d2ab818a13a23d091b116a3
571,595
def split_sentence(corpus: list): """split corpus :param corpus: list type sentence :return: word_list: two-dimensional list """ word_list = list() for i in range(len(corpus)): word_list.append(corpus[i].split(' ')) return word_list
38687400ae4af78a7875d287c436a6551cfa14df
571,598
def parse_headers(fp): """ Parses HTTP-like headers into a dictionary until an empty line is found. Invalid headers are ignored and if a header is found twice, it won't overwrite its previous value. Header-keys are converted to lower-case and stripped of whitespace at both ends. """ headers...
9752fa4c1e3ffb1e88249c0ca235cb8f69b1f5f2
571,606
def split_file(infile, prefix, max_size=50*1024*1024, file_buffer=1024): """ file: the input file prefix: prefix of the output files that will be created max_size: maximum size of each created file in bytes buffer: buffer size in bytes Returns the number of parts created. """ with open(...
27d329610d1545995d600ec53dd9ae48301e6d75
571,607
def any_not_none(*args): """ Returns a boolean indicating if any argument is not None. """ return any(arg is not None for arg in args)
ac73f9cdadb167713d3867f36b1103bc4501b5c3
571,608
def parse_name_scope(name): """ Given a tensor or op name, return the name scope of the raw name. Args: name: The name of a tensor or an op. Returns: str: The name scope """ i = name.rfind('/') if i != -1: return name[:i] if not name.startswith('^') else name[1:i] ...
dc0de1327a56f3d8cf110d4cd8a804a282bb52e1
571,611
def parse_where(where, prefix): """Helper method to parse a dict to SQL where clause query Parameters ---------- where : dict (key, value) Key may be field name optionally appended with filtering operator: name_eq be equal to the value name_ne be equal to the value name...
9e355adade1622ae830495427df804f205c25e1b
571,613
from datetime import datetime def timestamp_to_date(timestamp: float) -> datetime: """convert different timestamp precision to python format Python2.7: https://docs.python.org/2.7/library/datetime.html#datetime.datetime Python3+ :https://docs.python.org/3.7/library/datetime.html#datetime.datetime ...
64d3fe3da8041c6e48199cebc1b847d5294e62f9
571,614
from typing import Optional from typing import List from typing import Any def visiblename( name: str, all_things: Optional[List[str]] = None, obj: Optional[Any] = None ) -> bool: """Decide whether to show documentation on a variable.""" # Certain special names are redundant or internal. # XXX Remove ...
4cc62fa2e7fefed8a925cb1a33b261785786212c
571,615
def image_guess_size_from_field_name(field_name): """Attempt to guess the image size based on `field_name`. If it can't be guessed, return (0, 0) instead. :param field_name: the name of a field :type field_name: string :return: the guessed size :rtype: tuple (width, height) """ suffix...
b4008bac56f6b02aa0609913aa681f347be0cf17
571,616
def get_structure(pdbqt_file, model=None): """ Get an :class:`AtomArray` or :class:`AtomArrayStack` from the PDBQT file. EXPERIMENTAL: Future API changes are probable. Parameters ---------- pdbqt_file : PDBQTFile The PDBQT file. model : int, optional If this paramet...
67db3b912743b29a868054af0d24d41045d29a1f
571,618
def reading_in_word(file_name: str, paragraph: bool = True) -> list: """ reads in file and stores seperate paragraphs in list :param file_name (string): name of the file with the text paragraph (bool): If the text is spliced on paragraphs or not :return: paragraphs(list): list of paragraphs ...
a37f13bd7c73a6955eb29e46b925c6b96de7d37e
571,621
def countinclude(data, s="sam"): """Count how many words occur in a list up to and including the first occurrence of the word "sam".""" count = 0 for i in data: count += 1 if i == s: break return count
4dc1634a637b85859956c67b62583d447f90f3d8
571,623
def get_param_simu(self, idx): """ Return the list of parameter values for a specific simulation """ assert len(idx) == len(self.shape) # Create a list to store values param_value = [] for pe in self.paramexplorer_list: param_value.append(pe.value[idx]) return param_value
dc612fcd420f512b726711791123ae7a68fe5d17
571,626
def _check_filepath(filepath): """ Validate if the filepath attr/arg is a str :param str filepath: object to validate :return str: validated filepath :raise TypeError: if the filepath is not a string """ # might be useful if we want to have multiple locked paths in the future # def _che...
8f306e0ec76afd2cef0cd191ab2b2e8eee9ee328
571,630
import re def _clean_name(name): """ Remove characters that might be present in OPC UA structures but cannot be part of of Python class names """ name = re.sub(r'\W+', '_', name) name = re.sub(r'\.', '_', name) name = re.sub(r'"', '_', name) name = re.sub(r'^[0-9]+', r'_\g<0>', name) ...
b534a2b98ba8bb1705043b417ebf1a728f17e7e8
571,632
def get_error_message_from_exception(exception): """Extract first line of exception message :param exception: exception object :returns: first line of exception message """ try: return str(exception).split('\n', 1)[0] except Exception: return ''
5e00ba1fafa8eb47a0b78d6c69af0ec9e3a67a45
571,634
def continuous_binary_search(f, lo, hi, gap=1e-4): """Binary search for a function :param f: boolean monotone function with f(hi) = True :param int lo: :param int hi: with hi >= lo :param float gap: :returns: first value x in [lo,hi] such that f(x), x is computed up to some precisi...
85a4fae4734bc8c335fd484b2b17c87f19a7e8c6
571,636
def change_base(i, base=816394): """ Basic function to pass from + to - strand 1 --> 816394 300 --> 816094 """ return (base+1)-i
5c7a5e1ded5d5c0d948f4fff25360d257adbdf2e
571,638
def kgs2lbs(sets, sub=0): """Convert a set of weights in kilograms to pounds. :param list sets: Iterable of prescribed weights. :param int sub: Amount to subtract from each converted weight. Useful for when taking into account bar weight. """ return (int(round(x * 2.20462) - sub) for x in sets)
f25b864d7b05d04d9e30138bcb28fa05ffa7b223
571,640
def replicate(i, n, inplace=False): """Apply replicate (nearest/border) boundary conditions to an index Parameters ---------- i : int Index n : int Length of the field of view inplace : bool, default=False Returns ------- i : int Inde...
03d27f94f7a7f17923c23bbf63b2061c27c4f063
571,642
def flatten_json(y): """ This supplemental method flattens a JSON by renaming subfields using dots as delimiters between levels Args: y - the JSON to flatten Returns: A flattened JSON string """ out = {} def flatten(x, name=''): # If the Nested key-value #...
9eb3df166bb790b3a4f36bfaef6631ceb2007d64
571,644
def isExtOrSkin(project): """ project: a gerrit repository name Returns boolean, whether the repository is a MediaWiki extension or skin. """ return project.startswith(('mediawiki/extensions/', 'mediawiki/skins/'))
4d4b1d093b6b884414a3395a940687b77651a45b
571,653
from datetime import datetime def parse_date(string): """ Parse a `datetime.datetime` using a simple string format. :param str string: String to parse :rtype: datetime """ return datetime.strptime(string, '%Y-%m-%d')
5b24e89f5758ef71ac2dcc3ffc58172132d5d9ba
571,654
def all_not_none(*args): """ Returns a boolean indicating if all arguments are not None. """ return all(arg is not None for arg in args)
6e2f46dcc262d60e9374362975a8fc3cf54bc03d
571,656
import re def is_canonical(version): """Returns true if version is in canonical PEP440 format, otherwise False. See https://www.python.org/dev/peps/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions for detail. Parameters ---------- version : str String to ...
024f2bc29ee38b8b6b0a9d6b86e8d3658711ee39
571,660
import platform def get_platform_info() -> str: """Returns a string with the platform information.""" return ''' System platform information: system : %s node : %s release : %s machine : %s processor: %s summary : %s version : %s Python platform information: ve...
11f6a8489e16cd209bc8d18d4e1e8c602f0c7579
571,669
def restricted_utc_time_from_datetime(date): """Convert given ``datetime.datetime`` object `date` to an restricted ASN.1 UTC time string. """ if date.tzinfo is not None: date -= date.utcoffset() return date.strftime('%y%m%d%H%M%S') + 'Z'
418da1cc4d5eea8955a4a8263f803a4c1610c635
571,670
def eof(fd): """Determine if end-of-file is reached for file fd.""" b = fd.read(1) end = len(b) == 0 if not end: curpos = fd.tell() fd.seek(curpos - 1) return end
ecc500f09e58d5c40f5a9766bef219d2fd9c3656
571,672
import torch def v_interactions(W, scaled, cheb, tree, scheme): """Calculates the v-:ref:`interactions <eval>` used in a solution. :param W: the :func:`weights` for the solution. :param scaled: a :func:`scale`'d problem. :param cheb: a :class:`~pybbfmm.chebyshev.Chebyshev` object. :param tree: a...
c01cd969ed586fa659e64839293c688a95acd8df
571,673
def is_renku_project(client): """Check if repository is a renku project.""" try: return client.project is not None except ValueError: # Error in loading due to an older schema return client.renku_metadata_path.exists()
accdf499e03e0bb186bb80665bf1a298e0db477c
571,676
import itertools def zip_with_singletons(*args): """ Zip lists and singletons by repeating singletons Behaves usually for lists and repeat other arguments (including other iterables such as tuples np.array!) :param args: arguments to zip x1, x2, .. xn :return: zipped tuples (x11, x21, ......
b93af4e2e87fbcb26c61e0eac846ca2a4dd2b66c
571,679
def check_list_of_type(lst, cls, msg=''): """ Check that the given list contains only instances of cls. Raise TypeError if an element is not of the given type. If the list is None, an empty list is returned. :param lst: list of items or None :param cls: the class of which the elements should be ins...
95630c4eb7b6c4f2e5960a603f4fc1c4cefd5ecc
571,681
def check_filename(filepath, extension=".txt"): """ Take a path to a file and ensure the filename has the right extension, else add the extension. :param str filepath: The path to the file. :param str extension: Extension for the given file. If wrong extension in filepath then raise error. Extension...
bb1eb5452a903b7ae811a13fad44e6982517e53f
571,684
from typing import Counter def count_tokens(tokens): """ Simple counter, returning counts and the total """ counts = Counter(tokens) return counts, sum(counts.values())
433b11ab078784f70ee002a4fdee498ccf1d4aed
571,686
def exec_string(string, language="python", decorators=None): """Execute a string as python code. The languages available are ``python`` and ``mel``. During the process, creates a new function and calls it using the :func:`exec` builtin function. With this process, it is possible to apply decorato...
850e595523453b4d28abf745290886b4587e3a8b
571,689
def containsAny(str, set): """ Check whether 'str' contains ANY of the chars in 'set' """ return 1 in [c in str for c in set]
8c879631964a03025168710989e7c558e1563846
571,692
def _get_evaluator_specs(nodes, grpc_port): """ Returns the list of ip:port for all evaluator nodes """ # There is one evaluator per node return ['%s:%d' % (node_ip, grpc_port + 300) for node_ip in nodes.values()]
62b43b24038928e9df9c6f915e21d2887e69d31f
571,693
def react(r, ctx, ui, valids=None): """Check if the reaction is on the correct message, and is by the same author.""" return (r[0].message.id, r[1]) == (ui.id, ctx.author) and (valids is None or r[0].emoji in valids)
3fc354e2816045ca6fc5ca56e2ed04d68ffd857b
571,700
def get_username(tweet_id, twitter_api): """Returns the screen name of the user who posted the tweet""" tweet = twitter_api.get_status(tweet_id) return(tweet._json["user"]["screen_name"])
8d7b25970e9472dbdb021fdee3b35ef42b0146e8
571,701
def is_reverse_o2o(field): """ A little helper to check if the given field is reverse-o2o. The field is expected to be some sort of relation field or related object. """ return not hasattr(field, 'rel') and field.field.unique
f7921de55406a7b7c72d5769bb80ecef30ee505e
571,707
import typing from typing import TypeGuard import inspect def is_async_iterable(obj: typing.Any) -> TypeGuard[typing.AsyncIterable[object]]: """Determine if the object is an async iterable or not.""" attr = getattr(obj, "__aiter__", None) return inspect.isfunction(attr) or inspect.ismethod(attr)
890f931871455e863441ba5b813d23631c065c9d
571,708
def overlap(s1, s2): """Determine similarity of two sets.""" return len(s1 & s2) / min(len(s1), len(s2))
8ae7632498220fb77c56a55f6a934f168b717da4
571,709
def get_var_name(var) -> str: """Get an appropriate, plain variable name for a variable.""" return str(getattr(var, "name", var))
46e43543f859e2d178cc6e662b9f7ef97bd3f088
571,711
def construct_increment_confirmation_attempts_query(graph_uri, poststuk_uri): """ Construct a SPARQL query for incrementing (+1) the counter that keeps track of how many times the service attempted to send out a conformation for a certain message without succes. :param graph_uri: string :param post...
5614e318083d493b5e5e7482beebbe9fc303832a
571,712
def valueclass(*members): """ A classdecorator that makes a class into a standard value type. This decorator provides an __init__ method that takes in the supplied members and stores them in instance variables. This decorator also provides standard __eq__, __repr__ and __str__ functions that u...
2c02952f61da94c7b846fbd5d26849e0994b2d49
571,713
def get_attr_in_gmeta_class(model, config_name, default_value=None): """获取指定模型 GMeta 类中指定的属性 Params: model class django 模型类 config_name string GMeta 类中配置项的名称 default_value 任何数据类型 默认数据 """ gmeta_class = getattr(model, "GMeta", None) if not gmeta_class: return default...
755a8cc5aeb5304106a940929e133be9d163797f
571,714
def calc_adj_r2(r2, n, k): """ Calculate and return adjusted r2 score. Parameters ---------- r2 : Original r2 score. n : Number of points in data sample. k : Number of variables in model, excluding the constant. Returns ------- float Adjusted R2 s...
df28af837562d84a100a7da97fdc8ea86f156936
571,716
from pathlib import Path from typing import List def subdirs(path: Path) -> List[Path]: """ Return a list of Paths for subdirectories in a directory """ if path.is_dir(): return [f for f in path.iterdir() if f.is_dir()] else: return []
cd9663a7dee0809d60d398164011e7ed9a0167b0
571,720
from datetime import datetime def parse_date(date_string): """ Small function to parse a string into a datetime object since it can come in multiple formats from the external API. """ if not date_string: return None for date_format in ["%Y-%m-%d", "%Y-%m", "%Y"]: try: ...
d9449fdd0aba309a44f17a9e71dc4350c4505aed
571,721
def readMatrix(text): """Reads a matrix from text in the format m n x11 x12 ... x1n ... xm1 xm2 ... xmn """ items = text.split() if len(items) < 2: raise ValueError("Invalid matrix string") m,n = int(items[0]),int(items[1]) if len(items) != 2 + m*n: raise ValueError("Inva...
1c8cd651985478989ce36bea6441d9a3d01b327a
571,724
def parse_ood_line(line): """ For context see phase1-ood/README: TRAINSET and DEVSET contain the individual ratings from each rater, along with some demographic information for the rater. (TRAINSET only contains information about the labeled training data, not for the unlabeled samples.) The f...
64ed0b327c73942434e5c8b14df93d0c052f3f31
571,728
def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: """ This function can calculate any one of the three - 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples - >>> carrier_...
b89a8411c26bf1eba128703004751b83401052ec
571,729
def chop_list(blocks, src, start, end): """ For each alignment block in the sequence `blocks`, chop out the portion of the block that overlaps the interval [`start`,`end`) in the component/species named `src`. """ new_blocks = [] for block in blocks: ref = block.get_component_by_src(...
83a5b161a5f92c49198f40981ed9d9a22bc9ac60
571,731
def adim(q, star): """ non-dimensionalize the quantitie q by star. Parameters: - q : list - star : float """ return [a/star for a in q]
71e4daf92401be2f61ec6debde5b96344556c520
571,743
def normalize_file_permissions(st_mode): """ Normalizes the permission bits in the st_mode field from stat to 644/755 Popular VCSs only track whether a file is executable or not. The exact permissions can vary on systems with different umasks. Normalising to 644 (non executable) or 755 (executable)...
b3fab92fa7e8f90549bf8cd55fe4e1e38580efa4
571,744
def terminal_format(args): """ args is a list of tuples and returns one string line. 2-tuples are "{x[1]}".format(x[0]) i.e. value, format 3-tuples are "{}={x[2]}".format(x[0],x[1]) i.e. label, value, format """ line = "" for x in args: if len(x) == 3: line += ("{}={"+str(x[2])+"}").format(str(x...
154137c476883ab0d12bcd42a0645534ed779b27
571,751
def _derivative_add(a, b): """Derivative of a + b""" return a[1] + b[1]
5ba1afb5cb5988a89bee0044537313fd8ae32af2
571,756
def exchange_money(budget: float, exchange_rate: float) -> float: """Estimate value after exchange Args: budget (float): amount of money you are planning to exchange. exchange_rate (float): unit value of the foreign currency. Returns: float: exchanged value of the foreign currency ...
280b812863e2121b9adb71fb29a887fec3d25785
571,760
import hashlib def digest_binary(file): """Convert any binary to md5 hex digest.""" return hashlib.md5(file).hexdigest()
ccc1af732b9640d65be43b02214a307ec83fe8d0
571,765
def strip_identity(i): """ Normalize identity to only contain the ID. """ identity = i.replace('http://cltl.nl/entity#', '') return identity.replace(' ', '_')
67db32d9182f0850ab3b33f67a4b18651cb181e8
571,767
import time import logging import hmac import hashlib def generate_temp_url(path, seconds, key, method): """ Generates a temporary URL that gives unauthenticated access to the Swift object. :param path: The full path to the Swift object. Example: /v1/AUTH_account/c/o. :param seconds: The amount o...
784eacff50dca26eaf5d9f6fd3a8ed86d73007bc
571,768
def str_to_bool(bool_str: str) -> bool: """ Convert a string to a bool. Accepted values (compared in lower case): - `True` <=> `yes`, `true`, `t`, `1` - `False` <=> `no`, `false`, `f`, `0` .. code-block:: python >>> str_to_bool("yes") == True # Works with "yes", "true", "t", "y", "1...
9fdc20781ce7c66769bbe11593c86a7f251eed21
571,771
def get_list(list_var): """Returns empty string if variable is None.""" if list_var: return list_var else: return ""
49b324eaeb4697d5a5ada59412db6ba8815aa507
571,772
def is_ip_valid(ip_string: str, port: int) -> bool: """Receive ip address and port and return if valid. Args: ip_string (str): ip address to check. port (int): port to check. Returns: bool: is the string a valid ip address. """ if not isinstance(port, int): print('Inv...
7a6ac2d7e52711de7792930ae64d3982574f97bf
571,773
def get_minute_resolution(dataframe): """Aggregate the data to get one-minute resolution, where the number of seconds is 0, so each record is on the minute exactly. Output a new dataframe with one-minute resolution. """ minute_res_df = dataframe[dataframe['time_seconds'] == 0] print("Number of rows in minu...
daaa1da6330746433e984a060b2e6e1750cdde80
571,780
def top_sentences(query, sentences, idfs, n): """ Given a `query` (a set of words), `sentences` (a dictionary mapping sentences to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the `n` top sentences that match the query, ranked according to idf...
891827350e7be89715609e29a0a9fa3322d97b13
571,784
def _pop_message(message): """Pops the top-most space-separated component from the message.""" if " " in message: component, message = message.split(" ", 1) return component, message.lstrip(" ") return message, ""
b40a75826fbed9600d16582ae5bac40901cb9929
571,790
def synthesize_pipeline_name(val): """Synthesizes a pipeline name for the given pipeline object.""" return 'anonymous_pipeline[id:{}]'.format(id(val))
e859e9881ad706e48ff13d504a593fafb9e4a1dd
571,802
def gcd(a, b): """Returns the Greatest Common Divisor of the two integers passed as arguments. Args: a: an integer b: another integer Returns: Greatest Common Divisor of a and b >>> gcd(48, 64) 16 >>> gcd(44, 19) 1 """ if b == 0: return b return gcd(b, ...
b5bff8329b6048462510a1a8b49e23d7739e3ed9
571,803
import fnmatch import re def _find_matching_version(versions, version_pattern): """ Return the first matching version >>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x') '1.0.12' >>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x') """ pattern = fnmatch.translat...
cc6f5eaaac3c6cb5d655c859c4cbd2eb0b6965e5
571,805
def os_release_files(release, os_slug): """ Given a Relase object and os_slug return the files for that release """ return { 'release': release, 'files': release.files_for_os(os_slug), }
f43f8314a8d683d1a04caca609c4a7354a9c41fa
571,806
from collections import deque def problem_1_4(s: str) -> str: """ replace all spaces in a string with %20 >>> problem_1_4("foo bar ") 'foo%20bar' >>> problem_1_4("a s") Traceback (most recent call last): ... ValueError: Size of provided string is incorrect """ response = de...
89bae80b9a2270a1100f3f48b67813d736df0941
571,809
def static_map(keys): """ Returns a resolver that uses a static map to determine which keys are related to the specified column. Parameters: keys (dict): Dictionary keyed by table name of dictionaries keyed by column name each containing a list of related columns Returns: function: Res...
245f2493c46cc25c491c2184cd316d8ee7b855f2
571,810
def is_enabled(element): """Determine if an element is enabled. This is a wrapper around Selenium's WebElement.is_enabled() Parameters ---------- element : element The element to test. Returns ------- bool True if enabled, False otherwise. """ return element.s...
961c250d3d3ed26bff5cb3a8a1446f4f9c1bfb1b
571,811
def to_matrix_vector(transform): """Split a transform into it's matrix and vector components. The tranformation must be represented in homogeneous coordinates and is split into it's rotation matrix and translation vector components. Parameters ---------- transform : ndarray NxM tra...
210a01d0d4fb53e69f9a18ffa6358a0de0aca415
571,817
def get_post_meta_data(post): """ Retrieve a list of meta_data of a post :param post: dict The post in json format :return: list """ shortCode = post["node"]["shortcode"] postLikes = post["node"]['edge_media_preview_like']["count"] commentCount = post["node"]['edge_media_to_comment'...
0f7e7c38e977726547391ebda205f2fc51ba5e10
571,819
def find_grid_index_on_dimension(pos: float, min_value: float, cell_len: float) -> int: """ Parameters ---------- pos: float position min_value: float min value of the dimension cell_len: float size of each grid cell of the dimension Returns ------- int ...
a5fea9a2c2ada20b1b8fff35e737128149bb059c
571,822
import re def get_number(name): """ use regex to get the first integer in the name if none exists, return -1 """ try: num = int(re.findall("[0-9]+", name)[0]) except: num = -1 return num
c4e1bfe8afcd59e9aa217f2fdcb4270230a0ecec
571,826
import torch def area_under_curve(x, y): """Calculate area under curve""" return torch.trapz(x=x, y=y)
a78ff24b3ac8f20f8c66671de1e4fd7c5f905386
571,827
import traceback def load_code(mfile, fname): """ Load function from given python module (file) :param mfile: the python module/file name which provides fname :param fname: name of the function from mfile """ mname = mfile.split('.py')[0].replace('/', '.') try: mod = __import__(mn...
374606225cd0dee51c8dbde23cad3ef3e929b773
571,829
def recursive_example(input): """ Simple Recursive Function """ if input <= 0: return input else: output = recursive_example(input - 1) return output
f1f158ea38d24dcc6f011bd068b7d2429218fa55
571,833
import math def distance(a,b): """ simple distance a ,b = (lon,lat) """ x = a[0] - b[0] y = a[1] - b[1] return math.sqrt(x*x + y*y)
c442e34d66bcc7e8d66e01c500fea134e81494cf
571,834
def _dict_with_extra_specs(inst_type_query): """Takes an instance or instance type query returned by sqlalchemy and returns it as a dictionary, converting the extra_specs entry from a list of dicts: 'extra_specs' : [{'key': 'k1', 'value': 'v1', ...}, ...] to a single dict: 'extra_specs' : {'k...
06539eae1302ba225268693232144416667ec918
571,838
def _recursively_list_test_suites(suite): """ Recursively parses a test suite tree returns the names of test suites that contain tests that were executed """ ret_val = [] if suite.tests: ret_val.append(suite.name) for sub_suite in suite.suites: ret_val.extend(_recursively_list_t...
4933ae014c4831f422af931479e1bee155b4b302
571,843
def read_content(path): """Read the content of a file.""" with open(path, 'r') as in_file: return in_file.read()
39a9eff95ef0722974ecca1e05067d2a129c8b71
571,844
import base64 def urlsafe_b64encode_as_str(value): """ base64 url safe encoding which returns result as UTF-8 encoded string """ return base64.urlsafe_b64encode(value).decode("utf-8")
478932193b477370db0c97f1a58feec9ceb9c3cb
571,845
def _tr_xml_to_json_extension(xml_filename): """ _tr_xml_to_json_extension Translates example.xml to example.json (just the filename) """ if '.xml' in xml_filename: return xml_filename.replace('.xml', '.json') else: return xml_filename + '.json'
2a90c24f8a49d26ba0109af73de903cb3540550d
571,846
from datetime import datetime def epoch_ms_from_utc_datetime(utc: datetime) -> float: """Epoch ms from non-naive UTC datetime.""" return utc.timestamp() * 1000
b145d453dd525fc41a2cb70b67895df7534d002a
571,853
def put_bucket_policy(s3_obj, bucketname, policy): """ Adds bucket policy to a bucket Args: s3_obj (obj): MCG or OBC object bucketname (str): Name of the bucket policy (str): Bucket policy in Json format Returns: dict : Bucket policy response """ return s3_obj....
c1f098a49e743f180ed7882951f0bd38ba9eeb39
571,855
def split_comments(comments): """Split COMMENTS into flag comments and other comments. Flag comments are those that begin with '#,', e.g. '#,fuzzy'.""" flags = [] other = [] for c in comments: if len(c) > 1 and c[1] == ',': flags.append(c) else: other.append(...
8241238b2169534a54eb7df41868cc1d2e78a567
571,858
def indent(text, indentation, indentation_character="\t"): """Indents all lines of a string with the given indentation. Args: text: String to indent. indentation: Number of indentation characters to indent. indentation_character: indentation character to use """ blank = indentat...
39ea09b2bd8a9fed43907265cf3df0f94f6265b7
571,860
def select_bounds_around_rivermouth(pair,border=10): """Select a set of bounds for a plot of a river mouth""" imin = max(min(pair[0].get_lat(),pair[1].get_lat()) - border,0) imax = max(pair[0].get_lat(),pair[1].get_lat()) + border jmin = max(min(pair[0].get_lon(),pair[1].get_lon()) - border,0) jmax ...
2b51a4d55e2ca0ef2be51f1db5b1a16fc4440947
571,861