repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersEnvironment.step | def step(self):
"""Prompt the environment to change."""
current_state = max(self.infos(type=State),
key=attrgetter('creation_time'))
current_contents = float(current_state.contents)
new_contents = 1 - current_contents
info_out = State(origin=self, cont... | python | def step(self):
"""Prompt the environment to change."""
current_state = max(self.infos(type=State),
key=attrgetter('creation_time'))
current_contents = float(current_state.contents)
new_contents = 1 - current_contents
info_out = State(origin=self, cont... | [
"def",
"step",
"(",
"self",
")",
":",
"current_state",
"=",
"max",
"(",
"self",
".",
"infos",
"(",
"type",
"=",
"State",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'creation_time'",
")",
")",
"current_contents",
"=",
"float",
"(",
"current_state",
".",
... | Prompt the environment to change. | [
"Prompt",
"the",
"environment",
"to",
"change",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L369-L376 | train | Prompt the environment to change. |
Kortemme-Lab/klab | klab/cluster/python_script_template.py | print_subprocess_output | def print_subprocess_output(subp):
'''Prints the stdout and stderr output.'''
if subp:
if subp.errorcode != 0:
print('<error errorcode="%s">' % str(subp.errorcode))
print(subp.stderr)
print("</error>")
print_tag('stdout', '\n%s\n' % subp.stdout)
el... | python | def print_subprocess_output(subp):
'''Prints the stdout and stderr output.'''
if subp:
if subp.errorcode != 0:
print('<error errorcode="%s">' % str(subp.errorcode))
print(subp.stderr)
print("</error>")
print_tag('stdout', '\n%s\n' % subp.stdout)
el... | [
"def",
"print_subprocess_output",
"(",
"subp",
")",
":",
"if",
"subp",
":",
"if",
"subp",
".",
"errorcode",
"!=",
"0",
":",
"print",
"(",
"'<error errorcode=\"%s\">'",
"%",
"str",
"(",
"subp",
".",
"errorcode",
")",
")",
"print",
"(",
"subp",
".",
"stder... | Prints the stdout and stderr output. | [
"Prints",
"the",
"stdout",
"and",
"stderr",
"output",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cluster/python_script_template.py#L48-L58 | train | Prints the stdout and stderr output. |
Alveo/pyalveo | pyalveo/objects.py | ItemGroup.get_all | def get_all(self, force_download=False):
""" Retrieve the metadata for all items in this list from the server,
as Item objects
:rtype: List
:returns: a List of the corresponding Item objects
:type force_download: Boolean
:param force_download: True to download from the s... | python | def get_all(self, force_download=False):
""" Retrieve the metadata for all items in this list from the server,
as Item objects
:rtype: List
:returns: a List of the corresponding Item objects
:type force_download: Boolean
:param force_download: True to download from the s... | [
"def",
"get_all",
"(",
"self",
",",
"force_download",
"=",
"False",
")",
":",
"cl",
"=",
"self",
".",
"client",
"return",
"[",
"cl",
".",
"get_item",
"(",
"item",
",",
"force_download",
")",
"for",
"item",
"in",
"self",
".",
"item_urls",
"]"
] | Retrieve the metadata for all items in this list from the server,
as Item objects
:rtype: List
:returns: a List of the corresponding Item objects
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
... | [
"Retrieve",
"the",
"metadata",
"for",
"all",
"items",
"in",
"this",
"list",
"from",
"the",
"server",
"as",
"Item",
"objects"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L170-L185 | train | Retrieve the metadata for all items in this list from the server. |
Alveo/pyalveo | pyalveo/objects.py | ItemGroup.get_item | def get_item(self, item_index, force_download=False):
""" Retrieve the metadata for a specific item in this ItemGroup
:type item_index: int
:param item_index: the index of the item
:type force_download: Boolean
:param force_download: True to download from the server
... | python | def get_item(self, item_index, force_download=False):
""" Retrieve the metadata for a specific item in this ItemGroup
:type item_index: int
:param item_index: the index of the item
:type force_download: Boolean
:param force_download: True to download from the server
... | [
"def",
"get_item",
"(",
"self",
",",
"item_index",
",",
"force_download",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"get_item",
"(",
"self",
".",
"item_urls",
"[",
"item_index",
"]",
",",
"force_download",
")"
] | Retrieve the metadata for a specific item in this ItemGroup
:type item_index: int
:param item_index: the index of the item
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: Item
:... | [
"Retrieve",
"the",
"metadata",
"for",
"a",
"specific",
"item",
"in",
"this",
"ItemGroup"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L230-L246 | train | Retrieve the metadata for a specific item in this ItemGroup |
Alveo/pyalveo | pyalveo/objects.py | ItemList.refresh | def refresh(self):
""" Update this ItemList by re-downloading it from the server
:rtype: ItemList
:returns: this ItemList, after the refresh
:raises: APIError if the API request is not successful
"""
refreshed = self.client.get_item_list(self.url())
self.item_... | python | def refresh(self):
""" Update this ItemList by re-downloading it from the server
:rtype: ItemList
:returns: this ItemList, after the refresh
:raises: APIError if the API request is not successful
"""
refreshed = self.client.get_item_list(self.url())
self.item_... | [
"def",
"refresh",
"(",
"self",
")",
":",
"refreshed",
"=",
"self",
".",
"client",
".",
"get_item_list",
"(",
"self",
".",
"url",
"(",
")",
")",
"self",
".",
"item_urls",
"=",
"refreshed",
".",
"urls",
"(",
")",
"self",
".",
"list_name",
"=",
"refresh... | Update this ItemList by re-downloading it from the server
:rtype: ItemList
:returns: this ItemList, after the refresh
:raises: APIError if the API request is not successful | [
"Update",
"this",
"ItemList",
"by",
"re",
"-",
"downloading",
"it",
"from",
"the",
"server"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L345-L358 | train | Refreshes the item list by re - downloading it from the server and updating the list name |
Alveo/pyalveo | pyalveo/objects.py | ItemList.append | def append(self, items):
""" Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: ... | python | def append(self, items):
""" Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: ... | [
"def",
"append",
"(",
"self",
",",
"items",
")",
":",
"resp",
"=",
"self",
".",
"client",
".",
"add_to_item_list",
"(",
"items",
",",
"self",
".",
"url",
"(",
")",
")",
"self",
".",
"refresh",
"(",
")",
"return",
"resp"
] | Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: String
:returns: the server s... | [
"Add",
"some",
"items",
"to",
"this",
"ItemList",
"and",
"save",
"the",
"changes",
"to",
"the",
"server"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L361-L377 | train | Adds some items to the ItemList and saves the changes to the server |
Alveo/pyalveo | pyalveo/objects.py | Item.get_document | def get_document(self, index=0):
""" Return the metadata for the specified document, as a
Document object
:type index: int
:param index: the index of the document
:rtype: Document
:returns: the metadata for the specified document
"""
try:
r... | python | def get_document(self, index=0):
""" Return the metadata for the specified document, as a
Document object
:type index: int
:param index: the index of the document
:rtype: Document
:returns: the metadata for the specified document
"""
try:
r... | [
"def",
"get_document",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"try",
":",
"return",
"Document",
"(",
"self",
".",
"metadata",
"(",
")",
"[",
"'alveo:documents'",
"]",
"[",
"index",
"]",
",",
"self",
".",
"client",
")",
"except",
"IndexError",
... | Return the metadata for the specified document, as a
Document object
:type index: int
:param index: the index of the document
:rtype: Document
:returns: the metadata for the specified document | [
"Return",
"the",
"metadata",
"for",
"the",
"specified",
"document",
"as",
"a",
"Document",
"object"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L462-L478 | train | Return the metadata for the specified document as a Document object |
Alveo/pyalveo | pyalveo/objects.py | Item.get_primary_text | def get_primary_text(self, force_download=False):
""" Retrieve the primary text for this item from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the primar... | python | def get_primary_text(self, force_download=False):
""" Retrieve the primary text for this item from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the primar... | [
"def",
"get_primary_text",
"(",
"self",
",",
"force_download",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"get_primary_text",
"(",
"self",
".",
"url",
"(",
")",
",",
"force_download",
")"
] | Retrieve the primary text for this item from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the primary text
:raises: APIError if the API request is not su... | [
"Retrieve",
"the",
"primary",
"text",
"for",
"this",
"item",
"from",
"the",
"server"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L481-L495 | train | Retrieve the primary text for this item from the server. |
Alveo/pyalveo | pyalveo/objects.py | Item.get_annotations | def get_annotations(self, atype=None, label=None):
""" Retrieve the annotations for this item from the server
:type atype: String
:param atype: return only results with a matching Type field
:type label: String
:param label: return only results with a matching Label field
... | python | def get_annotations(self, atype=None, label=None):
""" Retrieve the annotations for this item from the server
:type atype: String
:param atype: return only results with a matching Type field
:type label: String
:param label: return only results with a matching Label field
... | [
"def",
"get_annotations",
"(",
"self",
",",
"atype",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"return",
"self",
".",
"client",
".",
"get_item_annotations",
"(",
"self",
".",
"url",
"(",
")",
",",
"atype",
",",
"label",
")"
] | Retrieve the annotations for this item from the server
:type atype: String
:param atype: return only results with a matching Type field
:type label: String
:param label: return only results with a matching Label field
:rtype: String
:returns: the annotations as a JSON s... | [
"Retrieve",
"the",
"annotations",
"for",
"this",
"item",
"from",
"the",
"server"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L498-L513 | train | Retrieve the annotations for this item from the server |
Alveo/pyalveo | pyalveo/objects.py | Document.get_content | def get_content(self, force_download=False):
""" Retrieve the content for this Document from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the content data... | python | def get_content(self, force_download=False):
""" Retrieve the content for this Document from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the content data... | [
"def",
"get_content",
"(",
"self",
",",
"force_download",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"get_document",
"(",
"self",
".",
"url",
"(",
")",
",",
"force_download",
")"
] | Retrieve the content for this Document from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the content data
:raises: APIError if the API request is not suc... | [
"Retrieve",
"the",
"content",
"for",
"this",
"Document",
"from",
"the",
"server"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L702-L716 | train | Retrieve the content for this Document from the server |
Alveo/pyalveo | pyalveo/objects.py | Document.download_content | def download_content(self, dir_path='', filename=None,
force_download=False):
""" Download the content for this document to a file
:type dir_path: String
:param dir_path: the path to which to write the data
:type filename: String
:param filename: filenam... | python | def download_content(self, dir_path='', filename=None,
force_download=False):
""" Download the content for this document to a file
:type dir_path: String
:param dir_path: the path to which to write the data
:type filename: String
:param filename: filenam... | [
"def",
"download_content",
"(",
"self",
",",
"dir_path",
"=",
"''",
",",
"filename",
"=",
"None",
",",
"force_download",
"=",
"False",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"get_filename",
"(",
")",
"path",
"=",
"... | Download the content for this document to a file
:type dir_path: String
:param dir_path: the path to which to write the data
:type filename: String
:param filename: filename to write to (if None, defaults to the document's
name, as specified by its metadata
:type for... | [
"Download",
"the",
"content",
"for",
"this",
"document",
"to",
"a",
"file"
] | 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/objects.py#L730-L756 | train | Download the content for this document to a file. |
thespacedoctor/HMpTy | HMpTy/mysql/conesearch.py | conesearch.search | def search(self):
"""
*Return the results of the database conesearch*
**Return:**
- ``conesearch``
**Usage:**
See class usage.
"""
self.log.debug('starting the ``get`` method')
sqlQuery = self._get_on_trixel_sources_from_database_query(... | python | def search(self):
"""
*Return the results of the database conesearch*
**Return:**
- ``conesearch``
**Usage:**
See class usage.
"""
self.log.debug('starting the ``get`` method')
sqlQuery = self._get_on_trixel_sources_from_database_query(... | [
"def",
"search",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``get`` method'",
")",
"sqlQuery",
"=",
"self",
".",
"_get_on_trixel_sources_from_database_query",
"(",
")",
"databaseRows",
"=",
"self",
".",
"_execute_query",
"(",
"s... | *Return the results of the database conesearch*
**Return:**
- ``conesearch``
**Usage:**
See class usage. | [
"*",
"Return",
"the",
"results",
"of",
"the",
"database",
"conesearch",
"*"
] | 3ce2bdb7ce3351468962ab907ede9a6074c15912 | https://github.com/thespacedoctor/HMpTy/blob/3ce2bdb7ce3351468962ab907ede9a6074c15912/HMpTy/mysql/conesearch.py#L245-L271 | train | Returns the results of the database conesearch |
thespacedoctor/HMpTy | HMpTy/mysql/conesearch.py | conesearch._get_on_trixel_sources_from_database_query | def _get_on_trixel_sources_from_database_query(
self):
"""*generate the mysql query before executing it*
"""
self.log.debug(
'completed the ````_get_on_trixel_sources_from_database_query`` method')
tableName = self.tableName
raCol = self.raCol
dec... | python | def _get_on_trixel_sources_from_database_query(
self):
"""*generate the mysql query before executing it*
"""
self.log.debug(
'completed the ````_get_on_trixel_sources_from_database_query`` method')
tableName = self.tableName
raCol = self.raCol
dec... | [
"def",
"_get_on_trixel_sources_from_database_query",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'completed the ````_get_on_trixel_sources_from_database_query`` method'",
")",
"tableName",
"=",
"self",
".",
"tableName",
"raCol",
"=",
"self",
".",
"raC... | *generate the mysql query before executing it* | [
"*",
"generate",
"the",
"mysql",
"query",
"before",
"executing",
"it",
"*"
] | 3ce2bdb7ce3351468962ab907ede9a6074c15912 | https://github.com/thespacedoctor/HMpTy/blob/3ce2bdb7ce3351468962ab907ede9a6074c15912/HMpTy/mysql/conesearch.py#L273-L336 | train | generate the mysql query that returns the list of on - trixel sources that are present in the database |
thespacedoctor/HMpTy | HMpTy/mysql/conesearch.py | conesearch._get_trixel_ids_that_overlap_conesearch_circles | def _get_trixel_ids_that_overlap_conesearch_circles(
self):
"""*Get an array of all of the trixels IDs that overlap the conesearch circles(s)*
**Return:**
- ``trixelArray`` -- an array of all the overlapping trixel ids
"""
self.log.debug(
'completed t... | python | def _get_trixel_ids_that_overlap_conesearch_circles(
self):
"""*Get an array of all of the trixels IDs that overlap the conesearch circles(s)*
**Return:**
- ``trixelArray`` -- an array of all the overlapping trixel ids
"""
self.log.debug(
'completed t... | [
"def",
"_get_trixel_ids_that_overlap_conesearch_circles",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'completed the ````_get_trixel_ids_that_overlap_conesearch_circles`` method'",
")",
"trixelArray",
"=",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtyp... | *Get an array of all of the trixels IDs that overlap the conesearch circles(s)*
**Return:**
- ``trixelArray`` -- an array of all the overlapping trixel ids | [
"*",
"Get",
"an",
"array",
"of",
"all",
"of",
"the",
"trixels",
"IDs",
"that",
"overlap",
"the",
"conesearch",
"circles",
"(",
"s",
")",
"*"
] | 3ce2bdb7ce3351468962ab907ede9a6074c15912 | https://github.com/thespacedoctor/HMpTy/blob/3ce2bdb7ce3351468962ab907ede9a6074c15912/HMpTy/mysql/conesearch.py#L338-L362 | train | Return an array of all of the trixels IDs that overlap the conesearch circles. |
thespacedoctor/HMpTy | HMpTy/mysql/conesearch.py | conesearch._execute_query | def _execute_query(
self,
sqlQuery):
"""* execute query and trim results*
**Key Arguments:**
- ``sqlQuery`` -- the sql database query to grab low-resolution results.
**Return:**
- ``databaseRows`` -- the database rows found on HTM trixles with re... | python | def _execute_query(
self,
sqlQuery):
"""* execute query and trim results*
**Key Arguments:**
- ``sqlQuery`` -- the sql database query to grab low-resolution results.
**Return:**
- ``databaseRows`` -- the database rows found on HTM trixles with re... | [
"def",
"_execute_query",
"(",
"self",
",",
"sqlQuery",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'completed the ````_execute_query`` method'",
")",
"try",
":",
"databaseRows",
"=",
"readquery",
"(",
"log",
"=",
"self",
".",
"log",
",",
"sqlQuery",
"=... | * execute query and trim results*
**Key Arguments:**
- ``sqlQuery`` -- the sql database query to grab low-resolution results.
**Return:**
- ``databaseRows`` -- the database rows found on HTM trixles with requested IDs | [
"*",
"execute",
"query",
"and",
"trim",
"results",
"*"
] | 3ce2bdb7ce3351468962ab907ede9a6074c15912 | https://github.com/thespacedoctor/HMpTy/blob/3ce2bdb7ce3351468962ab907ede9a6074c15912/HMpTy/mysql/conesearch.py#L364-L419 | train | Execute a sql query and trim the results |
thespacedoctor/HMpTy | HMpTy/mysql/conesearch.py | conesearch._list_crossmatch | def _list_crossmatch(
self,
dbRows):
"""*to a finer grain crossmatch of the input coordinates and the database results.*
**Key Arguments:**
- ``dbRows`` -- the rows return from the database on first crossmatch pass.
**Return:**
- ``matchIndices1`... | python | def _list_crossmatch(
self,
dbRows):
"""*to a finer grain crossmatch of the input coordinates and the database results.*
**Key Arguments:**
- ``dbRows`` -- the rows return from the database on first crossmatch pass.
**Return:**
- ``matchIndices1`... | [
"def",
"_list_crossmatch",
"(",
"self",
",",
"dbRows",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_list_crossmatch`` method'",
")",
"dbRas",
"=",
"[",
"]",
"dbRas",
"[",
":",
"]",
"=",
"[",
"d",
"[",
"self",
".",
"raCol",
"]",
"f... | *to a finer grain crossmatch of the input coordinates and the database results.*
**Key Arguments:**
- ``dbRows`` -- the rows return from the database on first crossmatch pass.
**Return:**
- ``matchIndices1`` -- indices of the coordinate in the original ra and dec lists
... | [
"*",
"to",
"a",
"finer",
"grain",
"crossmatch",
"of",
"the",
"input",
"coordinates",
"and",
"the",
"database",
"results",
".",
"*"
] | 3ce2bdb7ce3351468962ab907ede9a6074c15912 | https://github.com/thespacedoctor/HMpTy/blob/3ce2bdb7ce3351468962ab907ede9a6074c15912/HMpTy/mysql/conesearch.py#L421-L468 | train | This method is used to list the cross - match of the input coordinates and the database results. |
peergradeio/flask-mongo-profiler | flask_mongo_profiler/contrib/flask_admin/formatters/polymorphic_relations.py | generic_ref_formatter | def generic_ref_formatter(view, context, model, name, lazy=False):
"""
For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter
"""
try:
if lazy:
rel_model = getattr(model, name).fetch()
else:
rel_model = getattr(model,... | python | def generic_ref_formatter(view, context, model, name, lazy=False):
"""
For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter
"""
try:
if lazy:
rel_model = getattr(model, name).fetch()
else:
rel_model = getattr(model,... | [
"def",
"generic_ref_formatter",
"(",
"view",
",",
"context",
",",
"model",
",",
"name",
",",
"lazy",
"=",
"False",
")",
":",
"try",
":",
"if",
"lazy",
":",
"rel_model",
"=",
"getattr",
"(",
"model",
",",
"name",
")",
".",
"fetch",
"(",
")",
"else",
... | For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter | [
"For",
"GenericReferenceField",
"and",
"LazyGenericReferenceField"
] | a267eeb49fea07c9a24fb370bd9d7a90ed313ccf | https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/polymorphic_relations.py#L27-L65 | train | Generic ReferenceField formatter for GenericReferenceField and LazyGenericReferenceField |
peergradeio/flask-mongo-profiler | flask_mongo_profiler/contrib/flask_admin/formatters/polymorphic_relations.py | generic_lazy_ref_formatter | def generic_lazy_ref_formatter(view, context, model, name):
"""
See Also
--------
diff_formatter
"""
return generic_ref_formatter(view, context, model, name, True) | python | def generic_lazy_ref_formatter(view, context, model, name):
"""
See Also
--------
diff_formatter
"""
return generic_ref_formatter(view, context, model, name, True) | [
"def",
"generic_lazy_ref_formatter",
"(",
"view",
",",
"context",
",",
"model",
",",
"name",
")",
":",
"return",
"generic_ref_formatter",
"(",
"view",
",",
"context",
",",
"model",
",",
"name",
",",
"True",
")"
] | See Also
--------
diff_formatter | [
"See",
"Also",
"--------",
"diff_formatter"
] | a267eeb49fea07c9a24fb370bd9d7a90ed313ccf | https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/polymorphic_relations.py#L68-L74 | train | A generic ref formatter that returns a lazy version of the given model. |
peergradeio/flask-mongo-profiler | flask_mongo_profiler/contrib/flask_admin/formatters/polymorphic_relations.py | generic_document_type_formatter | def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) | python | def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) | [
"def",
"generic_document_type_formatter",
"(",
"view",
",",
"context",
",",
"model",
",",
"name",
")",
":",
"_document_model",
"=",
"model",
".",
"get",
"(",
"'document'",
")",
".",
"document_type",
"url",
"=",
"_document_model",
".",
"get_admin_list_url",
"(",
... | Return AdminLog.document field wrapped in URL to its list view. | [
"Return",
"AdminLog",
".",
"document",
"field",
"wrapped",
"in",
"URL",
"to",
"its",
"list",
"view",
"."
] | a267eeb49fea07c9a24fb370bd9d7a90ed313ccf | https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/polymorphic_relations.py#L77-L81 | train | Return AdminLog. document field wrapped in URL to its list view. |
Kortemme-Lab/klab | klab/plot/graphs/multicategory_scatterplot.py | multicategory_scatterplot | def multicategory_scatterplot(output_directory, file_prefix, df,
x_series_index, y_series_index, category_series_index,
series_color, plot_title = '',
x_axis_label = '', y_axis_label = '',
min_predict... | python | def multicategory_scatterplot(output_directory, file_prefix, df,
x_series_index, y_series_index, category_series_index,
series_color, plot_title = '',
x_axis_label = '', y_axis_label = '',
min_predict... | [
"def",
"multicategory_scatterplot",
"(",
"output_directory",
",",
"file_prefix",
",",
"df",
",",
"x_series_index",
",",
"y_series_index",
",",
"category_series_index",
",",
"series_color",
",",
"plot_title",
"=",
"''",
",",
"x_axis_label",
"=",
"''",
",",
"y_axis_la... | This function was adapted from the covariation benchmark. | [
"This",
"function",
"was",
"adapted",
"from",
"the",
"covariation",
"benchmark",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/plot/graphs/multicategory_scatterplot.py#L24-L227 | train | This function is adapted from the covariation benchmark. |
berkeley-cocosci/Wallace | wallace/custom.py | success_response | def success_response(field=None, data=None, request_type=""):
"""Return a generic success response."""
data_out = {}
data_out["status"] = "success"
if field:
data_out[field] = data
print("{} request successful.".format(request_type))
js = dumps(data_out, default=date_handler)
return ... | python | def success_response(field=None, data=None, request_type=""):
"""Return a generic success response."""
data_out = {}
data_out["status"] = "success"
if field:
data_out[field] = data
print("{} request successful.".format(request_type))
js = dumps(data_out, default=date_handler)
return ... | [
"def",
"success_response",
"(",
"field",
"=",
"None",
",",
"data",
"=",
"None",
",",
"request_type",
"=",
"\"\"",
")",
":",
"data_out",
"=",
"{",
"}",
"data_out",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"if",
"field",
":",
"data_out",
"[",
"field",
... | Return a generic success response. | [
"Return",
"a",
"generic",
"success",
"response",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L89-L97 | train | Return a generic success response. |
berkeley-cocosci/Wallace | wallace/custom.py | error_response | def error_response(error_type="Internal server error",
error_text=None,
status=400,
participant=None):
"""Return a generic server error response."""
traceback.print_exc()
print("Error: {}.".format(error_type))
page = error_page(
error_tex... | python | def error_response(error_type="Internal server error",
error_text=None,
status=400,
participant=None):
"""Return a generic server error response."""
traceback.print_exc()
print("Error: {}.".format(error_type))
page = error_page(
error_tex... | [
"def",
"error_response",
"(",
"error_type",
"=",
"\"Internal server error\"",
",",
"error_text",
"=",
"None",
",",
"status",
"=",
"400",
",",
"participant",
"=",
"None",
")",
":",
"traceback",
".",
"print_exc",
"(",
")",
"print",
"(",
"\"Error: {}.\"",
".",
... | Return a generic server error response. | [
"Return",
"a",
"generic",
"server",
"error",
"response",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L100-L117 | train | Return a generic server error response. |
berkeley-cocosci/Wallace | wallace/custom.py | return_page | def return_page(page):
"""Return a rendered template."""
try:
hit_id = request.args['hit_id']
assignment_id = request.args['assignment_id']
worker_id = request.args['worker_id']
mode = request.args['mode']
return render_template(
page,
hit_id=hit_i... | python | def return_page(page):
"""Return a rendered template."""
try:
hit_id = request.args['hit_id']
assignment_id = request.args['assignment_id']
worker_id = request.args['worker_id']
mode = request.args['mode']
return render_template(
page,
hit_id=hit_i... | [
"def",
"return_page",
"(",
"page",
")",
":",
"try",
":",
"hit_id",
"=",
"request",
".",
"args",
"[",
"'hit_id'",
"]",
"assignment_id",
"=",
"request",
".",
"args",
"[",
"'assignment_id'",
"]",
"worker_id",
"=",
"request",
".",
"args",
"[",
"'worker_id'",
... | Return a rendered template. | [
"Return",
"a",
"rendered",
"template",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L120-L139 | train | Return a rendered template. |
berkeley-cocosci/Wallace | wallace/custom.py | error_page | def error_page(participant=None, error_text=None, compensate=True,
error_type="default"):
"""Render HTML for error page."""
if error_text is None:
error_text = """There has been an error and so you are unable to
continue, sorry! If possible, please return the assignment so someon... | python | def error_page(participant=None, error_text=None, compensate=True,
error_type="default"):
"""Render HTML for error page."""
if error_text is None:
error_text = """There has been an error and so you are unable to
continue, sorry! If possible, please return the assignment so someon... | [
"def",
"error_page",
"(",
"participant",
"=",
"None",
",",
"error_text",
"=",
"None",
",",
"compensate",
"=",
"True",
",",
"error_type",
"=",
"\"default\"",
")",
":",
"if",
"error_text",
"is",
"None",
":",
"error_text",
"=",
"\"\"\"There has been an error and so... | Render HTML for error page. | [
"Render",
"HTML",
"for",
"error",
"page",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L142-L174 | train | Render the error page. |
berkeley-cocosci/Wallace | wallace/custom.py | launch | def launch():
"""Launch the experiment."""
exp = experiment(db.init_db(drop_all=False))
exp.log("Launching experiment...", "-----")
init_db()
exp.recruiter().open_recruitment(n=exp.initial_recruitment_size)
session_psiturk.commit()
session.commit()
return success_response(request_type="... | python | def launch():
"""Launch the experiment."""
exp = experiment(db.init_db(drop_all=False))
exp.log("Launching experiment...", "-----")
init_db()
exp.recruiter().open_recruitment(n=exp.initial_recruitment_size)
session_psiturk.commit()
session.commit()
return success_response(request_type="... | [
"def",
"launch",
"(",
")",
":",
"exp",
"=",
"experiment",
"(",
"db",
".",
"init_db",
"(",
"drop_all",
"=",
"False",
")",
")",
"exp",
".",
"log",
"(",
"\"Launching experiment...\"",
",",
"\"-----\"",
")",
"init_db",
"(",
")",
"exp",
".",
"recruiter",
"(... | Launch the experiment. | [
"Launch",
"the",
"experiment",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L197-L206 | train | Launch the experiment. |
berkeley-cocosci/Wallace | wallace/custom.py | summary | def summary():
"""Summarize the participants' status codes."""
exp = experiment(session)
return success_response(field="summary",
data=exp.log_summary(),
request_type="summary") | python | def summary():
"""Summarize the participants' status codes."""
exp = experiment(session)
return success_response(field="summary",
data=exp.log_summary(),
request_type="summary") | [
"def",
"summary",
"(",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"return",
"success_response",
"(",
"field",
"=",
"\"summary\"",
",",
"data",
"=",
"exp",
".",
"log_summary",
"(",
")",
",",
"request_type",
"=",
"\"summary\"",
")"
] | Summarize the participants' status codes. | [
"Summarize",
"the",
"participants",
"status",
"codes",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L219-L224 | train | Summarize the participants status codes. |
berkeley-cocosci/Wallace | wallace/custom.py | quitter | def quitter():
"""Overide the psiTurk quitter route."""
exp = experiment(session)
exp.log("Quitter route was hit.")
return Response(
dumps({"status": "success"}),
status=200,
mimetype='application/json') | python | def quitter():
"""Overide the psiTurk quitter route."""
exp = experiment(session)
exp.log("Quitter route was hit.")
return Response(
dumps({"status": "success"}),
status=200,
mimetype='application/json') | [
"def",
"quitter",
"(",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"exp",
".",
"log",
"(",
"\"Quitter route was hit.\"",
")",
"return",
"Response",
"(",
"dumps",
"(",
"{",
"\"status\"",
":",
"\"success\"",
"}",
")",
",",
"status",
"=",
"200"... | Overide the psiTurk quitter route. | [
"Overide",
"the",
"psiTurk",
"quitter",
"route",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L228-L236 | train | Overide the psiTurk quitter route. |
berkeley-cocosci/Wallace | wallace/custom.py | experiment_property | def experiment_property(prop):
"""Get a property of the experiment by name."""
exp = experiment(session)
p = getattr(exp, prop)
return success_response(field=prop, data=p, request_type=prop) | python | def experiment_property(prop):
"""Get a property of the experiment by name."""
exp = experiment(session)
p = getattr(exp, prop)
return success_response(field=prop, data=p, request_type=prop) | [
"def",
"experiment_property",
"(",
"prop",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"p",
"=",
"getattr",
"(",
"exp",
",",
"prop",
")",
"return",
"success_response",
"(",
"field",
"=",
"prop",
",",
"data",
"=",
"p",
",",
"request_type",
... | Get a property of the experiment by name. | [
"Get",
"a",
"property",
"of",
"the",
"experiment",
"by",
"name",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L240-L244 | train | Get a property of the experiment by name. |
berkeley-cocosci/Wallace | wallace/custom.py | ad_address | def ad_address(mode, hit_id):
"""Get the address of the ad on AWS.
This is used at the end of the experiment to send participants
back to AWS where they can complete and submit the HIT.
"""
if mode == "debug":
address = '/complete'
elif mode in ["sandbox", "live"]:
username = os... | python | def ad_address(mode, hit_id):
"""Get the address of the ad on AWS.
This is used at the end of the experiment to send participants
back to AWS where they can complete and submit the HIT.
"""
if mode == "debug":
address = '/complete'
elif mode in ["sandbox", "live"]:
username = os... | [
"def",
"ad_address",
"(",
"mode",
",",
"hit_id",
")",
":",
"if",
"mode",
"==",
"\"debug\"",
":",
"address",
"=",
"'/complete'",
"elif",
"mode",
"in",
"[",
"\"sandbox\"",
",",
"\"live\"",
"]",
":",
"username",
"=",
"os",
".",
"getenv",
"(",
"'psiturk_acce... | Get the address of the ad on AWS.
This is used at the end of the experiment to send participants
back to AWS where they can complete and submit the HIT. | [
"Get",
"the",
"address",
"of",
"the",
"ad",
"on",
"AWS",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L248-L283 | train | Get the address of the ad on AWS. |
berkeley-cocosci/Wallace | wallace/custom.py | assign_properties | def assign_properties(thing):
"""Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table.
"""
for p in rang... | python | def assign_properties(thing):
"""Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table.
"""
for p in rang... | [
"def",
"assign_properties",
"(",
"thing",
")",
":",
"for",
"p",
"in",
"range",
"(",
"5",
")",
":",
"property_name",
"=",
"\"property\"",
"+",
"str",
"(",
"p",
"+",
"1",
")",
"property",
"=",
"request_parameter",
"(",
"parameter",
"=",
"property_name",
",... | Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table. | [
"Assign",
"properties",
"to",
"an",
"object",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L365-L378 | train | Assign properties to an object. |
berkeley-cocosci/Wallace | wallace/custom.py | create_participant | def create_participant(worker_id, hit_id, assignment_id, mode):
"""Create a participant.
This route will be hit very early on as any nodes the participant creates
will be defined in reference to the participant object.
You must specify the worker_id, hit_id, assignment_id and mode in the url.
"""
... | python | def create_participant(worker_id, hit_id, assignment_id, mode):
"""Create a participant.
This route will be hit very early on as any nodes the participant creates
will be defined in reference to the participant object.
You must specify the worker_id, hit_id, assignment_id and mode in the url.
"""
... | [
"def",
"create_participant",
"(",
"worker_id",
",",
"hit_id",
",",
"assignment_id",
",",
"mode",
")",
":",
"# check this worker hasn't already taken part",
"parts",
"=",
"models",
".",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"worker_id",
"=",
"worker_id"... | Create a participant.
This route will be hit very early on as any nodes the participant creates
will be defined in reference to the participant object.
You must specify the worker_id, hit_id, assignment_id and mode in the url. | [
"Create",
"a",
"participant",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L383-L415 | train | Create a participant. |
berkeley-cocosci/Wallace | wallace/custom.py | get_participant | def get_participant(participant_id):
"""Get the participant with the given id."""
try:
ppt = models.Participant.query.filter_by(id=participant_id).one()
except NoResultFound:
return error_response(
error_type="/participant GET: no participant found",
status=403)
... | python | def get_participant(participant_id):
"""Get the participant with the given id."""
try:
ppt = models.Participant.query.filter_by(id=participant_id).one()
except NoResultFound:
return error_response(
error_type="/participant GET: no participant found",
status=403)
... | [
"def",
"get_participant",
"(",
"participant_id",
")",
":",
"try",
":",
"ppt",
"=",
"models",
".",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"participant_id",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"return",
"error_r... | Get the participant with the given id. | [
"Get",
"the",
"participant",
"with",
"the",
"given",
"id",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L419-L431 | train | Get the participant with the given id. |
berkeley-cocosci/Wallace | wallace/custom.py | get_network | def get_network(network_id):
"""Get the network with the given id."""
try:
net = models.Network.query.filter_by(id=network_id).one()
except NoResultFound:
return error_response(
error_type="/network GET: no network found",
status=403)
# return the data
return... | python | def get_network(network_id):
"""Get the network with the given id."""
try:
net = models.Network.query.filter_by(id=network_id).one()
except NoResultFound:
return error_response(
error_type="/network GET: no network found",
status=403)
# return the data
return... | [
"def",
"get_network",
"(",
"network_id",
")",
":",
"try",
":",
"net",
"=",
"models",
".",
"Network",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"network_id",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"return",
"error_response",
"(",... | Get the network with the given id. | [
"Get",
"the",
"network",
"with",
"the",
"given",
"id",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L435-L447 | train | Get the network with the given id. |
berkeley-cocosci/Wallace | wallace/custom.py | create_question | def create_question(participant_id):
"""Send a POST request to the question table.
Questions store information at the participant level, not the node
level.
You should pass the question (string) number (int) and response
(string) as arguments.
"""
# Get the participant.
try:
ppt... | python | def create_question(participant_id):
"""Send a POST request to the question table.
Questions store information at the participant level, not the node
level.
You should pass the question (string) number (int) and response
(string) as arguments.
"""
# Get the participant.
try:
ppt... | [
"def",
"create_question",
"(",
"participant_id",
")",
":",
"# Get the participant.",
"try",
":",
"ppt",
"=",
"models",
".",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"participant_id",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
... | Send a POST request to the question table.
Questions store information at the participant level, not the node
level.
You should pass the question (string) number (int) and response
(string) as arguments. | [
"Send",
"a",
"POST",
"request",
"to",
"the",
"question",
"table",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L451-L490 | train | Create a new question in the question table. |
berkeley-cocosci/Wallace | wallace/custom.py | node_neighbors | def node_neighbors(node_id):
"""Send a GET request to the node table.
This calls the neighbours method of the node
making the request and returns a list of descriptions of
the nodes (even if there is only one).
Required arguments: participant_id, node_id
Optional arguments: type, failed, connec... | python | def node_neighbors(node_id):
"""Send a GET request to the node table.
This calls the neighbours method of the node
making the request and returns a list of descriptions of
the nodes (even if there is only one).
Required arguments: participant_id, node_id
Optional arguments: type, failed, connec... | [
"def",
"node_neighbors",
"(",
"node_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# get the parameters",
"node_type",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"node_type\"",
",",
"parameter_type",
"=",
"\"known_class\"",
",",
"default",
... | Send a GET request to the node table.
This calls the neighbours method of the node
making the request and returns a list of descriptions of
the nodes (even if there is only one).
Required arguments: participant_id, node_id
Optional arguments: type, failed, connection
After getting the neighbou... | [
"Send",
"a",
"GET",
"request",
"to",
"the",
"node",
"table",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L494-L545 | train | Get the node s neighbors |
berkeley-cocosci/Wallace | wallace/custom.py | create_node | def create_node(participant_id):
"""Send a POST request to the node table.
This makes a new node for the participant, it calls:
1. exp.get_network_for_participant
2. exp.create_node
3. exp.add_node_to_network
4. exp.node_post_request
"""
exp = experiment(session)
# ... | python | def create_node(participant_id):
"""Send a POST request to the node table.
This makes a new node for the participant, it calls:
1. exp.get_network_for_participant
2. exp.create_node
3. exp.add_node_to_network
4. exp.node_post_request
"""
exp = experiment(session)
# ... | [
"def",
"create_node",
"(",
"participant_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# Get the participant.",
"try",
":",
"participant",
"=",
"models",
".",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"participant_id",
")",... | Send a POST request to the node table.
This makes a new node for the participant, it calls:
1. exp.get_network_for_participant
2. exp.create_node
3. exp.add_node_to_network
4. exp.node_post_request | [
"Send",
"a",
"POST",
"request",
"to",
"the",
"node",
"table",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L549-L607 | train | Create a new node for the participant. |
berkeley-cocosci/Wallace | wallace/custom.py | connect | def connect(node_id, other_node_id):
"""Connect to another node.
The ids of both nodes must be speficied in the url.
You can also pass direction (to/from/both) as an argument.
"""
exp = experiment(session)
# get the parameters
direction = request_parameter(parameter="direction", default="t... | python | def connect(node_id, other_node_id):
"""Connect to another node.
The ids of both nodes must be speficied in the url.
You can also pass direction (to/from/both) as an argument.
"""
exp = experiment(session)
# get the parameters
direction = request_parameter(parameter="direction", default="t... | [
"def",
"connect",
"(",
"node_id",
",",
"other_node_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# get the parameters",
"direction",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"direction\"",
",",
"default",
"=",
"\"to\"",
")",
"if",
"t... | Connect to another node.
The ids of both nodes must be speficied in the url.
You can also pass direction (to/from/both) as an argument. | [
"Connect",
"to",
"another",
"node",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L649-L692 | train | Connect to another node. |
berkeley-cocosci/Wallace | wallace/custom.py | get_info | def get_info(node_id, info_id):
"""Get a specific info.
Both the node and info id must be specified in the url.
"""
exp = experiment(session)
# check the node exists
node = models.Node.query.get(node_id)
if node is None:
return error_response(error_type="/info, node does not exist"... | python | def get_info(node_id, info_id):
"""Get a specific info.
Both the node and info id must be specified in the url.
"""
exp = experiment(session)
# check the node exists
node = models.Node.query.get(node_id)
if node is None:
return error_response(error_type="/info, node does not exist"... | [
"def",
"get_info",
"(",
"node_id",
",",
"info_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# check the node exists",
"node",
"=",
"models",
".",
"Node",
".",
"query",
".",
"get",
"(",
"node_id",
")",
"if",
"node",
"is",
"None",
":",
"... | Get a specific info.
Both the node and info id must be specified in the url. | [
"Get",
"a",
"specific",
"info",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L696-L733 | train | Get a specific info. |
berkeley-cocosci/Wallace | wallace/custom.py | node_transmit | def node_transmit(node_id):
"""Transmit to another node.
The sender's node id must be specified in the url.
As with node.transmit() the key parameters are what and to_whom.
However, the values these accept are more limited than for the back end
due to the necessity of serialization.
If what a... | python | def node_transmit(node_id):
"""Transmit to another node.
The sender's node id must be specified in the url.
As with node.transmit() the key parameters are what and to_whom.
However, the values these accept are more limited than for the back end
due to the necessity of serialization.
If what a... | [
"def",
"node_transmit",
"(",
"node_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"what",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"what\"",
",",
"optional",
"=",
"True",
")",
"to_whom",
"=",
"request_parameter",
"(",
"parameter",
"=... | Transmit to another node.
The sender's node id must be specified in the url.
As with node.transmit() the key parameters are what and to_whom.
However, the values these accept are more limited than for the back end
due to the necessity of serialization.
If what and to_whom are not specified they w... | [
"Transmit",
"to",
"another",
"node",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L913-L1006 | train | Transmit a node to another node. |
berkeley-cocosci/Wallace | wallace/custom.py | transformation_get | def transformation_get(node_id):
"""Get all the transformations of a node.
The node id must be specified in the url.
You can also pass transformation_type.
"""
exp = experiment(session)
# get the parameters
transformation_type = request_parameter(parameter="transformation_type",
... | python | def transformation_get(node_id):
"""Get all the transformations of a node.
The node id must be specified in the url.
You can also pass transformation_type.
"""
exp = experiment(session)
# get the parameters
transformation_type = request_parameter(parameter="transformation_type",
... | [
"def",
"transformation_get",
"(",
"node_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# get the parameters",
"transformation_type",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"transformation_type\"",
",",
"parameter_type",
"=",
"\"known_class\""... | Get all the transformations of a node.
The node id must be specified in the url.
You can also pass transformation_type. | [
"Get",
"all",
"the",
"transformations",
"of",
"a",
"node",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L1010-L1047 | train | Get all the transformations of a node. |
berkeley-cocosci/Wallace | wallace/custom.py | transformation_post | def transformation_post(node_id, info_in_id, info_out_id):
"""Transform an info.
The ids of the node, info in and info out must all be in the url.
You can also pass transformation_type.
"""
exp = experiment(session)
# Get the parameters.
transformation_type = request_parameter(parameter="t... | python | def transformation_post(node_id, info_in_id, info_out_id):
"""Transform an info.
The ids of the node, info in and info out must all be in the url.
You can also pass transformation_type.
"""
exp = experiment(session)
# Get the parameters.
transformation_type = request_parameter(parameter="t... | [
"def",
"transformation_post",
"(",
"node_id",
",",
"info_in_id",
",",
"info_out_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# Get the parameters.",
"transformation_type",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"transformation_type\"",
",... | Transform an info.
The ids of the node, info in and info out must all be in the url.
You can also pass transformation_type. | [
"Transform",
"an",
"info",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L1053-L1104 | train | Transform an info. |
berkeley-cocosci/Wallace | wallace/custom.py | api_notifications | def api_notifications():
"""Receive MTurk REST notifications."""
event_type = request.values['Event.1.EventType']
assignment_id = request.values['Event.1.AssignmentId']
# Add the notification to the queue.
db.logger.debug('rq: Queueing %s with id: %s for worker_function',
event_... | python | def api_notifications():
"""Receive MTurk REST notifications."""
event_type = request.values['Event.1.EventType']
assignment_id = request.values['Event.1.AssignmentId']
# Add the notification to the queue.
db.logger.debug('rq: Queueing %s with id: %s for worker_function',
event_... | [
"def",
"api_notifications",
"(",
")",
":",
"event_type",
"=",
"request",
".",
"values",
"[",
"'Event.1.EventType'",
"]",
"assignment_id",
"=",
"request",
".",
"values",
"[",
"'Event.1.AssignmentId'",
"]",
"# Add the notification to the queue.",
"db",
".",
"logger",
... | Receive MTurk REST notifications. | [
"Receive",
"MTurk",
"REST",
"notifications",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L1108-L1120 | train | Receive MTurk REST notifications. |
berkeley-cocosci/Wallace | wallace/custom.py | worker_function | def worker_function(event_type, assignment_id, participant_id):
"""Process the notification."""
db.logger.debug("rq: worker_function working on job id: %s",
get_current_job().id)
db.logger.debug('rq: Received Queue Length: %d (%s)', len(q),
', '.join(q.job_ids))
... | python | def worker_function(event_type, assignment_id, participant_id):
"""Process the notification."""
db.logger.debug("rq: worker_function working on job id: %s",
get_current_job().id)
db.logger.debug('rq: Received Queue Length: %d (%s)', len(q),
', '.join(q.job_ids))
... | [
"def",
"worker_function",
"(",
"event_type",
",",
"assignment_id",
",",
"participant_id",
")",
":",
"db",
".",
"logger",
".",
"debug",
"(",
"\"rq: worker_function working on job id: %s\"",
",",
"get_current_job",
"(",
")",
".",
"id",
")",
"db",
".",
"logger",
".... | Process the notification. | [
"Process",
"the",
"notification",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/custom.py#L1137-L1268 | train | This function processes the notification and returns the resource object. |
uogbuji/versa | tools/py/writer/rdfs.py | prep | def prep(link):
'''
Prepare a statement into a triple ready for rdflib
'''
s, p, o = link[:3]
s = URIRef(s)
p = URIRef(p)
o = URIRef(o) if isinstance(o, I) else Literal(o)
return s, p, o | python | def prep(link):
'''
Prepare a statement into a triple ready for rdflib
'''
s, p, o = link[:3]
s = URIRef(s)
p = URIRef(p)
o = URIRef(o) if isinstance(o, I) else Literal(o)
return s, p, o | [
"def",
"prep",
"(",
"link",
")",
":",
"s",
",",
"p",
",",
"o",
"=",
"link",
"[",
":",
"3",
"]",
"s",
"=",
"URIRef",
"(",
"s",
")",
"p",
"=",
"URIRef",
"(",
"p",
")",
"o",
"=",
"URIRef",
"(",
"o",
")",
"if",
"isinstance",
"(",
"o",
",",
... | Prepare a statement into a triple ready for rdflib | [
"Prepare",
"a",
"statement",
"into",
"a",
"triple",
"ready",
"for",
"rdflib"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/writer/rdfs.py#L39-L47 | train | Prepare a statement into a triple ready for rdflib
|
uogbuji/versa | tools/py/writer/rdfs.py | process | def process(source, target, rdfsonly, base=None, logger=logging):
'''
Prepare a statement into a triple ready for rdflib graph
'''
for link in source.match():
s, p, o = link[:3]
#SKip docheader statements
if s == (base or '') + '@docheader': continue
if p in RESOURCE_MAP... | python | def process(source, target, rdfsonly, base=None, logger=logging):
'''
Prepare a statement into a triple ready for rdflib graph
'''
for link in source.match():
s, p, o = link[:3]
#SKip docheader statements
if s == (base or '') + '@docheader': continue
if p in RESOURCE_MAP... | [
"def",
"process",
"(",
"source",
",",
"target",
",",
"rdfsonly",
",",
"base",
"=",
"None",
",",
"logger",
"=",
"logging",
")",
":",
"for",
"link",
"in",
"source",
".",
"match",
"(",
")",
":",
"s",
",",
"p",
",",
"o",
"=",
"link",
"[",
":",
"3",... | Prepare a statement into a triple ready for rdflib graph | [
"Prepare",
"a",
"statement",
"into",
"a",
"triple",
"ready",
"for",
"rdflib",
"graph"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/writer/rdfs.py#L50-L83 | train | Process a single statement into a triple ready for rdflib graph |
uogbuji/versa | tools/py/writer/rdfs.py | write | def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging):
'''
See the command line help
'''
prefixes = prefixes or {}
g = graph or rdflib.Graph()
#g.bind('bf', BFNS)
#g.bind('bfc', BFCNS)
#g.bind('bfd', BFDNS)
g.bind('v', VNS)
for k, v in prefixes.i... | python | def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging):
'''
See the command line help
'''
prefixes = prefixes or {}
g = graph or rdflib.Graph()
#g.bind('bf', BFNS)
#g.bind('bfc', BFCNS)
#g.bind('bfd', BFDNS)
g.bind('v', VNS)
for k, v in prefixes.i... | [
"def",
"write",
"(",
"models",
",",
"base",
"=",
"None",
",",
"graph",
"=",
"None",
",",
"rdfsonly",
"=",
"False",
",",
"prefixes",
"=",
"None",
",",
"logger",
"=",
"logging",
")",
":",
"prefixes",
"=",
"prefixes",
"or",
"{",
"}",
"g",
"=",
"graph"... | See the command line help | [
"See",
"the",
"command",
"line",
"help"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/writer/rdfs.py#L86-L101 | train | Write a list of models to a graph. |
projectshift/shift-boiler | boiler/feature/routing.py | routing_feature | def routing_feature(app):
"""
Add routing feature
Allows to define application routes un urls.py file and use lazy views.
Additionally enables regular exceptions in route definitions
"""
# enable regex routes
app.url_map.converters['regex'] = RegexConverter
urls = app.name.rsplit('.', 1... | python | def routing_feature(app):
"""
Add routing feature
Allows to define application routes un urls.py file and use lazy views.
Additionally enables regular exceptions in route definitions
"""
# enable regex routes
app.url_map.converters['regex'] = RegexConverter
urls = app.name.rsplit('.', 1... | [
"def",
"routing_feature",
"(",
"app",
")",
":",
"# enable regex routes",
"app",
".",
"url_map",
".",
"converters",
"[",
"'regex'",
"]",
"=",
"RegexConverter",
"urls",
"=",
"app",
".",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"+"... | Add routing feature
Allows to define application routes un urls.py file and use lazy views.
Additionally enables regular exceptions in route definitions | [
"Add",
"routing",
"feature",
"Allows",
"to",
"define",
"application",
"routes",
"un",
"urls",
".",
"py",
"file",
"and",
"use",
"lazy",
"views",
".",
"Additionally",
"enables",
"regular",
"exceptions",
"in",
"route",
"definitions"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/feature/routing.py#L5-L30 | train | Add routing feature for application |
rosshamish/undoredo | undoredo.py | undoable | def undoable(method):
"""
Decorator undoable allows an instance method to be undone.
It does this by wrapping the method call as a Command, then calling self.do() on the command.
Classes which use this decorator should implement a do() method like such:
def do(self, command):
retu... | python | def undoable(method):
"""
Decorator undoable allows an instance method to be undone.
It does this by wrapping the method call as a Command, then calling self.do() on the command.
Classes which use this decorator should implement a do() method like such:
def do(self, command):
retu... | [
"def",
"undoable",
"(",
"method",
")",
":",
"def",
"undoable_method",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"do",
"(",
"Command",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
")",
"return",
"undoable_method"
] | Decorator undoable allows an instance method to be undone.
It does this by wrapping the method call as a Command, then calling self.do() on the command.
Classes which use this decorator should implement a do() method like such:
def do(self, command):
return self.undo_manager.do(command) | [
"Decorator",
"undoable",
"allows",
"an",
"instance",
"method",
"to",
"be",
"undone",
"."
] | 634941181a74477b7ebafa43d9900e6f21fd0458 | https://github.com/rosshamish/undoredo/blob/634941181a74477b7ebafa43d9900e6f21fd0458/undoredo.py#L105-L118 | train | Decorator undoable allows an instance method to be undone. |
rosshamish/undoredo | undoredo.py | Command.do | def do(self):
"""
Set a restore point (copy the object), then call the method.
:return: obj.do_method(*args)
"""
self.restore_point = self.obj.copy()
return self.do_method(self.obj, *self.args) | python | def do(self):
"""
Set a restore point (copy the object), then call the method.
:return: obj.do_method(*args)
"""
self.restore_point = self.obj.copy()
return self.do_method(self.obj, *self.args) | [
"def",
"do",
"(",
"self",
")",
":",
"self",
".",
"restore_point",
"=",
"self",
".",
"obj",
".",
"copy",
"(",
")",
"return",
"self",
".",
"do_method",
"(",
"self",
".",
"obj",
",",
"*",
"self",
".",
"args",
")"
] | Set a restore point (copy the object), then call the method.
:return: obj.do_method(*args) | [
"Set",
"a",
"restore",
"point",
"(",
"copy",
"the",
"object",
")",
"then",
"call",
"the",
"method",
".",
":",
"return",
":",
"obj",
".",
"do_method",
"(",
"*",
"args",
")"
] | 634941181a74477b7ebafa43d9900e6f21fd0458 | https://github.com/rosshamish/undoredo/blob/634941181a74477b7ebafa43d9900e6f21fd0458/undoredo.py#L89-L95 | train | Set a restore point and call the method. |
projectshift/shift-boiler | boiler/migrations/config.py | MigrationsConfig.get_template_directory | def get_template_directory(self):
"""
Get path to migrations templates
This will get used when you run the db init command
"""
dir = os.path.join(os.path.dirname(__file__), 'templates')
return dir | python | def get_template_directory(self):
"""
Get path to migrations templates
This will get used when you run the db init command
"""
dir = os.path.join(os.path.dirname(__file__), 'templates')
return dir | [
"def",
"get_template_directory",
"(",
"self",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'templates'",
")",
"return",
"dir"
] | Get path to migrations templates
This will get used when you run the db init command | [
"Get",
"path",
"to",
"migrations",
"templates",
"This",
"will",
"get",
"used",
"when",
"you",
"run",
"the",
"db",
"init",
"command"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/migrations/config.py#L23-L29 | train | Get path to migrations templates
|
CodersOfTheNight/oshino | oshino/agents/__init__.py | Agent.pull_metrics | async def pull_metrics(self, event_fn, loop=None):
"""
Method called by core.
Should not be overwritten.
"""
if self.lazy and not self.ready:
return None
logger = self.get_logger()
ts = timer()
logger.trace("Waiting for process event")
... | python | async def pull_metrics(self, event_fn, loop=None):
"""
Method called by core.
Should not be overwritten.
"""
if self.lazy and not self.ready:
return None
logger = self.get_logger()
ts = timer()
logger.trace("Waiting for process event")
... | [
"async",
"def",
"pull_metrics",
"(",
"self",
",",
"event_fn",
",",
"loop",
"=",
"None",
")",
":",
"if",
"self",
".",
"lazy",
"and",
"not",
"self",
".",
"ready",
":",
"return",
"None",
"logger",
"=",
"self",
".",
"get_logger",
"(",
")",
"ts",
"=",
"... | Method called by core.
Should not be overwritten. | [
"Method",
"called",
"by",
"core",
".",
"Should",
"not",
"be",
"overwritten",
"."
] | 00f7e151e3ce1f3a7f43b353b695c4dba83c7f28 | https://github.com/CodersOfTheNight/oshino/blob/00f7e151e3ce1f3a7f43b353b695c4dba83c7f28/oshino/agents/__init__.py#L40-L55 | train | Method called by core. pull_metrics Method called by core. pull_metrics Should not be overwritten. |
CodersOfTheNight/oshino | oshino/agents/__init__.py | Agent.ready | def ready(self):
"""
Function used when agent is `lazy`.
It is being processed only when `ready` condition is satisfied
"""
logger = self.get_logger()
now = current_ts()
logger.trace("Current time: {0}".format(now))
logger.trace("Last Run: {0}".format(self... | python | def ready(self):
"""
Function used when agent is `lazy`.
It is being processed only when `ready` condition is satisfied
"""
logger = self.get_logger()
now = current_ts()
logger.trace("Current time: {0}".format(now))
logger.trace("Last Run: {0}".format(self... | [
"def",
"ready",
"(",
"self",
")",
":",
"logger",
"=",
"self",
".",
"get_logger",
"(",
")",
"now",
"=",
"current_ts",
"(",
")",
"logger",
".",
"trace",
"(",
"\"Current time: {0}\"",
".",
"format",
"(",
"now",
")",
")",
"logger",
".",
"trace",
"(",
"\"... | Function used when agent is `lazy`.
It is being processed only when `ready` condition is satisfied | [
"Function",
"used",
"when",
"agent",
"is",
"lazy",
".",
"It",
"is",
"being",
"processed",
"only",
"when",
"ready",
"condition",
"is",
"satisfied"
] | 00f7e151e3ce1f3a7f43b353b695c4dba83c7f28 | https://github.com/CodersOfTheNight/oshino/blob/00f7e151e3ce1f3a7f43b353b695c4dba83c7f28/oshino/agents/__init__.py#L66-L78 | train | Function used when agent is lazy. It is being processed only when agent is lazy. |
mardix/Mocha | mocha/contrib/auth/__init__.py | get_jwt_secret | def get_jwt_secret():
"""
Get the JWT secret
:return: str
"""
secret_key = __options__.get("jwt_secret") or config("JWT_SECRET") or config("SECRET_KEY")
if not secret_key:
raise exceptions.AuthError("Missing config JWT/SECRET_KEY")
return secret_key | python | def get_jwt_secret():
"""
Get the JWT secret
:return: str
"""
secret_key = __options__.get("jwt_secret") or config("JWT_SECRET") or config("SECRET_KEY")
if not secret_key:
raise exceptions.AuthError("Missing config JWT/SECRET_KEY")
return secret_key | [
"def",
"get_jwt_secret",
"(",
")",
":",
"secret_key",
"=",
"__options__",
".",
"get",
"(",
"\"jwt_secret\"",
")",
"or",
"config",
"(",
"\"JWT_SECRET\"",
")",
"or",
"config",
"(",
"\"SECRET_KEY\"",
")",
"if",
"not",
"secret_key",
":",
"raise",
"exceptions",
"... | Get the JWT secret
:return: str | [
"Get",
"the",
"JWT",
"secret",
":",
"return",
":",
"str"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L148-L156 | train | Get the JWT secret |
mardix/Mocha | mocha/contrib/auth/__init__.py | create_user | def create_user(username, password=None, email=None, first_name="", last_name="",
role="MEMBER", login_method=None):
"""
Create a new user
:param username:
:param password:
:param email:
:param first_name:
:param last_name:
:param role: str
:return: AuthUser
"""
... | python | def create_user(username, password=None, email=None, first_name="", last_name="",
role="MEMBER", login_method=None):
"""
Create a new user
:param username:
:param password:
:param email:
:param first_name:
:param last_name:
:param role: str
:return: AuthUser
"""
... | [
"def",
"create_user",
"(",
"username",
",",
"password",
"=",
"None",
",",
"email",
"=",
"None",
",",
"first_name",
"=",
"\"\"",
",",
"last_name",
"=",
"\"\"",
",",
"role",
"=",
"\"MEMBER\"",
",",
"login_method",
"=",
"None",
")",
":",
"if",
"not",
"log... | Create a new user
:param username:
:param password:
:param email:
:param first_name:
:param last_name:
:param role: str
:return: AuthUser | [
"Create",
"a",
"new",
"user",
":",
"param",
"username",
":",
":",
"param",
"password",
":",
":",
"param",
"email",
":",
":",
"param",
"first_name",
":",
":",
"param",
"last_name",
":",
":",
"param",
"role",
":",
"str",
":",
"return",
":",
"AuthUser"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L188-L213 | train | Create a new user in the cluster. |
mardix/Mocha | mocha/contrib/auth/__init__.py | get_user | def get_user(id=None, username=None, email=None, federated_id=None, provider=None, jwt=None):
"""
Retrieve the user based on the data provided
:param id:
:param username:
:param email:
:param federated_id:
:param provider:
:param jwt:
:return: AuthUser
"""
if id:
... | python | def get_user(id=None, username=None, email=None, federated_id=None, provider=None, jwt=None):
"""
Retrieve the user based on the data provided
:param id:
:param username:
:param email:
:param federated_id:
:param provider:
:param jwt:
:return: AuthUser
"""
if id:
... | [
"def",
"get_user",
"(",
"id",
"=",
"None",
",",
"username",
"=",
"None",
",",
"email",
"=",
"None",
",",
"federated_id",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"jwt",
"=",
"None",
")",
":",
"if",
"id",
":",
"return",
"_user",
"(",
"models"... | Retrieve the user based on the data provided
:param id:
:param username:
:param email:
:param federated_id:
:param provider:
:param jwt:
:return: AuthUser | [
"Retrieve",
"the",
"user",
"based",
"on",
"the",
"data",
"provided",
":",
"param",
"id",
":",
":",
"param",
"username",
":",
":",
"param",
"email",
":",
":",
"param",
"federated_id",
":",
":",
"param",
"provider",
":",
":",
"param",
"jwt",
":",
":",
... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L216-L238 | train | Retrieve the user based on the data provided |
mardix/Mocha | mocha/contrib/auth/__init__.py | get_user_by_auth_token | def get_user_by_auth_token(token=None):
"""
Return the AuthUser associated to the token, otherwise it will return None.
If token is not provided, it will pull it from the headers: Authorization
Exception:
Along with AuthError, it may
:param token:
:return: AuthUser
"""
if not token:... | python | def get_user_by_auth_token(token=None):
"""
Return the AuthUser associated to the token, otherwise it will return None.
If token is not provided, it will pull it from the headers: Authorization
Exception:
Along with AuthError, it may
:param token:
:return: AuthUser
"""
if not token:... | [
"def",
"get_user_by_auth_token",
"(",
"token",
"=",
"None",
")",
":",
"if",
"not",
"token",
":",
"token",
"=",
"request",
".",
"get_auth_token",
"(",
")",
"secret_key",
"=",
"get_jwt_secret",
"(",
")",
"s",
"=",
"utils",
".",
"unsign_jwt",
"(",
"token",
... | Return the AuthUser associated to the token, otherwise it will return None.
If token is not provided, it will pull it from the headers: Authorization
Exception:
Along with AuthError, it may
:param token:
:return: AuthUser | [
"Return",
"the",
"AuthUser",
"associated",
"to",
"the",
"token",
"otherwise",
"it",
"will",
"return",
"None",
".",
"If",
"token",
"is",
"not",
"provided",
"it",
"will",
"pull",
"it",
"from",
"the",
"headers",
":",
"Authorization"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L241-L259 | train | Returns the AuthUser associated to the token. If token is not provided it will pull it from the headers. |
mardix/Mocha | mocha/contrib/auth/__init__.py | get_user_by_action_token | def get_user_by_action_token(action, token):
"""
Get the user by action token
:param action: str
:param token: str
:return: AuthUser
"""
data = utils.unsign_url_safe(token,
secret_key=get_jwt_secret(),
salt=action)
if data... | python | def get_user_by_action_token(action, token):
"""
Get the user by action token
:param action: str
:param token: str
:return: AuthUser
"""
data = utils.unsign_url_safe(token,
secret_key=get_jwt_secret(),
salt=action)
if data... | [
"def",
"get_user_by_action_token",
"(",
"action",
",",
"token",
")",
":",
"data",
"=",
"utils",
".",
"unsign_url_safe",
"(",
"token",
",",
"secret_key",
"=",
"get_jwt_secret",
"(",
")",
",",
"salt",
"=",
"action",
")",
"if",
"data",
"is",
"None",
":",
"r... | Get the user by action token
:param action: str
:param token: str
:return: AuthUser | [
"Get",
"the",
"user",
"by",
"action",
"token",
":",
"param",
"action",
":",
"str",
":",
"param",
"token",
":",
"str",
":",
"return",
":",
"AuthUser"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L262-L274 | train | Get the user by action token |
mardix/Mocha | mocha/contrib/auth/__init__.py | with_username | def with_username(username, password):
"""
To authenticate a user with user and password
*** authenticate doesn't create a session. To create a session,
use login_user
:param username:
:param password:
:return: UserModel
"""
user = models.AuthUser.get_by_username(username)
ret... | python | def with_username(username, password):
"""
To authenticate a user with user and password
*** authenticate doesn't create a session. To create a session,
use login_user
:param username:
:param password:
:return: UserModel
"""
user = models.AuthUser.get_by_username(username)
ret... | [
"def",
"with_username",
"(",
"username",
",",
"password",
")",
":",
"user",
"=",
"models",
".",
"AuthUser",
".",
"get_by_username",
"(",
"username",
")",
"return",
"_user",
"(",
"user",
")",
"if",
"user",
"and",
"user",
".",
"password_matched",
"(",
"passw... | To authenticate a user with user and password
*** authenticate doesn't create a session. To create a session,
use login_user
:param username:
:param password:
:return: UserModel | [
"To",
"authenticate",
"a",
"user",
"with",
"user",
"and",
"password",
"***",
"authenticate",
"doesn",
"t",
"create",
"a",
"session",
".",
"To",
"create",
"a",
"session",
"use",
"login_user",
":",
"param",
"username",
":",
":",
"param",
"password",
":",
":"... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L277-L287 | train | Returns a UserModel containing a username and password. |
mardix/Mocha | mocha/contrib/auth/__init__.py | create_session | def create_session(user):
"""
Create the login session
:param user: UserModel
:return:
"""
def cb():
if user:
if __options__.get("require_email_verification") and not user.email_verified:
raise exceptions.VerifyEmailError()
if flask_login.login_u... | python | def create_session(user):
"""
Create the login session
:param user: UserModel
:return:
"""
def cb():
if user:
if __options__.get("require_email_verification") and not user.email_verified:
raise exceptions.VerifyEmailError()
if flask_login.login_u... | [
"def",
"create_session",
"(",
"user",
")",
":",
"def",
"cb",
"(",
")",
":",
"if",
"user",
":",
"if",
"__options__",
".",
"get",
"(",
"\"require_email_verification\"",
")",
"and",
"not",
"user",
".",
"email_verified",
":",
"raise",
"exceptions",
".",
"Verif... | Create the login session
:param user: UserModel
:return: | [
"Create",
"the",
"login",
"session",
":",
"param",
"user",
":",
"UserModel",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L300-L316 | train | Create the login session
|
mardix/Mocha | mocha/contrib/auth/__init__.py | _url_for_email | def _url_for_email(endpoint, base_url=None, **kw):
"""
Create an external url_for by using a custom base_url different from the domain we
are on
:param endpoint:
:param base_url:
:param kw:
:return:
"""
base_url = base_url or config("MAIL_EXTERNAL_BASE_URL")
_external = True if n... | python | def _url_for_email(endpoint, base_url=None, **kw):
"""
Create an external url_for by using a custom base_url different from the domain we
are on
:param endpoint:
:param base_url:
:param kw:
:return:
"""
base_url = base_url or config("MAIL_EXTERNAL_BASE_URL")
_external = True if n... | [
"def",
"_url_for_email",
"(",
"endpoint",
",",
"base_url",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"base_url",
"=",
"base_url",
"or",
"config",
"(",
"\"MAIL_EXTERNAL_BASE_URL\"",
")",
"_external",
"=",
"True",
"if",
"not",
"base_url",
"else",
"False",
... | Create an external url_for by using a custom base_url different from the domain we
are on
:param endpoint:
:param base_url:
:param kw:
:return: | [
"Create",
"an",
"external",
"url_for",
"by",
"using",
"a",
"custom",
"base_url",
"different",
"from",
"the",
"domain",
"we",
"are",
"on",
":",
"param",
"endpoint",
":",
":",
"param",
"base_url",
":",
":",
"param",
"kw",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L652-L666 | train | Create an external url_for by using a custom base_url different from the domain we
is on |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.change_username | def change_username(self, username):
"""
Change user's login email
:param user: AuthUser
:param email:
:return:
"""
def cb():
if self.login_method == "username" and "@" in username:
raise exceptions.AuthError(_("Username can't be an e... | python | def change_username(self, username):
"""
Change user's login email
:param user: AuthUser
:param email:
:return:
"""
def cb():
if self.login_method == "username" and "@" in username:
raise exceptions.AuthError(_("Username can't be an e... | [
"def",
"change_username",
"(",
"self",
",",
"username",
")",
":",
"def",
"cb",
"(",
")",
":",
"if",
"self",
".",
"login_method",
"==",
"\"username\"",
"and",
"\"@\"",
"in",
"username",
":",
"raise",
"exceptions",
".",
"AuthError",
"(",
"_",
"(",
"\"Usern... | Change user's login email
:param user: AuthUser
:param email:
:return: | [
"Change",
"user",
"s",
"login",
"email",
":",
"param",
"user",
":",
"AuthUser",
":",
"param",
"email",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L335-L365 | train | Change username of user |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.change_email | def change_email(self, email):
"""
Change user's login email
:param user: AuthUser
:param email:
:return:
"""
def cb():
if not utils.is_email_valid(email):
raise exceptions.AuthError("Email address invalid")
self.user.chang... | python | def change_email(self, email):
"""
Change user's login email
:param user: AuthUser
:param email:
:return:
"""
def cb():
if not utils.is_email_valid(email):
raise exceptions.AuthError("Email address invalid")
self.user.chang... | [
"def",
"change_email",
"(",
"self",
",",
"email",
")",
":",
"def",
"cb",
"(",
")",
":",
"if",
"not",
"utils",
".",
"is_email_valid",
"(",
"email",
")",
":",
"raise",
"exceptions",
".",
"AuthError",
"(",
"\"Email address invalid\"",
")",
"self",
".",
"use... | Change user's login email
:param user: AuthUser
:param email:
:return: | [
"Change",
"user",
"s",
"login",
"email",
":",
"param",
"user",
":",
"AuthUser",
":",
"param",
"email",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L367-L382 | train | Change user s login email |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.update_info | def update_info(self, _action=None, **kwargs):
"""
UPdate info
:param user:
:param email:
:return:
"""
def cb():
kwargs.pop("email", None)
kwargs.pop("username", None)
kwargs.pop("password_hash", None)
kwargs.pop("r... | python | def update_info(self, _action=None, **kwargs):
"""
UPdate info
:param user:
:param email:
:return:
"""
def cb():
kwargs.pop("email", None)
kwargs.pop("username", None)
kwargs.pop("password_hash", None)
kwargs.pop("r... | [
"def",
"update_info",
"(",
"self",
",",
"_action",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"cb",
"(",
")",
":",
"kwargs",
".",
"pop",
"(",
"\"email\"",
",",
"None",
")",
"kwargs",
".",
"pop",
"(",
"\"username\"",
",",
"None",
")",
... | UPdate info
:param user:
:param email:
:return: | [
"UPdate",
"info",
":",
"param",
"user",
":",
":",
"param",
"email",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L384-L401 | train | Update user info |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.change_password | def change_password(self, password):
"""
Change a user's password
:param user:
:param password:
:param password_confirm:
:return:
"""
def cb():
if not utils.is_password_valid(password):
raise exceptions.AuthError("Invalid Passw... | python | def change_password(self, password):
"""
Change a user's password
:param user:
:param password:
:param password_confirm:
:return:
"""
def cb():
if not utils.is_password_valid(password):
raise exceptions.AuthError("Invalid Passw... | [
"def",
"change_password",
"(",
"self",
",",
"password",
")",
":",
"def",
"cb",
"(",
")",
":",
"if",
"not",
"utils",
".",
"is_password_valid",
"(",
"password",
")",
":",
"raise",
"exceptions",
".",
"AuthError",
"(",
"\"Invalid Password\"",
")",
"self",
".",... | Change a user's password
:param user:
:param password:
:param password_confirm:
:return: | [
"Change",
"a",
"user",
"s",
"password",
":",
"param",
"user",
":",
":",
"param",
"password",
":",
":",
"param",
"password_confirm",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L403-L418 | train | Change a user s password |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.reset_password | def reset_password(self):
"""
Return the new random password that has been reset
:param user_login: AuthUserLogin
:return: string - the new password
"""
def cb():
password = get_random_password()
self.change_password(password)
return p... | python | def reset_password(self):
"""
Return the new random password that has been reset
:param user_login: AuthUserLogin
:return: string - the new password
"""
def cb():
password = get_random_password()
self.change_password(password)
return p... | [
"def",
"reset_password",
"(",
"self",
")",
":",
"def",
"cb",
"(",
")",
":",
"password",
"=",
"get_random_password",
"(",
")",
"self",
".",
"change_password",
"(",
"password",
")",
"return",
"password",
"return",
"signals",
".",
"user_update",
"(",
"self",
... | Return the new random password that has been reset
:param user_login: AuthUserLogin
:return: string - the new password | [
"Return",
"the",
"new",
"random",
"password",
"that",
"has",
"been",
"reset",
":",
"param",
"user_login",
":",
"AuthUserLogin",
":",
"return",
":",
"string",
"-",
"the",
"new",
"password"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L420-L432 | train | Reset the user s password |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.change_status | def change_status(self, status):
"""
Change the user's status
:param user:
:param email:
:return:
"""
def cb():
self.user.update(status=status)
return status
return signals.user_update(self, ACTIONS["STATUS"], cb,
... | python | def change_status(self, status):
"""
Change the user's status
:param user:
:param email:
:return:
"""
def cb():
self.user.update(status=status)
return status
return signals.user_update(self, ACTIONS["STATUS"], cb,
... | [
"def",
"change_status",
"(",
"self",
",",
"status",
")",
":",
"def",
"cb",
"(",
")",
":",
"self",
".",
"user",
".",
"update",
"(",
"status",
"=",
"status",
")",
"return",
"status",
"return",
"signals",
".",
"user_update",
"(",
"self",
",",
"ACTIONS",
... | Change the user's status
:param user:
:param email:
:return: | [
"Change",
"the",
"user",
"s",
"status",
":",
"param",
"user",
":",
":",
"param",
"email",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L434-L447 | train | Change the status of the user. |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.create_jwt | def create_jwt(self, expires_in=None):
"""
Create a secure timed JWT token that can be passed. It save the user id,
which later will be used to retrieve the data
:param user: AuthUser, the user's object
:param expires_in: - time in second for the token to expire
:return:... | python | def create_jwt(self, expires_in=None):
"""
Create a secure timed JWT token that can be passed. It save the user id,
which later will be used to retrieve the data
:param user: AuthUser, the user's object
:param expires_in: - time in second for the token to expire
:return:... | [
"def",
"create_jwt",
"(",
"self",
",",
"expires_in",
"=",
"None",
")",
":",
"s",
"=",
"utils",
".",
"sign_jwt",
"(",
"data",
"=",
"{",
"\"id\"",
":",
"self",
".",
"user",
".",
"id",
"}",
",",
"secret_key",
"=",
"get_jwt_secret",
"(",
")",
",",
"sal... | Create a secure timed JWT token that can be passed. It save the user id,
which later will be used to retrieve the data
:param user: AuthUser, the user's object
:param expires_in: - time in second for the token to expire
:return: string | [
"Create",
"a",
"secure",
"timed",
"JWT",
"token",
"that",
"can",
"be",
"passed",
".",
"It",
"save",
"the",
"user",
"id",
"which",
"later",
"will",
"be",
"used",
"to",
"retrieve",
"the",
"data"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L449-L462 | train | Create a secure timed JWT token that can be passed to the user |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.create_action_token | def create_action_token(self, action, expires_in):
"""
Create a url safe action token attached to the user
:param action:
:param expires_in:
:return:
"""
return utils.sign_url_safe(self.user.id,
secret_key=get_jwt_secret(),
... | python | def create_action_token(self, action, expires_in):
"""
Create a url safe action token attached to the user
:param action:
:param expires_in:
:return:
"""
return utils.sign_url_safe(self.user.id,
secret_key=get_jwt_secret(),
... | [
"def",
"create_action_token",
"(",
"self",
",",
"action",
",",
"expires_in",
")",
":",
"return",
"utils",
".",
"sign_url_safe",
"(",
"self",
".",
"user",
".",
"id",
",",
"secret_key",
"=",
"get_jwt_secret",
"(",
")",
",",
"salt",
"=",
"action",
",",
"exp... | Create a url safe action token attached to the user
:param action:
:param expires_in:
:return: | [
"Create",
"a",
"url",
"safe",
"action",
"token",
"attached",
"to",
"the",
"user",
":",
"param",
"action",
":",
":",
"param",
"expires_in",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L464-L474 | train | Create a url safe action token attached to the user |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.sign_data | def sign_data(self, data, expires_in=None, url_safe=True):
"""
To safely sign a user data. It will be signed with the user key
:param data: mixed
:param expires_in: The time for it to expire
:param url_safe: bool. If true it will allow it to be passed in URL
:return: str ... | python | def sign_data(self, data, expires_in=None, url_safe=True):
"""
To safely sign a user data. It will be signed with the user key
:param data: mixed
:param expires_in: The time for it to expire
:param url_safe: bool. If true it will allow it to be passed in URL
:return: str ... | [
"def",
"sign_data",
"(",
"self",
",",
"data",
",",
"expires_in",
"=",
"None",
",",
"url_safe",
"=",
"True",
")",
":",
"if",
"url_safe",
":",
"return",
"utils",
".",
"sign_url_safe",
"(",
"data",
",",
"secret_key",
"=",
"self",
".",
"secret_key",
",",
"... | To safely sign a user data. It will be signed with the user key
:param data: mixed
:param expires_in: The time for it to expire
:param url_safe: bool. If true it will allow it to be passed in URL
:return: str - the token/signed data | [
"To",
"safely",
"sign",
"a",
"user",
"data",
".",
"It",
"will",
"be",
"signed",
"with",
"the",
"user",
"key",
":",
"param",
"data",
":",
"mixed",
":",
"param",
"expires_in",
":",
"The",
"time",
"for",
"it",
"to",
"expire",
":",
"param",
"url_safe",
"... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L476-L493 | train | Signs a user data. |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.unsign_data | def unsign_data(self, data, url_safe=True):
"""
Retrieve the signed data. If it is expired, it will throw an exception
:param data: token/signed data
:param url_safe: bool. If true it will allow it to be passed in URL
:return: mixed, the data in its original form
"""
... | python | def unsign_data(self, data, url_safe=True):
"""
Retrieve the signed data. If it is expired, it will throw an exception
:param data: token/signed data
:param url_safe: bool. If true it will allow it to be passed in URL
:return: mixed, the data in its original form
"""
... | [
"def",
"unsign_data",
"(",
"self",
",",
"data",
",",
"url_safe",
"=",
"True",
")",
":",
"if",
"url_safe",
":",
"return",
"utils",
".",
"unsign_url_safe",
"(",
"data",
",",
"secret_key",
"=",
"self",
".",
"secret_key",
",",
"salt",
"=",
"self",
".",
"us... | Retrieve the signed data. If it is expired, it will throw an exception
:param data: token/signed data
:param url_safe: bool. If true it will allow it to be passed in URL
:return: mixed, the data in its original form | [
"Retrieve",
"the",
"signed",
"data",
".",
"If",
"it",
"is",
"expired",
"it",
"will",
"throw",
"an",
"exception",
":",
"param",
"data",
":",
"token",
"/",
"signed",
"data",
":",
"param",
"url_safe",
":",
"bool",
".",
"If",
"true",
"it",
"will",
"allow",... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L495-L509 | train | Retrieve the signed data. |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.signed_data_match | def signed_data_match(self, data, matched_data, url_safe=True):
"""
See if a data matched a signed one
:param data:
:param matched_data:
:param url_safe:
:return:
"""
try:
u_data = self.unsign_data(data, url_safe=url_safe)
return u_... | python | def signed_data_match(self, data, matched_data, url_safe=True):
"""
See if a data matched a signed one
:param data:
:param matched_data:
:param url_safe:
:return:
"""
try:
u_data = self.unsign_data(data, url_safe=url_safe)
return u_... | [
"def",
"signed_data_match",
"(",
"self",
",",
"data",
",",
"matched_data",
",",
"url_safe",
"=",
"True",
")",
":",
"try",
":",
"u_data",
"=",
"self",
".",
"unsign_data",
"(",
"data",
",",
"url_safe",
"=",
"url_safe",
")",
"return",
"u_data",
"==",
"match... | See if a data matched a signed one
:param data:
:param matched_data:
:param url_safe:
:return: | [
"See",
"if",
"a",
"data",
"matched",
"a",
"signed",
"one",
":",
"param",
"data",
":",
":",
"param",
"matched_data",
":",
":",
"param",
"url_safe",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L511-L523 | train | See if a data matched a signed oneova |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.send_email | def send_email(self, template, **kwargs):
"""
To send email to user
:param template:
:param kwargs:
:return:
"""
user_data = {
"id": self.id,
"username": self.username,
"name": self.name,
"first_name": self.first_nam... | python | def send_email(self, template, **kwargs):
"""
To send email to user
:param template:
:param kwargs:
:return:
"""
user_data = {
"id": self.id,
"username": self.username,
"name": self.name,
"first_name": self.first_nam... | [
"def",
"send_email",
"(",
"self",
",",
"template",
",",
"*",
"*",
"kwargs",
")",
":",
"user_data",
"=",
"{",
"\"id\"",
":",
"self",
".",
"id",
",",
"\"username\"",
":",
"self",
".",
"username",
",",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"first... | To send email to user
:param template:
:param kwargs:
:return: | [
"To",
"send",
"email",
"to",
"user",
":",
"param",
"template",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L525-L541 | train | Send email to user |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.send_password_reset | def send_password_reset(self, base_url=None, view_class=None, **kw):
"""
Reset a password and send email
:param user: AuthUser
:param email: str - The auth user login email
:param base_url: str - By default it will use the current url, base_url will allow custom url
:para... | python | def send_password_reset(self, base_url=None, view_class=None, **kw):
"""
Reset a password and send email
:param user: AuthUser
:param email: str - The auth user login email
:param base_url: str - By default it will use the current url, base_url will allow custom url
:para... | [
"def",
"send_password_reset",
"(",
"self",
",",
"base_url",
"=",
"None",
",",
"view_class",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"view",
"=",
"view_class",
"or",
"views",
".",
"auth",
".",
"Login",
"endpoint_reset",
"=",
"getattr",
"(",
"view",
... | Reset a password and send email
:param user: AuthUser
:param email: str - The auth user login email
:param base_url: str - By default it will use the current url, base_url will allow custom url
:param template: str - The email template
:param method: str - token or email - The me... | [
"Reset",
"a",
"password",
"and",
"send",
"email",
":",
"param",
"user",
":",
"AuthUser",
":",
"param",
"email",
":",
"str",
"-",
"The",
"auth",
"user",
"login",
"email",
":",
"param",
"base_url",
":",
"str",
"-",
"By",
"default",
"it",
"will",
"use",
... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L543-L584 | train | Send an email to reset a password and return the user s id |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel._create_verify_email_token_url | def _create_verify_email_token_url(self, base_url=None, view_class=None):
"""
To create a verify email token url
:param user: (object) AuthUser
:param base_url: a base_url to use instead of the native one
:param view_class: (obj) the view class, to allow build the url
:re... | python | def _create_verify_email_token_url(self, base_url=None, view_class=None):
"""
To create a verify email token url
:param user: (object) AuthUser
:param base_url: a base_url to use instead of the native one
:param view_class: (obj) the view class, to allow build the url
:re... | [
"def",
"_create_verify_email_token_url",
"(",
"self",
",",
"base_url",
"=",
"None",
",",
"view_class",
"=",
"None",
")",
":",
"view",
"=",
"view_class",
"or",
"views",
".",
"auth",
".",
"Login",
"endpoint",
"=",
"getattr",
"(",
"view",
",",
"\"verify_email\"... | To create a verify email token url
:param user: (object) AuthUser
:param base_url: a base_url to use instead of the native one
:param view_class: (obj) the view class, to allow build the url
:return: string | [
"To",
"create",
"a",
"verify",
"email",
"token",
"url",
":",
"param",
"user",
":",
"(",
"object",
")",
"AuthUser",
":",
"param",
"base_url",
":",
"a",
"base_url",
"to",
"use",
"instead",
"of",
"the",
"native",
"one",
":",
"param",
"view_class",
":",
"(... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L616-L634 | train | Create a verify email token url for the user |
mardix/Mocha | mocha/contrib/auth/__init__.py | UserModel.add_federation | def add_federation(self, provider, federated_id):
"""
Add federated login to the current user
:param provider:
:param federated_id:
:return:
"""
models.AuthUserFederation.new(user=self,
provider=provider,
... | python | def add_federation(self, provider, federated_id):
"""
Add federated login to the current user
:param provider:
:param federated_id:
:return:
"""
models.AuthUserFederation.new(user=self,
provider=provider,
... | [
"def",
"add_federation",
"(",
"self",
",",
"provider",
",",
"federated_id",
")",
":",
"models",
".",
"AuthUserFederation",
".",
"new",
"(",
"user",
"=",
"self",
",",
"provider",
"=",
"provider",
",",
"federated_id",
"=",
"federated_id",
")"
] | Add federated login to the current user
:param provider:
:param federated_id:
:return: | [
"Add",
"federated",
"login",
"to",
"the",
"current",
"user",
":",
"param",
"provider",
":",
":",
"param",
"federated_id",
":",
":",
"return",
":"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L636-L645 | train | Add federated login to the current user s user cache |
Kortemme-Lab/klab | klab/comms/mail.py | MailServer.sendgmail | def sendgmail(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = 'kortemmelab@gmail.com', pw_filepath = None):
'''For this function to work, the password for the gmail user must be colocated with this file or passed in.'''
smtpserver = smtpl... | python | def sendgmail(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = 'kortemmelab@gmail.com', pw_filepath = None):
'''For this function to work, the password for the gmail user must be colocated with this file or passed in.'''
smtpserver = smtpl... | [
"def",
"sendgmail",
"(",
"self",
",",
"subject",
",",
"recipients",
",",
"plaintext",
",",
"htmltext",
"=",
"None",
",",
"cc",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"useMIMEMultipart",
"=",
"True",
",",
"gmail_account",
"=",
"'kortemmelab@gmail.com'"... | For this function to work, the password for the gmail user must be colocated with this file or passed in. | [
"For",
"this",
"function",
"to",
"work",
"the",
"password",
"for",
"the",
"gmail",
"user",
"must",
"be",
"colocated",
"with",
"this",
"file",
"or",
"passed",
"in",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/comms/mail.py#L72-L95 | train | This function will send a gmail message to the recipients. |
adaptive-learning/proso-apps | proso_common/views.py | show_one | def show_one(request, post_process_fun, object_class, id, template='common_json.html'):
"""
Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
h... | python | def show_one(request, post_process_fun, object_class, id, template='common_json.html'):
"""
Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
h... | [
"def",
"show_one",
"(",
"request",
",",
"post_process_fun",
",",
"object_class",
",",
"id",
",",
"template",
"=",
"'common_json.html'",
")",
":",
"obj",
"=",
"get_object_or_404",
"(",
"object_class",
",",
"pk",
"=",
"id",
")",
"json",
"=",
"post_process_fun",
... | Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
html
turn on the HTML version of the API | [
"Return",
"object",
"of",
"the",
"given",
"type",
"with",
"the",
"specified",
"identifier",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L29-L43 | train | Show one object of the given type with the specified identifier. |
adaptive-learning/proso-apps | proso_common/views.py | show_more | def show_more(request, post_process_fun, get_fun, object_class, should_cache=True, template='common_json.html', to_json_kwargs=None):
"""
Return list of objects of the given type.
GET parameters:
limit:
number of returned objects (default 10, maximum 100)
page:
current page numb... | python | def show_more(request, post_process_fun, get_fun, object_class, should_cache=True, template='common_json.html', to_json_kwargs=None):
"""
Return list of objects of the given type.
GET parameters:
limit:
number of returned objects (default 10, maximum 100)
page:
current page numb... | [
"def",
"show_more",
"(",
"request",
",",
"post_process_fun",
",",
"get_fun",
",",
"object_class",
",",
"should_cache",
"=",
"True",
",",
"template",
"=",
"'common_json.html'",
",",
"to_json_kwargs",
"=",
"None",
")",
":",
"if",
"not",
"should_cache",
"and",
"'... | Return list of objects of the given type.
GET parameters:
limit:
number of returned objects (default 10, maximum 100)
page:
current page number
filter_column:
column name used to filter the results
filter_value:
value for the specified column used to filter t... | [
"Return",
"list",
"of",
"objects",
"of",
"the",
"given",
"type",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L46-L118 | train | Returns a list of objects of the given type. |
adaptive-learning/proso-apps | proso_common/views.py | log | def log(request):
"""
Log an event from the client to the server.
POST parameters (JSON keys):
message:
description (str) of the logged event
level:
debug|info|warn|error
data:
additional data (JSON) describing the logged event
"""
if request.method == "POS... | python | def log(request):
"""
Log an event from the client to the server.
POST parameters (JSON keys):
message:
description (str) of the logged event
level:
debug|info|warn|error
data:
additional data (JSON) describing the logged event
"""
if request.method == "POS... | [
"def",
"log",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"log_dict",
"=",
"json_body",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"if",
"'message'",
"not",
"in",
"log_dict",
":",
"retur... | Log an event from the client to the server.
POST parameters (JSON keys):
message:
description (str) of the logged event
level:
debug|info|warn|error
data:
additional data (JSON) describing the logged event | [
"Log",
"an",
"event",
"from",
"the",
"client",
"to",
"the",
"server",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L122-L154 | train | Logs an event from the client to the server. |
adaptive-learning/proso-apps | proso_common/views.py | custom_config | def custom_config(request):
"""
Save user-specific configuration property.
POST parameters (JSON keys):
app_name: application name for which the configuration property is
valid (e.g., proso_models)
key: name of the property (e.g., predictive_model.class)
value: value of ... | python | def custom_config(request):
"""
Save user-specific configuration property.
POST parameters (JSON keys):
app_name: application name for which the configuration property is
valid (e.g., proso_models)
key: name of the property (e.g., predictive_model.class)
value: value of ... | [
"def",
"custom_config",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"config_dict",
"=",
"json_body",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"CustomConfig",
".",
"objects",
".",
"try_create",... | Save user-specific configuration property.
POST parameters (JSON keys):
app_name: application name for which the configuration property is
valid (e.g., proso_models)
key: name of the property (e.g., predictive_model.class)
value: value of the property (number, string, boolean, .... | [
"Save",
"user",
"-",
"specific",
"configuration",
"property",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L158-L185 | train | Custom configuration for a specific user - specific configuration property. |
adaptive-learning/proso-apps | proso_common/views.py | languages | def languages(request):
"""
Returns languages that are available in the system.
Returns Dict: language_code -> domain
"""
return render_json(request,
settings.LANGUAGE_DOMAINS if hasattr(settings, 'LANGUAGE_DOMAINS') else
{"error": "Languages are not se... | python | def languages(request):
"""
Returns languages that are available in the system.
Returns Dict: language_code -> domain
"""
return render_json(request,
settings.LANGUAGE_DOMAINS if hasattr(settings, 'LANGUAGE_DOMAINS') else
{"error": "Languages are not se... | [
"def",
"languages",
"(",
"request",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"settings",
".",
"LANGUAGE_DOMAINS",
"if",
"hasattr",
"(",
"settings",
",",
"'LANGUAGE_DOMAINS'",
")",
"else",
"{",
"\"error\"",
":",
"\"Languages are not set. (Set LANGUAGE_... | Returns languages that are available in the system.
Returns Dict: language_code -> domain | [
"Returns",
"languages",
"that",
"are",
"available",
"in",
"the",
"system",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L192-L201 | train | Returns a list of languages that are available in the system. |
reillysiemens/layabout | examples/early-connection/example.py | channel_to_id | def channel_to_id(slack, channel):
""" Surely there's a better way to do this... """
channels = slack.api_call('channels.list').get('channels') or []
groups = slack.api_call('groups.list').get('groups') or []
if not channels and not groups:
raise RuntimeError("Couldn't get channels and groups."... | python | def channel_to_id(slack, channel):
""" Surely there's a better way to do this... """
channels = slack.api_call('channels.list').get('channels') or []
groups = slack.api_call('groups.list').get('groups') or []
if not channels and not groups:
raise RuntimeError("Couldn't get channels and groups."... | [
"def",
"channel_to_id",
"(",
"slack",
",",
"channel",
")",
":",
"channels",
"=",
"slack",
".",
"api_call",
"(",
"'channels.list'",
")",
".",
"get",
"(",
"'channels'",
")",
"or",
"[",
"]",
"groups",
"=",
"slack",
".",
"api_call",
"(",
"'groups.list'",
")"... | Surely there's a better way to do this... | [
"Surely",
"there",
"s",
"a",
"better",
"way",
"to",
"do",
"this",
"..."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/examples/early-connection/example.py#L15-L28 | train | Convert a Slack channel to an ID. |
reillysiemens/layabout | examples/early-connection/example.py | send_message | def send_message(slack):
""" Prompt for and send a message to a channel. """
channel = input('Which channel would you like to message? ')
message = input('What should the message be? ')
channel_id = channel_to_id(slack, channel)
print(f"Sending message to #{channel} (id: {channel_id})!")
slack.... | python | def send_message(slack):
""" Prompt for and send a message to a channel. """
channel = input('Which channel would you like to message? ')
message = input('What should the message be? ')
channel_id = channel_to_id(slack, channel)
print(f"Sending message to #{channel} (id: {channel_id})!")
slack.... | [
"def",
"send_message",
"(",
"slack",
")",
":",
"channel",
"=",
"input",
"(",
"'Which channel would you like to message? '",
")",
"message",
"=",
"input",
"(",
"'What should the message be? '",
")",
"channel_id",
"=",
"channel_to_id",
"(",
"slack",
",",
"channel",
")... | Prompt for and send a message to a channel. | [
"Prompt",
"for",
"and",
"send",
"a",
"message",
"to",
"a",
"channel",
"."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/examples/early-connection/example.py#L31-L38 | train | Prompt for and send a message to a channel. |
cozy/python_cozy_management | cozy_management/cli.py | main | def main():
'''
Main part of command line utility
'''
arguments = docopt.docopt(__doc__, version='Naval Fate 2.0')
if arguments['show_diag']:
diag.show()
if arguments['show_reporting']:
diag.reporting()
diag.show()
if arguments['ping_couchdb']:
try:
... | python | def main():
'''
Main part of command line utility
'''
arguments = docopt.docopt(__doc__, version='Naval Fate 2.0')
if arguments['show_diag']:
diag.show()
if arguments['show_reporting']:
diag.reporting()
diag.show()
if arguments['ping_couchdb']:
try:
... | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"docopt",
".",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"'Naval Fate 2.0'",
")",
"if",
"arguments",
"[",
"'show_diag'",
"]",
":",
"diag",
".",
"show",
"(",
")",
"if",
"arguments",
"[",
"'show_reportin... | Main part of command line utility | [
"Main",
"part",
"of",
"command",
"line",
"utility"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/cli.py#L61-L239 | train | This function is the entry point for the Naval Fate 2. 0 command line utility. It is the entry point for the Naval Fate 2. 0 command line utility. |
truveris/py-mdstat | mdstat/device.py | parse_device | def parse_device(lines):
"""Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and personality of the
device (... | python | def parse_device(lines):
"""Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and personality of the
device (... | [
"def",
"parse_device",
"(",
"lines",
")",
":",
"name",
",",
"status_line",
",",
"device",
"=",
"parse_device_header",
"(",
"lines",
".",
"pop",
"(",
"0",
")",
")",
"# There are edge cases when the device list is empty and the status line is",
"# merged with the header lin... | Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and personality of the
device (e.g. RAID1 vs RAID5, healthy vs ... | [
"Parse",
"all",
"the",
"lines",
"of",
"a",
"device",
"block",
"."
] | 881af99d1168694d2f38e606af377ef6cabe2297 | https://github.com/truveris/py-mdstat/blob/881af99d1168694d2f38e606af377ef6cabe2297/mdstat/device.py#L14-L51 | train | Parse all the lines of a device block. |
trendels/rhino | rhino/http.py | parse_etag_header | def parse_etag_header(header):
"""Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
... | python | def parse_etag_header(header):
"""Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
... | [
"def",
"parse_etag_header",
"(",
"header",
")",
":",
"m",
"=",
"etag_header_re",
".",
"match",
"(",
"header",
".",
"strip",
"(",
")",
")",
"if",
"not",
"m",
":",
"return",
"[",
"]",
"if",
"m",
".",
"group",
"(",
"1",
")",
":",
"# star",
"return",
... | Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
off. Returns an empty list if the hea... | [
"Parse",
"a",
"header",
"containing",
"one",
"or",
"more",
"ETags",
"or",
"a",
"wildcard",
"(",
"*",
")",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L31-L57 | train | Parse an ETag header. |
trendels/rhino | rhino/http.py | match_etag | def match_etag(etag, header, weak=False):
"""Try to match an ETag against a header value.
If `weak` is True, uses the weak comparison function.
"""
if etag is None:
return False
m = etag_re.match(etag)
if not m:
raise ValueError("Not a well-formed ETag: '%s'" % etag)
(is_wea... | python | def match_etag(etag, header, weak=False):
"""Try to match an ETag against a header value.
If `weak` is True, uses the weak comparison function.
"""
if etag is None:
return False
m = etag_re.match(etag)
if not m:
raise ValueError("Not a well-formed ETag: '%s'" % etag)
(is_wea... | [
"def",
"match_etag",
"(",
"etag",
",",
"header",
",",
"weak",
"=",
"False",
")",
":",
"if",
"etag",
"is",
"None",
":",
"return",
"False",
"m",
"=",
"etag_re",
".",
"match",
"(",
"etag",
")",
"if",
"not",
"m",
":",
"raise",
"ValueError",
"(",
"\"Not... | Try to match an ETag against a header value.
If `weak` is True, uses the weak comparison function. | [
"Try",
"to",
"match",
"an",
"ETag",
"against",
"a",
"header",
"value",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L60-L79 | train | Try to match an ETag against a header value. |
trendels/rhino | rhino/http.py | datetime_to_httpdate | def datetime_to_httpdate(dt):
"""Convert datetime.datetime or Unix timestamp to HTTP date."""
if isinstance(dt, (int, float)):
return format_date_time(dt)
elif isinstance(dt, datetime):
return format_date_time(datetime_to_timestamp(dt))
else:
raise TypeError("expected datetime.da... | python | def datetime_to_httpdate(dt):
"""Convert datetime.datetime or Unix timestamp to HTTP date."""
if isinstance(dt, (int, float)):
return format_date_time(dt)
elif isinstance(dt, datetime):
return format_date_time(datetime_to_timestamp(dt))
else:
raise TypeError("expected datetime.da... | [
"def",
"datetime_to_httpdate",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"format_date_time",
"(",
"dt",
")",
"elif",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"return",
"format... | Convert datetime.datetime or Unix timestamp to HTTP date. | [
"Convert",
"datetime",
".",
"datetime",
"or",
"Unix",
"timestamp",
"to",
"HTTP",
"date",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L99-L107 | train | Convert datetime. datetime or Unix timestamp to HTTP date. |
trendels/rhino | rhino/http.py | timedelta_to_httpdate | def timedelta_to_httpdate(td):
"""Convert datetime.timedelta or number of seconds to HTTP date.
Returns an HTTP date in the future.
"""
if isinstance(td, (int, float)):
return format_date_time(time.time() + td)
elif isinstance(td, timedelta):
return format_date_time(time.time() + to... | python | def timedelta_to_httpdate(td):
"""Convert datetime.timedelta or number of seconds to HTTP date.
Returns an HTTP date in the future.
"""
if isinstance(td, (int, float)):
return format_date_time(time.time() + td)
elif isinstance(td, timedelta):
return format_date_time(time.time() + to... | [
"def",
"timedelta_to_httpdate",
"(",
"td",
")",
":",
"if",
"isinstance",
"(",
"td",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"format_date_time",
"(",
"time",
".",
"time",
"(",
")",
"+",
"td",
")",
"elif",
"isinstance",
"(",
"td",
",",
... | Convert datetime.timedelta or number of seconds to HTTP date.
Returns an HTTP date in the future. | [
"Convert",
"datetime",
".",
"timedelta",
"or",
"number",
"of",
"seconds",
"to",
"HTTP",
"date",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L110-L121 | train | Convert datetime. timedelta or number of seconds to HTTP date. |
trendels/rhino | rhino/http.py | cache_control | def cache_control(max_age=None, private=False, public=False, s_maxage=None,
must_revalidate=False, proxy_revalidate=False, no_cache=False,
no_store=False):
"""Generate the value for a Cache-Control header.
Example:
>>> from rhino.http import cache_control as cc
>>> from datetim... | python | def cache_control(max_age=None, private=False, public=False, s_maxage=None,
must_revalidate=False, proxy_revalidate=False, no_cache=False,
no_store=False):
"""Generate the value for a Cache-Control header.
Example:
>>> from rhino.http import cache_control as cc
>>> from datetim... | [
"def",
"cache_control",
"(",
"max_age",
"=",
"None",
",",
"private",
"=",
"False",
",",
"public",
"=",
"False",
",",
"s_maxage",
"=",
"None",
",",
"must_revalidate",
"=",
"False",
",",
"proxy_revalidate",
"=",
"False",
",",
"no_cache",
"=",
"False",
",",
... | Generate the value for a Cache-Control header.
Example:
>>> from rhino.http import cache_control as cc
>>> from datetime import timedelta
>>> cc(public=1, max_age=3600)
'public, max-age=3600'
>>> cc(public=1, max_age=timedelta(hours=1))
'public, max-age=3600'
... | [
"Generate",
"the",
"value",
"for",
"a",
"Cache",
"-",
"Control",
"header",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L124-L156 | train | Generate the value for a Cache - Control header. |
chrillux/brottsplatskartan | brottsplatskartan/__init__.py | BrottsplatsKartan.get_incidents | def get_incidents(self) -> Union[list, bool]:
""" Get today's incidents. """
brotts_entries_left = True
incidents_today = []
url = self.url
while brotts_entries_left:
requests_response = requests.get(
url, params=self.parameters)
rate_li... | python | def get_incidents(self) -> Union[list, bool]:
""" Get today's incidents. """
brotts_entries_left = True
incidents_today = []
url = self.url
while brotts_entries_left:
requests_response = requests.get(
url, params=self.parameters)
rate_li... | [
"def",
"get_incidents",
"(",
"self",
")",
"->",
"Union",
"[",
"list",
",",
"bool",
"]",
":",
"brotts_entries_left",
"=",
"True",
"incidents_today",
"=",
"[",
"]",
"url",
"=",
"self",
".",
"url",
"while",
"brotts_entries_left",
":",
"requests_response",
"=",
... | Get today's incidents. | [
"Get",
"today",
"s",
"incidents",
"."
] | f38df4debd1799ddb384e467999d601cffbe9d94 | https://github.com/chrillux/brottsplatskartan/blob/f38df4debd1799ddb384e467999d601cffbe9d94/brottsplatskartan/__init__.py#L42-L92 | train | Get the incidents of the current page. |
TheGhouls/oct | oct/utilities/newproject.py | from_template | def from_template(args):
"""Create a new oct project from existing template
:param Namespace args: command line arguments
"""
project_name = args.name
template = args.template
with tarfile.open(template) as tar:
prefix = os.path.commonprefix(tar.getnames())
check_template(tar.g... | python | def from_template(args):
"""Create a new oct project from existing template
:param Namespace args: command line arguments
"""
project_name = args.name
template = args.template
with tarfile.open(template) as tar:
prefix = os.path.commonprefix(tar.getnames())
check_template(tar.g... | [
"def",
"from_template",
"(",
"args",
")",
":",
"project_name",
"=",
"args",
".",
"name",
"template",
"=",
"args",
".",
"template",
"with",
"tarfile",
".",
"open",
"(",
"template",
")",
"as",
"tar",
":",
"prefix",
"=",
"os",
".",
"path",
".",
"commonpre... | Create a new oct project from existing template
:param Namespace args: command line arguments | [
"Create",
"a",
"new",
"oct",
"project",
"from",
"existing",
"template"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/utilities/newproject.py#L39-L50 | train | Create a new oct project from a template file |
TheGhouls/oct | oct/utilities/newproject.py | from_oct | def from_oct(args):
"""Create a new oct project
:param Namespace args: the command line arguments
"""
project_name = args.name
env = Environment(loader=PackageLoader('oct.utilities', 'templates'))
config_content = env.get_template('configuration/config.json').render(script_name='v_user.py')
... | python | def from_oct(args):
"""Create a new oct project
:param Namespace args: the command line arguments
"""
project_name = args.name
env = Environment(loader=PackageLoader('oct.utilities', 'templates'))
config_content = env.get_template('configuration/config.json').render(script_name='v_user.py')
... | [
"def",
"from_oct",
"(",
"args",
")",
":",
"project_name",
"=",
"args",
".",
"name",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"PackageLoader",
"(",
"'oct.utilities'",
",",
"'templates'",
")",
")",
"config_content",
"=",
"env",
".",
"get_template",
"(",
... | Create a new oct project
:param Namespace args: the command line arguments | [
"Create",
"a",
"new",
"oct",
"project"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/utilities/newproject.py#L53-L85 | train | Create a new oct project containing all the necessary information. |
clement-alexandre/TotemBionet | totembionet/src/resource_table/resource_table_with_model.py | ResourceTableWithModel.as_data_frame | def as_data_frame(self) -> pandas.DataFrame:
""" Create a panda DataFrame representation of the resource table. """
header_gene = {}
header_multiplex = {}
headr_transitions = {}
for gene in self.influence_graph.genes:
header_gene[gene] = repr(gene)
header_... | python | def as_data_frame(self) -> pandas.DataFrame:
""" Create a panda DataFrame representation of the resource table. """
header_gene = {}
header_multiplex = {}
headr_transitions = {}
for gene in self.influence_graph.genes:
header_gene[gene] = repr(gene)
header_... | [
"def",
"as_data_frame",
"(",
"self",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"header_gene",
"=",
"{",
"}",
"header_multiplex",
"=",
"{",
"}",
"headr_transitions",
"=",
"{",
"}",
"for",
"gene",
"in",
"self",
".",
"influence_graph",
".",
"genes",
":",
... | Create a panda DataFrame representation of the resource table. | [
"Create",
"a",
"panda",
"DataFrame",
"representation",
"of",
"the",
"resource",
"table",
"."
] | f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table_with_model.py#L25-L43 | train | Create a panda DataFrame representation of the resource table. |
uw-it-aca/uw-restclients-sws | uw_sws/notice.py | _associate_short_long | def _associate_short_long(notices):
"""
If a notice is type ${1}Short, associate with its Long notice
in an attribute called long_notice.
"""
for notice in notices:
if notice.notice_type is not None and\
notice.notice_category == "StudentFinAid" and\
notice.no... | python | def _associate_short_long(notices):
"""
If a notice is type ${1}Short, associate with its Long notice
in an attribute called long_notice.
"""
for notice in notices:
if notice.notice_type is not None and\
notice.notice_category == "StudentFinAid" and\
notice.no... | [
"def",
"_associate_short_long",
"(",
"notices",
")",
":",
"for",
"notice",
"in",
"notices",
":",
"if",
"notice",
".",
"notice_type",
"is",
"not",
"None",
"and",
"notice",
".",
"notice_category",
"==",
"\"StudentFinAid\"",
"and",
"notice",
".",
"notice_type",
"... | If a notice is type ${1}Short, associate with its Long notice
in an attribute called long_notice. | [
"If",
"a",
"notice",
"is",
"type",
"$",
"{",
"1",
"}",
"Short",
"associate",
"with",
"its",
"Long",
"notice",
"in",
"an",
"attribute",
"called",
"long_notice",
"."
] | 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/notice.py#L72-L83 | train | Associate a Short notice with its Long notice. |
assamite/creamas | creamas/examples/spiro/spiro_agent_mp.py | SpiroAgent.create | def create(self, r, r_, R=200):
'''Create new spirograph image with given arguments. Returned image is
scaled to agent's preferred image size.
'''
x, y = give_dots(R, r, r_, spins=20)
xy = np.array([x, y]).T
xy = np.array(np.around(xy), dtype=np.int64)
xy = xy[(xy... | python | def create(self, r, r_, R=200):
'''Create new spirograph image with given arguments. Returned image is
scaled to agent's preferred image size.
'''
x, y = give_dots(R, r, r_, spins=20)
xy = np.array([x, y]).T
xy = np.array(np.around(xy), dtype=np.int64)
xy = xy[(xy... | [
"def",
"create",
"(",
"self",
",",
"r",
",",
"r_",
",",
"R",
"=",
"200",
")",
":",
"x",
",",
"y",
"=",
"give_dots",
"(",
"R",
",",
"r",
",",
"r_",
",",
"spins",
"=",
"20",
")",
"xy",
"=",
"np",
".",
"array",
"(",
"[",
"x",
",",
"y",
"]"... | Create new spirograph image with given arguments. Returned image is
scaled to agent's preferred image size. | [
"Create",
"new",
"spirograph",
"image",
"with",
"given",
"arguments",
".",
"Returned",
"image",
"is",
"scaled",
"to",
"agent",
"s",
"preferred",
"image",
"size",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent_mp.py#L140-L155 | train | Create new spirograph image with given arguments. Returned image is
scaled to agent s preferred image size. |
assamite/creamas | creamas/examples/spiro/spiro_agent_mp.py | SpiroAgent.randomize_args | def randomize_args(self):
'''Get new parameters for spirograph generation near agent's current
location (*spiro_args*).
'''
args = self.spiro_args + np.random.normal(0, self.move_radius,
self.spiro_args.shape)
np.clip(args, -199, ... | python | def randomize_args(self):
'''Get new parameters for spirograph generation near agent's current
location (*spiro_args*).
'''
args = self.spiro_args + np.random.normal(0, self.move_radius,
self.spiro_args.shape)
np.clip(args, -199, ... | [
"def",
"randomize_args",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"spiro_args",
"+",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"self",
".",
"move_radius",
",",
"self",
".",
"spiro_args",
".",
"shape",
")",
"np",
".",
"clip",
"(",
"... | Get new parameters for spirograph generation near agent's current
location (*spiro_args*). | [
"Get",
"new",
"parameters",
"for",
"spirograph",
"generation",
"near",
"agent",
"s",
"current",
"location",
"(",
"*",
"spiro_args",
"*",
")",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent_mp.py#L157-L168 | train | Get new parameters for spirograph generation near agent s current
location. |
assamite/creamas | creamas/examples/spiro/spiro_agent_mp.py | SpiroAgent.hedonic_value | def hedonic_value(self, novelty):
'''Given the agent's desired novelty, how good the novelty value is.
Not used if *desired_novelty*=-1
'''
lmax = gaus_pdf(self.desired_novelty, self.desired_novelty, 4)
pdf = gaus_pdf(novelty, self.desired_novelty, 4)
return pdf / lmax | python | def hedonic_value(self, novelty):
'''Given the agent's desired novelty, how good the novelty value is.
Not used if *desired_novelty*=-1
'''
lmax = gaus_pdf(self.desired_novelty, self.desired_novelty, 4)
pdf = gaus_pdf(novelty, self.desired_novelty, 4)
return pdf / lmax | [
"def",
"hedonic_value",
"(",
"self",
",",
"novelty",
")",
":",
"lmax",
"=",
"gaus_pdf",
"(",
"self",
".",
"desired_novelty",
",",
"self",
".",
"desired_novelty",
",",
"4",
")",
"pdf",
"=",
"gaus_pdf",
"(",
"novelty",
",",
"self",
".",
"desired_novelty",
... | Given the agent's desired novelty, how good the novelty value is.
Not used if *desired_novelty*=-1 | [
"Given",
"the",
"agent",
"s",
"desired",
"novelty",
"how",
"good",
"the",
"novelty",
"value",
"is",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent_mp.py#L170-L177 | train | Given the agent s desired novelty returns how good the novelty value is. |
assamite/creamas | creamas/examples/spiro/spiro_agent_mp.py | SpiroAgent.novelty | def novelty(self, img):
'''Image's distance to the agent's short-term memory. Usually distance
to the closest object/prototypical object model in the memory.
'''
dist = self.stmem.distance(img.flatten())
return dist | python | def novelty(self, img):
'''Image's distance to the agent's short-term memory. Usually distance
to the closest object/prototypical object model in the memory.
'''
dist = self.stmem.distance(img.flatten())
return dist | [
"def",
"novelty",
"(",
"self",
",",
"img",
")",
":",
"dist",
"=",
"self",
".",
"stmem",
".",
"distance",
"(",
"img",
".",
"flatten",
"(",
")",
")",
"return",
"dist"
] | Image's distance to the agent's short-term memory. Usually distance
to the closest object/prototypical object model in the memory. | [
"Image",
"s",
"distance",
"to",
"the",
"agent",
"s",
"short",
"-",
"term",
"memory",
".",
"Usually",
"distance",
"to",
"the",
"closest",
"object",
"/",
"prototypical",
"object",
"model",
"in",
"the",
"memory",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent_mp.py#L179-L184 | train | Image s distance to the agent s short - term memory. Usually distance
to the closest object model in the memory. |
assamite/creamas | creamas/examples/spiro/spiro_agent_mp.py | SpiroAgent.evaluate | def evaluate(self, artifact):
'''Evaluate the artifact with respect to the agents short term memory.
Returns value in [0, 1].
'''
if self.desired_novelty > 0:
return self.hedonic_value(self.novelty(artifact.obj))
return self.novelty(artifact.obj) / self.img_size, Non... | python | def evaluate(self, artifact):
'''Evaluate the artifact with respect to the agents short term memory.
Returns value in [0, 1].
'''
if self.desired_novelty > 0:
return self.hedonic_value(self.novelty(artifact.obj))
return self.novelty(artifact.obj) / self.img_size, Non... | [
"def",
"evaluate",
"(",
"self",
",",
"artifact",
")",
":",
"if",
"self",
".",
"desired_novelty",
">",
"0",
":",
"return",
"self",
".",
"hedonic_value",
"(",
"self",
".",
"novelty",
"(",
"artifact",
".",
"obj",
")",
")",
"return",
"self",
".",
"novelty"... | Evaluate the artifact with respect to the agents short term memory.
Returns value in [0, 1]. | [
"Evaluate",
"the",
"artifact",
"with",
"respect",
"to",
"the",
"agents",
"short",
"term",
"memory",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent_mp.py#L186-L193 | train | Evaluate the artifact with respect to the agents short term memory. Returns value in [ 0 1 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.