content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def factorial_recursive(n):
"""
Return the factorial of the given int
"""
# base case
if n < 2:
return 1
else:
return n * factorial_recursive(n-1) | 380ede9b10871ba8ccfc7855d260af145e2df66d | 490,791 |
def build_histogram(text):
"""Builds a distribution of the word types and numbers of word tokens."""
histogram = {}
words = text.split()
# make a distribution of word types and count of tokens
for word in words:
word = word.lower()
if word not in histogram:
histogram[word... | 32a9c6a53536104ca2bfed12bf0faedbd60b5731 | 554,654 |
def slice2limits(slices):
"""
Create a tuple of minimum, maximum limits from a set of slices.
Parameters
----------
slices : list
List of slice objects which return points between limits
Returns
-------
limits: tuple, (ndarray, ndarray)
Two tuple consisting of array of ... | 052eedc7edf181fa29e14c50bb07f3e673170b93 | 501,549 |
def get_8kfilings(df):
"""Extract 8-K filings only from documents."""
return df.loc[df.seq == 1].copy() | 5295b4427175284dfd4cb3fae8a539cd92352938 | 418,145 |
import math
def distance(point1, point2):
""" Calculates distance between two points.
:param point1: tuple (x, y) with coordinates of the first point
:param point2: tuple (x, y) with coordinates of the second point
:return: distance between two points in pixels
"""
return math.sqrt(math.pow(po... | e38be3e5cc3418ab8c5edefb560e95e583dede21 | 691,082 |
def largeur_image(image):
"""
Retourne la largeur de l'image ``image`` (en pixels).
Arguments :
img : nom de la variable Python contenant l'image
"""
return image.size[0] | e16f9a5927b11d8b752eb53fba39691997b6e764 | 596,262 |
import mimetypes
def is_video(file_path):
"""
Checks whether the file is a video.
"""
type = mimetypes.guess_type(file_path)[0]
return type and type.startswith('video') | 93c44492816f3156d1b899750ec1551379ae4bef | 125,591 |
def de_itemparser(line):
"""return a dict of {OfficalName: str, Synonyms: [str,]} from a de_item
The description item is a str, always starts with the proposed official
name of the protein. Synonyms are indicated between brackets. Examples
below
'Annexin A5 (Annexin V) (Lipocortin V) (Endonexin II... | b5417b7d047d16462051c889117bf0b0177157a8 | 63,407 |
def min_by(f, x, y):
"""Takes a function and two values, and returns whichever value produces the
smaller result when passed to the provided function"""
return x if f(x) < f(y) else y | 95aca87a35cf5795a4586a4162728fd3c5907ef9 | 390,157 |
def get_group_size_and_start(total_items, total_groups, group_id):
"""
Calculate group size and start index.
"""
base_size = total_items // total_groups
rem = total_items % total_groups
start = base_size * (group_id - 1) + min(group_id - 1, rem)
size = base_size + 1 if group_id <= rem else ... | 841b82db970bca60e34a72587c016e721a2b4bad | 273,311 |
def find_columns_by_key(df, keys):
"""
Find all Dataframe column names containing any of the keys
Parameters
----------
df : Dataframe
Dataframe
keys : array_like
List of keys of `str` type
Returns
-------
list
List of column names
"""
col = [c ... | 38765c14e8ea7be43623314192924971ee3f9906 | 406,387 |
import math
def compute_shannon(data):
"""
Calculate Shannon entropy value for a given byte array.
Keyword arguments:
data -- data bytes
"""
entropy = 0
for x in range(256):
it = float(data.count(x))/len(data)
if it > 0:
entropy += - it * math.log(it, 2)
r... | 3be2cdd3a3f7bea43cdcd4175b3d1717859379af | 594,984 |
import random
def null_boolean_field_data(field, **kwargs):
"""
Return random value for NullBooleanField
>>> result = any_form_field(forms.NullBooleanField())
>>> type(result)
<type 'unicode'>
>>> result in [u'1', u'2', u'3']
True
"""
return random.choice(['None', 'True', 'Fal... | 5e36b2ac7a6a30a849f618162216f463d9e08a61 | 201,958 |
def curried(func):
"""curried(func) takes function with signature:
func(self, *args)
and makes it:
curried_func(*args) --> func(self, *args)
That is, it makes the self implicit
"""
def curried_func(self, *args):
return func(self, *args)
curried_func.__doc__ = """Curried v... | 95d19e92747bbae18b3795fd79518cdae70906b1 | 160,508 |
import torch
def masked_precision(pred: torch.Tensor, target: torch.Tensor, eps: float=1e-6) -> torch.Tensor:
"""
Function to calculate the masked precision. Like precision,
but with usability mask in channel in the first channel
of the target, i.e. target should have one more channel
than predict... | f5951e1afc822ff82e39ed1d4ad9ef02643b2d93 | 359,813 |
import re
def contains_domain(address, domain):
"""Returns True if the email address contains the given,domain,in the domain position, false if not."""
domain = r'[\w\.-]+@'+domain+'$'
if re.match(domain,address):
return True
return False | 8ca7352995fe9b25e6c7e0094a4af89b65d10147 | 612,599 |
import re
def normalize(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
:param value: string.
String.
:return: string.
Cleaned string.
"""
value = re.sub('[^\w\s-]', '', value).strip()
value = re.sub(... | 629245ceb18fdf3b93adc20d434fc072c26e259d | 338,174 |
def readPhraseIndexFromFiles (filenames):
"""Takes a list of files; reads phrases from them, with one phrase per line, ignoring blank lines
and lines starting with '#'. Returns a map from words to the list of phrases they are the first word of."""
phraseIndex = dict()
for filename in filenames:
... | c2968c8d7613c501c7c6bd37ead7017ded57be09 | 663,845 |
def bool_to_yes_no(value, color_enabled=False, color_no=None, color_yes=None):
"""Convert a boolean (or ``None``) to a yes/no string.
:param value: The value to be converted.
:type value: bool
:param color_enabled: Whether to enable color callbacks. Useful for controlling color at run time.
:type ... | 4a4432fc62c7fcd42d82fadd60d76dd79567a829 | 393,412 |
import torch
def _create_1d_regression_dataset(n: int = 100, seed: int = 0) -> torch.Tensor:
"""Creates a simple 1-D dataset of a noisy linear function.
:param n: The number of datapoints to generate, defaults to 100
:param seed: Random number generator seed, defaults to 0
:return: A tensor that cont... | 1534c7a968dfb3663c1f4d953e3088225af54b5f | 690,702 |
def format_tags(tags):
"""Formats tags as comma-separated list of urls to tags index."""
return ", ".join([f'<a href="tags.html#{tag}">{tag}</a>' for tag in tags]) | 5371cc166650eb51bc94a23fcb4b2e2709c7d9d8 | 605,435 |
def time_to_str(time):
"""Convert time into 4 char string"""
time_str = str(time)
return "0"*(4-len(time_str))+time_str | 04049ff7eb263a0179b22c2e38aceb1b2a45f01a | 225,846 |
def get_samples(mcmc):
"""Get samples from variables in MCMC."""
return {k: v for k, v in mcmc.get_samples().items()} | d29761ac64cf079d21cee3099f63dd6439577a56 | 490,190 |
import csv
def parse_csv(csv_file):
"""Parses an individual CSV file into a set of data points
Args:
csv_file (File): a csv file
Returns:
List[List[int,int,float]]: A list of data points.
Each data points consist of
... | e2040af9ab9ff2036fb402484450d447f38de310 | 623,180 |
def gettext_getfunc( lang ):
"""
Returns a function used to translate to a specific catalog.
"""
# Note: you would get the gettext catalog here and install it in the
# closure.
def tr( s ):
# Note: we do not really translate here, we just prepend the
# language, but you get the ... | c303505812581a8101511bc23abfe8be8c390088 | 63,603 |
def convert_detector(old_detector):
"""
Convert an old detector string into a new string.
NOTE: Only exists to support old data formats.
"""
if old_detector:
old_detector = old_detector.strip() # Strip off superfluous white space
if old_detector == 'IM':
return 'MI... | b52d2299d411f5cb228b747e62ea8ec357607788 | 388,739 |
import re
def remove_number_from_cols(df):
""" Remove number ahead of column names, e.g. [[1]col1, [2]col2] --> [col1, col2] """
df = df.rename(columns={col:re.sub("\[\d+\]", "", col) for col in df.columns})
return df | 7de2f4495641bf1ee43a0cf1a839af2684c653e1 | 453,547 |
def flatten_voting_method(method):
"""Flatten a voting method data structure.
The incoming ``method`` data structure is as follows. At the time of
writing, all elections have an identical structure. In practice. the None
values could be different scalars. ::
{
"instructions": {
... | 14095dc027ea011d4a28df85cf0f1113d04f88e5 | 654,325 |
import requests
def get_public_key(repo):
""" Get a public key for the repository from travis. """
url = 'https://api.travis-ci.org/repos/%s' % repo
response = requests.get(url)
public_key = response.json().get('public_key', '')
return public_key.replace('RSA PUBLIC', 'PUBLIC') | fe370a08beb8e9b2f6ae84388865f994e45de0fc | 170,997 |
def get_state_dict(model):
"""Return model state dictionary whether or not distributed training was used"""
if hasattr(model, "module"):
return model.module.state_dict()
return model.state_dict() | fe1f22c63dac3b7d96b0f0485c9a010e98bae2f5 | 51,367 |
from pathlib import Path
import shutil
def copy(src: Path, dest: Path):
"""Copy backup from `src` to `dest`.
Args:
src (Path): the source to copy from
dest (Path): the destination to copy to
Returns:
bool: True if successful
"""
shutil.copy(str(src), str(dest))
print... | bb3d4e4dabdb56761d3776d3d67b2653a54a7e7f | 377,695 |
def getNamespace(modelName):
"""Get the name space from rig root
Args:
modelName (str): Rig top node name
Returns:
str: Namespace
"""
if not modelName:
return ""
if len(modelName.split(":")) >= 2:
nameSpace = ":".join(modelName.split(":")[:-1])
else:
... | abfb4c54f2dd1b54563f6c7c84e902ed4ee77b01 | 5,018 |
def non_zero_mean(vals):
"""Gives the non-zero mean of the values."""
return vals[vals > 0].mean() | 650f2083812e046f833a1412bb1ced8b9ed94a8c | 124,573 |
def to_tag(name):
"""
Creates a XML tag from a given string.
"""
temp = name.lower().replace(' ', '_')
temp = temp.replace('fir_', 'FIR_')
temp = temp.replace('a0_', 'A0_')
return temp | 3db295e1132467519437243a32eb50754998ee25 | 508,750 |
from typing import List
def to_lines(s: str) -> List[str]:
"""
Like `str.splitlines()`, except that an empty string results in a
one-element list and a trailing newline results in a trailing empty string
(and all without re-implementing Python's changing line-splitting
algorithm).
"""
line... | 90fac21f535537a731a4e3a3573a2f2cf548f161 | 569,316 |
def get_countN(x,n):
"""Count the number of nucleotide n in the string."""
return x.upper().count(n.upper()) | 7e5577dcf2a5666f77a915dd943cd5f59e2bd260 | 25,124 |
def is_unexpected_exception(exc_type: Exception) -> bool:
"""Check if exception type is unexpected (any exception except AssertionError, pytest.block.Exception, pytest.skip.Exception)."""
if exc_type and (isinstance(exc_type, (Exception, BaseException)) or issubclass(exc_type, (Exception, BaseException))):
... | d23f6e76ffec26fe7be8bce5e9b9a6dc07532845 | 285,227 |
def roundstr(size):
"""
Perform round-up processing
Round up and return as string
"""
return str(round(size, 1)) | 47f120a919637b5845be6db66f9884a5b1bf4333 | 416,649 |
def get_city_byname(cities, name):
""" Retorna o município cujo o nome foi especificado.
Retorna um objeto do tipo city ou None caso não seja encontrado.
Parâmetros:
- cities : lista de municípios.
- name : nome do município desejado.
"""
for city in cities:
if city.name == name:
... | ebe6ef1b064ae560dab9e55e977039df912b8ea4 | 306,617 |
def magnify_contents(contents, features):
"""
Create additional features in each entry by replicating some column
of the original data. In order for the colums to differ from the
original data append a suffix different for each new additional
artificial column.
"""
magnified_contents = []
... | ec2a43cdb280da74b44a6fec96d0708c90d03f18 | 27,978 |
def traverse_graph(graph, rules, domains, classifiers=None):
"""Traverses a rule graph and classifies a collection of domains.
Each node is a dictionary with the schema:
{
"title": "Rule name",
"children": [
{
"title": Rule name",
... | 7df0553793f4f8380b6d7af31653c68eeaf16486 | 465,864 |
import inspect
import re
def _getdoc(object):
"""Get the doc string or comments for an object."""
result = inspect.getdoc(object) or inspect.getcomments(object)
return result and re.sub('^ *\n', '', result.rstrip()) or '' | b5a2c526530910ec6f4cb498fa365ddcaec0f429 | 272,692 |
from typing import Tuple
def calc_pad_value(src_value: int,
dst_value: int) -> Tuple[int, int]:
"""
Calculate a padding values for a pair of source and destination numbers.
Parameters:
----------
src_value : int
Source number.
dst_value : int
Destination num... | 6231eae061c3a534f0b2fe4a313987dc3d4eed98 | 626,808 |
def find_last_in_flow_child(children):
"""Find and return the last in-flow child of given ``children``."""
for child in reversed(children):
if child.is_in_normal_flow():
return child | ad141fad32148b7ecb8dfd73f1d53026423e8e74 | 473,795 |
def extract_modified_bs_sequence(sax_sequence):
"""
This functions extracts the modified Behaviour Subsequence (BS) sequence list, which is the original sax word
sequence where every consecutive pairs of sax words are equal are fused into the same sax word.
:param sax_sequence: list of original sax wor... | 3a26278a478789032d35f994902440db3f879c9d | 653,610 |
def render_group(path, prefix):
"""Renders test_groups which represents a set of CI results.
Follows this format:
test_group('test-group-name', 'gcs-path')
"""
return 'test_group(\n \'%s\',\n \'%s/%s\'),' % (
path, prefix, path) | 44ecaa47ec137edfc2a67cbee509a9f912f0fb9a | 68,257 |
def find_category_dc(value):
"""Find the category of a dc value
:param value: Value for which we want the category
:type value: int
:return: Category corresponding to the value
:rtype: int
"""
if value == 0:
return 0
if 1 <= abs(value) <= 5:
return 1
if 6 <= abs(valu... | eaa8731658ce5a51eb0b5415fae4a3d0cdd60473 | 357,515 |
def stanardize_numeric_values(df, list_of_clms, ref_df):
"""
Use the median and interquartile range to
standardize the numeric variables
value = (value – median) / (p75 – p25)
"""
for code in list_of_clms:
median = ref_df[code]['50%']
p25 = ref_df[code]['25%']
p75 = ref_... | ff15caf1ae438401b5252f7bc5cb6ba784e2f8b1 | 192,268 |
def convert_error_code(error_code):
"""Convert error code from the format returned by pywin32 to the format that Microsoft documents everything in."""
return error_code % 2 ** 32 | 40197987e46fab5082b7ccad308edbefd472b852 | 663,692 |
def result_pks(response, cast=None):
"""
returns ids from wagtail admin search result
:param cast: cast pks to a type, default int
:param response: webtest response
:return: ids list
"""
cast = cast or int
result_rows = response.lxml.xpath('.//tr[@data-object-pk]/@data-object-pk')
re... | c46373733cf1451ccb7dbadd842726445112c9f2 | 33,450 |
def ensure_keys_defined(header, needed_keys=(), define_as="UNDEFINED"):
"""Define any keywords from `needed_keys` which are missing in `header`, or defined as 'UNDEFINED',
as `default`.
Normally this defines missing keys as UNDEFINED.
It can be used to redefine UNDEFINED as something else, like N/A.... | cbb0fb2134745d6aa50af927f00687e0a5949608 | 375,131 |
def _create_ad_schedule_info(client, day_of_week, start_hour, start_minute,
end_hour, end_minute):
"""Create a new ad schedule info with the specified parameters."""
ad_schedule_info = client.get_type('AdScheduleInfo', version='v2')
ad_schedule_info.day_of_week = day_of_week
... | b4acefa48ea1f3174ec71993dcd3c9e354c042be | 217,851 |
def ensure_bytes(s, encoding):
"""
Ensure *s* is a bytes string. Encode using *encoding* if it isn't.
"""
if isinstance(s, bytes):
return s
return s.encode(encoding) | f82f0ca37bd29c1b856ce9ff79b1bf92d00ea3d5 | 534,160 |
def validate_all(*validators):
"""
returns a validator that evaluates to true only if all validators passed through
the argument validators also evaluate to true
:param validators: validators to be chained
:return: a validator function
"""
def validator(value):
return all(v(value) f... | cc025212a5084ac7af41760f86b87b9b74ada54b | 485,829 |
def get_api_title(specs):
"""Fetch the API title
:param: specs: the JSON smartapi specs
"""
return specs['info']['title'] | ef54167d97a6835622aa5e1ce6a34f1e736df202 | 452,899 |
def formatNumber(number, billions="B", spacer=" ", isMoney = False):
"""
Format the number to a string with max 3 sig figs, and appropriate unit multipliers
Args:
number (float or int): The number to format.
billions (str): Default "G". The unit multiplier to use for bi... | c4d6bfd97df7bb69e451eb9a8a20626f69ed12cb | 343,881 |
from datetime import datetime
from typing import Optional
def get_epoch_time(time_as_str: Optional[str] = None,
fmt: str = '%d-%m-%Y %H:%M:%S.%f') -> int:
"""
>>> get_epoch_time('04-09-2020 17:13:40.162')
1599239620162
"""
fmt_time = datetime.now() if time_as_str is None else da... | ed48c044c4ef3505766f5f669a10a2281fc1589b | 288,998 |
def get_levelized_cost(solution, cost_class='monetary', carrier='power',
group=None, locations=None,
unit_multiplier=1.0):
"""
Get the levelized cost per unit of energy produced for the given
``cost_class`` and ``carrier``, optionally for a subset of technologie... | 96b8f9a9fceaa932bcee72033e73ad8b9551759d | 5,954 |
def getChildren(self):
"""Returns a Python list of the egg node's children."""
result = []
child = self.getFirstChild()
while (child != None):
result.append(child)
child = self.getNextChild()
return result | ae896bc923f62bbe4f06ebcdad748d6c1e628265 | 513,295 |
from pathlib import Path
def this_version() -> str:
"""Read the variable `__version__` from the module itself."""
contents = Path('monoclparse/_version.py').read_text()
*_, version = contents.strip().split()
return version.strip('\'') | fb10b229cca9c1b322d0af833a4ee994643109f4 | 471,040 |
def load_file(uri):
""" Load file from given uri.
"""
with open(uri, encoding='utf-8') as file:
return file.read() | 4c7ddd733f93ab1b491d8c31f2b64d42f29ecbd1 | 533,386 |
def _clean_2007_text(s):
"""Replace special 2007 formatting strings (XML escaped, etc.) with
actual text.
@param s (str) The string to clean.
@return (str) The cleaned string.
"""
s = s.replace("&", "&")\
.replace(">", ">")\
.replace("<", "<")\
.replac... | fdd94198a1d1b7562ca388aa316e17324c09bce9 | 485,284 |
def _get_annotations(cls):
"""
Get annotations for *cls*.
"""
anns = getattr(cls, "__annotations__", None)
if anns is None:
return {}
# Verify that the annotations aren't merely inherited.
for base_cls in cls.__mro__[1:]:
if anns is getattr(base_cls, "__annotations__", None)... | bfa3dde6ac6e3a3d124336cabd1dfe7f74decf28 | 484,483 |
import itertools
def _powerset(iterable, minsize=0):
"""From the itertools recipes."""
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r in range(minsize, len(s) + 1)
) | 41c5576ae031288957d827d82231eab43f1ce70b | 73,679 |
import math
def quadratic_equation(num1, num2, num3):
"""Solve quadratic equation"""
delta = (num2 ** 2) - (4 * num1 * num3)
if delta < 0:
return None
elif delta > 0:
return (-num2 + math.sqrt(delta)) / 2 * num1, (-num2 - math.sqrt(delta)) / 2 * num1
else:
return -num2 / 2 ... | 672c3b4158db58f1975058a8827b1871d52949d2 | 60,657 |
def copy_stimuli(stimuli):
"""
Return a copy of a list of stimuli. The returned copy can be modified
without affecting the original.
"""
new_list = []
for stim in stimuli:
stim_copy = stim.create_copy()
new_list.append(stim_copy)
return new_list | 58a3fc7b8bdb23088ad0bdda83db8d96ebca46f4 | 487,383 |
def sum_digits(num: int) -> int:
"""
Returns the sum of every digit in num.
>>> sum_digits(1)
1
>>> sum_digits(12345)
15
>>> sum_digits(999001)
28
"""
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
return digit_sum | 78680a648dbef0e4220f1628e275e5e84c2b28bb | 437,489 |
def flatten(data):
""" Given a batch of N-D tensors, reshapes them into 1-Dim flat tensor. """
B = data.size(0)
return data.view(B, -1) | dd434241a8f3a491e39094f485e12973e6ef4c4a | 84,126 |
from datetime import datetime
def get_week_from_ts(ts: datetime) -> int:
"""Returns the integer value of the week for the given time slot"""
return ts.isocalendar()[1] | a589e366fa9fa360c4e8e41fae3832d22340900b | 292,065 |
def make_s3_raw_record(bucket, key, size=100):
"""Helper for creating the s3 raw record"""
return {
's3': {
'configurationId': 'testConfigRule',
'object': {
'eTag': '0123456789abcdef0123456789abcdef',
'sequencer': '0A1B2C3D4E5F678901',
... | f6b82c8815da11af1898f1cb2445983220107f7a | 415,835 |
def fasta_name_seq(s):
"""
Interprets a string as a FASTA record. Does not make any
assumptions about wrapping of the sequence string.
"""
DELIMITER = ">"
try:
lines = s.splitlines()
assert len(lines) > 1
assert lines[0][0] == DELIMITE... | e450455710a945df25ad2cf4cc3c7f9ad662e7d3 | 9,676 |
import math
def deg2rad(angle):
"""Converts value in degrees to radians."""
return angle * math.pi / 180.0 | 6bc69b7ad8d99d554b4a7854f0a7aa9753addae9 | 509,271 |
import json
import collections
def textToJSON(text, orderedDict=True, showErrors=False):
"""
Turn a JSON object stored as text into a Python object.
Will be forced to a Python collections.OrderedDict if orderedDict argument
is True.
"""
try:
if orderedDict:
return json.loads(text, object_pairs_hook=collect... | 4fe816435f47fb445538f5165e742478aaf59273 | 358,526 |
def resolve_relative_name(package, module, relative):
"""Convert a relative import path into an absolute one.
:param str package: The ``__package__`` that we are in.
:param str module: The ``__name__`` of the module we are in.
:param str relative: The module name to resolve.
Absolute names are pas... | 04af75a3d0e8f18d54573af06f5e087e1804db24 | 284,993 |
def token_identity(it, token_payload=None):
""" Echo back what it gets. """
return (it, token_payload) | 6fe367d1e908a8812c8372e5909b54c8bb7b17f5 | 681,096 |
def int32(x):
"""Force conversion of x to 32-bit signed integer"""
x = int(x)
maxint = int(2**31-1)
minint = int(-2**31)
if x > maxint: x = maxint
if x < minint: x = minint
return x | 854338b7fd748ba5ddbbbd8c697288c6331995c4 | 697,941 |
def is_primary(row : dict):
"""
Determines if a row is in the Primary inbox.
These are emails that are in the Inbox,
but aren't in Spam, Promotions, or Trash.
"""
try:
if (
not row.get('Spam') and
not row.get('Category Promotions') and
not row.get('Tr... | 7c0b05333edfe734519c18b4732a3ce2b1cffe50 | 307,962 |
def _is_neighbor_ipaddress(config_db, ipaddress):
"""Returns True if a neighbor has the IP address <ipaddress>, False if not
"""
entry = config_db.get_entry('BGP_NEIGHBOR', ipaddress)
return True if entry else False | 8ccd3aad0390bf9a80fe6861d8c1ca3e42242485 | 146,715 |
import torch
def euclidean_distances(X, Y, squared=False):
"""
Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
Parameters
----------
X : {tensor-like}, shape (n_samples_1, n_features)
Y : {tensor-like}, shape (n_samples_2, n_feature... | 4f02bc0d1f60fd7916954dab1c07ad57fae7682e | 285,554 |
import math
def mod_one(x):
"""
Reduce a number modulo 1.
INPUT:
- ``x`` - an instance of Integer, int, RealNumber, etc.; the
number to reduce
OUTPUT:
- a float
EXAMPLES::
sage: from sage.plot.colors import mod_one
sage: mod_one(1)
1.0
sage: mod_... | 2f76d32ffbcda62cae459a45d82139e6b36b8ca4 | 358,161 |
def filter_nuc_variants(nuc_variants):
"""
Transforms nucleotide variants of type SUB longer than 1 in multiple variants of length 1.
Ignore insertions or substitutions of alternative sequence 'n'.
Removes duplicated variant impacts.
"""
new_nuc_variants = []
for n in nuc_variants:
s... | 4bdc507de783ba4d536352fc8144dc3b7ffc2737 | 582,860 |
def uri_scheme_behind_proxy(request, url):
"""
Fix uris with forwarded protocol.
When behind a proxy, django is reached in http, so generated urls are
using http too.
"""
if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https":
url = url.replace("http:", "https:", 1)
return... | 873ac1c70627fc8e8dd0cb2b86dec99246bb9344 | 40,949 |
from typing import Sequence
from typing import Mapping
def normalize_dist(dist, ndim):
"""Return a tuple containing dist-type for each dimension.
Parameters
----------
dist : str, list, tuple, or dict
ndim : int
Returns
-------
tuple of str
Contains string distribution type f... | 79c48d809d0c509039b93e8ea13a1934c9c04900 | 517,600 |
def convert(color):
"""Get (0-1, 0-1, 0-1) color code and converts it to (0-255, 0-255, 0-255).
Parameters
----------
color : tuple
RGB code in format (0-1, 0-1, 0-1)
Returns
-------
list
a list representing RBG color code in format (0-255, 0-255, 0-255)
"""
return ... | 4e57b4c575ad9a8c6fe9cda077d07dc67e41df3b | 643,746 |
def format_seconds(seconds):
"""
Format a floating point representing seconds into
a nice readable string.
Arguments:
seconds The seconds to format.
Returns:
A formatted string as either seconds, minutes, or hours.
"""
output_time = seconds
o... | 277279fb3c37ebbe9db1f6c4fb804391c3ab81e9 | 596,772 |
def geo_locate_multiple_ips(
self,
ip_address_list: list,
) -> dict:
"""Get geo-location information on multiple ip addresses from Cloud
Portal
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- POST
... | e8b5bec744d3011d90885de79acee855415316d0 | 371,037 |
import json
def is_jsonable(obj):
"""
Checks if obj is JSONable (can be converted to JSON object).
Parameters
----------
obj : any
The object/data-type we want to know if it is JSONable.
Returns
-----
boolean
True if obj is JSONable, or False if it is not.
"""
... | 50a568b898c9609206993372983d40add0be4603 | 693,922 |
def sqr(num):
"""
Computes the square of its argument.
:param num: number
:return: number
"""
return num*num | cb16d5638afeff0061415e45467b5fd4e644951f | 20,935 |
import math
def distance3D(loc3d1=tuple(), loc3d2=tuple()):
"""
get distance from (x1, y1, z1), (x2, y2, z2)
loc3d1 : (x1, y1, z1)
loc3d2 : (x2, y2, z2)
return : distance
"""
return math.sqrt((loc3d1[0] - loc3d2[0])**2 + (loc3d1[1] - loc3d2[1])**2 + (loc3d1[2] - loc3d2[2])**2) | e780a5125a725f3d99a1f730d9ba4b2b9167e059 | 64,290 |
def rows2labels(rows):
"""Given a list of rows, return a map from subject to rdfs:label value."""
labels = {}
for row in rows:
if row["predicate"] == "rdfs:label":
labels[row["subject"]] = row["value"]
return labels | 62637c530bf9fa769e470579496288b26fc0b355 | 322,149 |
from pathlib import Path
def extract_name(
filename: Path,
max_length: int = 100,
prefix: str = "",
suffix: str = "",
long_name: bool = False,
) -> str:
"""Extract the name from a file
Parameters
----------
filename
The input file
max_length
The maximum length ... | f190ec38b8a5e57512d48b1f3c6a258005f7547f | 440,783 |
from bs4 import BeautifulSoup
def parse_html(html: str) -> BeautifulSoup:
"""Parse the HTML with Beautiful Soup"""
return BeautifulSoup(html, features="html.parser") | 8e10667747f24b9f9790b2b512bc9d5635ec7cd9 | 30,787 |
def cutout_subimage(image2d,
startx=0,
starty=0,
width=100,
height=200):
"""Cutout a subimage ot of a bigger image
:param image2d: the original image
:type image2d: NumPy.Array
:param startx: startx, defaults to 0
:type... | 3e98bda2fc7eae0513a80cf699da60c6a7315e38 | 620,082 |
def _format_datetime_for_js(stamp):
"""Formats time stamp for Javascript."""
if not stamp:
return None
return stamp.strftime("%Y-%m-%d %H:%M:%S %Z") | a305c9c64f1ec9de0bd99181f14dedebae8cf940 | 34,182 |
def remove_angle(mol, a, b, c):
"""
utils.remove_angle
Remove a specific angle in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific angle (int)
Returns:
boolean
"""
if not hasattr(mol, 'angles'):
return False
for i, ... | 9e54c283e84b767809d13f9ee807a1a97d0e5503 | 458,010 |
def _convert(value, conversion_function):
""" Convert value using the optional conversion function. """
if conversion_function is not None:
value = conversion_function(value)
return value | ebb28156707d3d973ead5783ad9ee57c90319ee4 | 292,047 |
def matrix_to_board(matrix):
"""
Converts the matrix into a board.
Args:
matrix (np.array): The board in matrix representation.
Returns:
list: The board.
"""
return matrix.reshape(1, -1).tolist()[0] | 8c337e815f1e7e4642086c1a6704cd943bf992ff | 208,649 |
def get_binary_string(string_input):
"""
Generate binary string from input string
:param string_input: user input string
:return: binary_string: binary input string
"""
binary_str = ""
for char in string_input:
binary_str = binary_str + f'{ord(char):08b}'
return binary_str | 1154def212055cbb30c09cc1e4764f614784fb80 | 229,182 |
def _resize_row(array, new_len):
"""Alter the size of a list to match a specified length
If the list is too long, trim it. If it is too short, pad it with Nones
Args:
array (list): The data set to pad or trim
new_len int): The desired length for the data set
Returns:
list: A c... | 810be7f94234e428135598dc32eca99dd0d3fcca | 48,738 |
def set_lat_lon_attrs(ds):
""" Set CF latitude and longitude attributes"""
ds["lon"] = ds.lon.assign_attrs({
'axis' : 'X',
'long_name' : 'longitude',
'standard_name' : 'longitude',
'stored_direction' : 'increasing',
'type' : 'double',
'units' : 'degrees_east',
... | fe95bbd7bd698b7cc0d5d1a60713477ab36e909a | 658,940 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.