content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def vector(feature_key2idsfuncs, example, event_sequence,
always_keys=set()):
"""
Create a feature vector by applying the given feature functions to
the given example and event sequence and return it.
Runs quickly by applying only those feature functions whose keys
match the fact keys or... | 687a9e13cc4c6ce518c02e2c04fc2b45666814fc | 640,735 |
import math
def iterate_pagerank(corpus, damping_factor):
"""
Return PageRank values for each page by iteratively updating
PageRank values until convergence.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between 0 and 1). All
PageRank va... | 732b135b851b484b32a9de875b6f9e32d88f904a | 640,736 |
def copy_column_shift(df, column_source, column_target, shift_amount):
"""
Copy an existing column (shifted by shift_amount) to a new column in dataframe.
:param df: dataframe (sorted in ascending time order)
:param column_source: name of source column in dataframe with values to copy
:param column... | c6f20f3058de59a6bb9243fadd33b6e6502dbbf7 | 640,738 |
import re
def _match_time(value):
"""Return the time (leaveby, arriveat) in value, None if no time in value."""
mat = re.search(r"(\d{1,2}:\d{1,2})", value)
if mat is not None and len(mat.groups()) > 0:
return mat.groups()[0]
return None | d5457c4c463b0f776abc8912864a3cce1920547c | 640,742 |
def convert_from_string(x):
"""
Convert a string that may represent a Python item to its proper data type.
It consists in running `eval` on x, and if an error occurs, returning the
string itself.
"""
try:
return eval(x, {}, {})
except Exception:
return x | b404f09345b8be98d48cc0b37b60aa87cca3f0b6 | 640,743 |
def rescale_tick(tick: int, old_res: int, new_res):
"""Rescales the given tick from one resolution to another
:param tick: tick value to rescale
:param old_res: original tick resolution in PPQN
:param new_res: new tick resolution in PPQN
:return: rescaled tick value as an integer
:raises V... | d6b81060112defb667783cb5201680bc6794f20c | 640,745 |
def parse_address(address):
"""Parse and address on the format host:port.
Returns a tuple (host, port). Raises ValueError if format is
invalid or port is not an integer or out of range.
"""
words = address.split(':')
if len(words) != 2:
raise ValueError('address must contain exactly one... | 3b33fb8b9183f4316acba4ffeb7e90964cba9d21 | 640,746 |
def _calculate_endog_immunity_prob(initial_infections, synthetic_data):
"""Calculate the immunity probability from initial infections.
Args:
initial_infections (pandas.DataFrame): DataFrame with same index as
synthetic_data and one column for each day between start and end.
Dtyp... | 64a8293ea6d04346f4841e2132583d3d5b624cd9 | 640,747 |
def _find_sentence(translation, language):
"""Util that returns the sentence in the given language from translation, or None if it is not found
Args:
translation: `xml.etree.ElementTree.Element`, xml tree element extracted from the translation memory files.
language: `str`, language of interest... | a87608c918c6a0dc02b56e3892fb3fe52bc5309b | 640,748 |
def calc_tf_idf(idf, tf):
"""Calculate the TF-IDF score based on tf and idf components"""
tfidf = {}
for key, val in tf.items():
tfidf[key] = val * idf[key]
return tfidf | c46ce449c5e546ba648f9bc9122df7a5cca9382b | 640,751 |
def thread(read=20, write=20):
"""Return the kwargs for creating the Thread table."""
return {
'AttributeDefinitions': [
{
'AttributeName': 'ForumName',
'AttributeType': 'S'
},
{
'AttributeName': 'Subject',
... | 15a4022a94c0a326364dedefa4b0561e8055fbdf | 640,752 |
def BCR(conf_matrix):
"""
Given a confusion matrix, returns Balanced Classification Rate.
BCR is (1 - Balanced Error Rate).
BER Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
"""
parts = []
for true_response, guess_dict in list(conf_matrix.items()):
error = 0.0
t... | 855deb9d29ce5698014dfa6fbfbe5c92e5ac40fe | 640,754 |
from typing import Dict
def get_query_string(params: Dict) -> str:
"""Makes a string corresponding to the query string of `params`
Args:
params (Dict): Parameters given in the API call
Returns:
str: URL argument used to call the API
"""
return '&'.join([f'{k}={v}' for k, v in par... | 2caf787317831bb9ebe43b7e34861c7fba03cb5d | 640,755 |
def _common_length_of(l1, l2=None, l3=None):
"""
The arguments are containers or ``None``. The function applies
``len()`` to each element, and returns the common length. If the
length differs, ``ValueError`` is raised. Used to check arguments.
OUTPUT:
A tuple (number of entries, common length ... | 3a3f2ecfb541691d2ca833b14f9c8761f92584af | 640,761 |
def collect_forces(f, num_atom, hook, force_pos, word=None):
"""General function to collect forces from lines of a text file.
Parameters
----------
f :
Text file pointer such as that returned by ``open(filename)``.
num_atom : int
Number of atoms in cell. Quit parsing when number of ... | 103c98bfceed194210ef4ca9e04f96ae2d027ded | 640,762 |
def is_subclass(cls, class_or_tuple):
"""
Return whether 'cls' is a derived from another class or is the same class.
Does not raise `TypeError` if the given `cls` is not a class.
"""
try:
return issubclass(cls, class_or_tuple)
except TypeError:
return False | 8cfd6e18e6a2067d117ae212d56043e456cf1411 | 640,765 |
def BuildArtifactSourceTree(files, file_open=open):
"""Builds a dependency tree using from dependency mapping files.
Args:
files: A comma separated list of dependency mapping files.
file_open: Reference to the builtin open function so it may be overridden for
testing.
Returns:
A dict mapping build... | 895944c6ddac952fcb0d07de2d734a1da017da62 | 640,767 |
import math
def haversine(c0, c1):
"""
:param c0: coordinate 0 in form (lat0, lng0) with degree as unit
:param c1: coordinate 1 in form (lat1, lng1) with degree as unit
:return: The haversine distance of c0 and c1 in km
Compute the haversine distance between
https://en.wikipedia.org/wiki/Haver... | 7872f58ecc6b62ec0f9df405c83295bec9e852c1 | 640,769 |
def is_file_available (data, filename):
"""Return True is the given file is available in the input data file, otherwise return False"""
return True if filename in data else False | 39d4a4d8ca3c7b89a23a18ffaa1fb0d47b3e2f84 | 640,772 |
def filter_by_energy_structure(record):
"""
Include only records that have an 'energyratestructure' field defined.
True: filter out
False: keep
:param record:
:return:
"""
if "energyratestructure" not in record.keys():
return True
else:
return False | eeefbfdeaea7135225339b5fc54737e479d3690a | 640,773 |
def _get_label_proportion(data_set, target):
"""Get the proportion of each type. Implemented on spark.
Args:
data_set (pyspark.sql.dataframe.DataFrame): The data set.
target (str): The target column.
Returns:
label_proportion (dct): A dictionary, (key, values) ~ (attribute, count)
... | 802cf0b85e07656a4b4fff87403d49f4923ebbb6 | 640,776 |
def no_decompress(data):
"""Don't decompress"""
return data | d9b4000f7d42275837bdf74f6195e0284e9e9b65 | 640,780 |
import re
def sanitize(string):
""" Cleanses a string so it is safe to use in a file path """
return re.sub(r'[:/\\<>|?*\'\"]', '_', string) | c891fa2ff502af86d872fe93bc0e67da5fac2e78 | 640,781 |
import traceback
def _format_exc_value(e: BaseException, limit=None, chain=True):
"""Like traceback.format_exc() but takes an exception object."""
list = traceback.format_exception(
type(e), e, e.__traceback__, limit=limit, chain=chain
)
str = "".join(list)
return str | afe7c7d4987a5ad310e5b53917815567881fafc2 | 640,782 |
def adjust_widget(widget,window_title=None,size=None,**kwargs):
"""Apply some adjustments to a widget. Unused kwargs are returned."""
if window_title is not None:
widget.setWindowTitle(window_title)
if size is not None:
widget.resize(*size)
return kwargs | 636cb487440747bff2e709a7b36a4149cc95bf7c | 640,785 |
def converter_farenheight(temp: int) -> int:
"""Converts from kelvin to fahrenheit"""
# formula = (K − 273.15) × 9/5 + 32 = F
return round((temp - 273.15) * 9/5 + 32) | 37af9ffef7ff6958b0122a24f844b9d5779368ce | 640,790 |
def calc_tpr_protected(actual, predicted, sensitive, unprotected_vals, positive_pred, is_tnr=False):
"""
Returns P(C=YES|Y=YES, sensitive=privileged) and P(C=YES|Y=YES, sensitive=not privileged)
in that order where C is the predicited classification and where all not privileged values are
considered equ... | 482e5206f52ddd6d08ce5d20af57bc56a6ec680a | 640,791 |
def has_open_sequence(text: str) -> bool:
"""Figures out if the given text has any unclosed ANSI sequences.
It supports standard SGR (`\\x1b[1mHello`), OSC (`\\x1b[30;2ST\\x1b\\\\`) and Kitty APC codes
(`\x1b_Garguments;hex_data\\x1b\\\\`). It also recognizes incorrect syntax; it only considers
a tag c... | de0fae5275c2573bae4c5dd42818cc2f9fd83a14 | 640,792 |
def _get_attribute(attributes, key, all=False):
"""Safely get the LDAP attribute specified by ``key``.
If the attribute doesn't exist, ``None`` will be returned if
``all=False`` and ``[]`` will be returned if ``all=True``.
If the attribute does exist, its first value will be returned by
default. I... | 6210ffe5455628600ab85402c597f7e41d175faa | 640,793 |
def client(app):
"""
Returns session-wide Flask test client.
"""
return app.test_client() | c330fc0ca6699cf4196ee21226daa7d6533d0c7c | 640,794 |
def TransformFloat(r, precision=6, spec=None, undefined=''):
"""Returns the string representation of a floating point number.
One of these formats is used (1) ". _precision_ _spec_" if _spec_ is specified
(2) ". _precision_" unless 1e-04 <= abs(number) < 1e+09 (3) ".1f" otherwise.
Args:
r: A JSON-serializ... | 2e8e9ef431e48dc710c3019d9b83d78abb132bac | 640,796 |
import struct
def uint32_unpack(buf):
"""Unpack 32 bit integer from a stream"""
return struct.unpack('<L', buf)[0] | eac54b24cd84d826d95386cf797f46ad0997b178 | 640,798 |
def check_retry(status):
"""
Checks is the job needs to be retried. Jobs are retried if max_retries is not reached and the tower status is
temporarily unreachable.
Args:
status (:obj:`str`): the tower status.
Returns:
:obj:`bool`: True is the status is "temporarily unreachable"... | 4d358f64747568ae26a0e8618147190853de6af2 | 640,801 |
def _try_call(fn, args, kwargs):
"""Convenience function for evaluating argument `fn`."""
if fn is None:
return args[0]
try:
return fn(*args, **kwargs)
except TypeError:
return fn(*args) | f74618ca9892d2da5695143d5864eb50a348211d | 640,803 |
import re
def normalize_whitespace(value):
"""Replace multiple spaces into one"""
return re.sub(r"\s+", " ", value) | ba5eab4ca60b6a7720448ac991920ee270ab31ee | 640,806 |
def assign_colors_to_indices(indices_subsets):
""" Assigns different colors to different subsets of indices. """
# If there are no highlighted elements, return no colors.
if indices_subsets is None:
return [], {}
# Define the colors that will be used for highlighting different groups of elemen... | 5205411aa82a6c62718398e4a07fdc9c4ab66867 | 640,807 |
def p(F, d=2):
"""
Given the fidelity of a gate in :math:`d` dimensions, returns the
depolarizating probability of the twirled channel.
:param float F: Fidelity of a gate.
:param int d: Dimensionality of the Hilbert space on which the gate acts.
"""
return (d * F - 1) / (d - 1) | dd651e20a545a6aab81396a771528eeeccab0bea | 640,808 |
def get_return_name(i):
"""
Given some integer i, return the name of the ith return.
:param i: A nonnegative integer
:return: The name of the return identifier according to our internal naming
"""
return '$return_%d' % i | 3d47284cae76bb88325fb899442df05151c1f51f | 640,810 |
def fuel_used(pos, list_):
"""gives the fuel amount for a specific position"""
return sum([abs(pos - i) for i in list_]) | 20b4606d680089657b91c089cbc5407821a9b681 | 640,815 |
import requests
def handle_429(response, default_delay=70):
""" Handle 429: output warning and suuggested next steps
The user has exceeded their rate limit. This method will return the
number of seconds the caller should wait based on the dictated
rate-limiting logic specified by the API.
Parame... | 79f19c50033fb54e7bb897183eb551857f4d2026 | 640,819 |
def is_even(value):
"""
Checks if a given value is even.
If value is even the function returns True, otherwise it returns False.
"""
return value % 2 == 0 | 5b9b5462799604f56fbe9e15c92cc4b6896acbc1 | 640,823 |
def ismacro(o):
""" Is the given object a macro? """
return hasattr(o, 'macroName') | 4479cdc6ace739af670835c13929cc819ac317ef | 640,828 |
from typing import Iterable
from pathlib import Path
def find_stylesheets() -> Iterable[str]: # pragma: no cover
"""Fetch all stylesheets used in the official Kedro documentation"""
css_path = Path(__file__).resolve().parents[1] / "html" / "_static" / "css"
return (
str(css_path / "copybutton.css... | b7c7e846c6c898b384c06525225ae6e3642806dc | 640,830 |
def get_all_coins(exchanges):
"""
:param exchanges: [] of CryptoExchange
List of exchanges
:return: [] of str
List of coins in all exchanges
"""
return list(set([
coin for exchange in exchanges
for coin in exchange.build_wallets().keys()
])) | abe26199887bbfa0fbb06b1cd659bb22c62f253d | 640,832 |
def must_replace_suffix(str, suffix, replacement):
"""
Replaces the given suffix in the string. If the string does not have the suffix, a runtime
error will be raised.
"""
splits = str.rsplit(suffix, maxsplit=1)
if len(splits) != 2 or splits[1]:
raise RuntimeError(str + " does not contai... | d4577bfe05c95866553a776fd65493dec858d524 | 640,835 |
import re
def strip_whitespace(uni):
"""Strips all whitespace from a unicode string.
Args:
uni (unicode)
Returns:
unicode
"""
return re.sub(r"\s+", "", uni) | b68ab2de6c8f37ed6bf9b04281ce9878a3b8d094 | 640,837 |
from typing import Tuple
def get_ports(line: str) -> Tuple[str, str]:
"""Returns 2 port labels strings from interconnect file."""
line = line.replace('"', "")
line = line.replace("(", "")
line_fields = line.split(",")
port1 = line_fields[0]
port2 = line_fields[3]
return port1, port2 | 20720b5a64ccc30cceaa767156808e055d159951 | 640,843 |
def get_run_info_nextseq500( instrument_model, application_version, tree ):
"""
Helper function to get some info about the sequencing runs.
Args:
tree: xml tree
Returns:
dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc.
"""
... | e2ff69ef20282692c43cc08047c971e1a0106b98 | 640,845 |
def is_external(label):
"""Determines whether a label corresponds to an external artifact."""
return label.workspace_root.startswith("external") | 5378b4ab313bfe286d00bf4deaba7de84580724f | 640,853 |
def unroll(piano_roll):
"""
Unrolls a piano roll into a list of notes.
Args:
piano_roll (list of lists of lists): the piano roll list
"""
temp = []
for song in piano_roll:
for notes in song:
temp += notes
return temp | 464f5a1707f4c8abe6290e9fe044666038902fc2 | 640,856 |
def checkRecord(s: str) -> bool:
""" given a string s representing an attendance record for a student where each character
signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
The st... | e294ab577d930c38d8c603f3a8b357b22cb1f3e4 | 640,861 |
def point_str(x,y=0,z=0):
"""
Returns a string repr of a point.
Example: point_str(1,2,3) returns '(1.0,2.0,3.0)'
Parameter x: the x coordinate
Precondition: x is a number
Parameter y: the y coordinate
Precondition: y is a number
Parameter z: the x coordinate
Precondition: z... | 1586e0b789449cb56690d631aca921ca501b4dcb | 640,866 |
def displayHits(hits):
""" Handles the I/O of the song-searching functionality
Parameters
----------
hits : list
Holds json dictionaries with information of the songs that the
search turned up
Returns
-------
integer
Either -1 if no song was chosen or the index in hits with the
appropriate song's... | d7fd517245a4f56ca87d73f866cea9fbd66ed327 | 640,872 |
def prime_sieve(n: int) -> list[int]:
"""
Sieve of Erotosthenes
Function to return all the prime numbers up to a certain number
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>>> prime_sieve(3)
[2]
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
""... | fa1a12cd3b7e4aa50c3e87c5e14fe9e838fcb57f | 640,873 |
def version_check(version):
"""Checks if OpenFlow version is compatible and returns the version if it is
Parameters
----------
version: hex
The OpenFlow version taken from the SDN switch 'hello' message
Returns
-------
The OpenFlow version if match, else 0 for unknown version
... | a0edb7f70dca6f9be64b020c13a9a02f1d65572c | 640,875 |
def is_outpatient(med):
"""Return true if the medication record belong to a valid outpatient order."""
return med.ordering_mode_name == 'Outpatient' and med.order_status_name == 'Sent' | cbac59b5257134f9bc59de69c67fdf39bc9dc2a8 | 640,881 |
from typing import Tuple
from typing import Optional
import re
def decode_mention(mention: str) -> Tuple[Optional[str], Optional[int]]:
"""returns whether mention is a member mention or a channel mention (or neither) as well as the id of the mentioned object"""
match = re.search(r"<(#|@)!?(\d+)>", mention)
if matc... | 7981010aaac8289ebda6d12f923c5e7e5f5c2544 | 640,882 |
def get_binary(values, threshold, target):
"""
Transforms continuous or multiclass values into binary values (0/1)
Args:
values (list): vector of the target values
threshold (int or float): threshold used to assign a binary value
0 is assigned to 'bad' values... | 4c065990948d7ff65d4a0ca915e450663f378abf | 640,884 |
def calc_gamma_FeO_silicate(silicate_comp):
"""
Returns a value for gammaFeO in the silicate. Parameterization is based on Holdzheid,
where gammaFeO is taken as a constant value from 1.7-3, dependent only upon MgO content.
Parameters
----------
silicate_comp: dict
Dictionary of the composition of the silicate... | 336627053f9595a8d2848315db560a95710cd276 | 640,888 |
def flatten(l: list):
"""
Accepts a list containing one or more nested lists and returns a flattened copy.
Parameters
----------
l: list
A list containing one or more lists. Can contain zero lists but there's no point
Returns
-------
list
A flattened version of the orig... | 31393053cc6e4c7fe8191cc1fa2890faa8ec3277 | 640,889 |
import pathlib
def print_markdown(data, **kwargs):
"""Print listed data in GitHub-flavoured Markdown format so it can be
copy-pasted into issues. Can either take a list of tuples or a dictionary,
which will be converted to a list of tuples."""
def excl_value(value):
# don't print value if it ... | 347ea4d28846d34076ab1ad846a0aa3d32165af5 | 640,891 |
def generate_fasta_dict(sec_record_list):
"""
Creates a dictionary containing FASTA formatted strings from a list of sequence record objects.
This dictionary is keyed by the sequence ID.
:param sec_record_list: List of Biopython sequence record objects.
:return: Dictionary containing FASTA formatted strings.
"""... | 045dd447fecd772dbef4cac6529dd8f2e7d27263 | 640,893 |
def chop_at(s, sub, inclusive=False):
"""Truncate string ``s`` at the first occurrence of ``sub``.
If ``inclusive`` is true, truncate just after ``sub`` rather than at it.
>>> chop_at("plutocratic brats", "rat")
'plutoc'
>>> chop_at("plutocratic brats", "rat", True)
'plutocrat'
"""
pos... | 66401f4a8e36d299bb882269cd49cdbe089ca8f2 | 640,894 |
def format_percent(num):
"""
Format a percentage
"""
return int(round(num)) | d41680f4fd537ca70130fa0aff544c5865d0f066 | 640,895 |
def _is_namedtuple(obj):
"""Returns `True` if `obj` is a `collections.namedtuple`."""
return isinstance(obj, tuple) and hasattr(obj, "_fields") | f1928c1361774363c6dfb1ede91c8a3d65c93e13 | 640,896 |
def _reachable(graph):
"""Return a dictionary with all reachable nodes from the graph nodes.
Args:
graph: dict: dictionary representing a graph. Keys are the nodes
and values is a set containing the linked nodes.
Returns:
a new dictionary with the same keys, but whose values are al... | 0c122d43ac28384bc9763dda9ffdf808563b2b5e | 640,897 |
def add(n1, n2):
"""Return the sum of two numbers."""
return n1 + n2 | d4bb851d5ddddffe3bb10e25dc0ec00296ee8fd1 | 640,898 |
def moyenne_ponderee(a : float, b : float, c : float,
pa : float, pb : float, pc : float) -> float:
"""Hypothèse : pa + pb + pc != 0
Retourne la moyenne des trois nombres a, b, c, pondérés
respectivement par pa (pondération pour a), pb et pc.
"""
return ((a * pa) + (b * pb) + (c... | 2931cb3289bf9c241f7e64c8210fca8b836c96c6 | 640,900 |
def format_as_string(string: str):
"""
Formats a given string in a different color using ANSI escape sequences
(see https://stackoverflow.com/a/287944/5299750) and adds double quotes
:param string: to be printed
"""
ansi_start = '\033[32m'
ansi_end = '\033[0m'
return f"{ansi_start}\"{str... | 4ba55f4b35bf55e91085c49724d7dce81a8ed12a | 640,902 |
def track_prop_dict_length(track_prop_dict):
"""Returns the number of tracks in a track properties dictionary.
Raises an exception if the value lists in the input dictionary are
not all of the same length. Returns zero if the track properties
dict is empty."""
# A fancy way of checking if all value... | 76572405b8c2498dd9660651785b71ce2aa55490 | 640,906 |
def count_lines(abspath):
"""Count how many lines in a pure text file.
"""
with open(abspath, "rb") as f:
i = 0
for line in f:
i += 1
pass
return i | c892cefca6ec16b8d2b96b4b9bae3be6e22366d7 | 640,910 |
def _is_version_range(req):
"""Returns true if requirements specify a version range."""
assert len(req.specifier) > 0
specs = list(req.specifier)
if len(specs) == 1:
# "foo > 2.0" or "foo == 2.4.3"
return specs[0].operator != '=='
else:
# "foo > 2.0, < 3.0"
return Tr... | c0602a1b28d787d93897f8380e34ee683cc95ad0 | 640,911 |
def _get_error_threshold_function(error_threshold, simulator):
""" Returns a boolean-valued function that indicates whether a particular (x,y) pair is
outside a specified threshold
:param error_threshold: can be None or a string; if this is a string, the first character MAY be '+' or '-', to
indica... | 7dc15face5fd9f565494d194ec9fec5417e11a49 | 640,912 |
def latest_consent(user, org_id=None, include_suspended=False):
"""Lookup latest consent for user
:param user: subject of query
:param org_id: define to restrict to given org
:param include_suspended: set true to stop looking back, even if
the consent is marked suspended (aka withdrawn). By de... | 701dacb7b1269630060c9ea3e71a879836008244 | 640,915 |
def get_node_components_from_abstraction_graph(graph):
"""Extract the set of node ids from each node label in the input graph.
Parameters
----------
graph : Networkx undirected graphs
Abstract graph with set of node ids as labels.
Returns
-------
node_components : list[set(node ids... | d7b62f223d460043e7aa90ce53bb47c6fb15a40e | 640,916 |
def melt_cluster_rep_matrix(df, name="count"):
"""Helper function to melt a cluster rep matrix for saving as feather"""
return df.T.reset_index().melt(id_vars=["cluster", "rep"], var_name="FBgn", value_name=name) | 9fad9f1126d7dee6f38ac4e72a76b0d5d6244d96 | 640,917 |
def wheel(pos):
"""b->g->r color wheel from 0 to 1020, neopixels use grb format"""
if pos < 255:
return [0 , pos , 255]
elif pos < 510:
pos -= 255
return [0 , 255, 255 - pos]
elif pos < 765:
pos -= 510
return [ pos, 255, 0]
elif pos<=1020:
pos -= ... | 613d7233d6cb081336ebadcc5a5682fd5c9eb281 | 640,918 |
def _opacity_from_bin(bin, n_bins):
""" Return opacity for bin."""
if n_bins <= 0:
return 0.35
ratio = bin/float(n_bins)
if ratio < 0.2:
return 0.6
elif ratio < 0.3:
return 0.85
elif ratio < 0.5:
return 1.0
return 1.0 | c7ef062be3046ae845cf8ba09b221b34d22558a4 | 640,922 |
def fib(n, i=0, a=0, b=1):
"""Return the nth fibonacci number.
>>> fib(6)
8
>>> [fib(n) for n in range(6)]
[0, 1, 1, 2, 3, 5]
>>> fib(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
"""
if not n >= 0:
raise ValueError("n must be >= 0")
... | 64e5822f9e148dbd949cfa822424212facad3fe2 | 640,926 |
def purchase_intention(people_who_declared_interest, total_people):
"""Returns the purchase intention rate for a product.
This can be used for cart-to-detail, buy-to-detail, and similar calculations.
Args:
people_who_declared_interest (int): Number of people who declared interest in a product.
... | fa5e4c16fa3a796c2297d9b39b1e5ccc9f3459ce | 640,928 |
def file_get_contents(path : str) -> bytes:
""" Returns contents of file located at 'path' """
with open(path, 'rb') as f:
return f.read() | d8785080cc6e2a234ce44d8cc6961524f20de03c | 640,929 |
import random
def split_list_equal_sized_groups(lst: list, n: int, seed: int = 123) -> list:
"""This function splits a list in n approximately equal-sized subgroups
Args:
lst (list): input list that we want to split
n (int): number of splits
seed (int): random seed to use; defaults to ... | 68d1fc7a50895401eace475ed10bcc3fcf216dcf | 640,935 |
import base64
def encode(data, chunklen=6, linelen=78):
"""
Encode data with base64 and format it.
Arguments:
data: String to be encoded.
chunklen: Number of bytes in a chunk, defaults to 6.
linelen: Length of a line, defaults to 78 characters.
Returns:
The base64 enc... | cfb5a5c246682b2f2b7210c9dd7bc9fa37f08e81 | 640,936 |
def get_chart_url(country_code, interval, date1, date2):
"""Gets a url with the specified parameters"""
chart_url = f'https://spotifycharts.com/regional/{country_code}/{interval}/{date1}--{date2}'
return chart_url | a77688a863582e6e30114222eda24e588827995a | 640,939 |
def get_pdb_atom_info(line):
"""Split and read pdb-file line (QPREP-OUT).
Extract and return:
atomnumber, atomname, resname, resid)
"""
# UNIT: check if the correct numbers are extracted
atomnum = int(line[6:11])
atmname = line[13:17].strip()
resname = line[17:20].strip()
resin... | e0c05d1d543c7b08be3c404427c19b42a1b93a15 | 640,940 |
def get_rot_mat(T):
"""
Takes a homogeneous transformation matrix
and returns the corresponding rotation matrix
and position vector
:param T: 4 x 4 transformation matrix
:return:
rot_mat: 3 x 3 rotation matrix
pos_vec: 3 x 1 position vector
"""
rot_mat = T[0:3, 0:3]
... | 764ba2b00be138a7f750a7d154c1ff0eb5b4ce05 | 640,941 |
def get_ddfNames(opsimdb):
"""Given an opsim database object, return the DDF field names."""
propInfo = opsimdb.fetchPropInfo()
DD_Ids = propInfo[1]['DD']
DD_names = [propInfo[0][x].split(':')[1] for x in DD_Ids]
return DD_names | ec6c22d9aac55da708ba42647835fa14e752bf40 | 640,942 |
def append_correct_whitespace(token, pronoun):
"""
If the original pronoun was followed by whitespace, append whitespace to new pronoun.
"""
if token.text_with_ws != token.text:
whitespace = token.text_with_ws[-1]
pronoun = pronoun + whitespace
return pronoun | 8e2aa839b2b457f118a2b015605c2bfe0461f971 | 640,945 |
def social_networks(context, user):
"""
Return user's social network connections
"""
association_facebook = user.social_auth.filter(provider='facebook').first()
association_twitter = user.social_auth.filter(provider='twitter').first()
association_googleplus = user.social_auth.filter(provider='go... | 2406c6fec354ac4cb8824688e0f6289fceb549c1 | 640,947 |
import re
def preprocess_ents(label, text):
"""
Preprocess an entity
Parameters
----------
label: str:
The named entity label
text: str:
The name entity text
Returns
-------
tuple: returns a tuple of strings containing the label and text
"""
pattern = ':... | 17d99929266a630733faa101d227a318db561990 | 640,948 |
import math
def computeStartsOfInterval(maxVal: int, intervalLength=1024, min_overlap_part=0.33):
"""
Divide the [0; maxVal] interval into a uniform distribution with at least min_overlap_part of overlapping
:param maxVal: end of the base interval
:param intervalLength: length of the new intervals
... | baea88e231439b5d0cb57eb433126f000301b445 | 640,958 |
def checkPrefix(mainList, inputGTParams):
""" Compares two input GTs to see if they have the same prefix. Returns the index in the internal list of GTs of the match
or -1 in case of no match. """
if inputGTParams.find("_") == -1:
raise Exception("Invalid GT name. It does not contain an _, it cannot ... | 14dc18bb48bbb27e701914f65aac1c1cc1f626b7 | 640,961 |
def currency(value):
"""
Returns a string currency representation of a float
"""
return '${:,.2f}'.format(value) | c9ce50794d1e5c9ede66018b9ded5a25b7e69eaf | 640,962 |
def tensor_to_complex_np(data):
"""
Converts a complex torch tensor to numpy array.
Args:
data (torch.Tensor): Input data to be converted to numpy.
Returns:
np.array: Complex numpy version of data.
"""
data = data.numpy()
return data[..., 0] + 1j * data[..., 1] | bcd49b30eb05d209accfd5f4711807e9322139aa | 640,963 |
def should_reduce_batch_size(exception: Exception) -> bool:
"""
Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory
Args:
exception (`Exception`):
An exception
"""
_statements = [
"CUDA out of memory.", # CUDA OOM
"cuDN... | 799d2c23ed39bd9579ecbdcd48a6308772f8d9b6 | 640,966 |
import torch
def is_tensor(data):
"""Checks if data is a torch tensor."""
return type(data) == torch.Tensor | f3b8c07bfbdf76bb80ee0db90ca8a4136e037854 | 640,968 |
import imp
def load_module_file(module_name, file_path):
"""Load module given name and path."""
with open(file_path, 'r') as f:
return imp.load_module(module_name, f, "%s.py" % module_name,
(".py", "r", imp.PY_SOURCE)) | 472fd95e03767d329ad0bb19af3d21a554c9a8eb | 640,969 |
import inspect
def get_kwarg_names(func):
"""
Return a list of valid kwargs to function func
"""
sig = inspect.signature(func)
kwonlyargs = [p.name for p in sig.parameters.values()
if p.default is not p.empty]
return kwonlyargs | 05e4dbfdfd1d98bf1b4f04cb7689d485e584ac93 | 640,974 |
def DoesDatabaseExist(client_vm, connection_string, database_name):
"""Returns whether or not the specifid database exists on the server.
Args:
client_vm: client vm which will run the query
connection_string: database server connection string understood by psql
database_name: name of database to check ... | 506648e807517d2fa53e684f4ad6fd526925e364 | 640,977 |
def _synapse_error_msg(ex):
"""
Format a human readable error message
"""
if isinstance(ex, str):
return ex
return '\n' + ex.__class__.__name__ + ': ' + str(ex) + '\n\n' | 75e7ec392a9fed55f641cd722bfe210898d16185 | 640,978 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.