content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def kelvin_to_farenheit(temp: float):
""" Converts kelvin to farenheit """
far = (temp - 273.15) * (9 / 5) + 32
return int(far) | afbe3f29f8f99dd2287b5f9b666a55096672cb79 | 641,232 |
def first(iterable):
"""Returns the first value of the given iterable."""
return next(iter(iterable)) | f72bba1c1c97da2f1b3dbb3c7f74af7ae9e44e09 | 641,241 |
def _format_pep_8(camel_case_name: str) -> str:
"""
Helper that creates a pep8_compliant_method_name
from a given camelCaseMethodName.
"""
return camel_case_name[0].lower() + "".join(
f"_{letter.lower()}" if letter.isupper() else letter.lower()
for letter in camel_case_name[1:]
) | f0b051aca791b2e775887a553c2cc230dfbaf62b | 641,243 |
def linalg_vector_set_elem(a, n, v):
"""
Set vector element n to v. Returns copy of matrix
with change.
Parameters:
a (array): The vector
n (int): The index
v (number): The new value
"""
a1 = a.copy()
a1[n] = v
return a1 | 9afa885999a381ba4209217636984ac8457f502d | 641,244 |
import torch
def threshold_resize_torch(preds, shape, threshold=0.5):
"""
Thresholds and resizes predictions as a tensor.
Args:
preds (torch tensor): Predictions.
shape (tuple [2]): Shape to resize to
threshold (float, optional): Threshold. Defaults to 0.5.
Returns:
n... | 6c8e74df4c74df74501ddf04eaa3b4afd807ab08 | 641,245 |
def filter_list_sorter(feed_filter):
""" Provide a key to sort a list of feed filters. """
return feed_filter['class'] | 02536ac7a01e0e3e8e6e2f00d25244c5f9e90e74 | 641,248 |
def gc_content_percent(sequence):
"""
Calculates the GC-content percentage of the input sequence
Returns the percentage as an integer out of 100
"""
gc = sequence.count('G') + sequence.count('C')
atcg = len(sequence)
percent_gc = (gc * 100) / atcg
return percent_gc | 3e2344096df626556f1f0947d7a13dcd8e9ff600 | 641,250 |
def nucleotide_frequency(seq):
"""Count nucleotides in a given sequence. Return a dictionary"""
tmpFreqDict = {"A": 0, "C": 0, "G": 0, "T": 0}
for nuc in seq:
tmpFreqDict[nuc] += 1
return tmpFreqDict
# More Pythonic, using Counter
# return dict(Counter(seq)) | 756456a77e25bca3d38fcc170c1fc5491f11dd04 | 641,252 |
def rules(state, alive):
"""
1. Any live cell with two or three live neighbours survives.
2. Any dead cell with three live neighbours becomes a live cell.
3. All other live cells die in the next generation. Similarly, all other dead cells stay dead.
"""
if state == 1: # c... | 65538704c29eb651fd6ca7d693d24b06476e5858 | 641,254 |
from typing import Any
import importlib
def import_object(name: str) -> Any:
"""Dynamically import a Python object (e.g. class, function, ...).
.. note::
To dynamically import a module, use :func:`importlib.import_module`.
Args:
name (str): The path to the Python object to import.
... | e6d414bdf871f53dd0a61824fbda46a31d3e3c7b | 641,256 |
def _IsSourceExtension(s):
"""File extension (excluding dot) matches a source file extension."""
return s in ('c', 'cc', 'cpp', 'cxx') | 821741f630a5ca38377ab12207c39d8b943daf97 | 641,258 |
import sqlite3
async def db_check(bot, msg, cursor, table: str):
"""
This function is coroutine.
Checks if table exists.
:param bot: Bot instance
:param msg: Message
:param cursor: Database cursor
:param table: Table name
:return: Bool
"""
try:
cursor.execute('SELECT... | 6f032f2ac0f2d9f1d0e49890cd8db51e24c85c72 | 641,259 |
def gradient(color_one, color_two, blend_weight):
"""
Blend between two colors with a given ratio.
:param color_one: first color, as an (r,g,b) tuple
:param color_two: second color, as an (r,g,b) tuple
:param blend_weight: Blend weight (ratio) of second color, 0.0 to 1.0
"""
if blend_weig... | 7a3645acf3a83b093e96b706f8d118e47ef85c87 | 641,267 |
def no_signature(run_command, disk_path):
"""Return true if no known signatures exist on the disk."""
signatures = run_command(['blkid', '-p', disk_path])
return not 'UUID' in signatures[1] | 591adaf89461742c5eea7b7124dd37f3cc899e4c | 641,269 |
def _validate_prefix(prefix, avoid):
"""
Validate an install prefix.
"""
if prefix.startswith(avoid):
rest = prefix[0:len(avoid)]
return rest != "/" and rest != ""
return True | 6be541f65334a28ea09d6237f9e54cbfce9347f0 | 641,272 |
def compare_webapps(list1, list2):
""" Return list of matching dictionaries from two lists of dictionaries.
"""
check = set([(d['name'], d['id']) for d in list2])
return [d for d in list1 if (d['name'], d['id']) in check] | d02bac02e6dea5bbf7188b7e3afa6c6cbb64e054 | 641,274 |
import torch
def node_covering_index(cover_index:torch.LongTensor, distribution=False, num_nodes=None):
"""Compute the node covering index of a given cover matrix, i.e., the
number of occurrences of each node in the cover matrix.
Args:
cover_index (torch.LongTensor): Cover assignment matrix i... | e8626c502ada67fc19806d83e911263c3ff9bc95 | 641,277 |
import base64
def parse_signature(value: bytes) -> str:
"""
Return a base64 encoded signature.
Since the signatures dont really have any representation apart from bytes,
encode the bytes to a b64 string similar to stellar's xdr viewer.
"""
return base64.b64encode(value).decode() | 1456c34ff099a234c9ba77c264721326fa889e94 | 641,281 |
def test_model(clients_to_test, set_to_use='test'):
"""Tests self.model on given clients.
Tests model on self.selected_clients if clients_to_test=None.
Args:
clients_to_test: list of Client objects.
set_to_use: dataset to test on. Should be in ['train', 'test'].
"""
metrics = {}
... | aa1235328fd4e82a3dee1e60bb96de6115610bbf | 641,283 |
def split_image_name ( image_name ):
""" Splits a specified **image_name** into its constituent volume and file
names and returns a tuple of the form: ( volume_name, file_name ).
"""
col = image_name.find( ':' )
volume_name = image_name[ 1: col ]
file_name = image_name[ col + 1: ]
... | 151c73e5066607f230a115987eb1717cc77e97c6 | 641,285 |
def connect_db(client, db_name, username, password):
"""
Connect to a Arango database.
:param db_name: Database name.
:type db_name: str
:param username: Username for basic authentication.
:type username: str
:param password: Password for basic authentication.
:type password: str
:r... | 5665fa394285b8614ed5746a6a12b8391370a95a | 641,286 |
def f_bound(f, key, first, last, value, which, *args, **kwargs):
"""
:param f: the MONOTONIC function
:param key: keyword arguments or position of argument to be searched
:param first: [first, last)
:param last: [first, last)
:param value: value to be searched
:param which: lower bound or u... | 47f722c4ab23ec3b0bb74390659cf7e268c3fccb | 641,287 |
def process_target(target_str):
"""
Extract target architecture from a string of verbose compiler
invocation output.
"""
target_label = "Target:"
target_clean = ""
for line in target_str.splitlines(True):
line = line.strip().split()
if len(line) > 1 and line[0] == target_lab... | 9fab762e1f01363339e02b925b30a97c9ec45f4c | 641,292 |
def uuid_ints_to_uuid_str(uuid: tuple[int, int, int, int]):
"""Return a string representation given the 4 integer UUID representation."""
usc = tuple(hex(i % 2 ** 32)[2:10].zfill(8) for i in uuid)
return '-'.join([usc[0], usc[1][0:4], usc[1][4:8], usc[2][0:4], usc[2][4:8] + usc[3]]) | 4969e68bb459e3434f6d6e3840b2e9ecdc8ee7ca | 641,297 |
def _B36Check(b36val):
"""
Verify that a string is a valid path base-36 integer.
>>> _B36Check('Aa')
'aa'
>>> _B36Check('.')
Traceback (most recent call last):
...
ValueError: invalid ...
"""
int(b36val, 36)
return str(b36val).lower() | 4ab5b87c6725ac47eee77cb7b44981c9809f537f | 641,299 |
import requests
from bs4 import BeautifulSoup
def crawl(url):
"""Crawl a specific url and return the soup.
"""
req = requests.get(url)
req.encoding = 'utf-8' # force utf-8 encoding
soup = BeautifulSoup(req.text, 'html.parser')
return soup | 5ec6a26d046a6f8bba3d14b9202f811008cbf0fd | 641,300 |
from datetime import datetime
def date(date):
"""DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime``
type and the format changes between DokuWiki versions ... This function
convert *date* to a `datetime` object.
"""
date = date.value
return (datetime.strptime(date[:-5], '%Y-%m-%... | d0762991946847a3de4d392d3b1ae80880b7c6fe | 641,301 |
def scanning_title_provider(body):
"""Get the title of a page from its content body.
This implementation does not use a standard xml parser. Instead, it scans
the body text looking for content between <title> and </title>. This adds
the benefit of working with invalid, or non-standard, xhtml content.
... | 88b3ee2979bd6ce066cfbcc6c69c14ce3fce2f7b | 641,304 |
def file_to_list(filename: str) -> list:
""" Reads a file and returns a list with the cotent of each line. """
with open(filename, "r") as filehandler:
content = [line.strip() for line in filehandler.readlines()]
return content | ce67d07d8959cf818f63fe562a035c9535e2dd7a | 641,306 |
def _PasswordName(user):
"""Returns the name of the password file for the specified user.
"""
return "{0}_pwd".format(user) | 4769276583ecace1570b6fc3c2c9c0f579b4c5ba | 641,307 |
def _get_prefix(concept1, concept2):
"""
Build a Concept UI prefix as the combination of the
UI prefixes of two concepts.
:param Concept concept1: The first concept.
:param Concept concept2: The second concept.
:returns: New prefix
:rtype: str
"""
# ["NMCD_NMCD", "DSLD_NHP"]
pr... | 38ab07aad98315a20ed61e9bad13ba817c6f5a00 | 641,310 |
import platform
import unittest
def skip_unless_has_memory_collection(cls):
"""Class decorator to skip tests that require memory collection.
Any test that uses memory collection (such as the resource leak tests)
can decorate their class with skip_unless_has_memory_collection to
indicate that if the p... | d53c69b42503bd478f6a2322050aafe7eb8006bc | 641,314 |
def union(*items):
""" union(*items) → Return the set-union of the contents of all non-`None` arguments """
return set().union(item for item in items if item is not None) | 942998e782b503a96cbd6ab23843adc322309df8 | 641,315 |
def array_reverse(a):
"""
Reverses an array
"""
# Time O(n)
# Space O(n)
return a[::-1] | 38e84ca4995b7c1eaa30b358a6717a43fb9c604f | 641,321 |
def kebab_case(instr):
"""Convert a snake case string to kebab case."""
return instr.replace("_", "-") | 5c9e8a47a584b159689182f3be5c310370d39d6a | 641,323 |
from unittest.mock import call
import re
def is_release() -> bool:
"""Return if current branch is a release branch."""
tag_name = call("git describe --tags").replace("\n", "")
return re.match(r"^v\d+\.\d+\.\d+$", tag_name) is not None | f3eb14cdf279ff0b974b7ae16b4f430364fd50d5 | 641,328 |
import base64
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding:
data += b"=" * (4 - missing_padding)
return base64.urlsafe_... | 3d3fef2ef9b6e8092ef73ff6b9a282e890dd5c88 | 641,332 |
def repo_exists(github_repos, repo_slug):
"""Checks if a repository with a given slug exists among the public GitHub repositories.
Args:
- github_repos: List of GitHub repositories.
- repo_slug: Repository slug (usually in a form of path with a namespace, eg: "username/reponame").
Returns:
... | d245912d9e3a5df342a3e8077cff79c9c27f1d3e | 641,334 |
def get_sum(limit = 1000):
"""Gets the sum of the multiples of 3 or 5"""
sum = 0
for n in range(1, limit):
if n % 3 == 0 or n % 5 == 0:
sum += n
return sum | 9891fdf149cdba2cdc800ac3ec9e0b53d99b9b3e | 641,335 |
def _strip_suffix(service_name):
"""
Strip ".service" suffix from a given service name.
"""
return service_name[:-8] | f13f6e5eb82c38466e4b0657e1eefe0abb429139 | 641,338 |
from typing import Dict
from typing import Any
import importlib
import inspect
def _deserialize_from_settings(mod_name: str, class_name: str, settings: Dict) -> Any:
"""Deserialize an object from its settings.
Args:
mod_name: Name of the module.
class_name: Name of the class.
settings... | 9805020a60bf7a53c8f6b9e526dddec56ff6d545 | 641,339 |
def monta_lista_base(lista_ref):
"""A partir de uma lista_ref constrói uma nova lista
de mesmo tamanho e elementos None
Args:
lista_ref (list): lista de referência para o tamanho da nova lista
Returns:
[list]: lista com elementos None com mesmo tamanho de lista_ref
"""
return ... | 1ab395059bac4aec09480a7d01404a827acd8f1d | 641,341 |
from textwrap import dedent
def split_docstring(docstring):
"""
Split a docstring into a summary and a description.
Arguments:
docstring (str): the docstring
Returns:
summary (str or None): a one-line summary.
description (str or None): the multi-line description.
"""
... | 0d8d74a0629864757aa294ab967570ba508fdd32 | 641,342 |
def implicitConstraint(self):
"""
Evaluates the constraint function @ a given point ($\vec(x)$)
@ In, self, object, RAVEN container
@ Out, g(x1,x2), float, $g(\vec(x)) = x1 + x2 + objective - 9$
because the original constraint was x1 + x2 + objective > 9
the way the constraint is designed ... | 4e96b98953ddc16cb48d1bd7cf7aaf441fdc552c | 641,346 |
def parse_extra_alignments(extra_field):
"""
Parse the additional alignments field of a SAM file
:param extra_field: The 'XA' field of a SAM file (e.g. "XA:Z:NC_000913.3,+2729620,22M,0;NC_000913.3,+3427225,22M,0;")
:return: A list of tuples representing the positions of the additional alignments
""... | 5799794760e65ff20aa2f3767d49d17b873fb31e | 641,348 |
import gzip
import io
def smart_open(file, mode='rt', encoding='utf-8'):
"""Convenience function for reading compressed or plain text files.
:param file: The file to read.
:param encoding: The file encoding.
"""
if file.endswith('.gz'):
return gzip.open(file, mode=mode, encoding=encoding, newline... | f0848c07f72822cfa14b9bae92130ac7ce53b771 | 641,349 |
def check_version_2(dataset):
"""Checks if json-stat version attribute exists and is equal or greater \
than 2.0 for a given dataset.
Args:
dataset (OrderedDict): data in JSON-stat format, previously \
deserialized to a python object by \
... | bfc86b4d16750379a6ad9325f13ac267c0f414a3 | 641,350 |
def _train_dev_split(X, y, dev_ratio=0.25):
"""
This function spilts data into training set and development set.
"""
train_size = int(len(X) * (1 - dev_ratio))
return X[:train_size], y[:train_size], X[train_size:], y[train_size:] | a547cc105e6e89077dd99c43a50a77e6cc527259 | 641,353 |
def psi0(ctx, z):
"""Shortcut for psi(0,z) (the digamma function)"""
return ctx.psi(0, z) | d59412a12bffc32a3706d5d9469c27b2a2328a67 | 641,354 |
import logging
def check_response(response):
"""Check the status of responses from polyswarmd
Args:
response: Response dict parsed from JSON from polyswarmd
Returns:
(bool): True if successful else False
"""
status = response.get('status')
ret = status and status == 'OK'
i... | 4e712f45d21a8bbccfba6f79f126c7215825d5c8 | 641,357 |
from typing import Any
from typing import List
def listify(item: Any) -> List:
"""Convert any scalar value into list."""
if not item:
return []
if isinstance(item, list):
return item
if isinstance(item, (tuple, set)):
return list(item)
if isinstance(item, (int, float, str))... | b26b293869b13b942409b99e8c2cfbfe77424f6c | 641,358 |
def _ecdsa_get_pubkey(private_key) -> bytes:
""" returns the associated public key of a given ECDSA private key """
return private_key.public_key() | a4547df61880ba3f40b48a0328a66e0de678ce86 | 641,359 |
def eulers_cromer_method(f, dx, y, yp, range, cromer=True):
""" The Eulers method, and Eulers-Cromer method for second order
differential equations.
:param f: Second order differential equation to approximate the solution for.
:type f: lambda
:param dx: Step size. Smaller is better.
:type ... | 84a3b5b4543284a7c1fe265370dfa261851df58f | 641,362 |
def amap(attr, *args):
"""More convenient syntax for quick data exploration. Get an attribute
value for multiple objects. Name is short for "attrmap".
Parameters
----------
attr: str
Name of attribute to retrieve for each object.
args: any
Objects (usually of same type) to retri... | af3236c8a5d6c9431fb470b6e6e6bd1288f02313 | 641,364 |
import re
def _update_id(record, new_id):
"""
Update a record id to new_id, also modifying the ID in record.description
"""
old_id = record.id
record.id = new_id
# At least for FASTA, record ID starts the description
record.description = re.sub('^' + re.escape(old_id), new_id,
... | 6fc291a462ee4bd02dee998d4585612220b464f4 | 641,365 |
import json
import requests
def collection_exists(collection_name):
"""
Check if a collection already exists on DIVAServices
Arguments:
collection_name {string} -- the name of the collection on DIVAServices
Returns:
bool -- True if the collection exists, False otherwise
"""
... | eecdb84be1422fe9c6011c03bb9240f372dcb257 | 641,366 |
import warnings
def _get_secret_keys(config, secrets_config_key='SECRETS', secrets_list=None):
"""
Finds all of the configuration values that should be secret
"""
keys = []
if secrets_config_key is not None:
configuration_keys = config.get(secrets_config_key)
if configuration_keys ... | 1390da52b7e5cdbae26023931dd03bc54a4cbb8c | 641,368 |
from typing import Any
def return_input(obj: Any) -> Any:
"""A dummy function that always returns input."""
return obj | 5877fde16fca3ad5080b4c7aef7c6a21ffa4c3b4 | 641,370 |
def parse_error_msg(orig_msg):
"""
Parse "error" message received from backend
Format:
"error: %s\r\n"
"""
error = orig_msg[7:]
return "error", error | 2f719bde6cab50379bd3b9769d9ee394c5900b1e | 641,374 |
def add_calculated_rul(df):
"""Calculates Remaining Useful Life (RUL) and adds it to dataset, which is returned.
Parameters
-----------
df : pd.DataFrame
Dataframe containing time-series data.
Returns
pd.DataFrame
dataset, inclusive of calculated RUL values.
"""
... | 86163be9592320ee9da3b6687c8fef2260b788a4 | 641,376 |
def _strip_shell(cmd):
"""Strip a (potentially multi-line) command.
For example
$ foo \
> --bar baz \
> --quux 10
would becomes `foo --bar baz --quux 10`.
"""
parts = []
for line in cmd.strip().split("\n"):
without_console = line.lstrip("$> ").rstrip("\\ ")
... | 6acfb178e71faa1c8e416232db19d4a8ed72cab2 | 641,378 |
def list_local_tags(repo):
"""Return a list of the tags on the local repo."""
# A tag can point to a blob and the loop prunes blob tags from the list of tags to be sorted
tag_list = []
for bar in repo.tags:
try:
bar.commit.committed_datetime
except ValueError:
pas... | ef3e4cac7f8542ad55976a67ad48752134c8c8a6 | 641,379 |
def ask(msg, number=True):
"""Return valid user response to a question.
Accepts:
msg, str: What to display to the user
number, bool: Whether to enforce entry of a number
Returns:
response, (str|float): User entry, either string or float
"""
while True:
response = inp... | 257eac87dbe97fe9e38dbe0045dc1c190a9f5b08 | 641,380 |
from operator import getitem
from functools import reduce
def dpath(dict_, path):
"""Dig into dictionary by string path. e.g.
dpath({'a': {'b': {'c': 'd'}}}, 'a.b') -> {'c': 'd'}
"""
paths = path.split('.')
return reduce(
getitem,
paths,
dict_
) | 35dee83a37ae922d1e5023a726bfe5e0283c5843 | 641,381 |
def length(node):
"""
Count how many values there are in the linked list
:param node: value of head node, start of list
:return: int: number of list elements
"""
if node is not None:
return 1 + length(node.next_node) # count nodes basically
return 0 | 9652d54a8d727924bde45972abff403e0dcc43ff | 641,382 |
from typing import Union
import hashlib
import requests
def _pwned_password(passphrase: str) -> Union[int, bool]:
"""Check passphrase with Troy's Hunt haveibeenpwned API.
Query the API to check if the passphrase has already been pwned in the
past. If it has, returns the number of times it has been pwned,... | 7ff2f195d0cda81980ddc3e5655fd8f6d851699c | 641,388 |
def vector2string(vec):
"""
Helper function, converts vector to one string separated by spaces
:param vec:
:return:
"""
s = ""
for item in vec:
s += str(item) + " "
return s | 672e312c471e8e1c5af07dad7cfb051393e2a3e5 | 641,392 |
def last_received_endswith(agent, tail):
"""
Check if the agent's last received message ends with `tail`.
It is supposed to be executed as an agent method (in example: use it as
the condition in `wait_agent_condition` or execute it with the method
`execute_as_method`).
Parameters
---------... | 58526dec02f8f12ff06745c2ff2588e563d875e0 | 641,393 |
def version_to_str(vsn):
"""
Convert the given version tuple to a dot separated string representation
"""
return '.'.join(str(x) for x in vsn) | 97b76da4a5d8b2beabf1b47519ddb8d93599e10f | 641,394 |
def time_to_secs(t):
"""Convert a datetime.time object to seconds"""
return t.hour*3600 + t.minute*60 + t.second | 37b12e42b6841c6ce3c9a45ab90c0e33257ae2b1 | 641,395 |
def get_func_id(func):
"""Get a quasi-identifier of a given function."""
return func.__qualname__ | 8aba6fdb53d5c1ba89e0e4443b919070516224fa | 641,397 |
import math
def rotate(v, axis, angle):
"""Rotate a vector about an axis through an angle
Parameters
----------
v : array with exactly 3 numeric entries
The vector to be rotated.
axis : one of 'x', 'z'
The axis about which to rotate. Rotations about y are not
supported sin... | e0148dfc28216e8f6a4cc1e5d16a5e93ee023753 | 641,399 |
def sumd(n):
""" Return the sum of digits of a number.
number: non-negative integer
"""
# Base Case
if n == 0:
return 0
else:
# Mod (%) by 10 gives you the rightmost digit (227 % 10 == 7),
# while doing integer division by 10 removes the rightmost
# digit (22... | 6fbcf51c69e2e4a23ca6ca3851a37ee43bf170e3 | 641,404 |
def filter_startswith(word, beginning=None):
"""Filter a word starting with specified string.
:param word (str): The word.
:param beginning (str, optional): The beginning string to check.
:rtype: bool: The resulting check.
"""
return word.lower().startswith(beginning) | a6da1a1bff5a27ac9e0c480a008450766ef3ce8d | 641,408 |
def na_usd(total_pln, rate_usd):
"""Calculate values in USD"""
return total_pln / rate_usd | dcee34a18808fd41c78cfa1cef8c2547ca540f78 | 641,409 |
from typing import Dict
def calculate_percentages(hour_production: Dict[str, float]) -> Dict[str, int]:
"""Calculate percentages from all values in the dictionary.
Returns dictionary with same keys but percentage values as integers.
Percentage total not always 100 due to rounding to integers
"""
... | f9ac41958c86d2226924c017a165f378531bde29 | 641,410 |
import inspect
def calling_source_location(skip=0):
"""Return source location of current call stack, skip specified levels (not include itself)."""
skip += 1 # This function itself is excluded.
skipped = 0
frame = inspect.currentframe()
while frame:
if skipped == skip:
return ... | 8955026dc1427e62ad1e14bcb615ef5e86b5be1f | 641,414 |
def killwhitespace(string):
""" Merge consecutive spaces into one space. """
return " ".join(s.strip() for s in string.split()) | 53d45a99fa5ef42309fa4cc6bf74436b85c37b1b | 641,416 |
def first_of(attr, match, it):
""" Return the first item in a set with an attribute that matches match """
if it is not None:
for i in it:
try:
if getattr(i, attr) == match:
return i
except: pass
return None | 9221897112feaed61602a1d16777dafbf42a1dd4 | 641,418 |
import re
def clean_filename(unclean_name: str) -> str:
"""
Return a valid filename where any character that is not
a letter, number, dash, underscore, space, or period
is replaced with an underscore
"""
return re.sub(r'[^\w\-_. ]', '_', unclean_name) | 7f807cf471befa6194df8ee508f130aae9b7548d | 641,421 |
def descendants_query(node_id, node_label, edge_label="edge"):
"""Generate Cypher query finding descendant nodes starting at 'node_id'."""
return (
"MATCH path=(n:{} {{id: '{}'}})-[:{}*1..]->(m:{})\n".format(
node_label, node_id, edge_label, node_label) +
"RETURN m.id AS descendant, ... | 88911b937c7d6fb65ebb07a566b0ad3d1fe60720 | 641,429 |
def mocked_elasticsearch(mocked_elasticsearch_module_patcher):
"""
Fixture that resets all of the patched ElasticSearch API functions
"""
for mock in mocked_elasticsearch_module_patcher.patcher_mocks:
mock.reset_mock()
return mocked_elasticsearch_module_patcher | 0dabc985d1dbcd7eda3d365447c1241f54143644 | 641,438 |
import pkg_resources
def discover_controllers(entry_point='steppy.controllers'):
"""Discover controllers registered under given entry point
In:
- ``entry_point`` - The entry point under which to register controllers (default: "steppy.controllers")
Return:
- A dictionary {controller name: contr... | d0a225cd43416899bd948af8049c8528bea2c523 | 641,445 |
import collections
def reorder_props(props):
"""
If "children" is in props, then move it to the
front to respect dash convention
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
dict
Dictionary with {propName: pr... | 13911471c943187f6f022fcfbd22d9e4ad3a66af | 641,453 |
def ql(fmp, fs, f0p):
"""Calculate qL
qL = ((fmp - fs) / (fmp - f0p)) * (f0p / fs)
:param fmp: Fm'
:param fs: Fs
:param f0p: F0'
:returns: qL (float)
"""
return ((fmp - fs) / (fmp - f0p)) * (f0p / fs) | ea47510499a3d678b4d8cb6eae9455d26d4bd333 | 641,455 |
def tostr(lst):
"""Makes all values of a list into strings"""
return [str(i) for i in list(lst)] | 6cfb1f11fb446d8c26e657624516127042d4098a | 641,458 |
from typing import Tuple
def extract_entitlement(entitlement: str, text: str) -> Tuple[str, str, str, str]:
"""
Extracts entitlement components from an entitlement string
Args:
entitlement: The entitlement itself
text: The actual reply text
Returns:
Entitlement components
... | 8ecee278f03535f0a3f6426cd400d76c08f8e544 | 641,460 |
def extract_number_of_pages(soup):
"""
Extract the number of result pages from a result page.
"""
pager_span = soup.find('span', class_='smallPager')
return int(pager_span.string.split()[-1]) | b066d25154cd9b3abd972a1a6da0b1d73212db54 | 641,462 |
from typing import List
def date_filter_string(column: str, comp_type: int,
thresholds: List[str]):
""" Generate string for date-based filters
Generates a filter for filtering for specific rows based on different
date comparisons.
Args:
column: Column to filter on
... | ff565d93946894e5f3c6e89913a7ada7a24b84cd | 641,463 |
import torch
def ravel_index(idx, dims) -> torch.Tensor:
"""
Computes the linear index in an array of shape dims.
It performs the reverse functionality of unravel_index
Args:
idx: A LongTensor of shape (N, 3). Each row corresponds to indices into an
array of dimensions dims.
dims... | ff7319f8097ec3c4c6be303dc3415f0408210f71 | 641,464 |
def _is_password_valid(pw):
"""Returns `true` if password is strong enough for Firebase Auth."""
return len(pw) >= 6 | fbaff0d6b2866de14ddd7719cd369ea589f02e84 | 641,465 |
def get_snapping_pos_line_chart_vertical(data_objects, line_pos):
"""
Calculates the nearest pos of and objects from a line chart with an vertical line.
:param data_objects: The nodes of the data objects in the chart.
:type data_objects: dict[str, PolyLineNode]
:param line_pos: The necessary positi... | bb0db8aa9280d21119fd07d85b3046453fa4ffda | 641,467 |
import json
def parse_json_file(distribution_json_file):
"""
Parse a json distribution file for a distribution id.
Look for node of type 'dynamicPluginConfiguration' that contains the attribute id
Note: The file should contains only one distribution.
:param distribution_json_file: filepath
:r... | cbd3a29ca7e1370772b1699a598f4ff53e6bc12d | 641,472 |
def ensure_ref_position_is_valid(ref_position, num_alts, param_title):
"""
Ensures that `ref_position` is None or an integer that is in the interval
`[0, num_alts - 1]`. If None, ensures that intercepts are not the
parameters being estimated. Raises a helpful ValueError if otherwise.
Parameters
... | ac50cbe94ae2874f03c568bec7206d7cf05d85dc | 641,474 |
def _suggest_target_postcodes(system, threshold=None):
"""Sort postcodes by population density (descending)
- if considering threshold, filter out any with capacity above threshold
"""
postcodes = system.postcode_sectors.values()
total_postcodes = len(postcodes)
if threshold is not None:
... | eb6a6e2740df6c7adec9cf1eae30fa969d6a1be8 | 641,481 |
def parse_size(root):
"""Parse the width and height of the image out of the root node.
Args:
----
root: xml.etree.ElementTree.Element
Output:
------
width: str
height str
"""
size_node = root.find('size')
width = size_node.find('width').text
height = size_n... | 40ccfc56a4f1a7c8135104a2bebeb0c82fd939a2 | 641,484 |
import pkg_resources
def getResourcePath(name):
"""
Return the path to a resource
"""
return pkg_resources.resource_filename(__name__, "data/%s" % name) | 73242fe1c37bad0919177b2f27d5ffe130737939 | 641,485 |
import requests
def is_darksky_quota_error(err):
"""Return Tre if input 'err' is a DarkSky quota error, else False"""
tf = False
if isinstance(err, requests.exceptions.HTTPError):
resp = err.response
if resp.status_code == 403 and 'darksky' in resp.url:
tf = True
return tf | 5c6689580370b765d6fdfac884691dccac6768ac | 641,486 |
def colors(graph, node_type_attr='type'):
"""
Utility function that generates colors for node
types for drawing graph in Ipython Notebook.
:param graph: networkx.Graph
:returns: Dict. Nodes as keys, colors as values.
"""
colors_dict = {}
colors = []
counter = 1
for node, attrs i... | cee009fa85636f89b5d743b9da2fde334717ce03 | 641,487 |
def create_weighted_list(peoplex, no_showx):
"""
Function to create a list using weights (avoiding no shows)
:param peoplex:
:param no_showx:
:return:
"""
jc_listx = []
for name in peoplex:
if peoplex[name] == 0:
continue
if peoplex[name] in no_showx:
... | 6edbfb4d68f854bd7881854be54081da89a405a8 | 641,490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.