Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def inferURILocalSymbol(aUri):
# stringa = aUri.__str__()
stringa = aUri
try:
ns = stringa.split("#")[0]
name = stringa.split("#")[1]
except:
if "/" in stringa:
ns = stringa.rsplit("/", 1)[0]
name = stringa... | [
"\n From a URI returns a tuple (namespace, uri-last-bit)\n\n Eg\n from <'http://www.w3.org/2008/05/skos#something'>\n ==> ('something', 'http://www.w3.org/2008/05/skos')\n from <'http://www.w3.org/2003/01/geo/wgs84_pos'> we extract\n ==> ('wgs84_pos', 'http://www.w3.org/2003/01/geo/')\n\n ... |
Please provide a description of the function:def uri2niceString(aUri, namespaces=None):
if not namespaces:
namespaces = NAMESPACES_DEFAULT
if not aUri:
stringa = ""
elif type(aUri) == rdflib.term.URIRef:
# we have a URI: try to create a qName
stringa = aUri.toPython()
... | [
"\n From a URI, returns a nice string representation that uses also the namespace symbols\n Cuts the uri of the namespace, and replaces it with its shortcut (for base, attempts to infer it or leaves it blank)\n\n Namespaces are a list\n\n [('xml', rdflib.URIRef('http://www.w3.org/XML/1998/namespace'))\n... |
Please provide a description of the function:def niceString2uri(aUriString, namespaces=None):
if not namespaces:
namespaces = []
for aNamespaceTuple in namespaces:
if aNamespaceTuple[0] and aUriString.find(
aNamespaceTuple[0].__str__() + ":") == 0:
aUriString_n... | [
"\n From a string representing a URI possibly with the namespace qname, returns a URI instance.\n\n gold:Citation ==> rdflib.term.URIRef(u'http://purl.org/linguistics/gold/Citation')\n\n Namespaces are a list\n\n [('xml', rdflib.URIRef('http://www.w3.org/XML/1998/namespace'))\n ('', rdflib.URIRef('h... |
Please provide a description of the function:def entityLabel(rdfGraph, anEntity, language=DEFAULT_LANGUAGE, getall=True):
if getall:
temp = []
for o in rdfGraph.objects(anEntity, RDFS.label):
temp += [o]
return temp
else:
for o in rdfGraph.objects(anEntity, RDFS... | [
"\n Returns the rdfs.label value of an entity (class or property), if existing.\n Defaults to DEFAULT_LANGUAGE. Returns the RDF.Literal resource\n\n Args:\n language: 'en', 'it' etc..\n getall: returns a list of all labels rather than a string\n\n "
] |
Please provide a description of the function:def entityComment(rdfGraph, anEntity, language=DEFAULT_LANGUAGE, getall=True):
if getall:
temp = []
for o in rdfGraph.objects(anEntity, RDFS.comment):
temp += [o]
return temp
else:
for o in rdfGraph.objects(anEntity, ... | [
"\n Returns the rdfs.comment value of an entity (class or property), if existing.\n Defaults to DEFAULT_LANGUAGE. Returns the RDF.Literal resource\n\n Args:\n language: 'en', 'it' etc..\n getall: returns a list of all labels rather than a string\n\n "
] |
Please provide a description of the function:def shellPrintOverview(g, opts={'labels': False}):
ontologies = g.all_ontologies
# get opts
try:
labels = opts['labels']
except:
labels = False
print(Style.BRIGHT + "Namespaces\n-----------" + Style.RESET_ALL)
if g.namespaces:
... | [
"\n overview of graph invoked from command line\n\n @todo\n add pagination via something like this\n # import pydoc\n # pydoc.pager(\"SOME_VERY_LONG_TEXT\")\n\n "
] |
Please provide a description of the function:def get_files_with_extensions(folder, extensions):
out = []
for root, dirs, files in os.walk(folder):
for file in files:
filename, file_extension = os.path.splitext(file)
if file_extension.replace(".", "") in extensions:
... | [
"walk dir and return .* files as a list\n Note: directories are walked recursively"
] |
Please provide a description of the function:def try_sort_fmt_opts(rdf_format_opts_list, uri):
filename, file_extension = os.path.splitext(uri)
# print(filename, file_extension)
if file_extension == ".ttl" or file_extension == ".turtle":
return ['turtle', 'n3', 'nt', 'json-ld', 'rdfa', 'xml']
... | [
"reorder fmt options based on uri file type suffix - if available - so to test most likely serialization first when parsing some RDF \n\n NOTE this is not very nice as it is hardcoded and assumes the origin serializations to be this: ['turtle', 'xml', 'n3', 'nt', 'json-ld', 'rdfa']\n \n "
] |
Please provide a description of the function:def ask_visualization():
printDebug(
"Please choose an output format for the ontology visualization: (q=quit)\n",
"important")
while True:
text = ""
for viz in VISUALIZATIONS_LIST:
text += "%d) %s\n" % (VISUALIZATIONS_... | [
"\n ask user which viz output to use\n "
] |
Please provide a description of the function:def select_visualization(n):
try:
n = int(n) - 1
test = VISUALIZATIONS_LIST[n] # throw exception if number wrong
return n
except:
printDebug("Invalid viz-type option. Valid options are:", "red")
show_types()
raise... | [
"\n get viz choice based on numerical index\n "
] |
Please provide a description of the function:def build_visualization(ontouri, g, viz_index, path=None, title="", theme=""):
this_viz = VISUALIZATIONS_LIST[viz_index]
if this_viz['ID'] == "html-simple":
from .viz.viz_html_single import HTMLVisualizer
v = HTMLVisualizer(g, title)
elif ... | [
"\n 2017-01-20: new verion, less clever but also simpler\n\n :param g:\n :param viz_index:\n :param main_entity:\n :return:\n "
] |
Please provide a description of the function:def saveVizGithub(contents, ontouri):
title = "Ontospy: ontology export"
readme = % str(ontouri)
files = {
'index.html': {
'content': contents
},
'README.txt': {
'content': readme
},
'LICENSE.t... | [
"\n DEPRECATED on 2016-11-16\n Was working but had a dependecies on package 'uritemplate.py' which caused problems at installation time\n ",
"This ontology documentation was automatically generated with Ontospy (https://github.com/lambdamusic/Ontospy).\n\tThe graph URI is: %s",
"The MIT License (MIT)\n... |
Please provide a description of the function:def cli_run_viz(source=None, outputpath="", theme="", verbose=False):
if outputpath:
if not (os.path.exists(outputpath)) or not (os.path.isdir(outputpath)):
click.secho(
"WARNING: the -o option must include a valid directory path... | [
"\nThis application is a wrapper on the main ontospy-viz script. It generates docs for all models in the local library. Using the Complex-html template..\n@todo allow to pass a custom folder ..\n\n> python -m ontospy.viz.scripts.export_all -o ~/Desktop/test/ --theme random\n\n",
"\n<html>\n<head>\n <style media=... |
Please provide a description of the function:def action_analyze(sources,
endpoint=None,
print_opts=False,
verbose=False,
extra=False,
raw=False):
for x in sources:
click.secho("Parsing %s..." % str(x)... | [
"\r\n Load up a model into ontospy and analyze it\r\n "
] |
Please provide a description of the function:def action_serialize(source, out_fmt="turtle", verbose=False):
o = Ontospy(uri_or_path=source, verbose=verbose, build_all=False)
s = o.serialize(out_fmt)
print(s) | [
"\r\n Util: render RDF into a different serialization \r\n valid options are: xml, n3, turtle, nt, pretty-xml, json-ld\r\n "
] |
Please provide a description of the function:def action_jsonld_playground(source_path, verbose=False):
import webbrowser
BASE_URL = "https://json-ld.org/playground/#startTab=tab-expanded&json-ld="
my_file_handle = None
printDebug("Preparing... : %s" % str(source_path), "comment")
try:... | [
"\r\n Util: sends a json-ld file to the awesome https://json-ld.org/playground/\r\n "
] |
Please provide a description of the function:def action_listlocal(all_details=True):
" select a file from the local repo "
options = get_localontologies()
counter = 1
# printDebug("------------------", 'comment')
if not options:
printDebug(
"Your local library is empty... | [] |
Please provide a description of the function:def _print_table_ontologies():
ontologies = get_localontologies()
ONTOSPY_LOCAL_MODELS = get_home_location()
if ontologies:
print("")
temp = []
from collections import namedtuple
Row = namedtuple('Row', ['N', 'Added'... | [
"\r\n list all local files\r\n 2015-10-18: removed 'cached' from report\r\n 2016-06-17: made a subroutine of action_listlocal()\r\n "
] |
Please provide a description of the function:def action_import(location, verbose=True):
location = str(location) # prevent errors from unicode being passed
# 1) extract file from location and save locally
ONTOSPY_LOCAL_MODELS = get_home_location()
fullpath = ""
try:
if loc... | [
"\r\n Import files into the local repo\r\n "
] |
Please provide a description of the function:def action_import_folder(location):
if os.path.isdir(location):
onlyfiles = [
f for f in os.listdir(location)
if os.path.isfile(os.path.join(location, f))
]
for file in onlyfiles:
if not file.star... | [
"Try to import all files from a local folder"
] |
Please provide a description of the function:def action_webimport(hrlinetop=False):
DIR_OPTIONS = {1: "http://lov.okfn.org", 2: "http://prefix.cc/popular/"}
selection = None
while True:
if hrlinetop:
printDebug("----------")
text = "Please select which online director... | [
" select from the available online directories for import "
] |
Please provide a description of the function:def _import_LOV(
baseuri="http://lov.okfn.org/dataset/lov/api/v2/vocabulary/list",
keyword=""):
printDebug("----------\nReading source... <%s>" % baseuri)
query = requests.get(baseuri, params={})
all_options = query.json()
option... | [
"\r\n 2016-03-02: import from json list\r\n "
] |
Please provide a description of the function:def _import_PREFIXCC(keyword=""):
SOURCE = "http://prefix.cc/popular/all.file.vann"
options = []
printDebug("----------\nReading source...")
g = Ontospy(SOURCE, verbose=False)
for x in g.all_ontologies:
if keyword:
if ... | [
"\r\n List models from web catalog (prefix.cc) and ask which one to import\r\n 2015-10-10: originally part of main ontospy; now standalone only\r\n 2016-06-19: eliminated dependency on extras.import_web\r\n "
] |
Please provide a description of the function:def action_bootstrap(verbose=False):
printDebug("The following ontologies will be imported:")
printDebug("--------------")
count = 0
for s in BOOTSTRAP_ONTOLOGIES:
count += 1
print(count, "<%s>" % s)
printDebug("------------... | [
"Bootstrap the local REPO with a few cool ontologies"
] |
Please provide a description of the function:def action_update_library_location(_location):
# if not(os.path.exists(_location)):
# os.mkdir(_location)
# printDebug("Creating new folder..", "comment")
printDebug("Old location: '%s'" % get_home_location(), "comment")
if os.path.isdi... | [
"\r\n Sets the folder that contains models for the local library\r\n @todo: add options to move things over etc..\r\n note: this is called from 'manager'\r\n "
] |
Please provide a description of the function:def action_cache_reset():
printDebug()
printDebug(
)
ONTOSPY_LOCAL_MODELS = get_home_location()
# https://stackoverflow.com/questions/185936/how-to-delete-the-contents-of-a-folder-in-python
# NOTE This will not only delete the co... | [
"\r\n Delete all contents from cache folder\r\n Then re-generate cached version of all models in the local repo\r\n\r\n ",
"The existing cache will be erased and recreated.",
"This operation may take several minutes, depending on how many files exist in your local library."
] |
Please provide a description of the function:def actions_delete():
filename = action_listlocal()
ONTOSPY_LOCAL_MODELS = get_home_location()
if filename:
fullpath = ONTOSPY_LOCAL_MODELS + filename
if os.path.exists(fullpath):
var = input("Are you sure you want ... | [
"\r\n DEPRECATED (v 1.9.4)\r\n delete an ontology from the local repo\r\n "
] |
Please provide a description of the function:def action_visualize(args,
fromshell=False,
path=None,
title="",
viztype="",
theme="",
verbose=False):
from ..ontodocs.builder imp... | [
"\r\n export model into another format eg html, d3 etc...\r\n <fromshell> : the local name is being passed from ontospy shell\r\n "
] |
Please provide a description of the function:def parse_options():
parser = optparse.OptionParser(usage=USAGE, version=VERSION)
parser.add_option("-q", "--query",
action="store", type="string", default="", dest="query",
help="SPARQL query string")
parser.add_option("-f", "--fo... | [
"\n parse_options() -> opts, args\n\n Parse any command-line options given returning both\n the parsed options and arguments.\n "
] |
Please provide a description of the function:def compare_ordereddict(self, X, Y):
# check if OrderedDict instances have the same keys and values
child = self.compare_dicts(X, Y)
if isinstance(child, DeepExplanation):
return child
# check if the order of the keys is... | [
"Compares two instances of an OrderedDict."
] |
Please provide a description of the function:def stub(base_class=None, **attributes):
if base_class is None:
base_class = object
members = {
"__init__": lambda self: None,
"__new__": lambda *args, **kw: object.__new__(
*args, *kw
), # remove __new__ and metacla... | [
"creates a python class on-the-fly with the given keyword-arguments\n as class-attributes accessible with .attrname.\n\n The new class inherits from\n Use this to mock rather than stub.\n "
] |
Please provide a description of the function:def assertion(func):
func = assertionmethod(func)
setattr(AssertionBuilder, func.__name__, func)
return func | [
"Extend sure with a custom assertion method."
] |
Please provide a description of the function:def chainproperty(func):
func = assertionproperty(func)
setattr(AssertionBuilder, func.fget.__name__, func)
return func | [
"Extend sure with a custom chain property."
] |
Please provide a description of the function:def equal(self, what, epsilon=None):
try:
comparison = DeepComparison(self.obj, what, epsilon).compare()
error = False
except AssertionError as e:
error = e
comparison = None
if isinstance(com... | [
"compares given object ``X`` with an expected ``Y`` object.\n\n It primarily assures that the compared objects are absolute equal ``==``.\n\n :param what: the expected value\n :param epsilon: a delta to leverage upper-bound floating point permissiveness\n "
] |
Please provide a description of the function:def find_dependencies(self, dependent_rev, recurse=None):
if recurse is None:
recurse = self.options.recurse
try:
dependent = self.get_commit(dependent_rev)
except InvalidCommitish as e:
abort(e.message())... | [
"Find all dependencies of the given revision, recursively traversing\n the dependency tree if requested.\n "
] |
Please provide a description of the function:def find_dependencies_with_parent(self, dependent, parent):
self.logger.info(" Finding dependencies of %s via parent %s" %
(dependent.hex[:8], parent.hex[:8]))
diff = self.repo.diff(parent, dependent,
... | [
"Find all dependencies of the given revision caused by the\n given parent commit. This will be called multiple times for\n merge commits which have multiple parents.\n "
] |
Please provide a description of the function:def blame_diff_hunk(self, dependent, parent, path, hunk):
line_range_before = "-%d,%d" % (hunk.old_start, hunk.old_lines)
line_range_after = "+%d,%d" % (hunk.new_start, hunk.new_lines)
self.logger.info(" Blaming hunk %s @ %s (listed be... | [
"Run git blame on the parts of the hunk which exist in the\n older commit in the diff. The commits generated by git blame\n are the commits which the newer commit in the diff depends on,\n because without the lines from those commits, the hunk would\n not apply correctly.\n "
] |
Please provide a description of the function:def tree_lookup(self, target_path, commit):
segments = target_path.split("/")
tree_or_blob = commit.tree
path = ''
while segments:
dirent = segments.pop(0)
if isinstance(tree_or_blob, pygit2.Tree):
... | [
"Navigate to the tree or blob object pointed to by the given target\n path for the given commit. This is necessary because each git\n tree only contains entries for the directory it refers to, not\n recursively for all subdirectories.\n "
] |
Please provide a description of the function:def abbreviate_sha1(cls, sha1):
# For now we invoke git-rev-parse(1), but hopefully eventually
# we will be able to do this via pygit2.
cmd = ['git', 'rev-parse', '--short', sha1]
# cls.logger.debug(" ".join(cmd))
out = subpr... | [
"Uniquely abbreviates the given SHA1."
] |
Please provide a description of the function:def describe(cls, sha1):
# For now we invoke git-describe(1), but eventually we will be
# able to do this via pygit2, since libgit2 already provides
# an API for this:
# https://github.com/libgit2/pygit2/pull/459#issuecomment-68866... | [
"Returns a human-readable representation of the given SHA1."
] |
Please provide a description of the function:def refs_to(cls, sha1, repo):
matching = []
for refname in repo.listall_references():
symref = repo.lookup_reference(refname)
dref = symref.resolve()
oid = dref.target
commit = repo.get(oid)
... | [
"Returns all refs pointing to the given SHA1."
] |
Please provide a description of the function:def add_commit(self, commit):
sha1 = commit.hex
if sha1 in self._commits:
return self._commits[sha1]
title, separator, body = commit.message.partition("\n")
commit = {
'explored': False,
'sha1': sha... | [
"Adds the commit to the commits array if it doesn't already exist,\n and returns the commit's index in the array.\n "
] |
Please provide a description of the function:def get(self, path, params=None, headers=None):
response = requests.get(
self._url_for(path),
params=params,
headers=self._headers(headers)
)
self._handle_errors(response)
return response | [
"Perform a GET request, optionally providing query-string params.\n\n Args:\n path (str): A path that gets appended to ``base_url``.\n params (dict, optional): Dictionary of param names to values.\n\n Example:\n api_client.get('/users', params={'active': True})\n\n Re... |
Please provide a description of the function:def post(self, path, body, headers=None):
response = requests.post(
self._url_for(path),
data=json.dumps(body),
headers=self._headers(headers)
)
self._handle_errors(response)
return response | [
"Perform a POST request, providing a body, which will be JSON-encoded.\n\n Args:\n path (str): A path that gets appended to ``base_url``.\n body (dict): Dictionary that will be JSON-encoded and sent as the body.\n\n Example:\n api_client.post('/users', body={'name': 'Billy J... |
Please provide a description of the function:def create(self,params=None, headers=None):
path = '/creditor_bank_accounts'
if params is not None:
params = {self._envelope_key(): params}
try:
response = self._perform_request('POST', path, params, headers,
... | [
"Create a creditor bank account.\n\n Creates a new creditor bank account object.\n\n Args:\n params (dict, optional): Request body.\n\n Returns:\n ListResponse of CreditorBankAccount instances\n "
] |
Please provide a description of the function:def list(self,params=None, headers=None):
path = '/creditor_bank_accounts'
response = self._perform_request('GET', path, params, headers,
retry_failures=True)
return self._resource_for(respon... | [
"List creditor bank accounts.\n\n Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your\n creditor bank accounts.\n\n Args:\n params (dict, optional): Query string parameters.\n\n Returns:\n CreditorBankAccount\n "
] |
Please provide a description of the function:def get(self,identity,params=None, headers=None):
path = self._sub_url_params('/creditor_bank_accounts/:identity', {
'identity': identity,
})
response = self._perform_request('GET', path, params, headers,
... | [
"Get a single creditor bank account.\n\n Retrieves the details of an existing creditor bank account.\n\n Args:\n identity (string): Unique identifier, beginning with \"BA\".\n params (dict, optional): Query string parameters.\n\n Returns:\n ListResponse of... |
Please provide a description of the function:def disable(self,identity,params=None, headers=None):
path = self._sub_url_params('/creditor_bank_accounts/:identity/actions/disable', {
'identity': identity,
})
if params is not None:
params = {'... | [
"Disable a creditor bank account.\n\n Immediately disables the bank account, no money can be paid out to a\n disabled account.\n \n This will return a `disable_failed` error if the bank account has\n already been disabled.\n \n A disabled bank account can be re-enabl... |
Please provide a description of the function:def create(self,params=None, headers=None):
path = '/mandate_pdfs'
if params is not None:
params = {self._envelope_key(): params}
response = self._perform_request('POST', path, params, headers,
... | [
"Create a mandate PDF.\n\n Generates a PDF mandate and returns its temporary URL.\n \n Customer and bank account details can be left blank (for a blank\n mandate), provided manually, or inferred from the ID of an existing\n [mandate](#core-endpoints-mandates).\n \n B... |
Please provide a description of the function:def update(self,identity,params=None, headers=None):
path = self._sub_url_params('/payments/:identity', {
'identity': identity,
})
if params is not None:
params = {self._envelope_key(): params}
... | [
"Update a payment.\n\n Updates a payment object. This accepts only the metadata parameter.\n\n Args:\n identity (string): Unique identifier, beginning with \"PM\".\n params (dict, optional): Request body.\n\n Returns:\n ListResponse of Payment instances\n ... |
Please provide a description of the function:def load_config(force_default=False):
'''Find and load configuration params.
Config files are loaded in the following order:
- Beginning from current working dir, all the way to the root.
- User home (~).
- Module dir (defaults).
'''
def _load(cdi... | [] |
Please provide a description of the function:def resolve_config(self):
'''Resolve configuration params to native instances'''
conf = self.load_config(self.force_default)
for k in conf['hues']:
conf['hues'][k] = getattr(KEYWORDS, conf['hues'][k])
as_tuples = lambda name, obj: namedtuple(name, obj.k... | [] |
Please provide a description of the function:def apply(funcs, stack):
'''Apply functions to the stack, passing the resulting stack to next state.'''
return reduce(lambda x, y: y(x), funcs, stack) | [] |
Please provide a description of the function:def colorize(string, stack):
'''Apply optimal ANSI escape sequences to the string.'''
codes = optimize(stack)
if len(codes):
prefix = SEQ % ';'.join(map(str, codes))
suffix = SEQ % STYLE.reset
return prefix + string + suffix
else:
return string | [] |
Please provide a description of the function:def compute_agreement_score(num_matches, num1, num2):
denom = num1 + num2 - num_matches
if denom == 0:
return 0
return num_matches / denom | [
"\n Agreement score is used as a criteria to match unit1 and unit2.\n "
] |
Please provide a description of the function:def do_matching(sorting1, sorting2, delta_tp, min_accuracy):
event_counts_1 = dict()
event_counts_2 = dict()
matching_event_counts_12 = dict()
best_match_units_12 = dict()
matching_event_counts_21 = dict()
best_match_units_21 = dict()
unit_ma... | [
"\n This compute the matching between 2 sorters.\n \n Parameters\n ----------\n sorting1: SortingExtractor instance\n \n sorting2: SortingExtractor instance\n \n delta_tp: int\n \n \n Output\n ----------\n \n event_counts_1:\n \n event_counts_2\n \n matching_... |
Please provide a description of the function:def do_counting(sorting1, sorting2, delta_tp, unit_map12):
unit1_ids = sorting1.get_unit_ids()
unit2_ids = sorting2.get_unit_ids()
labels_st1 = dict()
labels_st2 = dict()
N1 = len(unit1_ids)
N2 = len(unit2_ids)
# copy spike trains for f... | [
"\n This count all counting score possible lieke:\n * TP: true positive\n * CL: classification error\n * FN: False negative\n * FP: False positive\n * TOT: \n * TOT_ST1: \n * TOT_ST2: \n\n Parameters\n ----------\n sorting1: SortingExtractor instance\n The groun... |
Please provide a description of the function:def do_confusion_matrix(sorting1, sorting2, unit_map12, labels_st1, labels_st2):
unit1_ids = np.array(sorting1.get_unit_ids())
unit2_ids = np.array(sorting2.get_unit_ids())
N1 = len(unit1_ids)
N2 = len(unit2_ids)
conf_matrix = np.zeros((N1 + 1,... | [
"\n Compute the confusion matrix between two sorting.\n \n Parameters\n ----------\n sorting1: SortingExtractor instance\n The ground truth sorting.\n \n sorting2: SortingExtractor instance\n The tested sorting.\n\n unit_map12: dict\n Dict of matching from sorting1 to so... |
Please provide a description of the function:def run_sorters(sorter_list, recording_dict_or_list, working_folder, grouping_property=None,
shared_binary_copy=False, engine=None, engine_kargs={}, debug=False, write_log=True):
assert not os.path.exists(working_folder), 'working_folde... | [
"\n This run several sorter on several recording.\n Simple implementation will nested loops.\n\n Need to be done with multiprocessing.\n\n sorter_list: list of str (sorter names)\n recording_dict_or_list: a dict (or a list) of recording\n working_folder : str\n\n engine = None ( = 'loop') or 'm... |
Please provide a description of the function:def collect_results(working_folder):
results = {}
working_folder = Path(working_folder)
output_folders = working_folder/'output_folders'
for rec_name in os.listdir(output_folders):
if not os.path.isdir(output_folders / rec_name):
co... | [
"\n Collect results in a working_folder.\n\n The output is nested dict[rec_name][sorter_name] of SortingExtrator.\n\n "
] |
Please provide a description of the function:def get_ISI_ratio(sorting, sampling_frequency, unit_ids=None, save_as_property=True):
'''This function calculates the ratio between the frequency of spikes present
within 0- to 2-ms (refractory period) interspike interval (ISI) and those at 0- to 20-ms
interval. ... | [] |
Please provide a description of the function:def gather_sorting_comparison(working_folder, ground_truths, use_multi_index=True):
working_folder = Path(working_folder)
comparisons = {}
out_dataframes = {}
# get run times:
run_times = pd.read_csv(working_folder / 'run_time.cs... | [
"\n Loop over output folder in a tree to collect sorting from\n several sorter on several dataset and returns sythetic DataFrame with \n several metrics (performance, run_time, ...)\n \n Use SortingComparison internally.\n \n \n Parameters\n ----------\n working_folder: str\n Th... |
Please provide a description of the function:def get_unit_waveforms(recording, sorting, unit_ids=None, grouping_property=None, start_frame=None, end_frame=None,
ms_before=3., ms_after=3., dtype=None, max_num_waveforms=np.inf, filter=False,
bandpass=[300, 6000], save_as_features... | [] |
Please provide a description of the function:def run_sorter(sorter_name_or_class, recording, output_folder=None, delete_output_folder=False,
grouping_property=None, parallel=False, debug=False, **params):
if isinstance(sorter_name_or_class, str):
SorterClass = sorter_dict[sorter_name_or... | [
"\n Generic function to run a sorter via function approach.\n\n 2 Usage with name or class:\n\n by name:\n >>> sorting = run_sorter('tridesclous', recording)\n\n by class:\n >>> sorting = run_sorter(TridesclousSorter, recording)\n\n "
] |
Please provide a description of the function:def compute_performance(SC, verbose=True, output='dict'):
counts = SC._counts
tp_rate = float(counts['TP']) / counts['TOT_ST1'] * 100
cl_rate = float(counts['CL']) / counts['TOT_ST1'] * 100
fn_rate = float(counts['FN']) / counts['TOT_ST1'] * 100
fp_... | [
"\n Return some performance value for comparison.\n\n Parameters\n -------\n SC: SortingComparison instance\n The SortingComparison\n\n verbose: bool\n Display on console or not\n\n output: dict or pandas\n\n\n Returns\n ----------\n\n performance: dict or pandas.Serie depen... |
Please provide a description of the function:def connect():
# Exchange authorization code for acceess token and create session
session = auth_flow.get_session(request.url)
client = UberRidesClient(session)
# Fetch profile for driver
profile = client.get_driver_profile().json
# Fetch last... | [
"Connect controller to handle token exchange and query Uber API."
] |
Please provide a description of the function:def _adapt_response(self, response):
if response.headers['content-type'] == 'application/json':
body = response.json()
status = response.status_code
if body.get('errors'):
return self._complex_response_to_... | [
"Convert error responses to standardized ErrorDetails."
] |
Please provide a description of the function:def _complex_response_to_error_adapter(self, body):
meta = body.get('meta')
errors = body.get('errors')
e = []
for error in errors:
status = error['status']
code = error['code']
title = error['titl... | [
"Convert a list of error responses."
] |
Please provide a description of the function:def _simple_response_to_error_adapter(self, status, original_body):
body = original_body.copy()
code = body.pop('code')
title = body.pop('message')
meta = body # save whatever is left in the response
e = [ErrorDetails(stat... | [
"Convert a single error response."
] |
Please provide a description of the function:def _adapt_response(self, response):
errors, meta = super(ServerError, self)._adapt_response(response)
return errors[0], meta | [
"Convert various error responses to standardized ErrorDetails."
] |
Please provide a description of the function:def _prepare(self):
if self.method not in http.ALLOWED_METHODS:
raise UberIllegalState('Unsupported HTTP Method.')
api_host = self.api_host
headers = self._build_headers(self.method, self.auth_session)
url = build_url(api... | [
"Builds a URL and return a PreparedRequest.\n\n Returns\n (requests.PreparedRequest)\n\n Raises\n UberIllegalState (APIError)\n "
] |
Please provide a description of the function:def _send(self, prepared_request):
session = Session()
response = session.send(prepared_request)
return Response(response) | [
"Send a PreparedRequest to the server.\n\n Parameters\n prepared_request (requests.PreparedRequest)\n\n Returns\n (Response)\n A Response object, whichcontains a server's\n response to an HTTP request.\n "
] |
Please provide a description of the function:def _build_headers(self, method, auth_session):
token_type = auth_session.token_type
if auth_session.server_token:
token = auth_session.server_token
else:
token = auth_session.oauth2credential.access_token
if... | [
"Create headers for the request.\n\n Parameters\n method (str)\n HTTP method (e.g. 'POST').\n auth_session (Session)\n The Session object containing OAuth 2.0 credentials.\n\n Returns\n headers (dict)\n Dictionary of access ... |
Please provide a description of the function:def authorization_code_grant_flow(credentials, storage_filename):
auth_flow = AuthorizationCodeGrant(
credentials.get('client_id'),
credentials.get('scopes'),
credentials.get('client_secret'),
credentials.get('redirect_url'),
)
... | [
"Get an access token through Authorization Code Grant.\n\n Parameters\n credentials (dict)\n All your app credentials and information\n imported from the configuration file.\n storage_filename (str)\n Filename to store OAuth 2.0 Credentials.\n\n Returns\n ... |
Please provide a description of the function:def hello_user(api_client):
try:
response = api_client.get_driver_profile()
except (ClientError, ServerError) as error:
fail_print(error)
return
else:
profile = response.json
first_name = profile.get('first_name')
... | [
"Use an authorized client to fetch and print profile information.\n\n Parameters\n api_client (UberRidesClient)\n An UberRidesClient with OAuth 2.0 credentials.\n "
] |
Please provide a description of the function:def _request_access_token(
grant_type,
client_id=None,
client_secret=None,
scopes=None,
code=None,
redirect_url=None,
refresh_token=None
):
url = build_url(auth.AUTH_HOST, auth.ACCESS_TOKEN_PATH)
if isinstance(scopes, set):
s... | [
"Make an HTTP POST to request an access token.\n\n Parameters\n grant_type (str)\n Either 'client_credientials' (Client Credentials Grant)\n or 'authorization_code' (Authorization Code Grant).\n client_id (str)\n Your app's Client ID.\n client_secret (str)\n ... |
Please provide a description of the function:def refresh_access_token(credential):
if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT:
response = _request_access_token(
grant_type=auth.REFRESH_TOKEN,
client_id=credential.client_id,
client_secret=credential.cli... | [
"Use a refresh token to request a new access token.\n\n Not suported for access tokens obtained via Implicit Grant.\n\n Parameters\n credential (OAuth2Credential)\n An authorized user's OAuth 2.0 credentials.\n\n Returns\n (Session)\n A new Session object with refreshed ... |
Please provide a description of the function:def _build_authorization_request_url(
self,
response_type,
redirect_url,
state=None
):
if response_type not in auth.VALID_RESPONSE_TYPES:
message = '{} is not a valid response type.'
raise UberIlleg... | [
"Form URL to request an auth code or access token.\n\n Parameters\n response_type (str)\n Either 'code' (Authorization Code Grant) or\n 'token' (Implicit Grant)\n redirect_url (str)\n The URL that the Uber server will redirect the user to aft... |
Please provide a description of the function:def _extract_query(self, redirect_url):
qs = urlparse(redirect_url)
# Implicit Grant redirect_urls have data after fragment identifier (#)
# All other redirect_urls return data after query identifier (?)
qs = qs.fragment if isinstanc... | [
"Extract query parameters from a url.\n\n Parameters\n redirect_url (str)\n The full URL that the Uber server redirected to after\n the user authorized your app.\n\n Returns\n (dict)\n A dictionary of query parameters.\n "
] |
Please provide a description of the function:def _generate_state_token(self, length=32):
choices = ascii_letters + digits
return ''.join(SystemRandom().choice(choices) for _ in range(length)) | [
"Generate CSRF State Token.\n\n CSRF State Tokens are passed as a parameter in the authorization\n URL and are checked when receiving responses from the Uber Auth\n server to prevent request forgery.\n "
] |
Please provide a description of the function:def get_authorization_url(self):
return self._build_authorization_request_url(
response_type=auth.CODE_RESPONSE_TYPE,
redirect_url=self.redirect_url,
state=self.state_token,
) | [
"Start the Authorization Code Grant process.\n\n This function starts the OAuth 2.0 authorization process and builds an\n authorization URL. You should redirect your user to this URL, where\n they can grant your application access to their Uber account.\n\n Returns\n (str)\n ... |
Please provide a description of the function:def _verify_query(self, query_params):
error_message = None
if self.state_token is not False:
# Check CSRF State Token against state token from GET request
received_state_token = query_params.get('state')
if recei... | [
"Verify response from the Uber Auth server.\n\n Parameters\n query_params (dict)\n Dictionary of query parameters attached to your redirect URL\n after user approved your app and was redirected.\n\n Returns\n authorization_code (str)\n ... |
Please provide a description of the function:def get_authorization_url(self):
return self._build_authorization_request_url(
response_type=auth.TOKEN_RESPONSE_TYPE,
redirect_url=self.redirect_url,
) | [
"Build URL for authorization request.\n\n Returns\n (str)\n The fully constructed authorization request URL.\n "
] |
Please provide a description of the function:def get_session(self, redirect_url):
query_params = self._extract_query(redirect_url)
error = query_params.get('error')
if error:
raise UberIllegalState(error)
# convert space delimited string to set
scopes = que... | [
"Create Session to store credentials.\n\n Parameters\n redirect_url (str)\n The full URL that the Uber server redirected to after\n the user authorized your app.\n\n Returns\n (Session)\n A Session object with OAuth 2.0 credentials.\n\... |
Please provide a description of the function:def get_session(self):
response = _request_access_token(
grant_type=auth.CLIENT_CREDENTIALS_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
scopes=self.scopes,
)
oauth2creden... | [
"Create Session to store credentials.\n\n Returns\n (Session)\n A Session object with OAuth 2.0 credentials.\n "
] |
Please provide a description of the function:def surge_handler(response, **kwargs):
if response.status_code == codes.conflict:
json = response.json()
errors = json.get('errors', [])
error = errors[0] if errors else json.get('error')
if error and error.get('code') == 'surge':
... | [
"Error Handler to surface 409 Surge Conflict errors.\n\n Attached as a callback hook on the Request object.\n\n Parameters\n response (requests.Response)\n The HTTP response from an API request.\n **kwargs\n Arbitrary keyword arguments.\n "
] |
Please provide a description of the function:def get_products(self, latitude, longitude):
args = OrderedDict([
('latitude', latitude),
('longitude', longitude),
])
return self._api_call('GET', 'v1.2/products', args=args) | [
"Get information about the Uber products offered at a given location.\n\n Parameters\n latitude (float)\n The latitude component of a location.\n longitude (float)\n The longitude component of a location.\n\n Returns\n (Response)\n ... |
Please provide a description of the function:def get_price_estimates(
self,
start_latitude,
start_longitude,
end_latitude,
end_longitude,
seat_count=None,
):
args = OrderedDict([
('start_latitude', start_latitude),
('start_long... | [
"Get price estimates for products at a given location.\n\n Parameters\n start_latitude (float)\n The latitude component of a start location.\n start_longitude (float)\n The longitude component of a start location.\n end_latitude (float)\n ... |
Please provide a description of the function:def get_pickup_time_estimates(
self,
start_latitude,
start_longitude,
product_id=None,
):
args = OrderedDict([
('start_latitude', start_latitude),
('start_longitude', start_longitude),
(... | [
"Get pickup time estimates for products at a given location.\n\n Parameters\n start_latitude (float)\n The latitude component of a start location.\n start_longitude (float)\n The longitude component of a start location.\n product_id (str)\n ... |
Please provide a description of the function:def get_promotions(
self,
start_latitude,
start_longitude,
end_latitude,
end_longitude,
):
args = OrderedDict([
('start_latitude', start_latitude),
('start_longitude', start_longitude),
... | [
"Get information about the promotions available to a user.\n\n Parameters\n start_latitude (float)\n The latitude component of a start location.\n start_longitude (float)\n The longitude component of a start location.\n end_latitude (float)\n ... |
Please provide a description of the function:def get_user_activity(self, offset=None, limit=None):
args = {
'offset': offset,
'limit': limit,
}
return self._api_call('GET', 'v1.2/history', args=args) | [
"Get activity about the user's lifetime activity with Uber.\n\n Parameters\n offset (int)\n The integer offset for activity results. Default is 0.\n limit (int)\n Integer amount of results to return. Maximum is 50.\n Default is 5.\n\n ... |
Please provide a description of the function:def estimate_ride(
self,
product_id=None,
start_latitude=None,
start_longitude=None,
start_place_id=None,
end_latitude=None,
end_longitude=None,
end_place_id=None,
seat_count=None,
):
... | [
"Estimate ride details given a product, start, and end location.\n\n Only pickup time estimates and surge pricing information are provided\n if no end location is provided.\n\n Parameters\n product_id (str)\n The unique ID of the product being requested. If none is\n ... |
Please provide a description of the function:def request_ride(
self,
product_id=None,
start_latitude=None,
start_longitude=None,
start_place_id=None,
start_address=None,
start_nickname=None,
end_latitude=None,
end_longitude=None,
end_place_... | [
"Request a ride on behalf of an Uber user.\n\n When specifying pickup and dropoff locations, you can either use\n latitude/longitude pairs or place ID (but not both).\n\n Parameters\n product_id (str)\n The unique ID of the product being requested. If none is\n ... |
Please provide a description of the function:def update_ride(
self,
ride_id,
end_latitude=None,
end_longitude=None,
end_place_id=None,
):
args = {}
if end_latitude is not None:
args.update({'end_latitude': end_latitude})
if end_lon... | [
"Update an ongoing ride's destination.\n\n To specify a new dropoff location, you can either use a\n latitude/longitude pair or place ID (but not both).\n\n Params\n ride_id (str)\n The unique ID of the Ride Request.\n end_latitude (float)\n T... |
Please provide a description of the function:def update_sandbox_ride(self, ride_id, new_status):
if new_status not in VALID_PRODUCT_STATUS:
message = '{} is not a valid product status.'
raise UberIllegalState(message.format(new_status))
args = {'status': new_status}
... | [
"Update the status of an ongoing sandbox request.\n\n Params\n ride_id (str)\n The unique ID of the Ride Request.\n new_status (str)\n Status from VALID_PRODUCT_STATUS.\n\n Returns\n (Response)\n A Response object with succe... |
Please provide a description of the function:def update_sandbox_product(
self,
product_id,
surge_multiplier=None,
drivers_available=None,
):
args = {
'surge_multiplier': surge_multiplier,
'drivers_available': drivers_available,
}
... | [
"Update sandbox product availability.\n\n Params\n product_id (str)\n Unique identifier representing a specific product for a\n given location.\n surge_multiplier (float)\n Optional surge multiplier to manipulate pricing of product.\n ... |
Please provide a description of the function:def refresh_oauth_credential(self):
if self.session.token_type == auth.SERVER_TOKEN_TYPE:
return
credential = self.session.oauth2credential
if credential.is_stale():
refresh_session = refresh_access_token(credential)
... | [
"Refresh session's OAuth 2.0 credentials if they are stale."
] |
Please provide a description of the function:def revoke_oauth_credential(self):
if self.session.token_type == auth.SERVER_TOKEN_TYPE:
return
credential = self.session.oauth2credential
revoke_access_token(credential) | [
"Revoke the session's OAuth 2.0 credentials."
] |
Please provide a description of the function:def get_driver_trips(self,
offset=None,
limit=None,
from_time=None,
to_time=None
):
args = {
'offset': offset,
... | [
"Get trips about the authorized Uber driver.\n\n Parameters\n offset (int)\n The integer offset for activity results. Offset the list of\n returned results by this amount. Default is zero.\n limit (int)\n Integer amount of results to return. ... |
Please provide a description of the function:def get_driver_payments(self,
offset=None,
limit=None,
from_time=None,
to_time=None
):
args = {
'offset': ... | [
"Get payments about the authorized Uber driver.\n\n Parameters\n offset (int)\n The integer offset for activity results. Offset the list of\n returned results by this amount. Default is zero.\n limit (int)\n Integer amount of results to retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.