content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def d2l(dx, fc, i):
""" second-order left-sided derivative at index i """
D = -fc[i+2] + 4.0*fc[i+1] -3.0*fc[i]
D = D/(2.0*dx)
return D | 0e2664d4ef6e17e98173c57aec66e805e0095723 | 648,728 |
from typing import Tuple
def custom_ravel(tup: Tuple[int, int], shape: Tuple[int, int]) -> int:
"""Ravel indexes for 2D array.
This is a jitted function, equivalent to the `numpy` implementation of
`ravel_multi_index`, but configured to accept only a single tuple as
the index to ravel, and only works... | 31741efb20dd22b1512b9ff3287d1bb56ded33ba | 648,730 |
import torch
def cat_arange(counts, dtype=torch.int32):
"""
Concatenate results of multiple arange calls
E.g.: cat_arange([2,1,3]) = [0, 1, 0, 0, 1, 2]
Credits: https://stackoverflow.com/a/20033438
:param torch.tensor counts: a 1D tensor
:return: equivalent to torch.cat([torch.arange(c) for c... | 61baf564bf03e7c0713ea2ef1b3ff9f08ae8949d | 648,733 |
def is_ends_with_underscore(value: str):
"""Does value end with underscore."""
if value == "":
return False
else:
return value[-1] == '_' | 19a1d9f117aa9804594ed05369aff73f07b753ea | 648,738 |
def verify_operator(operator):
"""
Check that ``operator`` is one of the allowed strings.
Legal operators include the following strings:
- '='
- '<='
- '>='
- '<'
- '>'
- '<>'
- 'like'
- 'regexp'
- 'is null'
- 'is not null'
EXAMPLES::
sage: from sage.da... | e3ade6551993e05e386ac1f992f52dacba15439a | 648,739 |
def str_to_float(source: str) -> float:
"""Converts a str to a float."""
return float(source) | 05081e2155ffe33e03f60e0fb945cd110c1fc4ab | 648,741 |
def get_parameter_list_from_request(req,parameter):
"""Extracts a parameter from the request.
Parameters
----------
req : HttpRequest
The HTTP request.
parameter : str
The parameter being extracted.
Returns
-------
List
List of comma separated parameters.
"... | 4b9f66e64455229a998eb199a3fc890d2ba8ba02 | 648,745 |
def notify_upgrade(app, flash):
"""If a new version is available, notifies the user via flash
that there is an upgrade to specter.desktop
:return the current version
"""
if app.specter.version.upgrade:
flash(
f"Upgrade notification: new version {app.specter.version.latest} is ava... | 01e5d2c3d6865a9dfafb61a3f7b8cd349ddb56c6 | 648,746 |
def underscore_to_camel(
text: str,
lower_first: bool = True
) -> str:
"""Convert a string with words separated by underscores to a camel-cased
string.
Args:
text (:obj:`str`): The camel-cased string to convert.
lower_first (:obj:`bool`, optional): Lowercase the first charac... | b33d322d957f9492c70382fe8ed6f05f5e2f8fc2 | 648,756 |
import yaml
def import_config(conf_name):
"""
Load YAML configuration file
"""
with open("../etc/config.yaml", 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile)
cfg_sect = cfg[conf_name]
return cfg_sect | ba55cdc7c853792027cf6a9083b3e19cecd40164 | 648,757 |
import re
def sub_name(s):
"""replaces brackets with '-' and removes ',* """
#replace brackets with '_' and remove ',*
#s = re.sub('\W', '',s_n) # dont do that, will replace '-' as well
s_n = re.sub('[()]',"-",s)
s_n = re.sub("'","",s_n)
s_n = re.sub('\*',"",s_n)
return s_n | 7e27257f192bd6ebf67e958bfbde6f26fd340794 | 648,759 |
import re
def is_inline_name(op):
"""Tell if given name is viable for inlining."""
if re.match(r'^i_.*$', op.getName(), re.I):
return True
return False | fd9044f6809cc6f437c5dc72df14a4057bcc6ca4 | 648,763 |
import pathlib
import yaml
def load_yaml(file):
"""
Loads the yaml file and returns a dictionary of the file contents.
Parameters
----------
file : string
Name of the yaml file with extension i.e. 'filename.yaml'.
Returns
-------
dict
Structured contents of the yaml f... | e52d60878cd6cf31ccda9429a4bf45e38fa5e9df | 648,765 |
import unicodedata
def string_width(string):
"""Measure rendering width of string.
Count ZENKAKU-character as 2-point and non ZENKAKU-character as 1-point
"""
widthmap = {'Na': 1, 'N': 1, 'H': 1, 'W': 2, 'F': 2, 'A': 2}
return sum(widthmap[unicodedata.east_asian_width(c)] for c in string) | 89e15d853f3e5caf5961f1635104f7647203bfb2 | 648,766 |
def fixIncorrectDateEncoding(Date):
"""
Fix date string to make it conform to ISO standard.
"""
if 'T00:00:00Z' in Date:
return Date
return Date + "T00:00:00Z" | 57b0bed00c214794d3d1e25c313ce3e3cbe61526 | 648,767 |
import re
def replace_forceinline(input_string):
"""__forceinline__'d methods can cause 'symbol multiply defined' errors in HIP.
Adding 'static' to all such methods leads to compilation errors, so
replacing '__forceinline__' with 'inline' as a workaround
https://github.com/ROCm-Developer-Tools/HIP/blo... | e7e8fe24c8d7c0273268f22499ce0437e0fcc768 | 648,768 |
def split_macros(macros):
"""Split user-provided macro strings into a dictionary."""
split = [macro.split('=', 1) for macro in macros]
return {var: value for var, value in split} | a22b4e13a858abed93b84fc6623dc45db924135e | 648,773 |
def sanitize_cr(realmrep):
""" Removes probably sensitive details from a realm representation.
:param realmrep: the realmrep dict to be sanitized
:return: sanitized realmrep dict
"""
result = realmrep.copy()
if 'secret' in result:
result['secret'] = '********'
if 'attributes' in res... | 63c4992736b936abe96611b002f212063134b6b5 | 648,774 |
from datetime import datetime
def format_modified_time(entry):
"""Formats the modified time (seconds since epoch) for display on screen"""
return datetime.fromtimestamp(entry['mtime']).strftime('%b %-d %H:%M') | 51589bae554732f89bf24bfd0f70aa1e57eb7a9d | 648,776 |
def record_item_style(context):
"""
Return the style to be usd for the metric's current record specific item.
Like the :func:`record_style` template tag, this expects a template context
variable ``'metric'`` referring to the metric instance in question, as well
as a context variable ``'record'`` co... | dcd3cd406e4f26fbdc9d57785988c5dcb6739509 | 648,780 |
def find_first(item, vector):
"""return the index of the first occurence of item in vector"""
for i in range(len(vector)):
if item == vector[i]:
return i
return len(vector) | 162052704f346ce853e9c67ae13bc9e56220f22a | 648,781 |
def to_str(Q):
"""An informal, nicely printable string representation of the Quaternion object.
"""
return "{:.3f} {:+.3f}i {:+.3f}j {:+.3f}k".format(Q.q[0], Q.q[1], Q.q[2], Q.q[3]) | 8e5b560682563a9d70e4ad78ecd5940066c779d2 | 648,786 |
import re
def decontracted(phrase):
"""
Change words abbreviations into their actual word meaning
:param phrase: sentence we want to change
:return: modified sentence
"""
# specific
phrase = re.sub(r"won't", "will not", phrase)
phrase = re.sub(r"can\'t", "can not", phrase)
# gener... | 97dcfc789b85382c5e72b6b737e1a5e7471448c0 | 648,787 |
async def get_alternate_id(db, name: str) -> str:
"""
Get an alternate id for an API key whose provided `name` is not unique. Appends an integer
suffix to the end of the `name`.
:param db: the application database object
:param name: the API key name
:return: an alternate unique id for the key
... | 9bf86a1a47cc4da55ec0fdada1f0a491e051d6f2 | 648,788 |
import hashlib
def _hash_file_obj(obj):
"""Hash a file-like object."""
return hashlib.sha256(obj).hexdigest() | 7b1eb0841d4dc3fe561603d3c5cdb2b230e20dee | 648,794 |
from typing import Union
from pathlib import Path
def expand_path(path: Union[str, Path]) -> Path:
"""Convert relative paths to absolute with resolving user directory."""
return Path(path).expanduser().resolve() | fdcfa9aeefacde5ad15d21710e3f596e2597f6a3 | 648,796 |
def _VerifyDirectoryIterables(existing, expected):
"""Compare two iterables representing contents of a directory.
Paths in |existing| and |expected| will be compared for exact match.
Arguments:
existing: An iterable containing paths that exist.
expected: An iterable of paths that are expected.
Raises... | 40daa32a2ad239a2fc6f309b41ca7f4d64bb7b25 | 648,798 |
def prime_factor_decomposition(num):
"""
Prime factor decomposition of a number.
:param num: input number.
:return: all prime factors of input number.
"""
primes = [2]
for i in range(3, num):
if i * i > num:
break
flag = True
for j in primes:
i... | 0073e6646e7af9ed94ebb757aa47547f649f3856 | 648,800 |
def avoid_duplicate_names(new_column_name, columns, suffix):
"""Adds a suffix in case of a column name collision in a recursive way
:param new_column_name: a possible new column name
:type: str
:param columns: existing column names
:type: list
:param suffix: suffix to add to prevent collisions
... | 61df74f97dc0026e0b4baa60c71ff7529dab32a1 | 648,802 |
def validate_list(value):
"""
Validate a list input.
Parameters:
value (any): Input value
Returns:
boolean: True if value is a list
"""
return isinstance(value, list) | 652cc544a2132f655025e41cc7920334da1e6020 | 648,804 |
def p(key):
"""Returns PDT namespace prefix"""
return '{http://ufal.mff.cuni.cz/pdt/pml/}%s' % (key) | 67917be8b250839404e90d31547d035f209599bc | 648,805 |
def evaluate_llh(llh: float, gt_llh: float, tol: float = 1e-3):
"""Evaluate whether log likelihoods match."""
if llh is None:
return False
return abs(llh - gt_llh) < tol | ae044444a4a4739e90907c21e4e2cd967150f702 | 648,807 |
import pathlib
def servo_yaml(tmp_path: pathlib.Path) -> pathlib.Path:
"""Return the path to an empty servo config file."""
config_path: pathlib.Path = tmp_path / "servo.yaml"
config_path.touch()
return config_path | cb51ed0830daf3abcbacfab8ca395071f4ec2574 | 648,809 |
def get_coords(x, y, params):
"""
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple c... | 1b696016f69894ca7aad6d07ae8ec48dff5911c8 | 648,817 |
def xor_decrypt(ciphertext: str, key: int) -> str:
""" Decrypt a hex-encoded ciphertext into plaintext.
Args:
ciphertext (str): The hex-encoded ciphertext
key (int): The single-byte key
Returns:
str: The plaintext
"""
return ''.join(chr(b ^ key) for b in bytes.fromhex(ciphe... | c54cc86fe47c6f4ae6682c55e7df99cf2114a94b | 648,826 |
def CreateFile(fileName):
"""
Create an empty file as per passed path and name
"""
try:
f = open(fileName, "w+")
f.close()
return 0, None
except Exception as e:
return -1, e | fed0605b3175220e187794452f82a881c9d83b7e | 648,827 |
def DictionaryLower(dictionaryForward: dict):
"""
Function to convert dictionaries with string entries to upper case.
Args:
dictionaryForward: Simple 1-dimensional dictionaries.
Returns: dictionary forward in lower case key/values.
"""
return dict((str(k).lower(), v.lower()) for k, v i... | 391b4876b2d61aa6ab55b989e12a59a9733ae363 | 648,829 |
import itertools
def flatten(x):
"""
Flatten list of lists
"""
flatted_list = list(itertools.chain(*x))
return flatted_list | b12eb6aa09676d1cd5d6b166fe4e8dc554f7a409 | 648,831 |
def divideList(x, k):
"""
Divide list @x into roughly @k parts.
"""
if k > len(x): return [[elem] for elem in x]
part_len = int(len(x) / k)
parts = []
start = 0
while start < len(x):
parts.append(x[start: start + part_len])
start += part_len
return parts | 5f9ec0f2d1e016491b7f37ee8e2e0c11d1b4f0e4 | 648,835 |
import time
def epoch(value):
"""
Convert datetime to unix epoch time.
Alternatively you can you this {{ my_date|date:"U" }}
:param value: datetime instance
:return: int
"""
try:
return int(time.mktime(value.timetuple()) * 1000)
except AttributeError:
return '' | c2d530542570911412b11c801d20a92af6c8a724 | 648,836 |
def to_byte(byte):
"""Make sure an object really represents an integer from 0 to 255,
and return the integer.
"""
byte = float(byte)
assert byte.is_integer(), f"Got a non-integer byte: {byte}!"
byte = int(byte)
assert byte >= 0, f"Got a negative value for a byte: {byte}!"
assert byte <=... | abbe94e31f28be1b6e59a8d7b246a56b25553945 | 648,843 |
def ifelse (pred:bool, cons, alt):
"""
If predicate consequent else alternative
"""
if pred:
return cons
else:
return alt | 421c170e8c1650950e295882267d5f5946e29d08 | 648,844 |
def parse_config(path):
"""
This method parses a config file and constructs a list of blocks.
Each block is a singular unit in the architecture as explained in
the paper. Blocks are represented as a dictionary in the list.
Input:
- path: path to the config file.
Returns:
- a list co... | 2f529c167abd9b2360ed424384aaea228e5352be | 648,848 |
import re
def parse_arches_from_config_in(fname):
"""Given a path to an arch/Config.in.* file, parse it to get the list
of BR2_ARCH values for this architecture."""
arches = set()
with open(fname, "r") as f:
parsing_arches = False
for line in f:
line = line.strip()
... | af1d8de9a5a210f4e009b942cf069f1c6d6c4e47 | 648,849 |
def test_module(client):
"""
Test connection to Azure by calling the list incidents API with limit=1
"""
client.http_request('GET', 'incidents', params={'$top': 1})
return 'ok' | b8878699e67d08b7b9d7e34804315abce1311d83 | 648,850 |
from typing import Mapping
from typing import Sequence
from typing import Union
from typing import List
import itertools
def hyper_grid(
grid_dict: Mapping[str, Sequence[Union[str, int, float]]]
) -> List[Mapping[str, Union[str, int, float]]]:
"""Converts a param-keyed dict of lists to a list of mapping.
Arg... | a62493e187be204ac6cd2995c4a997cf153990c1 | 648,854 |
def dict_to_qs(dct):
"""
Takes a dictionary and uses it to create a query string.
"""
itms = ["%s=%s" % (key, val) for key, val in list(dct.items())
if val is not None]
return "&".join(itms) | 5a670ca6d195ccac38a807c52fb227e5d43a3fa2 | 648,858 |
def factorial(n):
"""Factorial function. This will be used in the power series"""
if n==1:
return 1
return n * factorial(n-1) | 92442a4b079722ca42517ddb400096a00f471a1b | 648,861 |
def csv_to_set(x):
"""Convert a comma-separated list of strings to a set of strings."""
if not x:
return set()
else:
return set(x.split(",")) | eed054487d137b4ba134401bb4a0bb4b6d70e4a3 | 648,864 |
import re
def optimade_filter_conversion(filter_expr):
"""
Convert optimade filters to oqmdap formationenergy filters
Input:
:str : original filter expression
Output:
:str : converted filter expression
"""
filter_expr_out = filter_expr
# General conversion
filter_expr_... | b954d1fffe48f7578cef687adea23d3684d8a030 | 648,866 |
import inspect
def isderivedclass(klass, parent):
"""
Test if klass is derived from a parent class.
Parameters:
klass A <class 'klass'> object.
parent Class type or string name of the parent class.
Returns
True or False.
"""
try:
name = parent.__name__
except AttributeError:
nam... | 755810c78e4fd6b1ffef2861187b0b999fa904d7 | 648,869 |
def argmin(l):
"""
Get index of min element in list
"""
return min(zip(l, range(len(l))))[1] | 8160e171d1d430f3a390e76e0abbcb6c39e27592 | 648,870 |
def date_range_overlap(start_1, end_1, start_2, end_2):
"""
Based on: https://stackoverflow.com/questions/9044084/efficient-date-range-overlap-calculation-in-python
"""
latest_start = max(start_1, start_2)
earliest_end = min(end_1, end_2)
delta = (earliest_end - latest_start).days + 1
return... | 58be73b32620f606fcb6c12f3b74dad631c19d5e | 648,872 |
def _maven_artifact(group, artifact, version, packaging = None, classifier = None, override_license_types = None, exclusions = None, neverlink = None):
"""
Generates the data map for a Maven artifact given the available information about its coordinates.
Args:
group: *Required* The Maven artifact c... | 25eef1787010ab5fd16fbc28b42082e23e086866 | 648,873 |
from typing import Type
from enum import Enum
def string_to_konan_enum(
enum_string: str,
enum_class: Type,
) -> Enum:
"""Create an enum object from enum_string.
If the enum_class does NOT have a corresponding enum_string, then return enum_class.Other
enum_class must include the Other type
:p... | 5ec02ac680b9983957e79249ce4972b0c18f80e1 | 648,876 |
import bs4
def is_navigable_string(obj):
"""Is navigable string."""
return isinstance(obj, bs4.NavigableString) | 7cf8f2c1e6a1ca87aa62cd9a22930d0e53fc8e6d | 648,877 |
def core_result_type(selectable, s):
"""Given a SQLAlchemy Core selectable and a connection/session, get the
type constructor for the result row type."""
result_proxy = s.execute(selectable.limit(0))
return result_proxy._row_getter | 5ce237376289bb03c1b465f94b597124ff3af8d4 | 648,879 |
def f(x, y):
"""
Function that will be optimized
Parameters
----------
x : float
Value for parameter x.
y : float
Value for parameter x.
Returns
-------
float
Function value for f(x,y).
"""
if (x**2 + y**2) <= 2:
return (1-x)**2 + 100*((... | 2000faddd9bc0cb37e71bf64c86072a51ec1e9da | 648,880 |
import math
def normalize_weight(weight):
"""AS3 accepts ratios between 0 and 100 whereas Octavia
allows ratios in a range of 0 and 256, so we normalize
the Octavia value for AS3 consumption.
We also round up the result since we want avoid having a 0
(no traffic received at all) when setting a we... | 83a66d9dd3b58229f48b9510382f05f5e803abe6 | 648,881 |
def sgi_1973_to_2016(sgi_id: str) -> str:
"""
Convert the slightly different SGI1973 to the SGI2016 id format.
:examples:
>>> sgi_1973_to_2016("B55")
'B55'
>>> sgi_1973_to_2016("B55-19")
'B55-19'
>>> sgi_1973_to_2016("E73-2")
'E73-02'
"""
if "-" n... | 8109c96b66ca7b0707536ec61d4d457410f5967e | 648,884 |
def valid_user_input(ui: str) -> bool:
"""Determines if the passed string is a valid RPS choice."""
if ui == "rock" or ui == "paper" or ui == "scissors":
return True
return False | 648484999fcc3a81cce06e4480a1bb6bd5ed5069 | 648,886 |
def filter_data(data, condition):
"""
Remove elements that do not match the condition provided.
Takes a data list as input and returns a filtered list.
Conditions should be a list of strings of the following format:
'<field> <op> <value>'
where the following operations are valid: >, <, >=, <=,... | 7f966c8337f84ce516525c370a217f790b2f27a6 | 648,888 |
def vec_neg(a):
"""
Negates a vector element-wise
Parameters
----------
a: list[]
A vector of scalar values
Returns
-------
list[]
The negated vector of a
"""
# return [-a[n] for n in range(len(a))]
return [*map(lambda ai: -ai, a)] | 01a6c434eb1fbd3854bf1e7e8557b3154bc735bb | 648,890 |
def SumString(table : list) -> str:
"""
Connects all the strings in the list to a single string, optimal for the output of JLua.GetLuaString()
:param table: A string list like generated by readlines() or GetLuaString()
:return: The Connected string
"""
sumstring = ""
for string in table: su... | f6e187b3087bae1407df4948215f8dd2c62c489f | 648,891 |
from typing import Any
from typing import Mapping
from typing import Collection
def is_arraylike(obj: Any) -> bool:
"""Determine if the provided object is an non-mapping generic container type such as an array,\
tuple or set.
Example:
>>> from collectionish.utils import is_arraylike
>>>
... | 69ed931d76da77b71a248a790a5beb6f9d87d3f0 | 648,892 |
def paint_text(text_str, color_str):
"""
Adds markup around given text.
Supports some colors by name instead of hexadecimal.
:param text_str:
:param color_str: (str) Hexadecimal color.
:return: (str)
"""
return '[color={color_str}]{text_str}[/color]'.format(text_str=text_str,
... | 256dde931eeec82250fc178d28d9bdc07cd651c8 | 648,893 |
from pathlib import Path
def get_files_under_dir(root, pattern):
"""Construct list of path objects given pattern under the root directory.
"""
root = Path(root)
if root.exists():
return [p for p in root.glob(pattern) if p.is_file()]
else:
raise FileNotFoundError(f"Direcotry {root}... | 79a762c94b5edea9631ef6f96f53035f07faeded | 648,895 |
def compute_r_parameter(ago_susceptible: int, current_susceptible: int, current_infected: int) -> float:
"""
Function for compute infection ratio parameter based od SIR model.
Parameters
----------
ago_susceptible: int, required
Amount of susceptible people one interval before current itera... | cd33abad340a178ce03e669d135a065f1b78b2ea | 648,896 |
def rotate_right(x, y):
"""
Left rotates a list x by the number of steps specified
in y.
Examples:
>>> from sympy.utilities.iterables import rotate_right
>>> a = [0, 1, 2]
>>> rotate_right(a, 1)
[2, 0, 1]
"""
if len(x) == 0:
return x
y = len(x) - y % len(x)
retur... | bbf75b17d2d31bd9d9a648a168c229367c8b77c5 | 648,897 |
import difflib
def difflib_overlap(word_token1: list, word_token2: list) -> float:
""" Get similarity percentage from matching sequences between two strings """
seq = difflib.SequenceMatcher(a=word_token1, b=word_token2)
# Return similarity percentage based on difflib library Sequence Matcher
return... | 0cd770e1c71f387600a008247413eaa63d587804 | 648,908 |
from typing import Any
from typing import Callable
def find_nonmatching_fields(item: Any, match_fn: Callable[[Any], bool], *fields):
"""Check that the given fields of an object match the output of a function.
:param item: Any object with attributes to check.
:param match_fn: A callable function. Each att... | e1c31c03c73536ff3f23e1bfa9908700777ed231 | 648,909 |
def get_node_labels(session):
"""Returns all node labels in use in the database."""
result = session.run("MATCH (n) RETURN DISTINCT labels(n) as label")
labels = []
for record in result:
labels.append(record.get("label")[0])
return labels | bad38259676bc9d3657677e51eaf6890dde82080 | 648,910 |
def _XYDict(x_value, y_value, first='x', second='y'):
"""Take in x and y coordinates and return in dictionary form.
Args:
x_value: The value of the x coordinate.
y_value: The value of the y coordinate.
first: The key for first field.
second: The key for second field.
Returns:
A dict with a x... | 2db919b053d053f8e5bd5489cfb3f43f4cf555ff | 648,914 |
import json
def load_config(config_filepath):
"""
Using a json file with the master configuration (config file for each part of the pipeline),
return a dictionary containing the entire configuration settings in a hierarchical fashion.
"""
with open(config_filepath) as cnfg:
config = json.... | 51d9784990c4ad6e86edff8803caad89dcf22fff | 648,916 |
def span2toks(span, document):
"""
:param span: span array representing [start, end]
:param document: list of tokens from which to extract span tokens
:return: tokens from document indicated by span indices
"""
return document[span[0]:span[1] + 1] | a46570c5275ec9c987e999beabc967e284b62b1a | 648,918 |
def find_nearest_datapoint(lat, lon, ds):
"""Find the point in the dataset closest to the given latitude and longitude"""
datapoint_lats = ds.coords.indexes["latitude"]
datapoint_lons = ds.coords.indexes["longitude"]
lat_nearest = min(datapoint_lats, key=lambda x: abs(x - lat))
lon_nearest = min(dat... | ffc106e0ac092ce32d0e499369898f2139ac9ab9 | 648,919 |
def ignore_files(files, ignore):
"""Ignore files based on a search term of interest.
Parameters
----------
files : list of str
File list.
ignore : str
String to use to drop files from list.
Returns
-------
list of str
File list with ignored files dropped.
""... | e358e040f344e51ac83dc9fbee026e024aafada9 | 648,921 |
def BoxLength(box):
"""Returns the box length given the box coordinates."""
return box[1::2] - box[0::2] | 68dd9db68975a646a850e138e4033bab7f26638c | 648,926 |
def get_analyze_query(graph_name):
"""Format an ANALYZE query with the name of the inserted RDF graph."""
return f"ANALYZE {graph_name}" | d78ad2584b6a9470dfcdd574fbaffb40b7f5594e | 648,929 |
def validate(observation):
"""Make sure the observation table is valid, or raise an error."""
if observation is not None and type(observation) == dict:
return observation
elif type(observation) == list:
return observation
else:
raise RuntimeError('Must return dictionary from act(... | 5e7fe767f8229f514517742de5b4c50b0ee7c388 | 648,930 |
from functools import reduce
import operator
def product(values, base=1):
"""Get the product of the given values.
:param values: An iterable of values to be multiplied.
:param base: Applied to the beginning of the calculation.
:type base: int
"""
return reduce(operator.mul, values, base) | c645ec9f354f4ef265026128dc0914c3a60b8d1f | 648,935 |
def get_name_from_kwarg(var):
"""
Given some kwarg name, return the original variable name.
:param var: A string with a (internal) kwarg name
:return: The original variable name
"""
return var.replace('#kwarg_', '') | da84fa89814bc6bd44afcaef1bd673c137288711 | 648,942 |
def get_appendix_data(df, table):
"""
Given Appendix A DataFrame df and table name,
return Sequence, Start, and End numbers as lists.
"""
df = df[df['name'] == table]
return df['seq'].tolist(), df['start'].tolist(), df['end'].tolist() | 46ec1a9b5c0c065d9a261981efb5d7bb625971a9 | 648,951 |
def is_nonzero(delta):
"""Return True if any element of 2D list is nonzero."""
nonzero = False
for row in delta:
for element in row:
if element != 0:
nonzero = True
return nonzero | e166902466012f0670b17d67e9dc3348c928021b | 648,955 |
def parse_tags(tags):
"""
>>> parse_tags('writing')
'writing'
>>> parse_tags(['news', 'steemit', 3, {'5': {}, '3': {}, '1': {}}, {'39': {}, '45': {}, '11': {}}, {}, 'esteem'])
['news', 'steemit', 'esteem']
>>> parse_tags(['dlive', 'dlive-broadcast', 'game', 'DLIVEGAMING'])
['dlive', 'dliv... | fae032a58e4c477febddc1e6ea6851a95654a637 | 648,956 |
import re
def account_token(doc):
"""Flag user accounts with custom .is_account attribute"""
pattern = re.compile(r"@\w+")
for token in doc:
if bool(re.match(pattern, token.text)):
token._.is_account = True
return doc | bc45f53a36f5a58e8573608f5a0ea3e60bfe4b98 | 648,962 |
import warnings
def check_model(model: str) -> str:
"""Check model is 'aces' or 'btsettl'.
Parameters
----------
model: str
Model name. Should be either 'aces' or 'btsettl'.
Returns
-------
model: str
Valid model output; either 'aces' or 'btsettl'.
"""
if model == "ph... | 8ebafa33f25de2dc50340e9526494b03bf90165a | 648,963 |
def rstrip_special(line, JUNK="\n \t"):
"""
Returns the given line stripped of specific trailing characters
(spaces, tabs, and newlines by default).
Note that line.rstrip() would also strip sundry control characters,
the loss of which can interfere with Emacs editing, for one thing.
(Used by t... | 1848e931c464ff4b82fcb2d188d95d536b6512d6 | 648,966 |
import re
from pathlib import Path
def get_bibtex(filename):
""" Tries to extract a bibtex key from a filename and returns it.
If no bibtex key is found the function returns the filename (without suffix). """
bibtex = re.match(r'^[a-zA-Z]*\d{4}[a-z]?', Path(filename).stem)
if bibtex:
bibt... | f511a3beb4168605fccf9ffb420c75d6e9577f00 | 648,968 |
def requirements_file_to_list(fn="requirements.txt"):
"""read a requirements file and create a list that can be used in setup.
"""
with open(fn, 'r') as f:
return [x.rstrip() for x in list(f) if x and not x.startswith('#')] | 7bf8f1d183685945e08d64bf2430279ad9effb52 | 648,969 |
def resolve_aliases(kwargs, aliases):
"""Check and resolve to a standard label for any potential aliases.
Parameters
----------
kwargs : dict
Dictionary of labels and their values.
aliases : dict
Dictionary of label names and their list of aliases.
Returns
-------
out_k... | ba99c25ad2afc190e48e512de6e08d3a51bd643b | 648,975 |
import re
def rename_state_keys(state, keys_regex, replacement):
"""Rename keys from state that match a regex; replacement can use capture groups"""
regex = re.compile(keys_regex)
return {
(k if not regex.findall(k) else regex.sub(replacement, k)): v
for k, v in state.items()
} | 0ecd6353e31b927c16f365076acac6e67a44493d | 648,986 |
def hsv_to_rgb(h, s, v):
"""Converts HSV value to RGB values
Hue is in range 0-359 (degrees), value/saturation are in range 0-1 (float)
Direct implementation of:
http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_HSV_to_RGB
"""
h, s, v = [float(x) for x in (h, s, v)]
hi = (h / 60) % ... | bb50f18b05b93e3990d32b63259aff0a7d05cd49 | 648,987 |
from typing import Tuple
def check_class_number(class_number: str) -> Tuple[bool, str]:
""" Check class number"""
if int(class_number) < 1 or int(class_number) > 18:
return False, "Le numéro de classe doit être compris entre 1 et 18"
return True, "" | 3c4da994f5d8e377e96501524a9703dee6dcdfbd | 648,989 |
def pad(string, max_len):
"""
add some leading spaces to string to bring it up to max_len.
"""
string = str(string)
return " "*(max_len - len(string)) + string | 85eba565deee01771018740f31f40440e035746c | 648,995 |
def get_coverage_of_namespace(assembly, covered_lines, name_space, total_lines):
"""Get the coverage of a namespace."""
assembly_name = assembly["@Name"]
assembly_covered_lines = assembly["@CoveredStatements"]
assembly_total_lines = assembly["@TotalStatements"]
if assembly_name.startswith(name_spac... | f250e5d6c3595043e8ed122532fe7a0b12cdfb97 | 648,997 |
def has_next_page(json_data):
"""Check for more labels."""
page_info = json_data.get("data").get(
"repository").get("labels").get("pageInfo")
if page_info.get("hasNextPage"):
return True
return False | 460d34e77d3c54b7f5b97558a3b246f9d5483eb6 | 648,998 |
def get_grid_coordinates(imgnum,gridsize,w,h):
""" given an image number in our sprite, map the coordinates to it in X,Y,W,H format"""
y = (imgnum - 1)/gridsize
x = (imgnum -1) - (y * gridsize)
imgx = x * w
imgy =y * h
return "%s,%s,%s,%s" % (imgx,imgy,w,h) | 48f1e22b06b1a03f15e89acf8e2c5bf893f42e9e | 648,999 |
def trans_attr(attr, lang):
"""
Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated ... | d3abdc85cbcec8b8e97b4e7d754b4d82a4f23c73 | 649,001 |
import time
def time_fn(lbd):
"""
Times an expression.
If you need to time the operation:
result = heavy_function()
Then just write:
result = time_fn(lambda : heavy_function())
"""
start = time.time()
res = lbd()
end = time.time()
print("TIME: %... | 25e4da8b8fd7dcaaad1d774322c342d5fd4347ff | 649,002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.