content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _is_on_ray_left(x1, y1, x2, y2, x3, y3, inclusive=False, epsilon=0):
"""
Return whether x3,y3 is on the left side of the ray x1,y1 -> x2,y2.
If inclusive, then the answer is left or on the ray.
If otherwise, then the answer is strictly left.
"""
val = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)
if inclusive:
return val >= epsilon
return val > epsilon | b41cede7f203b3f85afff4b2c7feb8d0e1fb85f3 | 126,874 |
def clear(strlist):
"""Remove empty strings and spaces from sequence.
>>> clear(['123', '12', '', '2', '1', ''])
['123', '12', '2', '1']
"""
return list(filter(None, map(lambda x: x.strip(), strlist))) | 3901c076753ea8a489b849de4b3b0ebf41df69ed | 126,877 |
def chop_words(text, maximum_length=117):
"""
Deletes last word in a string until it does not exceed maximum length.
Args:
text (str): Status text.
maximum_length (int): Maximum character length.
Returns:
str or ``None``
"""
words = text.split()
for i in range(len(words)):
words.pop()
chopped_text = ' '.join(words)
if len(chopped_text) <= maximum_length:
return chopped_text
return None | 793a536b7240b6cb6fb2a4796fb33d6a2a3e7e64 | 126,878 |
import re
def pattern_matching(text: str) -> str:
"""
A regex based pattern matching function to remove the unwanted characters in the text.
:param text: The input text (str).
:return: A text without the patterns.
"""
patterns = re.compile(pattern="["
r"[-+]?\d*\.\d+|\d+"
r"([!\.\?؟]+)[\n]*"
r":\n"
r";\n"
r'؛\n'
r'[\n]+'
"]+", flags=re.UNICODE)
return str(patterns.sub(r'', text)) | 348a6f3a282d033ab2b18a0c4de14296efbd95c3 | 126,882 |
def url_match(url1: str, url2: str) -> bool:
"""
This function takes two urls and check if they are the same modulo '/' at the end
:param url1: mandatory, the first url
:type url1: str
:param url2: mandatory, the second url
:type url2: str
:rtype: Boolean
"""
return url1 == url2 or url1[:-1] == url2 or url1 == url2[:-1] | c7c15ed1665c2837ca5ec7af402b6f0b72e41c0d | 126,884 |
def make_list(data):
"""Ensure data is a list
:param data: data to check
:returns: data as list
"""
if isinstance(data, list):
return data
if data is None:
return []
return list(data) if not isinstance(data, str) else [data] | 97f0557f023e3c4e4f1f8710f51293f300b2f709 | 126,886 |
def validate_sql_select(value: str) -> str | None:
"""Validate that value is a SQL SELECT query."""
if not value.lstrip().lower().startswith("select"):
raise ValueError("Incorrect Query")
return value | 1cd221373adee7d0a06d30c39b82d6610273463f | 126,899 |
def no_filtering(
dat: str,
thresh_sam: int,
thresh_feat: int) -> bool:
"""Checks whether to skip filtering or not.
Parameters
----------
dat : str
Dataset name
thresh_sam : int
Samples threshold
thresh_feat : int
Features threshold
Returns
-------
skip : bool
Whether to skip filtering or not
"""
skip = False
if not thresh_sam and not thresh_feat:
print('Filtering threshold(s) of 0 do nothing: skipping...')
skip = True
thresh_sam_is_numeric = isinstance(thresh_sam, (float, int))
thresh_feat_is_numeric = isinstance(thresh_feat, (float, int))
if not thresh_sam_is_numeric or not thresh_feat_is_numeric:
print('Filtering threshold for %s not a '
'integer/float: skipping...' % dat)
skip = True
if thresh_sam < 0 or thresh_feat < 0:
print('Filtering threshold must be positive: skipping...')
skip = True
return skip | 49867e2597180ffad0bbd7a80ebd04d338b4cc91 | 126,901 |
def format_date(date):
"""
Returns a string representation of `date` datetime object, for printing purposes.
"""
return "{}/{}/{} {}:{}".format(date.day, date.month, date.year, date.hour, date.minute) | 5e873f5c046136b2edafb807c3a5f78ae7e07373 | 126,902 |
def fixture_sorted_param_names(allparams):
"""
Fixture for storing a sorted parameter list
"""
return sorted(list(allparams.keys())) | c358afea279514f6a8af36220765ad94f6395f9d | 126,904 |
def first(func, items):
"""Return the first item in the list for what func returns True"""
for item in items:
if func(item):
return item | 660e011657e94b096eae5b49544c50605d409b7e | 126,906 |
import torch
def normalize_weights(log_weight_hist, include_factor_N=True):
"""
Calculates normalized importance weights from logarithm of unnormalized weights.
If include_factor_N is set, then the result will be multiplied by the number of weights, s.t. the expectation is
simply the sum of weights and history. Otherwise, the average instead of the sum has to be taken.
"""
# use exp-norm trick:
# https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick
log_weight_hist_max, _ = log_weight_hist.max(dim=0)
log_weigth_hist_norm = log_weight_hist - log_weight_hist_max
weight_hist = torch.exp(log_weigth_hist_norm)
if include_factor_N:
weight_hist = weight_hist / weight_hist.sum(dim=0)
else:
weight_hist = weight_hist / weight_hist.mean(dim=0)
return weight_hist | 325b9b55f10dc31f3a2b5878683d98674504ead1 | 126,909 |
def inner(bra, ket):
"""Inner product of basis states bra and ket"""
return 0 if bra == 0 or ket == 0 else bra == ket | c3b2536aee4fa35c02c0045f19bc96fb1e06caf8 | 126,910 |
import json
def read_json(path: str) -> dict:
"""Read JSON from file path."""
with open(path, mode="r", encoding="utf-8") as file:
return json.load(file) | d1bbac8c808b93237eb317e14c6286c5bd62c2bb | 126,915 |
def className(item):
"""Returns class name given the item dictionary.
Args:
item: dictionary
Returns:
string usable as a class name
"""
obj = item['object'][0].upper() + item['object'][1:]
method = item['method'][0].upper() + item['method'][1:]
return 'ComputeV1%s%sHandler' % (obj, method) | f0535fa3aafb16d22ffd2a53e2b1103156040ece | 126,919 |
def ecgmathcalc(timelist, voltagelist):
"""Method that performs the basic math functions
This method takes the input lists from the fileparser and then obtains
the basic metrics. These include the max and min and duration. It also
obtains the length of the time list which is used in later calculations.
Max and min are both obtained using built in python functions and duration
is calculated by subtracting the endpoints.
:param timelist: List of time values
:param voltagelist: List of voltage values
:returns minvolt: Minimum voltage value recorded
:returns maxvolt: Maximum voltage value recorded
:returns duration: Duration of the ECG recording
:returns timelen: Length of the time list
"""
duration = 0
timelen = len(timelist)
# Determines Min and Max voltages in the file
minvolt = min(voltagelist)
maxvolt = max(voltagelist)
# Determines duration of input signal
duration = timelist[timelen-1] - timelist[0]
return minvolt, maxvolt, duration, timelen | 7f1154371afa610dc02d80c384d0513918bd9efb | 126,921 |
def get_missing_param_response(data=None):
"""
Returns error response for missing parameters
:param str data: message
:return: response
:rtype: object
"""
return {"status": 400, "message": "Missing query parameter.", "data": data} | 4d696878f1c1dc3ab5167726b57e573409663c31 | 126,927 |
import torch
def _batched_dotprod(x: torch.Tensor, y: torch.Tensor):
"""
Takes two tensors of shape (N,3) and returns their batched
dot product along the last dimension as a tensor of shape
(N,).
"""
return torch.einsum("ij,ij->i", x, y) | 96c9a402e9684d850add04aa24621e1ce7cc5626 | 126,928 |
import io
def description(filename):
"""
Returns the first non-heading paragraph from a ReStructuredText file.
:param str filename: the file to extract the description from
:returns str: the description of the package
"""
state = 'before_header'
result = []
# We use a simple DFA to parse the file which looks for blank, non-blank,
# and heading-delimiter lines.
with io.open(filename, 'r') as rst_file:
for line in rst_file:
line = line.rstrip()
# Manipulate state based on line content
if line == '':
if state == 'in_para':
state = 'after_para'
elif line == '=' * len(line):
if state == 'before_header':
state = 'in_header'
elif state == 'in_header':
state = 'before_para'
else:
if state == 'before_para':
state = 'in_para'
# Carry out state actions
if state == 'in_para':
result.append(line)
elif state == 'after_para':
break
return ' '.join(line.strip() for line in result) | 7e6cf62c470b722e5c39dc12231fe22f2874a71f | 126,929 |
def _separate_string(string: str, stride: int, separator: str) -> str:
"""Returns a separated string by separator at multiples of stride.
For example, the input:
* string: 'thequickbrownfoxjumpedoverthelazydog'
* stride: 3
* separator: '-'
Would produce a return value of:
'the-qui-ckb-row-nfo-xju-mpe-dov-ert-hel-azy-dog'
Args:
string: The string to split.
stride: The interval to insert the separator at.
separator: The string to insert at every stride interval.
Returns:
The original string with the separator present at every stride interval.
"""
result = ''
for (i, c) in enumerate(string):
if (i > 0 and i % stride == 0):
result += separator
result += c
return result | 378ed6795c5ce89c9dff0296801bd214dda05637 | 126,936 |
def merge(left, right):
"""Merges ordered lists 'left' and 'right'. It does this by comparing the
first elements and taking the smaller one and moving on to the next one in
the list, continuing until it gets to the end of both lists.
>>> merge([1, 5, 8], [1, 3, 8, 12])
[1, 1, 3, 5, 8, 8, 12]
>>> merge([], [1, 2])
[1, 2]
>>> merge([1, 2], [])
[1, 2]
"""
new = []
while left and right:
if left[0] < right[0]:
new.append(left.pop(0))
else:
new.append(right.pop(0))
new.extend(left)
new.extend(right)
return new | 697e965fb42a96d294fff6c11ed98a9853357617 | 126,941 |
from datetime import datetime
def read_daylio(filename):
"""
Read the daylio exported data.
Parameters
----------
filename : str
The Daylio CSV file path.
Returns
-------
daylio : tuple
Tuple of the dates (as datetime objects) and the recorded moods
(as a list of numbers as strings).
"""
# Parse the Daylio output.
columns = ['year', 'date', 'day', 'time', 'mood', 'activities', 'note']
mood = {c: [] for c in columns}
with open(filename, 'r') as f:
next(f) # skip header
lines = f.readlines()
for line in lines:
line = line.strip().split(',')
mood['year'].append(line[0])
mood['date'].append(line[1])
mood['day'].append(line[2])
mood['time'].append(line[3])
mood['mood'].append(line[4])
mood['activities'].append(line[5])
mood['note'].append(line[6])
# Convert the dates to datetime objects.
date_format = '%Y %d %B'
daymonth = [i.split(' ') for i in mood['date']]
dates = ['{y:04d} {d:02d} {m}'.format(y=int(i[0]), m=i[1][1], d=int(i[1][0])) for i in zip(mood['year'], daymonth)]
dates = [datetime.strptime(i, date_format) for i in dates]
# Convert mood to a numeric value (higher = better).
convert = {'rad': '5',
'good': '4',
'meh': '3',
'fugly': '2',
'awful': '1'}
for entry in convert:
for count, m in enumerate(mood['mood']):
if m == entry:
mood['mood'][count] = convert[entry]
return (dates, mood['mood']) | 9db665a27202fb0ef4090c39a4314d899eaeb030 | 126,942 |
def sym(mat):
"""Symmetrize matrix."""
return 0.5 * (mat + mat.T) | cb631cc720cef4d069cd8cfed90a9efb269cca33 | 126,943 |
from typing import Sequence
from typing import Iterator
import itertools
def powerset(seq: Sequence, exclude_empty: bool) -> Iterator[Sequence]:
"""Get an iterator over the powerset of the given sequence."""
start = 1 if exclude_empty else 0
return itertools.chain.from_iterable(
itertools.combinations(list(seq), r)
for r in range(start,
len(seq) + 1)) | a2f27bcc1144e1743e6a9fc2739950952301a72c | 126,944 |
import string
def populate_template(template, **kwargs):
""" Return a template string with filled argument values. """
return string.Template(template).safe_substitute(kwargs) | bc50b91108100405e36be44c81a5196671ec3050 | 126,948 |
def F_mol(F_mass, M_feed):
"""
Calculates the molar flow rate of feed.
Parameters
----------
F_mass : float
The mass flow rate of feed [kg/s]
M_feed : float
The molar mass feed of liquid. [kg/kmol]
Returns
-------
F_mol : float
The molar flow rate of feed, [kmol/s]
References
----------
???
"""
return F_mass / M_feed | 7b758f0f3f0d837974bab75a84dcf51039d4eed1 | 126,953 |
def format_list(l, separator=' ', sort=True):
"""
Make string of list. Also sort the list.
E.g. [1, 2, 3] -> '1 2 3'
"""
if sort:
l = sorted(str(n) for n in l)
else:
l = [str(n) for n in l]
return separator.join(l) | 431776c384dca5977e5b51d78d25faa9d545effa | 126,955 |
def get_class(soup, class_css, tag_name='div'):
"""
Get divs with the given class
:param soup: the html soup
:param class_css: the class name
:param tag_name: the markup tag, default is div
:return the list of divs with the given class
"""
return soup.find_all(tag_name, class_=str(class_css)) | d622a1de374e3ac8832a08edeffe18985013d123 | 126,958 |
import math
def optimal(nb_items):
"""
(Naive) attempt to find an optimal grid layout for N elements.
:param nb_items: The number of square elements to put on the grid.
:returns: A tuple ``(height, width)`` containing the number of rows and \
the number of cols of the resulting grid.
>>> _optimal(2)
(1, 2)
>>> _optimal(3)
(1, 3)
>>> _optimal(4)
(2, 2)
"""
# Compute first possibility
height1 = math.floor(math.sqrt(nb_items))
width1 = math.ceil(nb_items / height1)
# Compute second possibility
width2 = math.ceil(math.sqrt(nb_items))
height2 = math.ceil(nb_items / width2)
# Minimize the product of height and width
if height1 * width1 < height2 * width2:
height, width = height1, width1
else:
height, width = height2, width2
return (height, width) | 5db506f4f08566f266200e140b896ee830d7fed3 | 126,961 |
def read_pnm_header(infile, supported='P6'):
"""
Read a PNM header, return width and height of the image in pixels.
"""
header = []
while len(header) < 4:
line = infile.readline()
sharp = line.find('#')
if sharp > -1:
line = line[:sharp]
header.extend(line.split())
if len(header) == 3 and header[0] == 'P4':
break # PBM doesn't have maxval
if header[0] not in supported:
raise NotImplementedError('file format %s not supported' % header[0])
if header[0] != 'P4' and header[3] != '255':
raise NotImplementedError('maxval %s not supported' % header[3])
return int(header[1]), int(header[2]) | 6954f2b476f7fddec7b523cac0c77a2c63a954ab | 126,962 |
def list_filter_none(l):
"""
filter none values from a list
"""
return [v for v in l if v is not None] | 91ffccdaf5a3b6527ffe8e18a943886bd0743afa | 126,963 |
def get_traceback(exc=None):
"""
Returns the string with the traceback for the specifiec exc
object, or for the current exception exc is not specified.
"""
import io, traceback, sys # pylint: disable=multiple-imports
if exc is None:
exc = sys.exc_info()
if not exc:
return None
tb = exc[2]
sio = io.StringIO()
traceback.print_tb(tb, file=sio)
del tb # needs to be done explicitly see: http://docs.python.org/2/library/sys.html#sys.exc_info
return sio.getvalue() | ffe9419e07d9adc832a68cb3fd75079411c46316 | 126,964 |
import re
def to_regex(x):
"""Convert a string to a regex (returns None if `x` is None)"""
try:
return re.compile(x)
except TypeError:
return None | 7551a6d0ef941b08169a125426bb3f703d359c4b | 126,967 |
import time
def timer(f):
""" Decorator for timeing function (method) execution time.
After return from function will print string: ``func: <function name> took: <time in seconds> sec``.
Args:
f (Callable[Any]): function to decorate.
Returns:
Callable[Any]: Decorated function.
Example:
::
>>> from dlutils import timer
>>> @timer.timer
... def foo(x):
... for i in range(x):
... pass
...
>>> foo(100000)
func:'foo' took: 0.0019 sec
"""
def __wrapper(*args, **kw):
time_start = time.time()
result = f(*args, **kw)
time_end = time.time()
print('func:%r took: %2.4f sec' % (f.__name__, time_end - time_start))
return result
return __wrapper | 9ffa1bc0ab07e37063ed5c5c28272e585d57d516 | 126,968 |
def dist_coord(c1, c2):
"""
c1 = SkyCoord('05h55m10.30536s', '+07d24m25.4304s', frame='icrs')
c2 = SkyCoord('05h55m10.9s', '+07d26m08s', frame='icrs')
"""
sep = c1.separation(c2)
return sep.arcsecond | 5988422c9b1f689f00356faa387f390b5c427b0a | 126,972 |
from datetime import datetime
def get_state_by_time(python_time):
"""
returns state for rule based on given time
if given time is in the past returns 2 (withdrawed rule)
else returns 1
:param python_time:
:return: integer rstate
"""
present = datetime.now()
if python_time <= present:
return 2
else:
return 1 | 3ec7b97688654dfb55e0963093bf3cd0db85799c | 126,978 |
import re
def check_reference(ref):
"""
Returns True if ref looks like an actual object reference: xx/yy/zz or xx/yy
Returns False otherwise.
"""
obj_ref_regex = re.compile("^((\d+)|[A-Za-z].*)\/((\d+)|[A-Za-z].*)(\/\d+)?$")
# obj_ref_regex = re.compile("^(?P<wsid>\d+)\/(?P<objid>\d+)(\/(?P<ver>\d+))?$")
if ref is None or not obj_ref_regex.match(ref):
return False
return True | a568f984de20afa04e541cb3e12e69427cee42c2 | 126,979 |
import hashlib
def hash_digest(text):
"""
Create the hash digest for a text. These digest can be used to
create a unique filename from the path to the root file.
The used has function is md5.
Arguments:
text -- the text for which the digest should be created
"""
text_encoded = text.encode("utf8")
hash_result = hashlib.md5(text_encoded)
return hash_result.hexdigest() | 3be0bc300bc64749499f6d50d927d99de41d9081 | 126,982 |
def _get_pos_diff(sender_loc, receiver_loc=None):
"""
Get matrix of distances between agents in positions pos1 to positions pos2.
:param sender_loc: first set of positions
:param receiver_loc: second set of positions (use sender_loc if None)
:return: matrix of distances, len(pos1) x len(pos2)
"""
n = sender_loc.shape[0]
m = sender_loc.shape[1]
if receiver_loc is not None:
n2 = receiver_loc.shape[0]
m2 = receiver_loc.shape[1]
diff = sender_loc.reshape((n, 1, m)) - receiver_loc.reshape((1, n2, m2))
else:
diff = sender_loc.reshape((n, 1, m)) - sender_loc.reshape((1, n, m))
return diff | 438752be62917f84daac38636b3ed43416cf3029 | 126,983 |
def count_negatives(nums):
"""Return the number of negative numbers in the given list.
>>> count_negatives([5, -1, -2, 0, 3])
2
"""
nums.append(0)
# We could also have used the list.sort() method, which modifies a list, putting it in sorted order.
nums = sorted(nums)
return nums.index(0) | 7ec7f89474fc089ecd19f27a42e7f524d5c0539f | 126,986 |
import re
def expand_filenames(filename, filelist, command):
"""Expand % to filename and * to filelist in command."""
# Escape spaces for the shell
filename = filename.replace(" ", "\\\\\\\\ ")
filelist = [f.replace(" ", "\\\\\\\\ ") for f in filelist]
# Substitute % and * with escaping
command = re.sub(r'(?<!\\)(%)', filename, command)
command = re.sub(r'(?<!\\)(\*)', " ".join(filelist), command)
command = re.sub(r'(\\)(?!\\)', "", command)
return command | 4670bc6ead240f3d55a3000da47e318e04826e7e | 126,987 |
def remove_same_values(dataframe):
"""
identify and remove columns that only contain a single value
:param dataframe: dataframe of descriptors
:type dataframe: pandas dataframe
:return: pandas dataframe of descriptors with no columns of single value
:type: pandas dataframe
"""
same_values = [column for column in dataframe if dataframe[column].nunique() == 1]
output = dataframe.drop(columns = same_values)
return output | fcd1c0e4ed96899ada005e0fd3835ed4bf3cb341 | 126,988 |
from typing import Dict
from typing import Any
from typing import Union
from typing import List
def generate_list_dicts(asset_dict: Dict[str, Any]) -> Union[List[Any], Dict]:
"""
Takes a dictionary with a specific structure of a single key containing
a list of dictionaries and returns the list of dictionaries
Args:
asset_dict: Dictionary that contains a single asset type returned from the API
Returns:
A list of assets of the asset type requested
"""
return list(asset_dict.values())[0] | 927843d2aa07dec99ced93a96afc7c8a20cc73a9 | 126,991 |
def get_object_value(obj, attr):
"""Retrieves an arbitrary attribute value from an object.
Nested attributes can be specified using dot notation,
e.g. 'parent.child'.
:param object obj:
A valid Python object.
:param str attr:
The attribute name of the value to retrieve from the object.
:returns:
The attribute value, if it exists, or None.
:rtype:
any
"""
keys = attr.split(".")
val = obj
for key in keys:
if hasattr(val, key):
val = getattr(val, key)
else:
return None
return val | 704badf54a2608dbe239963dc2e9947093bafa3e | 126,997 |
from typing import Tuple
import re
def clean_pycon(source: str) -> Tuple[str, str]:
"""Clean up Python console syntax to pure Python."""
in_statement = False
source = re.sub(r'^\s*<BLANKLINE>', '', source, flags=re.MULTILINE)
clean_lines = []
for line in source.split('\n'):
if line.startswith('>>> '):
in_statement = True
clean_lines.append(line[4:])
elif in_statement and line.startswith('... '):
clean_lines.append(line[4:])
else:
in_statement = False
clean_lines.append('')
return source, '\n'.join(clean_lines) | 6429254471408204ec1ea4f07b97661a52000836 | 126,998 |
def islambda(func):
""" Test if the function func is a lambda ("anonymous" function) """
return getattr(func, 'func_name', False) == '<lambda>' | e76b699023b23909f7536e0b3513201ceaebef5c | 127,000 |
def boolean_dumper(dumper, value):
"""
Dump booleans as yes or no.
"""
value = u'yes' if value else u'no'
style = None
return dumper.represent_scalar(u'tag:yaml.org,2002:bool', value, style=style) | b6a2fefd8fb3d0af7b9718868685177e38ab7313 | 127,003 |
def _cast_dict_keys(data, key_cast):
"""Converts all dict keys in `data` using `key_cast`, recursively.
Can be used on any type, as this method will apply itself on dict and list
members, otherwise behaving as no-op.
>>> _cast_dict_keys({'key': 'value', 'other': {'a': 'b'}}, str.capitalize)
{'Key': 'value', 'Other': {'A': 'b'}}
>>> _cast_dict_keys(['1', '2', {'3': '4'}], int)
['1', '2', {3: '4'}]
>>> _cast_dict_keys(({'a': 1}, {'b': 2}), str.capitalize)
({'a': 1}, {'b': 2})
>>> _cast_dict_keys(1, str.capitalize)
1
"""
if isinstance(data, dict):
return {
key_cast(key): _cast_dict_keys(value, key_cast)
for key, value in data.items()
}
if isinstance(data, list):
return [_cast_dict_keys(value, key_cast) for value in data]
return data | 7dbd047cba572a393b25bfeef6ba116f5781a6e8 | 127,011 |
from typing import Tuple
def get_authorization_scheme_param(
authorization_header_value: str,
) -> Tuple[str, str]:
"""
Retrieves the authorization schema parameters from the authorization
header.
Args:
authorization_header_value: Value of the authorization header.
Returns:
Tuple of the format ``(scheme, param)``.
"""
if not authorization_header_value:
return "", ""
scheme, _, param = authorization_header_value.partition(" ")
return scheme, param | 51d9184a88b6fe031da6a46d20d35b09c5fba8ac | 127,014 |
def split_string(input_str):
"""
Parse input string and returns last comma separated element.
In case no comma found, all string is returned.
Args:
input_str(str): input string that will be parsed
Returns:
str: last comma separated element,
or all string in case no comma found.
"""
return input_str.split(',')[-1] | 3bae9da5fcdab9706bcfcb9c0036f60f22420ef8 | 127,015 |
import re
def replace_code_blocks(text):
"""
This function searches the provided text for code blocks in standard
markdown format and replaces them with HTML used by highlightjs
for code highlighting in HTML.
If the block starts with ```{language}\n then it will pull the language
specified and place it in the highlighjs class attribute
Parameters
----------
text: Markdown text with code blocks
"""
# pattern used by markdown code blocks
grouped_pattern = r'(```[\w]+\n)([^`]+)(```)'
# replace code blocks with language specification
code_blocks = re.findall(grouped_pattern, text)
end_html = '</code></pre>\n'
for block in code_blocks:
lang = block[0].lstrip('```').rstrip()
start_html = f'<pre><code class="{lang}">'
new_str = start_html + block[1] + end_html
old_str = block[0] + block[1] + block[2]
text = text.replace(old_str, new_str)
return text | c40b506e2db2ff22c4c6329a502fbe47c4bc1d84 | 127,016 |
def u_subtract(a, b):
"""
Return the subtraction of two number
--> u_subtract(10, 5)
5
"""
return a - b | e286033418755a457908428e8430cbab96986a3e | 127,018 |
def CalculateGroupIPolicy(cluster, group):
"""Calculate instance policy for group.
"""
return cluster.SimpleFillIPolicy(group.ipolicy) | ffb4aa930287a1ff483c3f0eb12352fd47eb9a41 | 127,020 |
def nnf_shape(A,B,patch_size):
"""
compute nnf shape as (A.w,A.h) - patch_size//2*2
"""
h,w = A.shape[0:2]
h_nnf = h-patch_size//2*2
w_nnf = w-patch_size//2*2
return (h_nnf,w_nnf,3) | 65067bc7a998bbd2b657b8444d111653108150a3 | 127,021 |
def enable_show_options(options):
"""Sets all show options to True."""
options.show_nagios = True
options.show_rrdfile = True
options.show_rawmetric = True
options.show_metric = True
options.show_skipped = True
return options | 6da8a5d4c1b381d5ab343c2035ff5262fbf69f23 | 127,027 |
def aligned_bases(read):
"""Function that counts the number of aligned bases from the CIGAR string and returns and integer"""
aligned = 0
for cigar in read.cigar:
if cigar[0] == 0:
aligned += cigar[1]
else:
pass
assert aligned >= 0
return(aligned) | fc5f62069c112782adb3fa75ce52abc076153006 | 127,031 |
def get_ontology_prefix(ontology_term: str) -> str:
"""Returns the ontology prefix for an ontology term
Example: For EFO:0002939, it would return efo
"""
return ontology_term.split(":")[0].lower() | 310462089e6816e98b335b5a6d5e9f27fc674bdb | 127,034 |
def unnestedDict(exDict):
"""Converts a dict-of-dicts to a singly nested dict for non-recursive parsing"""
out = {}
for kk, vv in exDict.items():
if isinstance(vv, dict):
out.update(unnestedDict(vv))
else:
out[kk] = vv
return out | c72124c5ee6220adbd72b41ace5d8bd544b7d8eb | 127,036 |
import base64
def encode_url_to_base64(url: str) -> str:
"""Gets a string (in this case, url but it can not be) and return it as base64 without padding ('=')
Args:
url: A string to encode
Returns:
Base64 encoded string with no padding
Examples:
>>> encode_url_to_base64('https://example.com')
'aHR0cHM6Ly9leGFtcGxlLmNvbQ'
"""
return base64.urlsafe_b64encode(url.encode()).decode().strip('=') | e509539e66d905a6eebb32a42532580cdee6fcbd | 127,038 |
import re
def get_first_section(wikified_text):
"""
Parses the wikipedia markup for a page and returns
the firs tsection
"""
title_pattern = re.compile('==.*?==')
iterator = title_pattern.finditer(wikified_text)
content_start = 0
content = ''
for match in iterator:
content = wikified_text[content_start:match.start()].encode("utf-8")
break
return content | ae230e0134fa54144d68c1b7029536b81c60591c | 127,040 |
def _gestational_age_enum_value_to_weeks(enum_value: int):
"""Convert enum value on child object to actual # of weeks.
This enables us to directly query the expanded child object with a
scalar value. 0 == "under 24 weeks"; 17 = "Over 40 weeks". To see
enumerated values, please reference studies/fields.py.
"""
return min(max(23, enum_value + 23), 40) if enum_value else None | 89e8890a6668ff65bc459ca1c78f37e6e8d92073 | 127,043 |
def change_fontsize(ax, fs):
"""change fontsize on given axis. This effects the following properties of ax
- ax.title
- ax.xaxis.label
- ax.yaxis.label
- ax.get_xticklabels()
- ax.get_yticklabels()
Parameters
----------
ax : mpl.axis
[description]
fs : float
new font size
Returns
-------
ax
mpl.axis
Examples
--------
fig, ax = plt.subplots(1, 1)
ax.plot(np.arange(10), np.arange(10))
change_fontsize(ax, 5)
"""
for item in (
[ax.title, ax.xaxis.label, ax.yaxis.label]
+ ax.get_xticklabels()
+ ax.get_yticklabels()
):
item.set_fontsize(fs)
return ax | 524ac72244ab0b71cea357b8181373143b0a3f62 | 127,048 |
def reverse(n: int) -> int:
""" This function takes in input 'n' and returns 'n' with all digits reversed. Assume positive 'n'. """
reversed_n = []
while n != 0:
i = n % 10
reversed_n.append(i)
n = (n - i) // 10
return int(''.join(map(str, reversed_n))) | e6346ed17605ab79f335f43cb8efa8e5b77c36dc | 127,050 |
def is_property_in_call_properties(log, ad, call_id, expected_property):
"""Return if the call_id has the expected property
Args:
log: logger object
ad: android_device object
call_id: call id.
expected_property: expected property.
Returns:
True if call_id has expected_property. False if not.
"""
properties = ad.droid.telecomCallGetProperties(call_id)
return (expected_property in properties) | ffefb9ef0b9bd887f48ab8ad7d393f3a8f38c573 | 127,058 |
def zero_float(string):
""" Try to make a string into a floating point number
and make it zero if it cannot be cast. This function
is useful because python will throw an error if you
try to cast a string to a float and it cannot be."""
try:
return float(string)
except:
return 0 | a902b8ea9fa994ccb674d65dba1e04ceb88fceb7 | 127,061 |
def geo2xy(ds, x, y):
"""
transforms geographic coordinate to x/y pixel values
:param ds: GDAL dataset object
:param x: x coordinate
:param y: y coordinate
:returns: list of x/y pixel values
"""
geotransform = ds.GetGeoTransform()
origin_x = geotransform[0]
origin_y = geotransform[3]
width = geotransform[1]
height = geotransform[5]
_x = int((x * width) + origin_x)
_y = int((y * height) + origin_y)
return [_x, _y] | 061f08d2b7a718b8d6c2660b1247d1324c88a54c | 127,067 |
import string
def is_mercurial_shorthash(revision: str) -> bool:
"""Return True if the text is a short changeset identification hash."""
return len(revision) == 12 and all(c in string.hexdigits for c in revision) | 79c0f82ceaf2ec6cd8d095b70dd29a14d68bb2cc | 127,068 |
def isfloat(value):
"""
check if value can be float, returns boolean
"""
try:
float(value)
return True
except ValueError:
return False | 4132b48c176a8d9d9c25b5f44a10bb4aefc14fbd | 127,074 |
def tweet_id_to_timestamp(theid):
""" Get millisecond creation time from twitter IDs
:param theid: int id from tweet object
:return: timestamp of object creation
----
!!Only works for tweets authored after 2010-06-01!!
----
"""
return ((theid >> 22) + 1288834974657) / 1000 | f583ea42848520dbee573b2b250ef9cbea72daa3 | 127,078 |
def region_filters(DF, lon_min, lon_max, lat_min, lat_max, shapefile=False):
"""Takes a Dataframe with the all the rivers information and filters the data
from the rivers in an especific region.
Parameters
----------
DF: Dataframe
is the River_sources dataframe.
lat_min, lat_max, lon_min, lon_max: float, float, float float
domain limits.
shapefile: bool, optional
True when dealing with a geopandas Dataframe.
Returns
-------
new_DF: Dataframe
a pandas Dataframe rivers in the especific region.
"""
if shapefile:
X = DF.geometry.x
Y = DF.geometry.y
else:
X = DF['X']
Y = DF['Y']
mask = (X <= lon_max) & (X > lon_min) & (Y <= lat_max) & (Y > lat_min)
new_DF = DF[mask]
return new_DF | 73be07602873444ab22e2febe7aea8c421e92321 | 127,079 |
from typing import Any
from typing import List
def concat_values(item1: Any, item2: Any) -> List[Any]:
"""
Concatinate item1 and item2 into a list
:param item1: The leading values to be concatinated.
:param item2: The values to add to item1.
:return: The result in list.
"""
item1 = item1 or []
item1 = item1 if isinstance(item1, list) else [item1]
item2 = item2 or []
item2 = item2 if isinstance(item2, list) else [item2]
return item1 + item2 | 80cb523542607e8c82db8f0a71b4b25e659e0402 | 127,082 |
def linear_search(arr, target):
"""
Searches for the first occurance of the provided target in the given array.
If target found then returns index of it, else None
Time Complexity = O(n)
Space Complexity = O(1)
"""
for idx in range(len(arr)):
if arr[idx] == target: return idx
return None | 04991a1c1c74ed0b3c8b883706f279b952df2834 | 127,083 |
def parse_header(header):
"""Parses a db header and returns a dictionary mapping column names to type
and position.
"""
columns = (header.rstrip()).split('\t')[1:]
schema = {}
for i, column in enumerate(columns):
name, data_type = column.split(':')
schema[name] = (i, data_type)
return schema | 2114a603dd7183fc837791010c82b35e73e37afc | 127,088 |
from itertools import combinations
from typing import Tuple
def report_repair_itertools(data) -> Tuple[int, int]:
"""Calculates expense report using itertools.combinations"""
required_sum = 2020
data = [int(x) for x in data]
def prod(l):
"""Returns the product of all items in a list"""
product = 1
if 0 in l:
# failsafe to save time, naturally
return 0
for item in l:
product *= item
return product
part_1 = prod([item for item in combinations(data, 2) if sum(item) == required_sum][0])
part_2 = prod([item for item in combinations(data, 3) if sum(item) == required_sum][0])
return part_1, part_2 | 4f91f1029ef1394a8ca5df5b255b0c8160f5940e | 127,093 |
def mse(y_test, y_forecast): # Completed
"""
Computes the MSE error of two time series.
"""
# Makes sure inputs are of the same length.
try:
assert len(y_test) == len(y_forecast)
except AssertionError:
raise NotImplementedError(
"Tried to call MSE function with unbalanced data.")
total = 0
n = len(y_test)
# Computes MSE using equation from lecture slide.
for i in range(n):
total += pow((y_test[i] - y_forecast[i]), 2)
result = total/(n)
print(f"Mean Square Error: {result:.2f}")
return y_test | 1d67c8f9a54b95e2e68ddcf5a989e746facb332a | 127,100 |
def parse_header(header):
"""
Extract size= and barcode= fields from the FASTA/FASTQ header line
>>> parse_header("name;size=12;barcode=ACG;")
('name', 12, 'ACG')
>>> parse_header("another name;size=200;foo=bar;")
('another name', 200, None)
"""
fields = header.split(';')
query_name = fields[0]
size = barcode = None
for field in fields[1:]:
if field == '':
continue
if '=' in field:
key, value = field.split('=', maxsplit=1)
if key == 'size':
size = int(value)
elif key == 'barcode':
barcode = value
return query_name, size, barcode | fcebaea017bf024e71da29b8bea505f0e6423fb1 | 127,106 |
def net_in_sol_rad(sol_rad, albedo=0.23):
""" Compute net incoming shortwave solar radiation after Eq. 33 in Allen et al. 1998.
Parameters
----------
sol_rad: array
Solar radiation in [MJ·m-2·d-1]. Either calculated from sunshine duration or temperature.
albedo : scalar
Proportion of gross incoming solar radiation that is reflected by the surface.
Albedo can be as high as 0.95 for freshly fallen snow and as low as 0.05 for wet bare soil.
A green vegetation over has an albedo of about 0.20-0.25 (Allen et al, 1998).
Returns
-------
array
Net incoming solar radiation in [MJ·m-2·d-1].
"""
return (1 - albedo) * sol_rad | 7fa4132aab9c83abc00a2d9542d228a172dcffce | 127,112 |
def dark_pixels(green, swir2, threshold=0.25):
""" Detect dark pixels from green and swir2 band
:param green: name of the green band
:type green: str
:param swir2: name of the swir2 band
:type swir2: str
:param threshold: threshold value from which are considered dark pixels
:type threshold: float
:return: a function
"""
def wrap(img):
return img.normalizedDifference([green, swir2]).gt(threshold)
return wrap | b256a08e312ebcf7d642feaf1b70f65000726ff1 | 127,116 |
def sum_sum(lists):
"""Returns total sum for list of lists."""
return sum(sum(x) for x in lists) | e814965ba8f16ac3d3b10711811973509a95d114 | 127,118 |
def number_to_name(number):
"""
Helper function that converts a "number" in the range
"0" to "4" into its corresponding (string) "name"
in the way described below.
0 - rock
1 - Spock
2 - paper
3 - lizard
4 - scissors
"""
# Define a variable that will hold the "name"
# and initialise it. Normally, after the execution of
# this function, "name" should have one of the
# following values: "rock", "Spock", "paper", "lizard", "scissors"
# depending on the input "number", or "" in case of
# a "number" not in the correct range.
name = ""
# A sequence of "if/elif/else" clauses should be used
# checking for conditions of the form
# number == <input_value> to distinguish the cases.
# A final "else" clause catches cases when "number" is
# not in the correct range.
if ( number == 0 ):
name = "rock"
elif ( number == 1 ):
name = "Spock"
elif ( number == 2 ):
name = "paper"
elif ( number == 3 ):
name = "lizard"
elif ( number == 4 ):
name = "scissors"
else:
name = ""
# Return "name".
return name | 4c137b14cb334c8e46a535f3266733d633c3fd58 | 127,120 |
def roman_leap(date):
"""Return the leap indicator of Roman date 'date'."""
return date[4] | e671de92f4c4ee520a2c65ffd5e427cdb8588259 | 127,121 |
def pressure(sample_wrapper):
"""
Returns pressure.
:param sample_wrapper: sample wrapper object
:type sample_wrapper: HandwritingSampleWrapper
:return: pressure
:rtype: numpy.ndarray or np.NaN
"""
return sample_wrapper.sample_pressure | 1635fe467802c5a8b3c4de4f9e306771077e55c0 | 127,122 |
def readline_invisible(code):
"""
Wrap ``code`` with the special characters to tell readline that it is
invisible.
"""
return '\001%s\002' % code | 2de2a2369135145109b010d38b8099aa7367ceaf | 127,123 |
def get_mean_test_scores(score_grid):
""" Return the "mean" and "test" columns of the score grid dataset
"""
score_grid = score_grid.copy()
return score_grid[[c for c in score_grid.columns if 'test' in c and 'mean' in c]] | 8eb5c63de0898edabb29ffdfacb1ebd1b17986e0 | 127,126 |
def create_slice(indices: str) -> slice:
"""Creates a slice object from a string representing the slice.
:param indices: String representing the slice, e.g. ``...,3:5,:``
:type indices: str
:return: Slice object corresponding to the input indices.
:rtype: slice
"""
return eval(f'np.s_[{indices}]') | 70e7d5bcbe30886b3cd7a6632f3afd02116021ea | 127,127 |
def parse_list_of_str(val):
"""Parses a comma-separated list of strings"""
return val.split(',') | b8cd16742060cd3ce0b255b89b662cd0e8a9fa89 | 127,129 |
def flip_bit_char(bit):
"""
lips the character '1' to '0' and vice-versa. Throws an error for any other value.
:param bit: a string, either '1' or '0'
:return: the flipped binary character
"""
if bit == '1':
return '0'
elif bit == '0':
return '1'
else:
raise ValueError("No such bit-char: {}".format(bit)) | 1c24262e132f6164b4f392e56e4020143eaab5f3 | 127,132 |
from pathlib import Path
import yaml
def _read_info_file(out_dir: Path) -> None:
"""Read the file out_dir / info.yml and return its content."""
with (out_dir / "info.yml").open("r") as f:
return yaml.load(f, Loader=yaml.FullLoader) | 0204f1d2d6b65b21a04544c072fcd358f91880b5 | 127,138 |
def read_word(bus, i2caddr, adr):
"""
Read two bytes, high and low, from the accelerometer
return int
"""
high = bus.read_byte_data(i2caddr, adr)
low = bus.read_byte_data(i2caddr, adr + 1)
val = (high << 8) + low # combine the high and low values
return val | a2b07421f906af18d80995efc612d5730a9bc3f9 | 127,139 |
import csv
import logging
import pprint
def csv_to_list(path):
"""Read csv and return a mongoDB bulk insertable list"""
with open(path, 'r') as c:
reader = csv.reader(c)
reader_rows = [row for row in reader]
column_names = reader_rows[0]
logging.info(pprint.pprint(column_names))
insertable_list = []
for x in range(len(reader_rows)):
if x == 0:
continue
document = {}
for y in range(len(reader_rows[x])):
document[column_names[y]] = reader_rows[x][y]
insertable_list.append(document)
return insertable_list | 1c264054a666f3999f9a918b6e6279c9d412c198 | 127,143 |
import colorsys
def label_color_css(bg_color):
"""Create CSS for a label color."""
r, g, b = [int(bg_color[i : i + 2], 16) / 255 for i in [0, 2, 4]]
h, l, s = colorsys.rgb_to_hls(r, g, b)
return "".join(
f"--label-{ltr}:{int(val * fac)};"
for ltr, val, fac in zip(
"rgbhsl", [r, g, b, h, s, l], [255, 255, 255, 360, 100, 100]
)
) | f48a45d6fe3ec6f7e5b6f422e59af54cf8813715 | 127,146 |
def name_from_hcs_orient_vcs(hcs, orient=None, vcs=None):
"""
Construct a coordinate system name from an hcs, orientation and vcs. If orient or vcs are None or
empty, the name will not include these parts.
:param hcs: horizontal coordinate system string
:param orient: orientation string
:param vcs: vertical coordinate system string
:returns: "hcs <orient> [vcs]"
.. versionadded:: 9.2
"""
if orient:
orient = ' <' + orient + '>'
else:
orient = ''
if vcs:
vcs = ' [' + vcs + ']'
else:
vcs = ''
return hcs + orient + vcs | 355f5c8bc70a67afa274a9256af07a84c82c420d | 127,147 |
def find_complete_edge(v1, v2):
"""Find the edge index k of an unsorted pair of vertices (v1, v2)."""
if v2 < v1:
v1, v2 = v2, v1
return v1 + v2 * (v2 - 1) // 2 | 7692c7e32915f70c2f32e11975e5f2e81b69f080 | 127,152 |
def vectorfield(w, t, p):
"""Defines the differential equations for the coupled
spring-mass system. Arguments:
w : vector of the state variables: w = [x1,v1,x2,v2]
t : time
p : vector of the parameters: p = [m,k]
"""
x1, v1, x2, v2 = w
m, k = p
# Create f = (x1',y1',x2',y2'):
f = [v1, (-k * x1 + k * (x2 - x1)) / m, v2, (-k * x2 - k * (x2 - x1)) / m]
return f | d2a67c11ed85b2333d018f43fc228526284c998a | 127,155 |
def separate_callback_data(data):
""" Separate the callback data"""
return data.split(";") | 2f47c260f454ea24838b4d50266e0a30d69cc881 | 127,156 |
def neighbors(G,n):
"""Return a list of nodes connected to node n. """
return G.neighbors(n) | 0edd62770224699720b8f3b9651f564e40b14c9c | 127,158 |
def join_sub_grids(sub_grids):
"""Join sub_grids together, by corresponding rows."""
rows = []
sub_rows = len(sub_grids[0])
for row in range(sub_rows):
rows.append('')
for index, col in enumerate(sub_grids):
rows[row] += col[row]
return rows | 35c336da8fe52cccaf43b6b5e37423f6e8798f12 | 127,161 |
def heartbeat_interval(n):
"""
Interval in seconds that we desire heartbeats based on number of workers
"""
if n <= 10:
return 0.5
elif n < 50:
return 1
elif n < 200:
return 2
else:
return 5 | 9f4344e58bfda962df8b40983e80a5aa47e79178 | 127,162 |
def cleanEOL(s):
"""Remove \r from the end of string `s'."""
return s.rstrip("\r") | 4c34c92821970863226da8cb1f7e582adadfbccd | 127,167 |
import pathlib
def admissible_seed_size(seed, args):
"""
Checks if seed size is below file_size_limit.
:returns: True if that is the case and False otherwise.
"""
seed_size_in_bytes = pathlib.Path(seed).stat().st_size
if seed_size_in_bytes >= args.file_size_limit:
return False
return True | f04b68a90d5974b4216d8f4833e84edf05efcac7 | 127,169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.