repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
sernst/cauldron
cauldron/render/texts.py
markdown
def markdown( source: str = None, source_path: str = None, preserve_lines: bool = False, font_size: float = None, **kwargs ) -> dict: """ Renders a markdown file with support for Jinja2 templating. Any keyword arguments will be passed to Jinja2 for templating prior to...
python
def markdown( source: str = None, source_path: str = None, preserve_lines: bool = False, font_size: float = None, **kwargs ) -> dict: """ Renders a markdown file with support for Jinja2 templating. Any keyword arguments will be passed to Jinja2 for templating prior to...
[ "def", "markdown", "(", "source", ":", "str", "=", "None", ",", "source_path", ":", "str", "=", "None", ",", "preserve_lines", ":", "bool", "=", "False", ",", "font_size", ":", "float", "=", "None", ",", "*", "*", "kwargs", ")", "->", "dict", ":", ...
Renders a markdown file with support for Jinja2 templating. Any keyword arguments will be passed to Jinja2 for templating prior to rendering the markdown to HTML for display within the notebook. :param source: A string of markdown text that should be rendered to HTML for notebook display. ...
[ "Renders", "a", "markdown", "file", "with", "support", "for", "Jinja2", "templating", ".", "Any", "keyword", "arguments", "will", "be", "passed", "to", "Jinja2", "for", "templating", "prior", "to", "rendering", "the", "markdown", "to", "HTML", "for", "display"...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/texts.py#L156-L261
sernst/cauldron
setup.py
populate_extra_files
def populate_extra_files(): """ Creates a list of non-python data files to include in package distribution """ out = ['cauldron/settings.json'] for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True): out.append(entry) for entry in glob.iglob('cauldron/resources/te...
python
def populate_extra_files(): """ Creates a list of non-python data files to include in package distribution """ out = ['cauldron/settings.json'] for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True): out.append(entry) for entry in glob.iglob('cauldron/resources/te...
[ "def", "populate_extra_files", "(", ")", ":", "out", "=", "[", "'cauldron/settings.json'", "]", "for", "entry", "in", "glob", ".", "iglob", "(", "'cauldron/resources/examples/**/*'", ",", "recursive", "=", "True", ")", ":", "out", ".", "append", "(", "entry", ...
Creates a list of non-python data files to include in package distribution
[ "Creates", "a", "list", "of", "non", "-", "python", "data", "files", "to", "include", "in", "package", "distribution" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/setup.py#L39-L55
sernst/cauldron
cauldron/cli/commands/steps/renaming.py
create_rename_entry
def create_rename_entry( step: 'projects.ProjectStep', insertion_index: int = None, stash_path: str = None ) -> typing.Union[None, STEP_RENAME]: """ Creates a STEP_RENAME for the given ProjectStep instance :param step: The ProjectStep instance for which the STEP_RENAME will ...
python
def create_rename_entry( step: 'projects.ProjectStep', insertion_index: int = None, stash_path: str = None ) -> typing.Union[None, STEP_RENAME]: """ Creates a STEP_RENAME for the given ProjectStep instance :param step: The ProjectStep instance for which the STEP_RENAME will ...
[ "def", "create_rename_entry", "(", "step", ":", "'projects.ProjectStep'", ",", "insertion_index", ":", "int", "=", "None", ",", "stash_path", ":", "str", "=", "None", ")", "->", "typing", ".", "Union", "[", "None", ",", "STEP_RENAME", "]", ":", "project", ...
Creates a STEP_RENAME for the given ProjectStep instance :param step: The ProjectStep instance for which the STEP_RENAME will be created :param insertion_index: An optional index where a step will be inserted as part of this renaming process. Allows files to be renamed prior to the inse...
[ "Creates", "a", "STEP_RENAME", "for", "the", "given", "ProjectStep", "instance" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commands/steps/renaming.py#L24-L76
sernst/cauldron
cauldron/cli/commands/steps/renaming.py
synchronize_step_names
def synchronize_step_names( project: 'projects.Project', insert_index: int = None ) -> Response: """ :param project: :param insert_index: """ response = Response() response.returned = dict() if not project.naming_scheme: return response create_mapper_func = fun...
python
def synchronize_step_names( project: 'projects.Project', insert_index: int = None ) -> Response: """ :param project: :param insert_index: """ response = Response() response.returned = dict() if not project.naming_scheme: return response create_mapper_func = fun...
[ "def", "synchronize_step_names", "(", "project", ":", "'projects.Project'", ",", "insert_index", ":", "int", "=", "None", ")", "->", "Response", ":", "response", "=", "Response", "(", ")", "response", ".", "returned", "=", "dict", "(", ")", "if", "not", "p...
:param project: :param insert_index:
[ ":", "param", "project", ":", ":", "param", "insert_index", ":" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commands/steps/renaming.py#L173-L226
sernst/cauldron
cauldron/cli/sync/comm.py
assemble_url
def assemble_url( endpoint: str, remote_connection: 'environ.RemoteConnection' = None ) -> str: """ Assembles a fully-resolved remote connection URL from the given endpoint and remote_connection structure. If the remote_connection is omitted, the global remote_connection object stored in...
python
def assemble_url( endpoint: str, remote_connection: 'environ.RemoteConnection' = None ) -> str: """ Assembles a fully-resolved remote connection URL from the given endpoint and remote_connection structure. If the remote_connection is omitted, the global remote_connection object stored in...
[ "def", "assemble_url", "(", "endpoint", ":", "str", ",", "remote_connection", ":", "'environ.RemoteConnection'", "=", "None", ")", "->", "str", ":", "url_root", "=", "(", "remote_connection", ".", "url", "if", "remote_connection", "else", "environ", ".", "remote...
Assembles a fully-resolved remote connection URL from the given endpoint and remote_connection structure. If the remote_connection is omitted, the global remote_connection object stored in the environ module will be used in its place. :param endpoint: The endpoint for the API call :param re...
[ "Assembles", "a", "fully", "-", "resolved", "remote", "connection", "URL", "from", "the", "given", "endpoint", "and", "remote_connection", "structure", ".", "If", "the", "remote_connection", "is", "omitted", "the", "global", "remote_connection", "object", "stored", ...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/comm.py#L6-L37
sernst/cauldron
cauldron/cli/sync/comm.py
parse_http_response
def parse_http_response(http_response: HttpResponse) -> 'environ.Response': """ Returns a Cauldron response object parsed from the serialized JSON data specified in the http_response argument. If the response doesn't contain valid Cauldron response data, an error Cauldron response object is returned...
python
def parse_http_response(http_response: HttpResponse) -> 'environ.Response': """ Returns a Cauldron response object parsed from the serialized JSON data specified in the http_response argument. If the response doesn't contain valid Cauldron response data, an error Cauldron response object is returned...
[ "def", "parse_http_response", "(", "http_response", ":", "HttpResponse", ")", "->", "'environ.Response'", ":", "try", ":", "response", "=", "environ", ".", "Response", ".", "deserialize", "(", "http_response", ".", "json", "(", ")", ")", "except", "Exception", ...
Returns a Cauldron response object parsed from the serialized JSON data specified in the http_response argument. If the response doesn't contain valid Cauldron response data, an error Cauldron response object is returned instead. :param http_response: The response object from an http request th...
[ "Returns", "a", "Cauldron", "response", "object", "parsed", "from", "the", "serialized", "JSON", "data", "specified", "in", "the", "http_response", "argument", ".", "If", "the", "response", "doesn", "t", "contain", "valid", "Cauldron", "response", "data", "an", ...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/comm.py#L40-L65
sernst/cauldron
cauldron/cli/sync/comm.py
send_request
def send_request( endpoint: str, data: dict = None, remote_connection: 'environ.RemoteConnection' = None, method: str = None, timeout: int = 10, max_retries: int = 10, **kwargs ) -> 'environ.Response': """ Sends a request to the remote kernel specified by ...
python
def send_request( endpoint: str, data: dict = None, remote_connection: 'environ.RemoteConnection' = None, method: str = None, timeout: int = 10, max_retries: int = 10, **kwargs ) -> 'environ.Response': """ Sends a request to the remote kernel specified by ...
[ "def", "send_request", "(", "endpoint", ":", "str", ",", "data", ":", "dict", "=", "None", ",", "remote_connection", ":", "'environ.RemoteConnection'", "=", "None", ",", "method", ":", "str", "=", "None", ",", "timeout", ":", "int", "=", "10", ",", "max_...
Sends a request to the remote kernel specified by the RemoteConnection object and processes the result. If the request fails or times out it will be retried until the max retries is reached. After that a failed response will be returned instead. :param endpoint: Remote endpoint where the reques...
[ "Sends", "a", "request", "to", "the", "remote", "kernel", "specified", "by", "the", "RemoteConnection", "object", "and", "processes", "the", "result", ".", "If", "the", "request", "fails", "or", "times", "out", "it", "will", "be", "retried", "until", "the", ...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/comm.py#L68-L134
sernst/cauldron
cauldron/cli/server/routes/display.py
view
def view(route: str): """ Retrieves the contents of the file specified by the view route if it exists. """ project = cauldron.project.get_internal_project() results_path = project.results_path if project else None if not project or not results_path: return '', 204 path = os.path...
python
def view(route: str): """ Retrieves the contents of the file specified by the view route if it exists. """ project = cauldron.project.get_internal_project() results_path = project.results_path if project else None if not project or not results_path: return '', 204 path = os.path...
[ "def", "view", "(", "route", ":", "str", ")", ":", "project", "=", "cauldron", ".", "project", ".", "get_internal_project", "(", ")", "results_path", "=", "project", ".", "results_path", "if", "project", "else", "None", "if", "not", "project", "or", "not",...
Retrieves the contents of the file specified by the view route if it exists.
[ "Retrieves", "the", "contents", "of", "the", "file", "specified", "by", "the", "view", "route", "if", "it", "exists", "." ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/display.py#L10-L28
sernst/cauldron
cauldron/session/writing/__init__.py
save
def save( project: 'projects.Project', write_list: typing.List[tuple] = None ) -> typing.List[tuple]: """ Computes the file write list for the current state of the project if no write_list was specified in the arguments, and then writes each entry in that list to disk. :param projec...
python
def save( project: 'projects.Project', write_list: typing.List[tuple] = None ) -> typing.List[tuple]: """ Computes the file write list for the current state of the project if no write_list was specified in the arguments, and then writes each entry in that list to disk. :param projec...
[ "def", "save", "(", "project", ":", "'projects.Project'", ",", "write_list", ":", "typing", ".", "List", "[", "tuple", "]", "=", "None", ")", "->", "typing", ".", "List", "[", "tuple", "]", ":", "try", ":", "writes", "=", "(", "to_write_list", "(", "...
Computes the file write list for the current state of the project if no write_list was specified in the arguments, and then writes each entry in that list to disk. :param project: The project to be saved :param write_list: The file writes list for the project if one already exists, or N...
[ "Computes", "the", "file", "write", "list", "for", "the", "current", "state", "of", "the", "project", "if", "no", "write_list", "was", "specified", "in", "the", "arguments", "and", "then", "writes", "each", "entry", "in", "that", "list", "to", "disk", "." ...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/__init__.py#L14-L45
sernst/cauldron
cauldron/session/writing/__init__.py
list_asset_writes
def list_asset_writes( project: 'projects.Project' ) -> typing.List[file_io.FILE_COPY_ENTRY]: """ Returns a list containing the file/directory writes that should be executed to deploy the project assets to the results folder. If the project has no assets an empty list is returned. :param pr...
python
def list_asset_writes( project: 'projects.Project' ) -> typing.List[file_io.FILE_COPY_ENTRY]: """ Returns a list containing the file/directory writes that should be executed to deploy the project assets to the results folder. If the project has no assets an empty list is returned. :param pr...
[ "def", "list_asset_writes", "(", "project", ":", "'projects.Project'", ")", "->", "typing", ".", "List", "[", "file_io", ".", "FILE_COPY_ENTRY", "]", ":", "def", "make_asset_copy", "(", "directory", ":", "str", ")", "->", "file_io", ".", "FILE_COPY_ENTRY", ":"...
Returns a list containing the file/directory writes that should be executed to deploy the project assets to the results folder. If the project has no assets an empty list is returned. :param project: The project for which the assets should be copied :return: A list containing the file c...
[ "Returns", "a", "list", "containing", "the", "file", "/", "directory", "writes", "that", "should", "be", "executed", "to", "deploy", "the", "project", "assets", "to", "the", "results", "folder", ".", "If", "the", "project", "has", "no", "assets", "an", "em...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/__init__.py#L94-L127
sernst/cauldron
cauldron/runner/__init__.py
add_library_path
def add_library_path(path: str) -> bool: """ Adds the path to the Python system path if not already added and the path exists. :param path: The path to add to the system paths :return: Whether or not the path was added. Only returns False if the path was not added because it...
python
def add_library_path(path: str) -> bool: """ Adds the path to the Python system path if not already added and the path exists. :param path: The path to add to the system paths :return: Whether or not the path was added. Only returns False if the path was not added because it...
[ "def", "add_library_path", "(", "path", ":", "str", ")", "->", "bool", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "False", "if", "path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "app...
Adds the path to the Python system path if not already added and the path exists. :param path: The path to add to the system paths :return: Whether or not the path was added. Only returns False if the path was not added because it doesn't exist
[ "Adds", "the", "path", "to", "the", "Python", "system", "path", "if", "not", "already", "added", "and", "the", "path", "exists", "." ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L15-L33
sernst/cauldron
cauldron/runner/__init__.py
remove_library_path
def remove_library_path(path: str) -> bool: """ Removes the path from the Python system path if it is found in the system paths. :param path: The path to remove from the system paths :return: Whether or not the path was removed. """ if path in sys.path: sys.path.rem...
python
def remove_library_path(path: str) -> bool: """ Removes the path from the Python system path if it is found in the system paths. :param path: The path to remove from the system paths :return: Whether or not the path was removed. """ if path in sys.path: sys.path.rem...
[ "def", "remove_library_path", "(", "path", ":", "str", ")", "->", "bool", ":", "if", "path", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "remove", "(", "path", ")", "return", "True", "return", "False" ]
Removes the path from the Python system path if it is found in the system paths. :param path: The path to remove from the system paths :return: Whether or not the path was removed.
[ "Removes", "the", "path", "from", "the", "Python", "system", "path", "if", "it", "is", "found", "in", "the", "system", "paths", "." ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L36-L51
sernst/cauldron
cauldron/runner/__init__.py
close
def close(): """...""" os.chdir(os.path.expanduser('~')) project = cauldron.project.internal_project if not project: return False [remove_library_path(path) for path in project.library_directories] remove_library_path(project.source_directory) cauldron.project.unload() return T...
python
def close(): """...""" os.chdir(os.path.expanduser('~')) project = cauldron.project.internal_project if not project: return False [remove_library_path(path) for path in project.library_directories] remove_library_path(project.source_directory) cauldron.project.unload() return T...
[ "def", "close", "(", ")", ":", "os", ".", "chdir", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ")", "project", "=", "cauldron", ".", "project", ".", "internal_project", "if", "not", "project", ":", "return", "False", "[", "remove_librar...
...
[ "..." ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L68-L79
sernst/cauldron
cauldron/runner/__init__.py
reload_libraries
def reload_libraries(library_directories: list = None): """ Reload the libraries stored in the project's local and shared library directories """ directories = library_directories or [] project = cauldron.project.get_internal_project() if project: directories += project.library_direc...
python
def reload_libraries(library_directories: list = None): """ Reload the libraries stored in the project's local and shared library directories """ directories = library_directories or [] project = cauldron.project.get_internal_project() if project: directories += project.library_direc...
[ "def", "reload_libraries", "(", "library_directories", ":", "list", "=", "None", ")", ":", "directories", "=", "library_directories", "or", "[", "]", "project", "=", "cauldron", ".", "project", ".", "get_internal_project", "(", ")", "if", "project", ":", "dire...
Reload the libraries stored in the project's local and shared library directories
[ "Reload", "the", "libraries", "stored", "in", "the", "project", "s", "local", "and", "shared", "library", "directories" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L82-L123
sernst/cauldron
cauldron/runner/__init__.py
complete
def complete( response: Response, project: typing.Union[Project, None], starting: ProjectStep = None, force: bool = False, limit: int = -1 ) -> list: """ Runs the entire project, writes the results files, and returns the URL to the report file :param response: ...
python
def complete( response: Response, project: typing.Union[Project, None], starting: ProjectStep = None, force: bool = False, limit: int = -1 ) -> list: """ Runs the entire project, writes the results files, and returns the URL to the report file :param response: ...
[ "def", "complete", "(", "response", ":", "Response", ",", "project", ":", "typing", ".", "Union", "[", "Project", ",", "None", "]", ",", "starting", ":", "ProjectStep", "=", "None", ",", "force", ":", "bool", "=", "False", ",", "limit", ":", "int", "...
Runs the entire project, writes the results files, and returns the URL to the report file :param response: :param project: :param starting: :param force: :param limit: :return: Local URL to the report path
[ "Runs", "the", "entire", "project", "writes", "the", "results", "files", "and", "returns", "the", "URL", "to", "the", "report", "file" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L180-L231
sernst/cauldron
cauldron/session/projects/steps.py
ProjectStep.elapsed_time
def elapsed_time(self) -> float: """ The number of seconds that has elapsed since the step started running if the step is still running. Or, if the step has already finished running, the amount of time that elapsed during the last execution of the step. """ curren...
python
def elapsed_time(self) -> float: """ The number of seconds that has elapsed since the step started running if the step is still running. Or, if the step has already finished running, the amount of time that elapsed during the last execution of the step. """ curren...
[ "def", "elapsed_time", "(", "self", ")", "->", "float", ":", "current_time", "=", "datetime", ".", "utcnow", "(", ")", "start", "=", "self", ".", "start_time", "or", "current_time", "end", "=", "self", ".", "end_time", "or", "current_time", "return", "(", ...
The number of seconds that has elapsed since the step started running if the step is still running. Or, if the step has already finished running, the amount of time that elapsed during the last execution of the step.
[ "The", "number", "of", "seconds", "that", "has", "elapsed", "since", "the", "step", "started", "running", "if", "the", "step", "is", "still", "running", ".", "Or", "if", "the", "step", "has", "already", "finished", "running", "the", "amount", "of", "time",...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L97-L107
sernst/cauldron
cauldron/session/projects/steps.py
ProjectStep.get_elapsed_timestamp
def get_elapsed_timestamp(self) -> str: """ A human-readable version of the elapsed time for the last execution of the step. The value is derived from the `ProjectStep.elapsed_time` property. """ t = self.elapsed_time minutes = int(t / 60) seconds = int(t ...
python
def get_elapsed_timestamp(self) -> str: """ A human-readable version of the elapsed time for the last execution of the step. The value is derived from the `ProjectStep.elapsed_time` property. """ t = self.elapsed_time minutes = int(t / 60) seconds = int(t ...
[ "def", "get_elapsed_timestamp", "(", "self", ")", "->", "str", ":", "t", "=", "self", ".", "elapsed_time", "minutes", "=", "int", "(", "t", "/", "60", ")", "seconds", "=", "int", "(", "t", "-", "(", "60", "*", "minutes", ")", ")", "millis", "=", ...
A human-readable version of the elapsed time for the last execution of the step. The value is derived from the `ProjectStep.elapsed_time` property.
[ "A", "human", "-", "readable", "version", "of", "the", "elapsed", "time", "for", "the", "last", "execution", "of", "the", "step", ".", "The", "value", "is", "derived", "from", "the", "ProjectStep", ".", "elapsed_time", "property", "." ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L109-L119
sernst/cauldron
cauldron/session/projects/steps.py
ProjectStep.get_dom
def get_dom(self) -> str: """ Retrieves the current value of the DOM for the step """ if self.is_running: return self.dumps() if self.dom is not None: return self.dom dom = self.dumps() self.dom = dom return dom
python
def get_dom(self) -> str: """ Retrieves the current value of the DOM for the step """ if self.is_running: return self.dumps() if self.dom is not None: return self.dom dom = self.dumps() self.dom = dom return dom
[ "def", "get_dom", "(", "self", ")", "->", "str", ":", "if", "self", ".", "is_running", ":", "return", "self", ".", "dumps", "(", ")", "if", "self", ".", "dom", "is", "not", "None", ":", "return", "self", ".", "dom", "dom", "=", "self", ".", "dump...
Retrieves the current value of the DOM for the step
[ "Retrieves", "the", "current", "value", "of", "the", "DOM", "for", "the", "step" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L179-L190
sernst/cauldron
cauldron/session/projects/steps.py
ProjectStep.dumps
def dumps(self) -> str: """Writes the step information to an HTML-formatted string""" code_file_path = os.path.join( self.project.source_directory, self.filename ) code = dict( filename=self.filename, path=code_file_path, code=r...
python
def dumps(self) -> str: """Writes the step information to an HTML-formatted string""" code_file_path = os.path.join( self.project.source_directory, self.filename ) code = dict( filename=self.filename, path=code_file_path, code=r...
[ "def", "dumps", "(", "self", ")", "->", "str", ":", "code_file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "project", ".", "source_directory", ",", "self", ".", "filename", ")", "code", "=", "dict", "(", "filename", "=", "self", "."...
Writes the step information to an HTML-formatted string
[ "Writes", "the", "step", "information", "to", "an", "HTML", "-", "formatted", "string" ]
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L192-L267
seomoz/qless-py
qless/__init__.py
retry
def retry(*excepts): '''A decorator to specify a bunch of exceptions that should be caught and the job retried. It turns out this comes up with relative frequency''' @decorator.decorator def new_func(func, job): '''No docstring''' try: func(job) except tuple(excepts):...
python
def retry(*excepts): '''A decorator to specify a bunch of exceptions that should be caught and the job retried. It turns out this comes up with relative frequency''' @decorator.decorator def new_func(func, job): '''No docstring''' try: func(job) except tuple(excepts):...
[ "def", "retry", "(", "*", "excepts", ")", ":", "@", "decorator", ".", "decorator", "def", "new_func", "(", "func", ",", "job", ")", ":", "'''No docstring'''", "try", ":", "func", "(", "job", ")", "except", "tuple", "(", "excepts", ")", ":", "job", "....
A decorator to specify a bunch of exceptions that should be caught and the job retried. It turns out this comes up with relative frequency
[ "A", "decorator", "to", "specify", "a", "bunch", "of", "exceptions", "that", "should", "be", "caught", "and", "the", "job", "retried", ".", "It", "turns", "out", "this", "comes", "up", "with", "relative", "frequency" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L28-L38
seomoz/qless-py
qless/__init__.py
Jobs.tracked
def tracked(self): '''Return an array of job objects that are being tracked''' results = json.loads(self.client('track')) results['jobs'] = [Job(self, **job) for job in results['jobs']] return results
python
def tracked(self): '''Return an array of job objects that are being tracked''' results = json.loads(self.client('track')) results['jobs'] = [Job(self, **job) for job in results['jobs']] return results
[ "def", "tracked", "(", "self", ")", ":", "results", "=", "json", ".", "loads", "(", "self", ".", "client", "(", "'track'", ")", ")", "results", "[", "'jobs'", "]", "=", "[", "Job", "(", "self", ",", "*", "*", "job", ")", "for", "job", "in", "re...
Return an array of job objects that are being tracked
[ "Return", "an", "array", "of", "job", "objects", "that", "are", "being", "tracked" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L50-L54
seomoz/qless-py
qless/__init__.py
Jobs.tagged
def tagged(self, tag, offset=0, count=25): '''Return the paginated jids of jobs tagged with a tag''' return json.loads(self.client('tag', 'get', tag, offset, count))
python
def tagged(self, tag, offset=0, count=25): '''Return the paginated jids of jobs tagged with a tag''' return json.loads(self.client('tag', 'get', tag, offset, count))
[ "def", "tagged", "(", "self", ",", "tag", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "client", "(", "'tag'", ",", "'get'", ",", "tag", ",", "offset", ",", "count", ")", ")" ]
Return the paginated jids of jobs tagged with a tag
[ "Return", "the", "paginated", "jids", "of", "jobs", "tagged", "with", "a", "tag" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L56-L58
seomoz/qless-py
qless/__init__.py
Jobs.failed
def failed(self, group=None, start=0, limit=25): '''If no group is provided, this returns a JSON blob of the counts of the various types of failures known. If a type is provided, returns paginated job objects affected by that kind of failure.''' if not group: return json.load...
python
def failed(self, group=None, start=0, limit=25): '''If no group is provided, this returns a JSON blob of the counts of the various types of failures known. If a type is provided, returns paginated job objects affected by that kind of failure.''' if not group: return json.load...
[ "def", "failed", "(", "self", ",", "group", "=", "None", ",", "start", "=", "0", ",", "limit", "=", "25", ")", ":", "if", "not", "group", ":", "return", "json", ".", "loads", "(", "self", ".", "client", "(", "'failed'", ")", ")", "else", ":", "...
If no group is provided, this returns a JSON blob of the counts of the various types of failures known. If a type is provided, returns paginated job objects affected by that kind of failure.
[ "If", "no", "group", "is", "provided", "this", "returns", "a", "JSON", "blob", "of", "the", "counts", "of", "the", "various", "types", "of", "failures", "known", ".", "If", "a", "type", "is", "provided", "returns", "paginated", "job", "objects", "affected"...
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L60-L70
seomoz/qless-py
qless/__init__.py
Jobs.get
def get(self, *jids): '''Return jobs objects for all the jids''' if jids: return [ Job(self.client, **j) for j in json.loads(self.client('multiget', *jids))] return []
python
def get(self, *jids): '''Return jobs objects for all the jids''' if jids: return [ Job(self.client, **j) for j in json.loads(self.client('multiget', *jids))] return []
[ "def", "get", "(", "self", ",", "*", "jids", ")", ":", "if", "jids", ":", "return", "[", "Job", "(", "self", ".", "client", ",", "*", "*", "j", ")", "for", "j", "in", "json", ".", "loads", "(", "self", ".", "client", "(", "'multiget'", ",", "...
Return jobs objects for all the jids
[ "Return", "jobs", "objects", "for", "all", "the", "jids" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L72-L78
seomoz/qless-py
qless/workers/__init__.py
Worker.title
def title(cls, message=None): '''Set the title of the process''' if message == None: return getproctitle() else: setproctitle('qless-py-worker %s' % message) logger.info(message)
python
def title(cls, message=None): '''Set the title of the process''' if message == None: return getproctitle() else: setproctitle('qless-py-worker %s' % message) logger.info(message)
[ "def", "title", "(", "cls", ",", "message", "=", "None", ")", ":", "if", "message", "==", "None", ":", "return", "getproctitle", "(", ")", "else", ":", "setproctitle", "(", "'qless-py-worker %s'", "%", "message", ")", "logger", ".", "info", "(", "message...
Set the title of the process
[ "Set", "the", "title", "of", "the", "process" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L43-L49
seomoz/qless-py
qless/workers/__init__.py
Worker.divide
def divide(cls, jobs, count): '''Divide up the provided jobs into count evenly-sized groups''' jobs = list(zip(*zip_longest(*[iter(jobs)] * count))) # If we had no jobs to resume, then we get an empty list jobs = jobs or [()] * count for index in range(count): # Filte...
python
def divide(cls, jobs, count): '''Divide up the provided jobs into count evenly-sized groups''' jobs = list(zip(*zip_longest(*[iter(jobs)] * count))) # If we had no jobs to resume, then we get an empty list jobs = jobs or [()] * count for index in range(count): # Filte...
[ "def", "divide", "(", "cls", ",", "jobs", ",", "count", ")", ":", "jobs", "=", "list", "(", "zip", "(", "*", "zip_longest", "(", "*", "[", "iter", "(", "jobs", ")", "]", "*", "count", ")", ")", ")", "# If we had no jobs to resume, then we get an empty li...
Divide up the provided jobs into count evenly-sized groups
[ "Divide", "up", "the", "provided", "jobs", "into", "count", "evenly", "-", "sized", "groups" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L52-L60
seomoz/qless-py
qless/workers/__init__.py
Worker.clean
def clean(cls, path): '''Clean up all the files in a provided path''' for pth in os.listdir(path): pth = os.path.abspath(os.path.join(path, pth)) if os.path.isdir(pth): logger.debug('Removing directory %s' % pth) shutil.rmtree(pth) else...
python
def clean(cls, path): '''Clean up all the files in a provided path''' for pth in os.listdir(path): pth = os.path.abspath(os.path.join(path, pth)) if os.path.isdir(pth): logger.debug('Removing directory %s' % pth) shutil.rmtree(pth) else...
[ "def", "clean", "(", "cls", ",", "path", ")", ":", "for", "pth", "in", "os", ".", "listdir", "(", "path", ")", ":", "pth", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "pth", ")", ")", "if", ...
Clean up all the files in a provided path
[ "Clean", "up", "all", "the", "files", "in", "a", "provided", "path" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L63-L72
seomoz/qless-py
qless/workers/__init__.py
Worker.sandbox
def sandbox(cls, path): '''Ensures path exists before yielding, cleans up after''' # Ensure the path exists and is clean try: os.makedirs(path) logger.debug('Making %s' % path) except OSError: if not os.path.isdir(path): raise f...
python
def sandbox(cls, path): '''Ensures path exists before yielding, cleans up after''' # Ensure the path exists and is clean try: os.makedirs(path) logger.debug('Making %s' % path) except OSError: if not os.path.isdir(path): raise f...
[ "def", "sandbox", "(", "cls", ",", "path", ")", ":", "# Ensure the path exists and is clean", "try", ":", "os", ".", "makedirs", "(", "path", ")", "logger", ".", "debug", "(", "'Making %s'", "%", "path", ")", "except", "OSError", ":", "if", "not", "os", ...
Ensures path exists before yielding, cleans up after
[ "Ensures", "path", "exists", "before", "yielding", "cleans", "up", "after" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L76-L91
seomoz/qless-py
qless/workers/__init__.py
Worker.resumable
def resumable(self): '''Find all the jobs that we'd previously been working on''' # First, find the jids of all the jobs registered to this client. # Then, get the corresponding job objects jids = self.client.workers[self.client.worker_name]['jobs'] jobs = self.client.jobs.get(*j...
python
def resumable(self): '''Find all the jobs that we'd previously been working on''' # First, find the jids of all the jobs registered to this client. # Then, get the corresponding job objects jids = self.client.workers[self.client.worker_name]['jobs'] jobs = self.client.jobs.get(*j...
[ "def", "resumable", "(", "self", ")", ":", "# First, find the jids of all the jobs registered to this client.", "# Then, get the corresponding job objects", "jids", "=", "self", ".", "client", ".", "workers", "[", "self", ".", "client", ".", "worker_name", "]", "[", "'j...
Find all the jobs that we'd previously been working on
[ "Find", "all", "the", "jobs", "that", "we", "d", "previously", "been", "working", "on" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L116-L126
seomoz/qless-py
qless/workers/__init__.py
Worker.jobs
def jobs(self): '''Generator for all the jobs''' # If we should resume work, then we should hand those out first, # assuming we can still heartbeat them for job in self.resume: try: if job.heartbeat(): yield job except exception...
python
def jobs(self): '''Generator for all the jobs''' # If we should resume work, then we should hand those out first, # assuming we can still heartbeat them for job in self.resume: try: if job.heartbeat(): yield job except exception...
[ "def", "jobs", "(", "self", ")", ":", "# If we should resume work, then we should hand those out first,", "# assuming we can still heartbeat them", "for", "job", "in", "self", ".", "resume", ":", "try", ":", "if", "job", ".", "heartbeat", "(", ")", ":", "yield", "jo...
Generator for all the jobs
[ "Generator", "for", "all", "the", "jobs" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L128-L146
seomoz/qless-py
qless/workers/__init__.py
Worker.listener
def listener(self): '''Listen for pubsub messages relevant to this worker in a thread''' channels = ['ql:w:' + self.client.worker_name] listener = Listener(self.client.redis, channels) thread = threading.Thread(target=self.listen, args=(listener,)) thread.start() try: ...
python
def listener(self): '''Listen for pubsub messages relevant to this worker in a thread''' channels = ['ql:w:' + self.client.worker_name] listener = Listener(self.client.redis, channels) thread = threading.Thread(target=self.listen, args=(listener,)) thread.start() try: ...
[ "def", "listener", "(", "self", ")", ":", "channels", "=", "[", "'ql:w:'", "+", "self", ".", "client", ".", "worker_name", "]", "listener", "=", "Listener", "(", "self", ".", "client", ".", "redis", ",", "channels", ")", "thread", "=", "threading", "."...
Listen for pubsub messages relevant to this worker in a thread
[ "Listen", "for", "pubsub", "messages", "relevant", "to", "this", "worker", "in", "a", "thread" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L149-L159
seomoz/qless-py
qless/workers/__init__.py
Worker.listen
def listen(self, listener): '''Listen for events that affect our ownership of a job''' for message in listener.listen(): try: data = json.loads(message['data']) if data['event'] in ('canceled', 'lock_lost', 'put'): self.kill(data['jid']) ...
python
def listen(self, listener): '''Listen for events that affect our ownership of a job''' for message in listener.listen(): try: data = json.loads(message['data']) if data['event'] in ('canceled', 'lock_lost', 'put'): self.kill(data['jid']) ...
[ "def", "listen", "(", "self", ",", "listener", ")", ":", "for", "message", "in", "listener", ".", "listen", "(", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "message", "[", "'data'", "]", ")", "if", "data", "[", "'event'", "]", ...
Listen for events that affect our ownership of a job
[ "Listen", "for", "events", "that", "affect", "our", "ownership", "of", "a", "job" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L161-L169
seomoz/qless-py
qless/workers/__init__.py
Worker.signals
def signals(self, signals=('QUIT', 'USR1', 'USR2')): '''Register our signal handler''' for sig in signals: signal.signal(getattr(signal, 'SIG' + sig), self.handler)
python
def signals(self, signals=('QUIT', 'USR1', 'USR2')): '''Register our signal handler''' for sig in signals: signal.signal(getattr(signal, 'SIG' + sig), self.handler)
[ "def", "signals", "(", "self", ",", "signals", "=", "(", "'QUIT'", ",", "'USR1'", ",", "'USR2'", ")", ")", ":", "for", "sig", "in", "signals", ":", "signal", ".", "signal", "(", "getattr", "(", "signal", ",", "'SIG'", "+", "sig", ")", ",", "self", ...
Register our signal handler
[ "Register", "our", "signal", "handler" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L175-L178
seomoz/qless-py
qless/workers/__init__.py
Worker.handler
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum == signal.SIGQUIT: # QUIT - Finish processing, but don't do any more work after that self.stop() elif signum == signal.SIGUSR1: # USR1 - Print the backtrace ...
python
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum == signal.SIGQUIT: # QUIT - Finish processing, but don't do any more work after that self.stop() elif signum == signal.SIGUSR1: # USR1 - Print the backtrace ...
[ "def", "handler", "(", "self", ",", "signum", ",", "frame", ")", ":", "# pragma: no cover", "if", "signum", "==", "signal", ".", "SIGQUIT", ":", "# QUIT - Finish processing, but don't do any more work after that", "self", ".", "stop", "(", ")", "elif", "signum", "...
Signal handler for this process
[ "Signal", "handler", "for", "this", "process" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L185-L205
WimpyAnalytics/django-andablog
andablog/migrations/0004_shorten_entry_title.py
truncate_entry_titles
def truncate_entry_titles(apps, schema_editor): """This function will truncate the values of Entry.title so they are 255 characters or less. """ Entry = apps.get_model("andablog", "Entry") for entry in Entry.objects.all(): # Truncate to 255 characters (or less) but keep whole words intact. ...
python
def truncate_entry_titles(apps, schema_editor): """This function will truncate the values of Entry.title so they are 255 characters or less. """ Entry = apps.get_model("andablog", "Entry") for entry in Entry.objects.all(): # Truncate to 255 characters (or less) but keep whole words intact. ...
[ "def", "truncate_entry_titles", "(", "apps", ",", "schema_editor", ")", ":", "Entry", "=", "apps", ".", "get_model", "(", "\"andablog\"", ",", "\"Entry\"", ")", "for", "entry", "in", "Entry", ".", "objects", ".", "all", "(", ")", ":", "# Truncate to 255 char...
This function will truncate the values of Entry.title so they are 255 characters or less.
[ "This", "function", "will", "truncate", "the", "values", "of", "Entry", ".", "title", "so", "they", "are", "255", "characters", "or", "less", "." ]
train
https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/andablog/migrations/0004_shorten_entry_title.py#L12-L22
seomoz/qless-py
qless/workers/greenlet.py
GeventWorker.process
def process(self, job): '''Process a job''' sandbox = self.sandboxes.pop(0) try: with Worker.sandbox(sandbox): job.sandbox = sandbox job.process() finally: # Delete its entry from our greenlets mapping self.greenlets.pop...
python
def process(self, job): '''Process a job''' sandbox = self.sandboxes.pop(0) try: with Worker.sandbox(sandbox): job.sandbox = sandbox job.process() finally: # Delete its entry from our greenlets mapping self.greenlets.pop...
[ "def", "process", "(", "self", ",", "job", ")", ":", "sandbox", "=", "self", ".", "sandboxes", ".", "pop", "(", "0", ")", "try", ":", "with", "Worker", ".", "sandbox", "(", "sandbox", ")", ":", "job", ".", "sandbox", "=", "sandbox", "job", ".", "...
Process a job
[ "Process", "a", "job" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/greenlet.py#L28-L38
seomoz/qless-py
qless/workers/greenlet.py
GeventWorker.kill
def kill(self, jid): '''Stop the greenlet processing the provided jid''' greenlet = self.greenlets.get(jid) if greenlet is not None: logger.warn('Lost ownership of %s' % jid) greenlet.kill()
python
def kill(self, jid): '''Stop the greenlet processing the provided jid''' greenlet = self.greenlets.get(jid) if greenlet is not None: logger.warn('Lost ownership of %s' % jid) greenlet.kill()
[ "def", "kill", "(", "self", ",", "jid", ")", ":", "greenlet", "=", "self", ".", "greenlets", ".", "get", "(", "jid", ")", "if", "greenlet", "is", "not", "None", ":", "logger", ".", "warn", "(", "'Lost ownership of %s'", "%", "jid", ")", "greenlet", "...
Stop the greenlet processing the provided jid
[ "Stop", "the", "greenlet", "processing", "the", "provided", "jid" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/greenlet.py#L40-L45
seomoz/qless-py
qless/workers/greenlet.py
GeventWorker.run
def run(self): '''Work on jobs''' # Register signal handlers self.signals() # Start listening with self.listener(): try: generator = self.jobs() while not self.shutdown: self.pool.wait_available() ...
python
def run(self): '''Work on jobs''' # Register signal handlers self.signals() # Start listening with self.listener(): try: generator = self.jobs() while not self.shutdown: self.pool.wait_available() ...
[ "def", "run", "(", "self", ")", ":", "# Register signal handlers", "self", ".", "signals", "(", ")", "# Start listening", "with", "self", ".", "listener", "(", ")", ":", "try", ":", "generator", "=", "self", ".", "jobs", "(", ")", "while", "not", "self",...
Work on jobs
[ "Work", "on", "jobs" ]
train
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/greenlet.py#L47-L76
Riffstation/flask-philo
flask_philo/db/postgresql/connection.py
init_db_conn
def init_db_conn(connection_name, connection_string, scopefunc=None): """ Initialize a postgresql connection by each connection string defined in the configuration file """ engine = create_engine(connection_string) session = scoped_session(sessionmaker(), scopefunc=scopefunc) session.configu...
python
def init_db_conn(connection_name, connection_string, scopefunc=None): """ Initialize a postgresql connection by each connection string defined in the configuration file """ engine = create_engine(connection_string) session = scoped_session(sessionmaker(), scopefunc=scopefunc) session.configu...
[ "def", "init_db_conn", "(", "connection_name", ",", "connection_string", ",", "scopefunc", "=", "None", ")", ":", "engine", "=", "create_engine", "(", "connection_string", ")", "session", "=", "scoped_session", "(", "sessionmaker", "(", ")", ",", "scopefunc", "=...
Initialize a postgresql connection by each connection string defined in the configuration file
[ "Initialize", "a", "postgresql", "connection", "by", "each", "connection", "string", "defined", "in", "the", "configuration", "file" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/connection.py#L47-L55
Riffstation/flask-philo
flask_philo/db/postgresql/connection.py
initialize
def initialize(g, app): """ If postgresql url is defined in configuration params a scoped session will be created """ if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']: # Database connection established for console commands for k, v in app.config['DATABASES']['...
python
def initialize(g, app): """ If postgresql url is defined in configuration params a scoped session will be created """ if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']: # Database connection established for console commands for k, v in app.config['DATABASES']['...
[ "def", "initialize", "(", "g", ",", "app", ")", ":", "if", "'DATABASES'", "in", "app", ".", "config", "and", "'POSTGRESQL'", "in", "app", ".", "config", "[", "'DATABASES'", "]", ":", "# Database connection established for console commands", "for", "k", ",", "v...
If postgresql url is defined in configuration params a scoped session will be created
[ "If", "postgresql", "url", "is", "defined", "in", "configuration", "params", "a", "scoped", "session", "will", "be", "created" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/connection.py#L58-L102
Riffstation/flask-philo
flask_philo/jinja2/__init__.py
load_extensions_from_config
def load_extensions_from_config(**config): """ Loads extensions """ extensions = [] if 'EXTENSIONS' in config: for ext in config['EXTENSIONS']: try: extensions.append(locate(ext)) except Exception as e: print(e) return extensions
python
def load_extensions_from_config(**config): """ Loads extensions """ extensions = [] if 'EXTENSIONS' in config: for ext in config['EXTENSIONS']: try: extensions.append(locate(ext)) except Exception as e: print(e) return extensions
[ "def", "load_extensions_from_config", "(", "*", "*", "config", ")", ":", "extensions", "=", "[", "]", "if", "'EXTENSIONS'", "in", "config", ":", "for", "ext", "in", "config", "[", "'EXTENSIONS'", "]", ":", "try", ":", "extensions", ".", "append", "(", "l...
Loads extensions
[ "Loads", "extensions" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/jinja2/__init__.py#L53-L64
Riffstation/flask-philo
flask_philo/jinja2/__init__.py
TemplatesManager.set_request
def set_request(self, r): """ Appends request object to the globals dict """ for k in self.environments.keys(): self.environments[k].globals['REQUEST'] = r
python
def set_request(self, r): """ Appends request object to the globals dict """ for k in self.environments.keys(): self.environments[k].globals['REQUEST'] = r
[ "def", "set_request", "(", "self", ",", "r", ")", ":", "for", "k", "in", "self", ".", "environments", ".", "keys", "(", ")", ":", "self", ".", "environments", "[", "k", "]", ".", "globals", "[", "'REQUEST'", "]", "=", "r" ]
Appends request object to the globals dict
[ "Appends", "request", "object", "to", "the", "globals", "dict" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/jinja2/__init__.py#L18-L23
Riffstation/flask-philo
flask_philo/db/elasticsearch/connection.py
init_db_conn
def init_db_conn(connection_name, HOSTS=None): """ Initialize a redis connection by each connection string defined in the configuration file """ el = elasticsearch.Elasticsearch(hosts=HOSTS) el_pool.connections[connection_name] = ElasticSearchClient(el)
python
def init_db_conn(connection_name, HOSTS=None): """ Initialize a redis connection by each connection string defined in the configuration file """ el = elasticsearch.Elasticsearch(hosts=HOSTS) el_pool.connections[connection_name] = ElasticSearchClient(el)
[ "def", "init_db_conn", "(", "connection_name", ",", "HOSTS", "=", "None", ")", ":", "el", "=", "elasticsearch", ".", "Elasticsearch", "(", "hosts", "=", "HOSTS", ")", "el_pool", ".", "connections", "[", "connection_name", "]", "=", "ElasticSearchClient", "(", ...
Initialize a redis connection by each connection string defined in the configuration file
[ "Initialize", "a", "redis", "connection", "by", "each", "connection", "string", "defined", "in", "the", "configuration", "file" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/elasticsearch/connection.py#L71-L77
Riffstation/flask-philo
flask_philo/cloud/aws/utils.py
parse_tags
def parse_tags(targs): """ Tags can be in the forma key:value or simply value """ tags = {} for t in targs: split_tag = t.split(':') if len(split_tag) > 1: tags['tag:' + split_tag[0]] = split_tag[1] else: tags['tag:' + split_tag[0]] = '' return tag...
python
def parse_tags(targs): """ Tags can be in the forma key:value or simply value """ tags = {} for t in targs: split_tag = t.split(':') if len(split_tag) > 1: tags['tag:' + split_tag[0]] = split_tag[1] else: tags['tag:' + split_tag[0]] = '' return tag...
[ "def", "parse_tags", "(", "targs", ")", ":", "tags", "=", "{", "}", "for", "t", "in", "targs", ":", "split_tag", "=", "t", ".", "split", "(", "':'", ")", "if", "len", "(", "split_tag", ")", ">", "1", ":", "tags", "[", "'tag:'", "+", "split_tag", ...
Tags can be in the forma key:value or simply value
[ "Tags", "can", "be", "in", "the", "forma", "key", ":", "value", "or", "simply", "value" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/cloud/aws/utils.py#L1-L12
Riffstation/flask-philo
flask_philo/views.py
BaseView.json_response
def json_response(self, status=200, data={}, headers={}): ''' To set flask to inject specific headers on response request, such as CORS_ORIGIN headers ''' mimetype = 'application/json' header_dict = {} for k, v in headers.items(): header_dict[k] =...
python
def json_response(self, status=200, data={}, headers={}): ''' To set flask to inject specific headers on response request, such as CORS_ORIGIN headers ''' mimetype = 'application/json' header_dict = {} for k, v in headers.items(): header_dict[k] =...
[ "def", "json_response", "(", "self", ",", "status", "=", "200", ",", "data", "=", "{", "}", ",", "headers", "=", "{", "}", ")", ":", "mimetype", "=", "'application/json'", "header_dict", "=", "{", "}", "for", "k", ",", "v", "in", "headers", ".", "i...
To set flask to inject specific headers on response request, such as CORS_ORIGIN headers
[ "To", "set", "flask", "to", "inject", "specific", "headers", "on", "response", "request", "such", "as", "CORS_ORIGIN", "headers" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/views.py#L25-L40
Riffstation/flask-philo
flask_philo/views.py
BaseView.template_response
def template_response(self, template_name, headers={}, **values): """ Constructs a response, allowing custom template name and content_type """ response = make_response( self.render_template(template_name, **values)) for field, value in headers.items(): r...
python
def template_response(self, template_name, headers={}, **values): """ Constructs a response, allowing custom template name and content_type """ response = make_response( self.render_template(template_name, **values)) for field, value in headers.items(): r...
[ "def", "template_response", "(", "self", ",", "template_name", ",", "headers", "=", "{", "}", ",", "*", "*", "values", ")", ":", "response", "=", "make_response", "(", "self", ".", "render_template", "(", "template_name", ",", "*", "*", "values", ")", ")...
Constructs a response, allowing custom template name and content_type
[ "Constructs", "a", "response", "allowing", "custom", "template", "name", "and", "content_type" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/views.py#L49-L59
Riffstation/flask-philo
flask_philo/cloud/aws/key_pair.py
describe_key_pairs
def describe_key_pairs(): """ Returns all key pairs for region """ region_keys = {} for r in boto3.client('ec2', 'us-west-2').describe_regions()['Regions']: region = r['RegionName'] client = boto3.client('ec2', region_name=region) try: pairs = client.describe_key_...
python
def describe_key_pairs(): """ Returns all key pairs for region """ region_keys = {} for r in boto3.client('ec2', 'us-west-2').describe_regions()['Regions']: region = r['RegionName'] client = boto3.client('ec2', region_name=region) try: pairs = client.describe_key_...
[ "def", "describe_key_pairs", "(", ")", ":", "region_keys", "=", "{", "}", "for", "r", "in", "boto3", ".", "client", "(", "'ec2'", ",", "'us-west-2'", ")", ".", "describe_regions", "(", ")", "[", "'Regions'", "]", ":", "region", "=", "r", "[", "'RegionN...
Returns all key pairs for region
[ "Returns", "all", "key", "pairs", "for", "region" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/cloud/aws/key_pair.py#L29-L43
Riffstation/flask-philo
flask_philo/__init__.py
init_app
def init_app(module, BASE_DIR, **kwargs): """ Initalize an app, call this method once from start_app """ global app def init_config(): """ Load settings module and attach values to the application config dictionary """ if 'FLASK_PHILO_SETTINGS_MODULE' not in ...
python
def init_app(module, BASE_DIR, **kwargs): """ Initalize an app, call this method once from start_app """ global app def init_config(): """ Load settings module and attach values to the application config dictionary """ if 'FLASK_PHILO_SETTINGS_MODULE' not in ...
[ "def", "init_app", "(", "module", ",", "BASE_DIR", ",", "*", "*", "kwargs", ")", ":", "global", "app", "def", "init_config", "(", ")", ":", "\"\"\"\n Load settings module and attach values to the application\n config dictionary\n \"\"\"", "if", "'FLASK_...
Initalize an app, call this method once from start_app
[ "Initalize", "an", "app", "call", "this", "method", "once", "from", "start_app" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/__init__.py#L27-L110
Riffstation/flask-philo
flask_philo/__init__.py
execute_command
def execute_command(cmd, **kwargs): """ execute a console command """ cmd_dict = { c: 'flask_philo.commands_flask_philo.' + c for c in dir(commands_flask_philo) if not c.startswith('_') and c != 'os' # noqa } # loading specific app commands try: import console_c...
python
def execute_command(cmd, **kwargs): """ execute a console command """ cmd_dict = { c: 'flask_philo.commands_flask_philo.' + c for c in dir(commands_flask_philo) if not c.startswith('_') and c != 'os' # noqa } # loading specific app commands try: import console_c...
[ "def", "execute_command", "(", "cmd", ",", "*", "*", "kwargs", ")", ":", "cmd_dict", "=", "{", "c", ":", "'flask_philo.commands_flask_philo.'", "+", "c", "for", "c", "in", "dir", "(", "commands_flask_philo", ")", "if", "not", "c", ".", "startswith", "(", ...
execute a console command
[ "execute", "a", "console", "command" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/__init__.py#L113-L135
Riffstation/flask-philo
flask_philo/db/postgresql/__init__.py
syncdb
def syncdb(): """ Create tables if they don't exist """ from flask_philo.db.postgresql.schema import Base from flask_philo.db.postgresql.orm import BaseModel # noqa from flask_philo.db.postgresql.connection import get_pool for conn_name, conn in get_pool().connections.items(): Base...
python
def syncdb(): """ Create tables if they don't exist """ from flask_philo.db.postgresql.schema import Base from flask_philo.db.postgresql.orm import BaseModel # noqa from flask_philo.db.postgresql.connection import get_pool for conn_name, conn in get_pool().connections.items(): Base...
[ "def", "syncdb", "(", ")", ":", "from", "flask_philo", ".", "db", ".", "postgresql", ".", "schema", "import", "Base", "from", "flask_philo", ".", "db", ".", "postgresql", ".", "orm", "import", "BaseModel", "# noqa", "from", "flask_philo", ".", "db", ".", ...
Create tables if they don't exist
[ "Create", "tables", "if", "they", "don", "t", "exist" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/__init__.py#L1-L10
Riffstation/flask-philo
flask_philo/db/postgresql/types.py
PasswordHash.new
def new(cls, password, rounds): """Creates a PasswordHash from the given password.""" if isinstance(password, str): password = password.encode('utf8') value = bcrypt.hashpw(password, bcrypt.gensalt(rounds)) return cls(value)
python
def new(cls, password, rounds): """Creates a PasswordHash from the given password.""" if isinstance(password, str): password = password.encode('utf8') value = bcrypt.hashpw(password, bcrypt.gensalt(rounds)) return cls(value)
[ "def", "new", "(", "cls", ",", "password", ",", "rounds", ")", ":", "if", "isinstance", "(", "password", ",", "str", ")", ":", "password", "=", "password", ".", "encode", "(", "'utf8'", ")", "value", "=", "bcrypt", ".", "hashpw", "(", "password", ","...
Creates a PasswordHash from the given password.
[ "Creates", "a", "PasswordHash", "from", "the", "given", "password", "." ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/types.py#L47-L52
Riffstation/flask-philo
flask_philo/db/postgresql/types.py
Password._convert
def _convert(self, value): """Returns a PasswordHash from the given string. PasswordHash instances or None values will return unchanged. Strings will be hashed and the resulting PasswordHash returned. Any other input will result in a TypeError. """ if isinstance(value, P...
python
def _convert(self, value): """Returns a PasswordHash from the given string. PasswordHash instances or None values will return unchanged. Strings will be hashed and the resulting PasswordHash returned. Any other input will result in a TypeError. """ if isinstance(value, P...
[ "def", "_convert", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "PasswordHash", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "value", ".", "encode", "(", "'utf-8'", ...
Returns a PasswordHash from the given string. PasswordHash instances or None values will return unchanged. Strings will be hashed and the resulting PasswordHash returned. Any other input will result in a TypeError.
[ "Returns", "a", "PasswordHash", "from", "the", "given", "string", "." ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/types.py#L76-L90
Riffstation/flask-philo
flask_philo/db/redis/connection.py
init_db_conn
def init_db_conn( connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None): """ Initialize a redis connection by each connection string defined in the configuration file """ rpool = redis.ConnectionPool( host=HOST, port=PORT, db=DB, password=PASSWORD) r = redis.Redis(connec...
python
def init_db_conn( connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None): """ Initialize a redis connection by each connection string defined in the configuration file """ rpool = redis.ConnectionPool( host=HOST, port=PORT, db=DB, password=PASSWORD) r = redis.Redis(connec...
[ "def", "init_db_conn", "(", "connection_name", ",", "HOST", "=", "None", ",", "PORT", "=", "None", ",", "DB", "=", "None", ",", "PASSWORD", "=", "None", ")", ":", "rpool", "=", "redis", ".", "ConnectionPool", "(", "host", "=", "HOST", ",", "port", "=...
Initialize a redis connection by each connection string defined in the configuration file
[ "Initialize", "a", "redis", "connection", "by", "each", "connection", "string", "defined", "in", "the", "configuration", "file" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/redis/connection.py#L62-L71
Riffstation/flask-philo
flask_philo/db/redis/connection.py
initialize
def initialize(g, app): """ If redis connection parameters are defined in configuration params a session will be created """ if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']: # Initialize connections for console commands for k, v in app.config['DATABASES']['REDIS...
python
def initialize(g, app): """ If redis connection parameters are defined in configuration params a session will be created """ if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']: # Initialize connections for console commands for k, v in app.config['DATABASES']['REDIS...
[ "def", "initialize", "(", "g", ",", "app", ")", ":", "if", "'DATABASES'", "in", "app", ".", "config", "and", "'REDIS'", "in", "app", ".", "config", "[", "'DATABASES'", "]", ":", "# Initialize connections for console commands", "for", "k", ",", "v", "in", "...
If redis connection parameters are defined in configuration params a session will be created
[ "If", "redis", "connection", "parameters", "are", "defined", "in", "configuration", "params", "a", "session", "will", "be", "created" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/redis/connection.py#L74-L101
Riffstation/flask-philo
flask_philo/serializers.py
BaseSerializer._initialize_from_dict
def _initialize_from_dict(self, data): """ Loads serializer from a request object """ self._json = data self._validate() for name, value in self._json.items(): if name in self._properties: if '$ref' in self._properties[name]: ...
python
def _initialize_from_dict(self, data): """ Loads serializer from a request object """ self._json = data self._validate() for name, value in self._json.items(): if name in self._properties: if '$ref' in self._properties[name]: ...
[ "def", "_initialize_from_dict", "(", "self", ",", "data", ")", ":", "self", ".", "_json", "=", "data", "self", ".", "_validate", "(", ")", "for", "name", ",", "value", "in", "self", ".", "_json", ".", "items", "(", ")", ":", "if", "name", "in", "se...
Loads serializer from a request object
[ "Loads", "serializer", "from", "a", "request", "object" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L60-L81
Riffstation/flask-philo
flask_philo/serializers.py
BaseSerializer._initialize_from_model
def _initialize_from_model(self, model): """ Loads a model from """ for name, value in model.__dict__.items(): if name in self._properties: setattr(self, name, value)
python
def _initialize_from_model(self, model): """ Loads a model from """ for name, value in model.__dict__.items(): if name in self._properties: setattr(self, name, value)
[ "def", "_initialize_from_model", "(", "self", ",", "model", ")", ":", "for", "name", ",", "value", "in", "model", ".", "__dict__", ".", "items", "(", ")", ":", "if", "name", "in", "self", ".", "_properties", ":", "setattr", "(", "self", ",", "name", ...
Loads a model from
[ "Loads", "a", "model", "from" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L83-L89
Riffstation/flask-philo
flask_philo/serializers.py
BaseSerializer.update
def update(self): """ Finds record and update it based in serializer values """ obj = self.__model__.objects.get_for_update(id=self.id) for name, value in self.__dict__.items(): if name in self._properties: setattr(obj, name, value) obj.update(...
python
def update(self): """ Finds record and update it based in serializer values """ obj = self.__model__.objects.get_for_update(id=self.id) for name, value in self.__dict__.items(): if name in self._properties: setattr(obj, name, value) obj.update(...
[ "def", "update", "(", "self", ")", ":", "obj", "=", "self", ".", "__model__", ".", "objects", ".", "get_for_update", "(", "id", "=", "self", ".", "id", ")", "for", "name", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", ...
Finds record and update it based in serializer values
[ "Finds", "record", "and", "update", "it", "based", "in", "serializer", "values" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L91-L100
Riffstation/flask-philo
flask_philo/serializers.py
BaseSerializer.to_json
def to_json(self): """ Returns a json representation """ data = {} for k, v in self.__dict__.items(): if not k.startswith('_'): # values not serializable, should be converted to strings if isinstance(v, datetime): v ...
python
def to_json(self): """ Returns a json representation """ data = {} for k, v in self.__dict__.items(): if not k.startswith('_'): # values not serializable, should be converted to strings if isinstance(v, datetime): v ...
[ "def", "to_json", "(", "self", ")", ":", "data", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "not", "k", ".", "startswith", "(", "'_'", ")", ":", "# values not serializable, should be converted...
Returns a json representation
[ "Returns", "a", "json", "representation" ]
train
https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L102-L119
remram44/usagestats
usagestats.py
OPERATING_SYSTEM
def OPERATING_SYSTEM(stats, info): """General information about the operating system. This is a flag you can pass to `Stats.submit()`. """ info.append(('architecture', platform.machine().lower())) info.append(('distribution', "%s;%s" % (platform.linux_distribution()[0:2]))) inf...
python
def OPERATING_SYSTEM(stats, info): """General information about the operating system. This is a flag you can pass to `Stats.submit()`. """ info.append(('architecture', platform.machine().lower())) info.append(('distribution', "%s;%s" % (platform.linux_distribution()[0:2]))) inf...
[ "def", "OPERATING_SYSTEM", "(", "stats", ",", "info", ")", ":", "info", ".", "append", "(", "(", "'architecture'", ",", "platform", ".", "machine", "(", ")", ".", "lower", "(", ")", ")", ")", "info", ".", "append", "(", "(", "'distribution'", ",", "\...
General information about the operating system. This is a flag you can pass to `Stats.submit()`.
[ "General", "information", "about", "the", "operating", "system", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L41-L50
remram44/usagestats
usagestats.py
SESSION_TIME
def SESSION_TIME(stats, info): """Total time of this session. Reports the time elapsed from the construction of the `Stats` object to this `submit()` call. This is a flag you can pass to `Stats.submit()`. """ duration = time.time() - stats.started_time secs = int(duration) msecs = int(...
python
def SESSION_TIME(stats, info): """Total time of this session. Reports the time elapsed from the construction of the `Stats` object to this `submit()` call. This is a flag you can pass to `Stats.submit()`. """ duration = time.time() - stats.started_time secs = int(duration) msecs = int(...
[ "def", "SESSION_TIME", "(", "stats", ",", "info", ")", ":", "duration", "=", "time", ".", "time", "(", ")", "-", "stats", ".", "started_time", "secs", "=", "int", "(", "duration", ")", "msecs", "=", "int", "(", "(", "duration", "-", "secs", ")", "*...
Total time of this session. Reports the time elapsed from the construction of the `Stats` object to this `submit()` call. This is a flag you can pass to `Stats.submit()`.
[ "Total", "time", "of", "this", "session", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L53-L64
remram44/usagestats
usagestats.py
PYTHON_VERSION
def PYTHON_VERSION(stats, info): """Python interpreter version. This is a flag you can pass to `Stats.submit()`. """ # Some versions of Python have a \n in sys.version! version = sys.version.replace(' \n', ' ').replace('\n', ' ') python = ';'.join([str(c) for c in sys.version_info] + [version])...
python
def PYTHON_VERSION(stats, info): """Python interpreter version. This is a flag you can pass to `Stats.submit()`. """ # Some versions of Python have a \n in sys.version! version = sys.version.replace(' \n', ' ').replace('\n', ' ') python = ';'.join([str(c) for c in sys.version_info] + [version])...
[ "def", "PYTHON_VERSION", "(", "stats", ",", "info", ")", ":", "# Some versions of Python have a \\n in sys.version!", "version", "=", "sys", ".", "version", ".", "replace", "(", "' \\n'", ",", "' '", ")", ".", "replace", "(", "'\\n'", ",", "' '", ")", "python"...
Python interpreter version. This is a flag you can pass to `Stats.submit()`.
[ "Python", "interpreter", "version", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L67-L75
remram44/usagestats
usagestats.py
Stats.read_config
def read_config(self): """Reads the configuration. This method can be overloaded to integrate with your application's own configuration mechanism. By default, a single 'status' file is read from the reports' directory. This should set `self.status` to one of the state constants...
python
def read_config(self): """Reads the configuration. This method can be overloaded to integrate with your application's own configuration mechanism. By default, a single 'status' file is read from the reports' directory. This should set `self.status` to one of the state constants...
[ "def", "read_config", "(", "self", ")", ":", "if", "self", ".", "enabled", "and", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "location", ")", ":", "try", ":", "os", ".", "makedirs", "(", "self", ".", "location", ",", "0o700", ")", ...
Reads the configuration. This method can be overloaded to integrate with your application's own configuration mechanism. By default, a single 'status' file is read from the reports' directory. This should set `self.status` to one of the state constants, and make sure `self.loca...
[ "Reads", "the", "configuration", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L180-L214
remram44/usagestats
usagestats.py
Stats.write_config
def write_config(self, enabled): """Writes the configuration. This method can be overloaded to integrate with your application's own configuration mechanism. By default, a single 'status' file is written in the reports' directory, containing either ``ENABLED`` or ``DISABLED``; i...
python
def write_config(self, enabled): """Writes the configuration. This method can be overloaded to integrate with your application's own configuration mechanism. By default, a single 'status' file is written in the reports' directory, containing either ``ENABLED`` or ``DISABLED``; i...
[ "def", "write_config", "(", "self", ",", "enabled", ")", ":", "status_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "location", ",", "'status'", ")", "with", "open", "(", "status_file", ",", "'w'", ")", "as", "fp", ":", "if", "enabled...
Writes the configuration. This method can be overloaded to integrate with your application's own configuration mechanism. By default, a single 'status' file is written in the reports' directory, containing either ``ENABLED`` or ``DISABLED``; if the file doesn't exist, `UNSET` is assumed...
[ "Writes", "the", "configuration", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L216-L234
remram44/usagestats
usagestats.py
Stats.enable_reporting
def enable_reporting(self): """Call this method to explicitly enable reporting. The current report will be uploaded, plus the previously recorded ones, and the configuration will be updated so that future runs also upload automatically. """ if self.status == Stats.ENABLE...
python
def enable_reporting(self): """Call this method to explicitly enable reporting. The current report will be uploaded, plus the previously recorded ones, and the configuration will be updated so that future runs also upload automatically. """ if self.status == Stats.ENABLE...
[ "def", "enable_reporting", "(", "self", ")", ":", "if", "self", ".", "status", "==", "Stats", ".", "ENABLED", ":", "return", "if", "not", "self", ".", "enableable", ":", "logger", ".", "critical", "(", "\"Can't enable reporting\"", ")", "return", "self", "...
Call this method to explicitly enable reporting. The current report will be uploaded, plus the previously recorded ones, and the configuration will be updated so that future runs also upload automatically.
[ "Call", "this", "method", "to", "explicitly", "enable", "reporting", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L236-L249
remram44/usagestats
usagestats.py
Stats.disable_reporting
def disable_reporting(self): """Call this method to explicitly disable reporting. The current report will be discarded, along with the previously recorded ones that haven't been uploaded. The configuration is updated so that future runs do not record or upload reports. """ ...
python
def disable_reporting(self): """Call this method to explicitly disable reporting. The current report will be discarded, along with the previously recorded ones that haven't been uploaded. The configuration is updated so that future runs do not record or upload reports. """ ...
[ "def", "disable_reporting", "(", "self", ")", ":", "if", "self", ".", "status", "==", "Stats", ".", "DISABLED", ":", "return", "if", "not", "self", ".", "disableable", ":", "logger", ".", "critical", "(", "\"Can't disable reporting\"", ")", "return", "self",...
Call this method to explicitly disable reporting. The current report will be discarded, along with the previously recorded ones that haven't been uploaded. The configuration is updated so that future runs do not record or upload reports.
[ "Call", "this", "method", "to", "explicitly", "disable", "reporting", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L251-L271
remram44/usagestats
usagestats.py
Stats.note
def note(self, info): """Record some info to the report. :param info: Dictionary of info to record. Note that previous info recorded under the same keys will not be overwritten. """ if self.recording: if self.notes is None: raise ValueError("This repo...
python
def note(self, info): """Record some info to the report. :param info: Dictionary of info to record. Note that previous info recorded under the same keys will not be overwritten. """ if self.recording: if self.notes is None: raise ValueError("This repo...
[ "def", "note", "(", "self", ",", "info", ")", ":", "if", "self", ".", "recording", ":", "if", "self", ".", "notes", "is", "None", ":", "raise", "ValueError", "(", "\"This report has already been submitted\"", ")", "self", ".", "notes", ".", "extend", "(", ...
Record some info to the report. :param info: Dictionary of info to record. Note that previous info recorded under the same keys will not be overwritten.
[ "Record", "some", "info", "to", "the", "report", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L282-L291
remram44/usagestats
usagestats.py
Stats.submit
def submit(self, info, *flags): """Finish recording and upload or save the report. This closes the `Stats` object, no further methods should be called. The report is either saved, uploaded or discarded, depending on configuration. If uploading is enabled, previous reports might be ...
python
def submit(self, info, *flags): """Finish recording and upload or save the report. This closes the `Stats` object, no further methods should be called. The report is either saved, uploaded or discarded, depending on configuration. If uploading is enabled, previous reports might be ...
[ "def", "submit", "(", "self", ",", "info", ",", "*", "flags", ")", ":", "if", "not", "self", ".", "recording", ":", "return", "env_val", "=", "os", ".", "environ", ".", "get", "(", "self", ".", "env_var", ",", "''", ")", ".", "lower", "(", ")", ...
Finish recording and upload or save the report. This closes the `Stats` object, no further methods should be called. The report is either saved, uploaded or discarded, depending on configuration. If uploading is enabled, previous reports might be uploaded too. If uploading is not explic...
[ "Finish", "recording", "and", "upload", "or", "save", "the", "report", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L293-L383
remram44/usagestats
wsgi/usagestats_server.py
store
def store(report, address): """Stores the report on disk. """ now = time.time() secs = int(now) msecs = int((now - secs) * 1000) submitted_date = filename = None # avoids warnings while True: submitted_date = '%d.%03d' % (secs, msecs) filename = 'report_%s.txt' % submitted_d...
python
def store(report, address): """Stores the report on disk. """ now = time.time() secs = int(now) msecs = int((now - secs) * 1000) submitted_date = filename = None # avoids warnings while True: submitted_date = '%d.%03d' % (secs, msecs) filename = 'report_%s.txt' % submitted_d...
[ "def", "store", "(", "report", ",", "address", ")", ":", "now", "=", "time", ".", "time", "(", ")", "secs", "=", "int", "(", "now", ")", "msecs", "=", "int", "(", "(", "now", "-", "secs", ")", "*", "1000", ")", "submitted_date", "=", "filename", ...
Stores the report on disk.
[ "Stores", "the", "report", "on", "disk", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/wsgi/usagestats_server.py#L17-L47
remram44/usagestats
wsgi/usagestats_server.py
application
def application(environ, start_response): """WSGI interface. """ def send_response(status, body): if not isinstance(body, bytes): body = body.encode('utf-8') start_response(status, [('Content-Type', 'text/plain'), ('Content-Length', '%d' % len(bo...
python
def application(environ, start_response): """WSGI interface. """ def send_response(status, body): if not isinstance(body, bytes): body = body.encode('utf-8') start_response(status, [('Content-Type', 'text/plain'), ('Content-Length', '%d' % len(bo...
[ "def", "application", "(", "environ", ",", "start_response", ")", ":", "def", "send_response", "(", "status", ",", "body", ")", ":", "if", "not", "isinstance", "(", "body", ",", "bytes", ")", ":", "body", "=", "body", ".", "encode", "(", "'utf-8'", ")"...
WSGI interface.
[ "WSGI", "interface", "." ]
train
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/wsgi/usagestats_server.py#L50-L83
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.read
def read(self, pin): """ Read the pin state of an input pin. Make sure you put the pin in input modus with the IODIR* register or direction_* attribute first. :Example: >>> expander = MCP23017I2C(gw) >>> # Read the logic level on pin B3 >>> expander.read('B3') F...
python
def read(self, pin): """ Read the pin state of an input pin. Make sure you put the pin in input modus with the IODIR* register or direction_* attribute first. :Example: >>> expander = MCP23017I2C(gw) >>> # Read the logic level on pin B3 >>> expander.read('B3') F...
[ "def", "read", "(", "self", ",", "pin", ")", ":", "port", ",", "pin", "=", "self", ".", "pin_to_port", "(", "pin", ")", "self", ".", "i2c_write", "(", "[", "0x12", "+", "port", "]", ")", "raw", "=", "self", ".", "i2c_read", "(", "1", ")", "valu...
Read the pin state of an input pin. Make sure you put the pin in input modus with the IODIR* register or direction_* attribute first. :Example: >>> expander = MCP23017I2C(gw) >>> # Read the logic level on pin B3 >>> expander.read('B3') False >>> # Read the logic...
[ "Read", "the", "pin", "state", "of", "an", "input", "pin", ".", "Make", "sure", "you", "put", "the", "pin", "in", "input", "modus", "with", "the", "IODIR", "*", "register", "or", "direction_", "*", "attribute", "first", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L142-L163
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.read_port
def read_port(self, port): """ Read the pin state of a whole port (8 pins) :Example: >>> expander = MCP23017I2C(gw) >>> # Read pin A0-A7 as a int (A0 and A1 are high) >>> expander.read_port('A') 3 >>> # Read pin B0-B7 as a int (B2 is high) >>> expander.r...
python
def read_port(self, port): """ Read the pin state of a whole port (8 pins) :Example: >>> expander = MCP23017I2C(gw) >>> # Read pin A0-A7 as a int (A0 and A1 are high) >>> expander.read_port('A') 3 >>> # Read pin B0-B7 as a int (B2 is high) >>> expander.r...
[ "def", "read_port", "(", "self", ",", "port", ")", ":", "if", "port", "==", "'A'", ":", "raw", "=", "self", ".", "i2c_read_register", "(", "0x12", ",", "1", ")", "elif", "port", "==", "'B'", ":", "raw", "=", "self", ".", "i2c_read_register", "(", "...
Read the pin state of a whole port (8 pins) :Example: >>> expander = MCP23017I2C(gw) >>> # Read pin A0-A7 as a int (A0 and A1 are high) >>> expander.read_port('A') 3 >>> # Read pin B0-B7 as a int (B2 is high) >>> expander.read_port('B') 4 :param...
[ "Read", "the", "pin", "state", "of", "a", "whole", "port", "(", "8", "pins", ")" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L165-L185
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.write
def write(self, pin, value): """ Set the pin state. Make sure you put the pin in output mode first. :param pin: The label for the pin to write to. (Ex. A0) :param value: Boolean representing the new state """ port, pin = self.pin_to_port(pin) portname = 'A' ...
python
def write(self, pin, value): """ Set the pin state. Make sure you put the pin in output mode first. :param pin: The label for the pin to write to. (Ex. A0) :param value: Boolean representing the new state """ port, pin = self.pin_to_port(pin) portname = 'A' ...
[ "def", "write", "(", "self", ",", "pin", ",", "value", ")", ":", "port", ",", "pin", "=", "self", ".", "pin_to_port", "(", "pin", ")", "portname", "=", "'A'", "if", "port", "==", "1", ":", "portname", "=", "'B'", "self", ".", "_update_register", "(...
Set the pin state. Make sure you put the pin in output mode first. :param pin: The label for the pin to write to. (Ex. A0) :param value: Boolean representing the new state
[ "Set", "the", "pin", "state", ".", "Make", "sure", "you", "put", "the", "pin", "in", "output", "mode", "first", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L187-L199
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.write_port
def write_port(self, port, value): """ Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255) """ if port == 'A': self.GPIOA = value elif port == 'B': self.GPIOB = value ...
python
def write_port(self, port, value): """ Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255) """ if port == 'A': self.GPIOA = value elif port == 'B': self.GPIOB = value ...
[ "def", "write_port", "(", "self", ",", "port", ",", "value", ")", ":", "if", "port", "==", "'A'", ":", "self", ".", "GPIOA", "=", "value", "elif", "port", "==", "'B'", ":", "self", ".", "GPIOB", "=", "value", "else", ":", "raise", "AttributeError", ...
Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255)
[ "Use", "a", "whole", "port", "as", "a", "bus", "and", "write", "a", "byte", "to", "it", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L201-L213
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.sync
def sync(self): """ Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the h...
python
def sync(self): """ Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the h...
[ "def", "sync", "(", "self", ")", ":", "registers", "=", "{", "0x00", ":", "'IODIRA'", ",", "0x01", ":", "'IODIRB'", ",", "0x02", ":", "'IPOLA'", ",", "0x03", ":", "'IPOLB'", ",", "0x04", ":", "'GPINTENA'", ",", "0x05", ":", "'GPINTENB'", ",", "0x0C",...
Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the helper attributes (mcp23017.d...
[ "Upload", "the", "changed", "registers", "to", "the", "chip" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L215-L238
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.get_pins
def get_pins(self): """ Get a list containing references to all 16 pins of the chip. :Example: >>> expander = MCP23017I2C(gw) >>> pins = expander.get_pins() >>> pprint.pprint(pins) [<GPIOPin A0 on MCP23017I2C>, <GPIOPin A1 on MCP23017I2C>, <GPIOPin A2 ...
python
def get_pins(self): """ Get a list containing references to all 16 pins of the chip. :Example: >>> expander = MCP23017I2C(gw) >>> pins = expander.get_pins() >>> pprint.pprint(pins) [<GPIOPin A0 on MCP23017I2C>, <GPIOPin A1 on MCP23017I2C>, <GPIOPin A2 ...
[ "def", "get_pins", "(", "self", ")", ":", "result", "=", "[", "]", "for", "a", "in", "range", "(", "0", ",", "7", ")", ":", "result", ".", "append", "(", "GPIOPin", "(", "self", ",", "'_action'", ",", "{", "'pin'", ":", "'A{}'", ".", "format", ...
Get a list containing references to all 16 pins of the chip. :Example: >>> expander = MCP23017I2C(gw) >>> pins = expander.get_pins() >>> pprint.pprint(pins) [<GPIOPin A0 on MCP23017I2C>, <GPIOPin A1 on MCP23017I2C>, <GPIOPin A2 on MCP23017I2C>, <GPIOP...
[ "Get", "a", "list", "containing", "references", "to", "all", "16", "pins", "of", "the", "chip", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L260-L290
MartijnBraam/pyElectronics
electronics/pin.py
DigitalInputPin.read
def read(self): """ Get the logic input level for the pin :return: True if the input is high """ m = getattr(self.chip, self.method) return m(**self.arguments)
python
def read(self): """ Get the logic input level for the pin :return: True if the input is high """ m = getattr(self.chip, self.method) return m(**self.arguments)
[ "def", "read", "(", "self", ")", ":", "m", "=", "getattr", "(", "self", ".", "chip", ",", "self", ".", "method", ")", "return", "m", "(", "*", "*", "self", ".", "arguments", ")" ]
Get the logic input level for the pin :return: True if the input is high
[ "Get", "the", "logic", "input", "level", "for", "the", "pin" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/pin.py#L29-L35
MartijnBraam/pyElectronics
electronics/pin.py
GPIOPin.write
def write(self, value): """ Set the logic output level for the pin. :type value: bool :param value: True for a logic high """ if self.inverted: value = not value m = getattr(self.chip, self.method) m(value=value, **self.arguments)
python
def write(self, value): """ Set the logic output level for the pin. :type value: bool :param value: True for a logic high """ if self.inverted: value = not value m = getattr(self.chip, self.method) m(value=value, **self.arguments)
[ "def", "write", "(", "self", ",", "value", ")", ":", "if", "self", ".", "inverted", ":", "value", "=", "not", "value", "m", "=", "getattr", "(", "self", ".", "chip", ",", "self", ".", "method", ")", "m", "(", "value", "=", "value", ",", "*", "*...
Set the logic output level for the pin. :type value: bool :param value: True for a logic high
[ "Set", "the", "logic", "output", "level", "for", "the", "pin", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/pin.py#L72-L81
inveniosoftware/invenio-theme
invenio_theme/ext.py
InvenioTheme.init_app
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ self.init_config(app) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_...
python
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ self.init_config(app) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_...
[ "def", "init_app", "(", "self", ",", "app", ",", "*", "*", "kwargs", ")", ":", "self", ".", "init_config", "(", "app", ")", "# Initialize extensions", "self", ".", "menu_ext", ".", "init_app", "(", "app", ")", "self", ".", "menu", "=", "app", ".", "e...
Initialize application object. :param app: An instance of :class:`~flask.Flask`.
[ "Initialize", "application", "object", "." ]
train
https://github.com/inveniosoftware/invenio-theme/blob/4e07607b1a40805df1d8e4ab9cc2afd728579ca9/invenio_theme/ext.py#L39-L74
inveniosoftware/invenio-theme
invenio_theme/ext.py
InvenioTheme.init_config
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ _vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE'] # Sets RequireJS config and SASS binary as well if not already set. for k in dir(config): ...
python
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ _vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE'] # Sets RequireJS config and SASS binary as well if not already set. for k in dir(config): ...
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "_vars", "=", "[", "'BASE_TEMPLATE'", ",", "'COVER_TEMPLATE'", ",", "'SETTINGS_TEMPLATE'", "]", "# Sets RequireJS config and SASS binary as well if not already set.", "for", "k", "in", "dir", "(", "config", ")",...
Initialize configuration. :param app: An instance of :class:`~flask.Flask`.
[ "Initialize", "configuration", "." ]
train
https://github.com/inveniosoftware/invenio-theme/blob/4e07607b1a40805df1d8e4ab9cc2afd728579ca9/invenio_theme/ext.py#L76-L97
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.set_range
def set_range(self, accel=1, gyro=1): """Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gat...
python
def set_range(self, accel=1, gyro=1): """Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gat...
[ "def", "set_range", "(", "self", ",", "accel", "=", "1", ",", "gyro", "=", "1", ")", ":", "self", ".", "i2c_write_register", "(", "0x1c", ",", "accel", ")", "self", ".", "i2c_write_register", "(", "0x1b", ",", "gyro", ")", "self", ".", "accel_range", ...
Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range...
[ "Set", "the", "measurement", "range", "for", "the", "accel", "and", "gyro", "MEMS", ".", "Higher", "range", "means", "less", "resolution", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L55-L75
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.set_slave_bus_bypass
def set_slave_bus_bypass(self, enable): """Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly Dont forget to use wakeup() or else the slave bus is unavailable :param enable: :return: """ current = self.i2c_read_register(0x...
python
def set_slave_bus_bypass(self, enable): """Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly Dont forget to use wakeup() or else the slave bus is unavailable :param enable: :return: """ current = self.i2c_read_register(0x...
[ "def", "set_slave_bus_bypass", "(", "self", ",", "enable", ")", ":", "current", "=", "self", ".", "i2c_read_register", "(", "0x37", ",", "1", ")", "[", "0", "]", "if", "enable", ":", "current", "|=", "0b00000010", "else", ":", "current", "&=", "0b1111110...
Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly Dont forget to use wakeup() or else the slave bus is unavailable :param enable: :return:
[ "Put", "the", "aux", "i2c", "bus", "on", "the", "MPU", "-", "6050", "in", "bypass", "mode", "thus", "connecting", "it", "to", "the", "main", "i2c", "bus", "directly" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L77-L89
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.temperature
def temperature(self): """Read the value for the internal temperature sensor. :returns: Temperature in degree celcius as float :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.temperature() 49.38 """ if not self.awake: ...
python
def temperature(self): """Read the value for the internal temperature sensor. :returns: Temperature in degree celcius as float :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.temperature() 49.38 """ if not self.awake: ...
[ "def", "temperature", "(", "self", ")", ":", "if", "not", "self", ".", "awake", ":", "raise", "Exception", "(", "\"MPU6050 is in sleep mode, use wakeup()\"", ")", "raw", "=", "self", ".", "i2c_read_register", "(", "0x41", ",", "2", ")", "raw", "=", "struct",...
Read the value for the internal temperature sensor. :returns: Temperature in degree celcius as float :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.temperature() 49.38
[ "Read", "the", "value", "for", "the", "internal", "temperature", "sensor", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L101-L118
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.acceleration
def acceleration(self): """Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125) """ if not se...
python
def acceleration(self): """Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125) """ if not se...
[ "def", "acceleration", "(", "self", ")", ":", "if", "not", "self", ".", "awake", ":", "raise", "Exception", "(", "\"MPU6050 is in sleep mode, use wakeup()\"", ")", "raw", "=", "self", ".", "i2c_read_register", "(", "0x3B", ",", "6", ")", "x", ",", "y", ","...
Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125)
[ "Return", "the", "acceleration", "in", "G", "s" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L120-L144
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.angular_rate
def angular_rate(self): """Return the angular rate for every axis in degree/second. :returns: Angular rate for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.angular_rate() (1.380859375, 1.6318359375, 1.8828125) ...
python
def angular_rate(self): """Return the angular rate for every axis in degree/second. :returns: Angular rate for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.angular_rate() (1.380859375, 1.6318359375, 1.8828125) ...
[ "def", "angular_rate", "(", "self", ")", ":", "if", "not", "self", ".", "awake", ":", "raise", "Exception", "(", "\"MPU6050 is in sleep mode, use wakeup()\"", ")", "raw", "=", "self", ".", "i2c_read_register", "(", "0x43", ",", "6", ")", "x", ",", "y", ","...
Return the angular rate for every axis in degree/second. :returns: Angular rate for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.angular_rate() (1.380859375, 1.6318359375, 1.8828125)
[ "Return", "the", "angular", "rate", "for", "every", "axis", "in", "degree", "/", "second", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L146-L170
inveniosoftware/invenio-theme
invenio_theme/bundles.py
LazyNpmBundle._get_contents
def _get_contents(self): """Create strings from lazy strings.""" return [ str(value) if is_lazy_string(value) else value for value in super(LazyNpmBundle, self)._get_contents() ]
python
def _get_contents(self): """Create strings from lazy strings.""" return [ str(value) if is_lazy_string(value) else value for value in super(LazyNpmBundle, self)._get_contents() ]
[ "def", "_get_contents", "(", "self", ")", ":", "return", "[", "str", "(", "value", ")", "if", "is_lazy_string", "(", "value", ")", "else", "value", "for", "value", "in", "super", "(", "LazyNpmBundle", ",", "self", ")", ".", "_get_contents", "(", ")", "...
Create strings from lazy strings.
[ "Create", "strings", "from", "lazy", "strings", "." ]
train
https://github.com/inveniosoftware/invenio-theme/blob/4e07607b1a40805df1d8e4ab9cc2afd728579ca9/invenio_theme/bundles.py#L33-L38
MartijnBraam/pyElectronics
electronics/devices/bmp180.py
BMP180.load_calibration
def load_calibration(self): """Load factory calibration data from device.""" registers = self.i2c_read_register(0xAA, 22) ( self.cal['AC1'], self.cal['AC2'], self.cal['AC3'], self.cal['AC4'], self.cal['AC5'], self.cal['AC6']...
python
def load_calibration(self): """Load factory calibration data from device.""" registers = self.i2c_read_register(0xAA, 22) ( self.cal['AC1'], self.cal['AC2'], self.cal['AC3'], self.cal['AC4'], self.cal['AC5'], self.cal['AC6']...
[ "def", "load_calibration", "(", "self", ")", ":", "registers", "=", "self", ".", "i2c_read_register", "(", "0xAA", ",", "22", ")", "(", "self", ".", "cal", "[", "'AC1'", "]", ",", "self", ".", "cal", "[", "'AC2'", "]", ",", "self", ".", "cal", "[",...
Load factory calibration data from device.
[ "Load", "factory", "calibration", "data", "from", "device", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/bmp180.py#L59-L74
MartijnBraam/pyElectronics
electronics/devices/bmp180.py
BMP180.temperature
def temperature(self): """Get the temperature from the sensor. :returns: The temperature in degree celcius as a float :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.temperature() 21.4 """ ut = self.get_raw_temp() ...
python
def temperature(self): """Get the temperature from the sensor. :returns: The temperature in degree celcius as a float :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.temperature() 21.4 """ ut = self.get_raw_temp() ...
[ "def", "temperature", "(", "self", ")", ":", "ut", "=", "self", ".", "get_raw_temp", "(", ")", "x1", "=", "(", "(", "ut", "-", "self", ".", "cal", "[", "'AC6'", "]", ")", "*", "self", ".", "cal", "[", "'AC5'", "]", ")", ">>", "15", "x2", "=",...
Get the temperature from the sensor. :returns: The temperature in degree celcius as a float :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.temperature() 21.4
[ "Get", "the", "temperature", "from", "the", "sensor", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/bmp180.py#L87-L104
MartijnBraam/pyElectronics
electronics/devices/bmp180.py
BMP180.pressure
def pressure(self): """ Get barometric pressure in milibar :returns: The pressure in milibar as a int :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.pressure() 75216 """ ut = self.get_raw_temp() up = ...
python
def pressure(self): """ Get barometric pressure in milibar :returns: The pressure in milibar as a int :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.pressure() 75216 """ ut = self.get_raw_temp() up = ...
[ "def", "pressure", "(", "self", ")", ":", "ut", "=", "self", ".", "get_raw_temp", "(", ")", "up", "=", "self", ".", "get_raw_pressure", "(", ")", "x1", "=", "(", "(", "ut", "-", "self", ".", "cal", "[", "'AC6'", "]", ")", "*", "self", ".", "cal...
Get barometric pressure in milibar :returns: The pressure in milibar as a int :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.pressure() 75216
[ "Get", "barometric", "pressure", "in", "milibar" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/bmp180.py#L106-L143
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
BusPirate.switch_mode
def switch_mode(self, new_mode): """ Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants """ packet = bytearray() packet.append(new_mode) self.device.write(packet) possible_responses = { sel...
python
def switch_mode(self, new_mode): """ Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants """ packet = bytearray() packet.append(new_mode) self.device.write(packet) possible_responses = { sel...
[ "def", "switch_mode", "(", "self", ",", "new_mode", ")", ":", "packet", "=", "bytearray", "(", ")", "packet", ".", "append", "(", "new_mode", ")", "self", ".", "device", ".", "write", "(", "packet", ")", "possible_responses", "=", "{", "self", ".", "MO...
Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants
[ "Explicitly", "switch", "the", "Bus", "Pirate", "mode" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L79-L101
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
BusPirate.set_peripheral
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to ena...
python
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to ena...
[ "def", "set_peripheral", "(", "self", ",", "power", "=", "None", ",", "pullup", "=", "None", ",", "aux", "=", "None", ",", "chip_select", "=", "None", ")", ":", "if", "power", "is", "not", "None", ":", "self", ".", "power", "=", "power", "if", "pul...
Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to enable the internal pull-up resistors. False to disable :param aux: Set the AUX pin ou...
[ "Set", "the", "peripheral", "config", "at", "runtime", ".", "If", "a", "parameter", "is", "None", "then", "the", "config", "will", "not", "be", "changed", "." ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L103-L134
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
BusPirate._set_i2c_speed
def _set_i2c_speed(self, i2c_speed): """ Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz' """ lower_bits_mapping = { '400kHz': 3, '100kHz': 2, '50kHz': 1, '5kHz': 0, } if i2c_speed not in lower_bits_mapping: ra...
python
def _set_i2c_speed(self, i2c_speed): """ Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz' """ lower_bits_mapping = { '400kHz': 3, '100kHz': 2, '50kHz': 1, '5kHz': 0, } if i2c_speed not in lower_bits_mapping: ra...
[ "def", "_set_i2c_speed", "(", "self", ",", "i2c_speed", ")", ":", "lower_bits_mapping", "=", "{", "'400kHz'", ":", "3", ",", "'100kHz'", ":", "2", ",", "'50kHz'", ":", "1", ",", "'5kHz'", ":", "0", ",", "}", "if", "i2c_speed", "not", "in", "lower_bits_...
Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz'
[ "Set", "I2C", "speed", "to", "one", "of", "400kHz", "100kHz", "50kHz", "5kHz" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L211-L226
MartijnBraam/pyElectronics
electronics/devices/hmc5883l.py
HMC5883L.config
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL): """ Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants """ averaging_con...
python
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL): """ Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants """ averaging_con...
[ "def", "config", "(", "self", ",", "averaging", "=", "1", ",", "datarate", "=", "15", ",", "mode", "=", "MODE_NORMAL", ")", ":", "averaging_conf", "=", "{", "1", ":", "0", ",", "2", ":", "1", ",", "4", ":", "2", ",", "8", ":", "3", "}", "if",...
Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants
[ "Set", "the", "base", "config", "for", "sensor" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/hmc5883l.py#L37-L72
MartijnBraam/pyElectronics
electronics/devices/hmc5883l.py
HMC5883L.set_resolution
def set_resolution(self, resolution=1090): """ Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss. The possible options are: ======================= ========== ============= Recommended Gauss range Resolution Gauss per bi...
python
def set_resolution(self, resolution=1090): """ Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss. The possible options are: ======================= ========== ============= Recommended Gauss range Resolution Gauss per bi...
[ "def", "set_resolution", "(", "self", ",", "resolution", "=", "1090", ")", ":", "options", "=", "{", "1370", ":", "0", ",", "1090", ":", "1", ",", "820", ":", "2", ",", "660", ":", "3", ",", "440", ":", "4", ",", "390", ":", "5", ",", "330", ...
Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss. The possible options are: ======================= ========== ============= Recommended Gauss range Resolution Gauss per bit ======================= ========== ============= ...
[ "Set", "the", "resolution", "of", "the", "sensor" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/hmc5883l.py#L74-L113
MartijnBraam/pyElectronics
electronics/devices/hmc5883l.py
HMC5883L.gauss
def gauss(self): """ Get the magnetometer values as gauss for each axis as a tuple (x,y,z) :example: >>> sensor = HMC5883L(gw) >>> sensor.gauss() (16.56, 21.2888, 26.017599999999998) """ raw = self.raw() factors = { 1370: 0.73, ...
python
def gauss(self): """ Get the magnetometer values as gauss for each axis as a tuple (x,y,z) :example: >>> sensor = HMC5883L(gw) >>> sensor.gauss() (16.56, 21.2888, 26.017599999999998) """ raw = self.raw() factors = { 1370: 0.73, ...
[ "def", "gauss", "(", "self", ")", ":", "raw", "=", "self", ".", "raw", "(", ")", "factors", "=", "{", "1370", ":", "0.73", ",", "1090", ":", "0.92", ",", "820", ":", "1.22", ",", "660", ":", "1.52", ",", "440", ":", "2.27", ",", "390", ":", ...
Get the magnetometer values as gauss for each axis as a tuple (x,y,z) :example: >>> sensor = HMC5883L(gw) >>> sensor.gauss() (16.56, 21.2888, 26.017599999999998)
[ "Get", "the", "magnetometer", "values", "as", "gauss", "for", "each", "axis", "as", "a", "tuple", "(", "x", "y", "z", ")" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/hmc5883l.py#L128-L150
MartijnBraam/pyElectronics
electronics/devices/lm75.py
LM75.temperature
def temperature(self): """ Get the temperature in degree celcius """ result = self.i2c_read(2) value = struct.unpack('>H', result)[0] if value < 32768: return value / 256.0 else: return (value - 65536) / 256.0
python
def temperature(self): """ Get the temperature in degree celcius """ result = self.i2c_read(2) value = struct.unpack('>H', result)[0] if value < 32768: return value / 256.0 else: return (value - 65536) / 256.0
[ "def", "temperature", "(", "self", ")", ":", "result", "=", "self", ".", "i2c_read", "(", "2", ")", "value", "=", "struct", ".", "unpack", "(", "'>H'", ",", "result", ")", "[", "0", "]", "if", "value", "<", "32768", ":", "return", "value", "/", "...
Get the temperature in degree celcius
[ "Get", "the", "temperature", "in", "degree", "celcius" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/lm75.py#L29-L38
MartijnBraam/pyElectronics
electronics/devices/segmentdisplay.py
SegmentDisplayGPIO.write
def write(self, char): """ Display a single character on the display :type char: str or int :param char: Character to display """ char = str(char).lower() self.segments.write(self.font[char])
python
def write(self, char): """ Display a single character on the display :type char: str or int :param char: Character to display """ char = str(char).lower() self.segments.write(self.font[char])
[ "def", "write", "(", "self", ",", "char", ")", ":", "char", "=", "str", "(", "char", ")", ".", "lower", "(", ")", "self", ".", "segments", ".", "write", "(", "self", ".", "font", "[", "char", "]", ")" ]
Display a single character on the display :type char: str or int :param char: Character to display
[ "Display", "a", "single", "character", "on", "the", "display" ]
train
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/segmentdisplay.py#L205-L212
edx/edx-sphinx-theme
edx_theme/__init__.py
get_html_theme_path
def get_html_theme_path(): """ Get the absolute path of the directory containing the theme files. """ return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
python
def get_html_theme_path(): """ Get the absolute path of the directory containing the theme files. """ return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
[ "def", "get_html_theme_path", "(", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")" ]
Get the absolute path of the directory containing the theme files.
[ "Get", "the", "absolute", "path", "of", "the", "directory", "containing", "the", "theme", "files", "." ]
train
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L24-L28
edx/edx-sphinx-theme
edx_theme/__init__.py
feedback_form_url
def feedback_form_url(project, page): """ Create a URL for feedback on a particular page in a project. """ return FEEDBACK_FORM_FMT.format(pageid=quote("{}: {}".format(project, page)))
python
def feedback_form_url(project, page): """ Create a URL for feedback on a particular page in a project. """ return FEEDBACK_FORM_FMT.format(pageid=quote("{}: {}".format(project, page)))
[ "def", "feedback_form_url", "(", "project", ",", "page", ")", ":", "return", "FEEDBACK_FORM_FMT", ".", "format", "(", "pageid", "=", "quote", "(", "\"{}: {}\"", ".", "format", "(", "project", ",", "page", ")", ")", ")" ]
Create a URL for feedback on a particular page in a project.
[ "Create", "a", "URL", "for", "feedback", "on", "a", "particular", "page", "in", "a", "project", "." ]
train
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L31-L35
edx/edx-sphinx-theme
edx_theme/__init__.py
update_context
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument """ Update the page rendering context to include ``feedback_form_url``. """ context['feedback_form_url'] = feedback_form_url(app.config.project, pagename)
python
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument """ Update the page rendering context to include ``feedback_form_url``. """ context['feedback_form_url'] = feedback_form_url(app.config.project, pagename)
[ "def", "update_context", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "# pylint: disable=unused-argument", "context", "[", "'feedback_form_url'", "]", "=", "feedback_form_url", "(", "app", ".", "config", ".", "project...
Update the page rendering context to include ``feedback_form_url``.
[ "Update", "the", "page", "rendering", "context", "to", "include", "feedback_form_url", "." ]
train
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L38-L42
edx/edx-sphinx-theme
edx_theme/__init__.py
setup
def setup(app): """ Sphinx extension to update the rendering context with the feedback form URL. Arguments: app (Sphinx): Application object for the Sphinx process Returns: a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata) """ event = 'ht...
python
def setup(app): """ Sphinx extension to update the rendering context with the feedback form URL. Arguments: app (Sphinx): Application object for the Sphinx process Returns: a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata) """ event = 'ht...
[ "def", "setup", "(", "app", ")", ":", "event", "=", "'html-page-context'", "if", "six", ".", "PY3", "else", "b'html-page-context'", "app", ".", "connect", "(", "event", ",", "update_context", ")", "return", "{", "'parallel_read_safe'", ":", "True", ",", "'pa...
Sphinx extension to update the rendering context with the feedback form URL. Arguments: app (Sphinx): Application object for the Sphinx process Returns: a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata)
[ "Sphinx", "extension", "to", "update", "the", "rendering", "context", "with", "the", "feedback", "form", "URL", "." ]
train
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L45-L62