repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
fabric/fabric | fabric/connection.py | Connection.local | python | def local(self, *args, **kwargs):
# Superclass run() uses runners.local, so we can literally just call it
# straight.
return super(Connection, self).run(*args, **kwargs) | Execute a shell command on the local system.
This method is effectively a wrapper of `invoke.run`; see its docs for
details and call signature.
.. versionadded:: 2.0 | train | https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L626-L637 | null | class Connection(Context):
"""
A connection to an SSH daemon, with methods for commands and file transfer.
**Basics**
This class inherits from Invoke's `~invoke.context.Context`, as it is a
context within which commands, tasks etc can operate. It also encapsulates
a Paramiko `~paramiko.client.... |
fabric/fabric | fabric/connection.py | Connection.sftp | python | def sftp(self):
if self._sftp is None:
self._sftp = self.client.open_sftp()
return self._sftp | Return a `~paramiko.sftp_client.SFTPClient` object.
If called more than one time, memoizes the first result; thus, any
given `.Connection` instance will only ever have a single SFTP client,
and state (such as that managed by
`~paramiko.sftp_client.SFTPClient.chdir`) will be preserved.
... | train | https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L640-L653 | null | class Connection(Context):
"""
A connection to an SSH daemon, with methods for commands and file transfer.
**Basics**
This class inherits from Invoke's `~invoke.context.Context`, as it is a
context within which commands, tasks etc can operate. It also encapsulates
a Paramiko `~paramiko.client.... |
fabric/fabric | fabric/connection.py | Connection.forward_local | python | def forward_local(
self,
local_port,
remote_port=None,
remote_host="localhost",
local_host="localhost",
):
if not remote_port:
remote_port = local_port
# TunnelManager does all of the work, sitting in the background (so we
# can yield) and... | Open a tunnel connecting ``local_port`` to the server's environment.
For example, say you want to connect to a remote PostgreSQL database
which is locked down and only accessible via the system it's running
on. You have SSH access to this server, so you can temporarily make
port 5432 on... | train | https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L682-L772 | null | class Connection(Context):
"""
A connection to an SSH daemon, with methods for commands and file transfer.
**Basics**
This class inherits from Invoke's `~invoke.context.Context`, as it is a
context within which commands, tasks etc can operate. It also encapsulates
a Paramiko `~paramiko.client.... |
fabric/fabric | fabric/connection.py | Connection.forward_remote | python | def forward_remote(
self,
remote_port,
local_port=None,
remote_host="127.0.0.1",
local_host="localhost",
):
if not local_port:
local_port = remote_port
# Callback executes on each connection to the remote port and is given
# a Channel hooke... | Open a tunnel connecting ``remote_port`` to the local environment.
For example, say you're running a daemon in development mode on your
workstation at port 8080, and want to funnel traffic to it from a
production or staging environment.
In most situations this isn't possible as your of... | train | https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L781-L882 | null | class Connection(Context):
"""
A connection to an SSH daemon, with methods for commands and file transfer.
**Basics**
This class inherits from Invoke's `~invoke.context.Context`, as it is a
context within which commands, tasks etc can operate. It also encapsulates
a Paramiko `~paramiko.client.... |
yaml/pyyaml | lib/yaml/__init__.py | scan | python | def scan(stream, Loader=Loader):
loader = Loader(stream)
try:
while loader.check_token():
yield loader.get_token()
finally:
loader.dispose() | Scan a YAML stream and produce scanning tokens. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L58-L67 | [
"def check_token(self, *choices):\n if not self.scanned:\n self.scan()\n if self.tokens:\n if not choices:\n return True\n for choice in choices:\n if isinstance(self.tokens[0], choice):\n return True\n return False\n",
"def check_token(self, *cho... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | parse | python | def parse(stream, Loader=Loader):
loader = Loader(stream)
try:
while loader.check_event():
yield loader.get_event()
finally:
loader.dispose() | Parse a YAML stream and produce parsing events. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L69-L78 | [
"def dispose(self):\n pass\n",
"def dispose(self):\n pass\n",
"def check_event(self, *choices):\n if not self.parsed:\n self.parse()\n if self.events:\n if not choices:\n return True\n for choice in choices:\n if isinstance(self.events[0], choice):\n ... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | compose | python | def compose(stream, Loader=Loader):
loader = Loader(stream)
try:
return loader.get_single_node()
finally:
loader.dispose() | Parse the first YAML document in a stream
and produce the corresponding representation tree. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L80-L89 | [
"def dispose(self):\n pass\n",
"def dispose(self):\n pass\n",
"def get_single_node(self):\n # Drop the STREAM-START event.\n self.get_event()\n\n # Compose a document if the stream is not empty.\n document = None\n if not self.check_event(StreamEndEvent):\n document = self.compose_do... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | compose_all | python | def compose_all(stream, Loader=Loader):
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose() | Parse all YAML documents in a stream
and produce corresponding representation trees. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L91-L101 | [
"def dispose(self):\n pass\n",
"def dispose(self):\n pass\n",
"def check_node(self):\n # Drop the STREAM-START event.\n if self.check_event(StreamStartEvent):\n self.get_event()\n\n # If there are more documents available?\n return not self.check_event(StreamEndEvent)\n"
] |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | load | python | def load(stream, Loader=None):
if Loader is None:
load_warning('load')
Loader = FullLoader
loader = Loader(stream)
try:
return loader.get_single_data()
finally:
loader.dispose() | Parse the first YAML document in a stream
and produce the corresponding Python object. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L103-L116 | [
"def load_warning(method):\n if _warnings_enabled['YAMLLoadWarning'] is False:\n return\n\n import warnings\n\n message = (\n \"calling yaml.%s() without Loader=... is deprecated, as the \"\n \"default Loader is unsafe. Please read \"\n \"https://msg.pyyaml.org/load for full det... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | load_all | python | def load_all(stream, Loader=None):
if Loader is None:
load_warning('load_all')
Loader = FullLoader
loader = Loader(stream)
try:
while loader.check_data():
yield loader.get_data()
finally:
loader.dispose() | Parse all YAML documents in a stream
and produce corresponding Python objects. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L118-L132 | [
"def load_warning(method):\n if _warnings_enabled['YAMLLoadWarning'] is False:\n return\n\n import warnings\n\n message = (\n \"calling yaml.%s() without Loader=... is deprecated, as the \"\n \"default Loader is unsafe. Please read \"\n \"https://msg.pyyaml.org/load for full det... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | emit | python | def emit(events, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
getvalue = None
if stream is None:
from StringIO import StringIO
stream = StringIO()
getvalue = stream.getvalue
dumper = Dumper(stream, canonica... | Emit YAML parsing events into a stream.
If stream is None, return the produced string instead. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L194-L214 | null |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | serialize | python | def serialize(node, stream=None, Dumper=Dumper, **kwds):
return serialize_all([node], stream, Dumper=Dumper, **kwds) | Serialize a representation tree into a YAML stream.
If stream is None, return the produced string instead. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L247-L252 | [
"def serialize_all(nodes, stream=None, Dumper=Dumper,\n canonical=None, indent=None, width=None,\n allow_unicode=None, line_break=None,\n encoding='utf-8', explicit_start=None, explicit_end=None,\n version=None, tags=None):\n \"\"\"\n Serialize a sequence of representation trees in... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | dump | python | def dump(data, stream=None, Dumper=Dumper, **kwds):
return dump_all([data], stream, Dumper=Dumper, **kwds) | Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L288-L293 | [
"def dump_all(documents, stream=None, Dumper=Dumper,\n default_style=None, default_flow_style=False,\n canonical=None, indent=None, width=None,\n allow_unicode=None, line_break=None,\n encoding='utf-8', explicit_start=None, explicit_end=None,\n version=None, tags=None, sort_keys=T... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | safe_dump_all | python | def safe_dump_all(documents, stream=None, **kwds):
return dump_all(documents, stream, Dumper=SafeDumper, **kwds) | Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L295-L301 | [
"def dump_all(documents, stream=None, Dumper=Dumper,\n default_style=None, default_flow_style=False,\n canonical=None, indent=None, width=None,\n allow_unicode=None, line_break=None,\n encoding='utf-8', explicit_start=None, explicit_end=None,\n version=None, tags=None, sort_keys=T... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | safe_dump | python | def safe_dump(data, stream=None, **kwds):
return dump_all([data], stream, Dumper=SafeDumper, **kwds) | Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L303-L309 | [
"def dump_all(documents, stream=None, Dumper=Dumper,\n default_style=None, default_flow_style=False,\n canonical=None, indent=None, width=None,\n allow_unicode=None, line_break=None,\n encoding='utf-8', explicit_start=None, explicit_end=None,\n version=None, tags=None, sort_keys=T... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | add_implicit_resolver | python | def add_implicit_resolver(tag, regexp, first=None,
Loader=Loader, Dumper=Dumper):
Loader.add_implicit_resolver(tag, regexp, first)
Dumper.add_implicit_resolver(tag, regexp, first) | Add an implicit scalar detector.
If an implicit scalar value matches the given regexp,
the corresponding tag is assigned to the scalar.
first is a sequence of possible initial characters or None. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L311-L320 | null |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | add_path_resolver | python | def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind) | Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L322-L330 | null |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
__version__ = '5.1'
try:
from cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
#--------------------------------------------------------------... |
yaml/pyyaml | lib/yaml/__init__.py | YAMLObject.to_yaml | python | def to_yaml(cls, dumper, data):
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
flow_style=cls.yaml_flow_style) | Convert a Python object to a representation node. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L399-L404 | null | class YAMLObject(object):
"""
An object that can dump itself to a YAML stream
and load itself from a YAML stream.
"""
__metaclass__ = YAMLObjectMetaclass
__slots__ = () # no direct instantiation, so allow immutable subclasses
yaml_loader = Loader
yaml_dumper = Dumper
yaml_tag = N... |
yaml/pyyaml | lib3/yaml/__init__.py | serialize_all | python | def serialize_all(nodes, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None):
getvalue = None
if stream is None:
if encoding is None:
... | Serialize a sequence of representation trees into a YAML stream.
If stream is None, return the produced string instead. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib3/yaml/__init__.py#L215-L243 | [
"def dispose(self):\n # Reset the state attributes (to clear self-references)\n self.states = []\n self.state = None\n",
"def open(self):\n if self.closed is None:\n self.emit(StreamStartEvent(encoding=self.use_encoding))\n self.closed = False\n elif self.closed:\n raise Serial... |
from .error import *
from .tokens import *
from .events import *
from .nodes import *
from .loader import *
from .dumper import *
__version__ = '5.1'
try:
from .cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
import io
#----------------------------------------------... |
yaml/pyyaml | examples/pygments-lexer/yaml.py | something | python | def something(TokenClass):
def callback(lexer, match, context):
text = match.group()
if not text:
return
yield match.start(), TokenClass, text
context.pos = match.end()
return callback | Do not produce empty tokens. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/examples/pygments-lexer/yaml.py#L32-L40 | null |
"""
yaml.py
Lexer for YAML, a human-friendly data serialization language
(http://yaml.org/).
Written by Kirill Simonov <xi@resolvent.net>.
License: Whatever suitable for inclusion into the Pygments package.
"""
from pygments.lexer import \
ExtendedRegexLexer, LexerContext, include, bygroups
from pygments.... |
yaml/pyyaml | examples/pygments-lexer/yaml.py | set_indent | python | def set_indent(TokenClass, implicit=False):
def callback(lexer, match, context):
text = match.group()
if context.indent < context.next_indent:
context.indent_stack.append(context.indent)
context.indent = context.next_indent
if not implicit:
context.next_in... | Set the previously saved indentation level. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/examples/pygments-lexer/yaml.py#L76-L87 | null |
"""
yaml.py
Lexer for YAML, a human-friendly data serialization language
(http://yaml.org/).
Written by Kirill Simonov <xi@resolvent.net>.
License: Whatever suitable for inclusion into the Pygments package.
"""
from pygments.lexer import \
ExtendedRegexLexer, LexerContext, include, bygroups
from pygments.... |
yaml/pyyaml | examples/pygments-lexer/yaml.py | parse_block_scalar_empty_line | python | def parse_block_scalar_empty_line(IndentTokenClass, ContentTokenClass):
def callback(lexer, match, context):
text = match.group()
if (context.block_scalar_indent is None or
len(text) <= context.block_scalar_indent):
if text:
yield match.start(), IndentToke... | Process an empty line in a block scalar. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/examples/pygments-lexer/yaml.py#L106-L121 | null |
"""
yaml.py
Lexer for YAML, a human-friendly data serialization language
(http://yaml.org/).
Written by Kirill Simonov <xi@resolvent.net>.
License: Whatever suitable for inclusion into the Pygments package.
"""
from pygments.lexer import \
ExtendedRegexLexer, LexerContext, include, bygroups
from pygments.... |
yaml/pyyaml | examples/pygments-lexer/yaml.py | parse_plain_scalar_indent | python | def parse_plain_scalar_indent(TokenClass):
def callback(lexer, match, context):
text = match.group()
if len(text) <= context.indent:
context.stack.pop()
context.stack.pop()
return
if text:
yield match.start(), TokenClass, text
conte... | Process indentation spaces in a plain scalar. | train | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/examples/pygments-lexer/yaml.py#L143-L154 | null |
"""
yaml.py
Lexer for YAML, a human-friendly data serialization language
(http://yaml.org/).
Written by Kirill Simonov <xi@resolvent.net>.
License: Whatever suitable for inclusion into the Pygments package.
"""
from pygments.lexer import \
ExtendedRegexLexer, LexerContext, include, bygroups
from pygments.... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.middleware | python | def middleware(self, *args, **kwargs):
kwargs.setdefault('priority', 5)
kwargs.setdefault('relative', None)
kwargs.setdefault('attach_to', None)
kwargs.setdefault('with_context', False)
if len(args) == 1 and callable(args[0]):
middle_f = args[0]
self._midd... | Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The middleware function to use as the decorator
:rtype: fn | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L37-L60 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def exception(self, *args, **kwargs):
"""Decorate... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.exception | python | def exception(self, *args, **kwargs):
if len(args) == 1 and callable(args[0]):
if isinstance(args[0], type) and issubclass(args[0], Exception):
pass
else: # pragma: no cover
raise RuntimeError("Cannot use the @exception decorator "
... | Decorate and register an exception handler
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The exception function to use as the decorator
:rtype... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L62-L83 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.listener | python | def listener(self, event, *args, **kwargs):
if len(args) == 1 and callable(args[0]): # pragma: no cover
raise RuntimeError("Cannot use the @listener decorator without "
"arguments")
def wrapper(listener_f):
if len(kwargs) > 0:
list... | Create a listener from a decorated function.
:param event: Event to listen to.
:type event: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L85-L105 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.route | python | def route(self, uri, *args, **kwargs):
if len(args) == 0 and callable(uri): # pragma: no cover
raise RuntimeError("Cannot use the @route decorator without "
"arguments.")
kwargs.setdefault('methods', frozenset({'GET'}))
kwargs.setdefault('host', None)
... | Create a plugin route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L107-L130 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.websocket | python | def websocket(self, uri, *args, **kwargs):
kwargs.setdefault('host', None)
kwargs.setdefault('strict_slashes', None)
kwargs.setdefault('subprotocols', None)
kwargs.setdefault('name', None)
def wrapper(handler_f):
self._ws.append(FutureWebsocket(handler_f, uri, args,... | Create a websocket route from a decorated function
:param uri: endpoint at which the socket endpoint will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L132-L152 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.static | python | def static(self, uri, file_or_directory, *args, **kwargs):
kwargs.setdefault('pattern', r'/?.+')
kwargs.setdefault('use_modified_since', True)
kwargs.setdefault('use_content_range', False)
kwargs.setdefault('stream_large_files', False)
kwargs.setdefault('name', 'static')
... | Create a websocket route from a decorated function
:param uri: endpoint at which the socket endpoint will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L154-L174 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.first_plugin_context | python | def first_plugin_context(self):
# Note, because registrations are stored in a set, its not _really_
# the first one, but whichever one it sees first in the set.
first_spf_reg = next(iter(self.registrations))
return self.get_context_from_spf(first_spf_reg) | Returns the context is associated with the first app this plugin was
registered on | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L191-L197 | [
"def get_context_from_spf(self, spf):\n rt_err = RuntimeError(\n \"Cannot use the plugin's Context before it is \"\n \"registered.\")\n if isinstance(spf, PluginRegistration):\n reg = spf\n else:\n reg = self.find_plugin_registration(spf)\n (s, n, u) = reg\n try:\n ... | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.decorate | python | def decorate(cls, app, *args, run_middleware=False, with_context=False,
**kwargs):
from spf.framework import SanicPluginsFramework
spf = SanicPluginsFramework(app) # get the singleton from the app
try:
assoc = spf.register_plugin(cls, skip_reg=True)
except V... | This is a decorator that can be used to apply this plugin to a specific
route/view on your app, rather than the whole app.
:param app:
:type app: Sanic | Blueprint
:param args:
:type args: tuple(Any)
:param run_middleware:
:type run_middleware: bool
:param... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L257-L368 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/plugin.py | SanicPlugin.route_wrapper | python | async def route_wrapper(self, route, request, context, request_args,
request_kw, *decorator_args, with_context=None,
**decorator_kw):
# by default, do nothing, just run the wrapped function
if with_context:
resp = route(request, context... | This is the function that is called when a route is decorated with
your plugin decorator. Context will normally be None, but the user
can pass use_context=True so the route will get the plugin
context | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L370-L385 | null | class SanicPlugin(object):
__slots__ = ('registrations', '_routes', '_ws', '_static',
'_middlewares', '_exceptions', '_listeners', '_initialized',
'__weakref__')
AssociatedTuple = PluginAssociated
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate ... |
ashleysommer/sanicpluginsframework | spf/context.py | ContextDict.replace | python | def replace(self, key, value):
if key in self._inner().keys():
return self.__setitem__(key, value)
parents_searched = [self]
parent = self._parent_context
while parent:
try:
if key in parent.keys():
return parent.__setitem__(key... | If this ContextDict doesn't already have this key, it sets
the value on a parent ContextDict if that parent has the key,
otherwise sets the value on this ContextDict.
:param key:
:param value:
:return: Nothing
:rtype: None | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/context.py#L123-L149 | [
"def _inner(self):\n \"\"\"\n :return: the internal dictionary\n :rtype: dict\n \"\"\"\n return object.__getattribute__(self, '_dict')\n"
] | class ContextDict(object):
"""
This is the specialised dictionary that is used by Sanic Plugins Framework
to manage Context objects. It can be hierarchical, and it searches its
parents if it cannot find an item in its own dictionary. It can create its
own children.
"""
__slots__ = ('_spf', '_parent_context'... |
ashleysommer/sanicpluginsframework | spf/context.py | ContextDict.update | python | def update(self, E=None, **F):
if E is not None:
if hasattr(E, 'keys'):
for K in E:
self.replace(K, E[K])
elif hasattr(E, 'items'):
for K, V in E.items():
self.replace(K, V)
else:
for K, V... | Update ContextDict from dict/iterable E and F
:return: Nothing
:rtype: None | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/context.py#L152-L169 | [
"def replace(self, key, value):\n \"\"\"\n If this ContextDict doesn't already have this key, it sets\n the value on a parent ContextDict if that parent has the key,\n otherwise sets the value on this ContextDict.\n :param key:\n :param value:\n :return: Nothing\n :rtype: None\n \"\"\"\n ... | class ContextDict(object):
"""
This is the specialised dictionary that is used by Sanic Plugins Framework
to manage Context objects. It can be hierarchical, and it searches its
parents if it cannot find an item in its own dictionary. It can create its
own children.
"""
__slots__ = ('_spf', '_parent_context'... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | ContextualizeAssociated.middleware | python | def middleware(self, *args, **kwargs):
kwargs.setdefault('priority', 5)
kwargs.setdefault('relative', None)
kwargs.setdefault('attach_to', None)
kwargs['with_context'] = True # This is the whole point of this plugin
plugin = self.plugin
reg = self.reg
if len(arg... | Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The middleware function to use as the decorator
:rtype: fn | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L14-L38 | null | class ContextualizeAssociated(ContextualizeAssociatedTuple):
__slots__ = ()
# Decorator
def route(self, uri, *args, **kwargs):
"""Create a plugin route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:type uri: str
:param args: captur... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | ContextualizeAssociated.route | python | def route(self, uri, *args, **kwargs):
if len(args) == 0 and callable(uri):
raise RuntimeError("Cannot use the @route decorator without "
"arguments.")
kwargs.setdefault('methods', frozenset({'GET'}))
kwargs.setdefault('host', None)
kwargs.setde... | Create a plugin route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L40-L67 | null | class ContextualizeAssociated(ContextualizeAssociatedTuple):
__slots__ = ()
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures t... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | ContextualizeAssociated.listener | python | def listener(self, event, *args, **kwargs):
if len(args) == 1 and callable(args[0]):
raise RuntimeError("Cannot use the @listener decorator without "
"arguments")
kwargs['with_context'] = True # This is the whole point of this plugin
plugin = self.plug... | Create a listener from a decorated function.
:param event: Event to listen to.
:type event: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L69-L92 | null | class ContextualizeAssociated(ContextualizeAssociatedTuple):
__slots__ = ()
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures t... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | ContextualizeAssociated.websocket | python | def websocket(self, uri, *args, **kwargs):
kwargs.setdefault('host', None)
kwargs.setdefault('strict_slashes', None)
kwargs.setdefault('subprotocols', None)
kwargs.setdefault('name', None)
kwargs['with_context'] = True # This is the whole point of this plugin
plugin = s... | Create a websocket route from a decorated function
:param uri: endpoint at which the socket endpoint will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L94-L119 | null | class ContextualizeAssociated(ContextualizeAssociatedTuple):
__slots__ = ()
# Decorator
def middleware(self, *args, **kwargs):
"""Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures t... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | Contextualize.middleware | python | def middleware(self, *args, **kwargs):
kwargs.setdefault('priority', 5)
kwargs.setdefault('relative', None)
kwargs.setdefault('attach_to', None)
kwargs['with_context'] = True # This is the whole point of this plugin
if len(args) == 1 and callable(args[0]):
middle_f =... | Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The middleware function to use as the decorator
:rtype: fn | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L173-L194 | [
"def middleware(self, *args, **kwargs):\n \"\"\"Decorate and register middleware\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any)\n :return: The middleware function to use ... | class Contextualize(SanicPlugin):
__slots__ = ()
AssociatedTuple = ContextualizeAssociated
def _add_new_middleware(self, reg, middle_f, *args, **kwargs):
# A user should never call this directly.
# it should be called only by the AssociatedTuple
assert reg in self.registrations
... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | Contextualize.route | python | def route(self, uri, *args, **kwargs):
if len(args) == 0 and callable(uri):
raise RuntimeError("Cannot use the @route decorator without "
"arguments.")
kwargs.setdefault('methods', frozenset({'GET'}))
kwargs.setdefault('host', None)
kwargs.setde... | Create a plugin route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L197-L222 | null | class Contextualize(SanicPlugin):
__slots__ = ()
AssociatedTuple = ContextualizeAssociated
def _add_new_middleware(self, reg, middle_f, *args, **kwargs):
# A user should never call this directly.
# it should be called only by the AssociatedTuple
assert reg in self.registrations
... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | Contextualize.listener | python | def listener(self, event, *args, **kwargs):
if len(args) == 1 and callable(args[0]):
raise RuntimeError("Cannot use the @listener decorator without "
"arguments")
kwargs['with_context'] = True # This is the whole point of this plugin
def wrapper(liste... | Create a listener from a decorated function.
:param event: Event to listen to.
:type event: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L225-L245 | null | class Contextualize(SanicPlugin):
__slots__ = ()
AssociatedTuple = ContextualizeAssociated
def _add_new_middleware(self, reg, middle_f, *args, **kwargs):
# A user should never call this directly.
# it should be called only by the AssociatedTuple
assert reg in self.registrations
... |
ashleysommer/sanicpluginsframework | spf/plugins/contextualize.py | Contextualize.websocket | python | def websocket(self, uri, *args, **kwargs):
kwargs.setdefault('host', None)
kwargs.setdefault('strict_slashes', None)
kwargs.setdefault('subprotocols', None)
kwargs.setdefault('name', None)
kwargs['with_context'] = True # This is the whole point of this plugin
def wrapp... | Create a websocket route from a decorated function
:param uri: endpoint at which the socket endpoint will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
... | train | https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugins/contextualize.py#L247-L269 | null | class Contextualize(SanicPlugin):
__slots__ = ()
AssociatedTuple = ContextualizeAssociated
def _add_new_middleware(self, reg, middle_f, *args, **kwargs):
# A user should never call this directly.
# it should be called only by the AssociatedTuple
assert reg in self.registrations
... |
saltstack/salt-pylint | saltpylint/fileperms.py | FilePermsChecker.process_module | python | def process_module(self, node):
'''
process a module
'''
for listing in self.config.fileperms_ignore_paths:
if node.file.split('{0}/'.format(os.getcwd()))[-1] in glob.glob(listing):
# File is ignored, no checking should be done
return
... | process a module | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/fileperms.py#L52-L117 | null | class FilePermsChecker(BaseChecker):
'''
Check for files with undesirable permissions
'''
__implements__ = IRawChecker
name = 'fileperms'
msgs = {'E0599': ('Module file has the wrong file permissions(expected %s): %s',
'file-perms',
('Wrong file perm... |
saltstack/salt-pylint | setup.py | _parse_requirements_file | python | def _parse_requirements_file(requirements_file):
'''
Parse requirements.txt and return list suitable for
passing to ``install_requires`` parameter in ``setup()``.
'''
parsed_requirements = []
with open(requirements_file) as rfh:
for line in rfh.readlines():
line = line.strip(... | Parse requirements.txt and return list suitable for
passing to ``install_requires`` parameter in ``setup()``. | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/setup.py#L30-L42 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
The setup script for SaltPyLint
'''
# pylint: disable=file-perms,wrong-import-position
from __future__ import absolute_import, with_statement
import io
import os
import sys
SETUP_KWARGS = {}
USE_SETUPTOOLS = False
# Change to salt source's directory prior to running a... |
saltstack/salt-pylint | setup.py | _release_version | python | def _release_version():
'''
Returns release version
'''
with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_:
exec_locals = {}
exec_globals = {}
contents = fh_.read()
if not isinstance(contents, str):
contents = conten... | Returns release version | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/setup.py#L45-L56 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
The setup script for SaltPyLint
'''
# pylint: disable=file-perms,wrong-import-position
from __future__ import absolute_import, with_statement
import io
import os
import sys
SETUP_KWARGS = {}
USE_SETUPTOOLS = False
# Change to salt source's directory prior to running a... |
saltstack/salt-pylint | saltpylint/py3modernize/__init__.py | Py3Modernize.process_module | python | def process_module(self, node):
'''
process a module
'''
# Patch lib2to3.fixer_util.touch_import!
fixer_util.touch_import = salt_lib2to3_touch_import
flags = {}
if self.config.modernize_print_function:
flags['print_function'] = True
salt_av... | process a module | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/py3modernize/__init__.py#L144-L239 | null | class Py3Modernize(BaseChecker):
'''
Check for PEP263 compliant file encoding in file.
'''
__implements__ = IRawChecker
name = 'modernize'
msgs = {'W1698': ('Unable to run modernize. Parse Error: %s',
'modernize-parse-error',
('Incompatible Python 3 ... |
saltstack/salt-pylint | saltpylint/virt.py | VirtChecker.visit_functiondef | python | def visit_functiondef(self, node):
'''
Verifies no logger statements inside __virtual__
'''
if (not isinstance(node, astroid.FunctionDef) or
node.is_method()
or node.type != 'function'
or not node.body
):
# only process functions... | Verifies no logger statements inside __virtual__ | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/virt.py#L26-L65 | null | class VirtChecker(BaseChecker):
'''
checks for compliance inside __virtual__
'''
__implements__ = IAstroidChecker
name = 'virt-checker'
VIRT_LOG = 'log-in-virtual'
msgs = {
'E1401': ('Log statement detected inside __virtual__ function. Remove it.',
VIRT_LOG,
... |
saltstack/salt-pylint | saltpylint/pep263.py | FileEncodingChecker.process_module | python | def process_module(self, node):
'''
process a module
the module's content is accessible via node.file_stream object
'''
pep263 = re.compile(six.b(self.RE_PEP263))
try:
file_stream = node.file_stream
except AttributeError:
# Pylint >= 1.8.... | process a module
the module's content is accessible via node.file_stream object | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/pep263.py#L57-L110 | null | class FileEncodingChecker(BaseChecker):
'''
Check for PEP263 compliant file encoding in file.
'''
__implements__ = IRawChecker
name = 'pep263'
msgs = {'W9901': ('PEP263: Multiple file encodings',
'multiple-encoding-in-file',
('There are multiple enco... |
saltstack/salt-pylint | saltpylint/ext/pyqver2.py | get_versions | python | def get_versions(source):
tree = compiler.parse(source)
checker = compiler.walk(tree, NodeChecker())
return checker.vers | Return information about the Python versions required for specific features.
The return value is a dictionary with keys as a version number as a tuple
(for example Python 2.6 is (2,6)) and the value are a list of features that
require the indicated Python version. | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/ext/pyqver2.py#L252-L261 | null | # -*- coding: utf-8 -*-
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the author be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and... |
saltstack/salt-pylint | saltpylint/strings.py | register | python | def register(linter):
'''required method to auto register this checker '''
linter.register_checker(StringCurlyBracesFormatIndexChecker(linter))
linter.register_checker(StringLiteralChecker(linter)) | required method to auto register this checker | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/strings.py#L260-L263 | null | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
==========================================
PyLint Extended String Formatting Checkers
==========================================
Proper string formatting PyLint checker
'''
# Import Python libs
from __future__ i... |
saltstack/salt-pylint | saltpylint/strings.py | StringLiteralChecker.process_non_raw_string_token | python | def process_non_raw_string_token(self, prefix, string_body, start_row):
'''
check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: inte... | check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source. | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/strings.py#L247-L258 | null | class StringLiteralChecker(BaseTokenChecker):
'''
Check string literals
'''
__implements__ = (ITokenChecker, IRawChecker)
name = 'string_literal'
msgs = STRING_LITERALS_MSGS
def process_module(self, module):
self._unicode_literals = 'unicode_literals' in module.future_imports
d... |
saltstack/salt-pylint | saltpylint/blacklist.py | register | python | def register(linter):
'''
Required method to auto register this checker
'''
linter.register_checker(ResourceLeakageChecker(linter))
linter.register_checker(BlacklistedImportsChecker(linter))
linter.register_checker(MovedTestCaseClassChecker(linter))
linter.register_checker(BlacklistedLoaderM... | Required method to auto register this checker | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L560-L568 | null | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2017 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
saltpylint.blacklist
~~~~~~~~~~~~~~~~~~~~
Checks blacklisted imports and code usage ... |
saltstack/salt-pylint | saltpylint/blacklist.py | BlacklistedImportsChecker.visit_import | python | def visit_import(self, node):
'''triggered when an import statement is seen'''
module_filename = node.root().file
if fnmatch.fnmatch(module_filename, '__init__.py*') and \
not fnmatch.fnmatch(module_filename, 'test_*.py*'):
return
modnode = node.root()
... | triggered when an import statement is seen | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L66-L76 | null | class BlacklistedImportsChecker(BaseChecker):
__implements__ = IAstroidChecker
name = 'blacklisted-imports'
msgs = BLACKLISTED_IMPORTS_MSGS
priority = -2
def open(self):
self.blacklisted_modules = ('salttesting',
'integration',
... |
saltstack/salt-pylint | saltpylint/blacklist.py | BlacklistedImportsChecker.visit_importfrom | python | def visit_importfrom(self, node):
'''triggered when a from statement is seen'''
module_filename = node.root().file
if fnmatch.fnmatch(module_filename, '__init__.py*') and \
not fnmatch.fnmatch(module_filename, 'test_*.py*'):
return
basename = node.modname
... | triggered when a from statement is seen | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L79-L86 | null | class BlacklistedImportsChecker(BaseChecker):
__implements__ = IAstroidChecker
name = 'blacklisted-imports'
msgs = BLACKLISTED_IMPORTS_MSGS
priority = -2
def open(self):
self.blacklisted_modules = ('salttesting',
'integration',
... |
saltstack/salt-pylint | saltpylint/blacklist.py | BlacklistedImportsChecker._check_blacklisted_module | python | def _check_blacklisted_module(self, node, mod_path):
'''check if the module is blacklisted'''
for mod_name in self.blacklisted_modules:
if mod_path == mod_name or mod_path.startswith(mod_name + '.'):
names = []
for name, name_as in node.names:
... | check if the module is blacklisted | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L88-L221 | null | class BlacklistedImportsChecker(BaseChecker):
__implements__ = IAstroidChecker
name = 'blacklisted-imports'
msgs = BLACKLISTED_IMPORTS_MSGS
priority = -2
def open(self):
self.blacklisted_modules = ('salttesting',
'integration',
... |
saltstack/salt-pylint | saltpylint/blacklist.py | BlacklistedLoaderModulesUsageChecker.visit_import | python | def visit_import(self, node):
'''triggered when an import statement is seen'''
if self.process_module:
# Store salt imported modules
for module, import_as in node.names:
if not module.startswith('salt'):
continue
if import_as an... | triggered when an import statement is seen | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L277-L288 | null | class BlacklistedLoaderModulesUsageChecker(BaseChecker):
__implements__ = IAstroidChecker
name = 'blacklisted-unmocked-patching'
msgs = BLACKLISTED_LOADER_USAGE_MSGS
priority = -2
def open(self):
self.process_module = False
self.salt_dunders = (
'__opts__', '__salt__',... |
saltstack/salt-pylint | saltpylint/blacklist.py | BlacklistedLoaderModulesUsageChecker.visit_importfrom | python | def visit_importfrom(self, node):
'''triggered when a from statement is seen'''
if self.process_module:
if not node.modname.startswith('salt'):
return
# Store salt imported modules
for module, import_as in node.names:
if import_as and i... | triggered when a from statement is seen | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L291-L302 | null | class BlacklistedLoaderModulesUsageChecker(BaseChecker):
__implements__ = IAstroidChecker
name = 'blacklisted-unmocked-patching'
msgs = BLACKLISTED_LOADER_USAGE_MSGS
priority = -2
def open(self):
self.process_module = False
self.salt_dunders = (
'__opts__', '__salt__',... |
saltstack/salt-pylint | saltpylint/smartup.py | register | python | def register(linter):
'''
Register the transformation functions.
'''
try:
MANAGER.register_transform(nodes.Class, rootlogger_transform)
except AttributeError:
MANAGER.register_transform(nodes.ClassDef, rootlogger_transform) | Register the transformation functions. | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/smartup.py#L39-L46 | null | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013-2018 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
===========================
Pylint Smartup Transformers
========================... |
saltstack/salt-pylint | saltpylint/pep8.py | register | python | def register(linter):
'''
required method to auto register this checker
'''
if HAS_PEP8 is False:
return
linter.register_checker(PEP8Indentation(linter))
linter.register_checker(PEP8Whitespace(linter))
linter.register_checker(PEP8BlankLine(linter))
linter.register_checker(PEP8Im... | required method to auto register this checker | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/pep8.py#L462-L479 | null | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013-2018 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
===================
PEP-8 PyLint Plugin
===================
A bridge betwee... |
saltstack/salt-pylint | saltpylint/pep8.py | _PEP8BaseChecker.process_module | python | def process_module(self, node):
'''
process a module
the module's content is accessible via node.file_stream object
'''
nodepaths = []
if not isinstance(node.path, list):
nodepaths = [node.path]
else:
nodepaths = node.path
for nod... | process a module
the module's content is accessible via node.file_stream object | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/pep8.py#L90-L145 | null | class _PEP8BaseChecker(BaseChecker):
__implements__ = IRawChecker
name = 'pep8'
priority = -1
options = ()
msgs = None
_msgs = {}
msgs_map = {}
def __init__(self, linter=None):
# To avoid PyLints deprecation about a missing symbolic name and
# because I don't want to... |
saltstack/salt-pylint | saltpylint/minpyver.py | MininumPythonVersionChecker.process_module | python | def process_module(self, node):
'''
process a module
'''
if not HAS_PYQVER:
return
minimum_version = tuple([int(x) for x in self.config.minimum_python_version.split('.')])
with open(node.path, 'r') as rfh:
for version, reasons in pyqver2.get_versi... | process a module | train | https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/minpyver.py#L59-L74 | [
"def get_versions(source):\n \"\"\"Return information about the Python versions required for specific features.\n\n The return value is a dictionary with keys as a version number as a tuple\n (for example Python 2.6 is (2,6)) and the value are a list of features that\n require the indicated Python versi... | class MininumPythonVersionChecker(BaseChecker):
'''
Check the minimal required python version
'''
__implements__ = IRawChecker
name = 'mininum-python-version'
msgs = {'E0598': ('Incompatible Python %s code found: %s',
'minimum-python-version',
'The c... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.get_motion_detection | python | def get_motion_detection(self):
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.Co... | Fetch current motion state from camera | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L141-L179 | [
"def element_query(self, element):\n \"\"\"Build tree query for a given element.\"\"\"\n return '{%s}%s' % (self.namespace, element)\n"
] | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera._set_motion_detection | python | def _set_motion_detection(self, enable):
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
enabled = self._motion_detection_xml.find(self.element_query('enabled'))
if enabled is None:
_LOGGING.error("Couldn't find 'enabled' in the xm... | Set desired motion detection state on camera | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L189-L218 | [
"def element_query(self, element):\n \"\"\"Build tree query for a given element.\"\"\"\n return '{%s}%s' % (self.namespace, element)\n"
] | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.add_update_callback | python | def add_update_callback(self, callback, sensor):
self._updateCallbacks.append([callback, sensor])
_LOGGING.debug('Added update callback to %s on %s', callback, sensor) | Register as callback for when a matching device sensor changes. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L220-L223 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera._do_update_callback | python | def _do_update_callback(self, msg):
for callback, sensor in self._updateCallbacks:
if sensor == msg:
_LOGGING.debug('Update callback %s for sensor %s',
callback, sensor)
callback(msg) | Call registered callback functions. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L225-L231 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.initialize | python | def initialize(self):
device_info = self.get_device_info()
if device_info is None:
self.name = None
self.cam_id = None
self.event_states = None
return
for key in device_info:
if key == 'deviceName':
self.name = device_... | Initialize deviceInfo and available events. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L237-L274 | [
"def get_motion_detection(self):\n \"\"\"Fetch current motion state from camera\"\"\"\n url = ('%s/ISAPI/System/Video/inputs/'\n 'channels/1/motionDetection') % self.root_url\n\n try:\n response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)\n except (requests.exceptions.RequestEx... | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.get_event_triggers | python | def get_event_triggers(self):
events = {}
nvrflag = False
event_xml = []
url = '%s/ISAPI/Event/triggers' % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.not_found:
... | Returns dict of supported events.
Key = Event Type
List = Channels that have that event activated | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L276-L369 | [
"def element_query(self, element):\n \"\"\"Build tree query for a given element.\"\"\"\n return '{%s}%s' % (self.namespace, element)\n"
] | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.get_device_info | python | def get_device_info(self):
device_info = {}
url = '%s/ISAPI/System/deviceInfo' % self.root_url
using_digest = False
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.unauthorized:
_LOGGING... | Parse deviceInfo into dictionary. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L371-L428 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.watchdog_handler | python | def watchdog_handler(self):
_LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name)
self.watchdog.stop()
self.reset_thrd.set() | Take care of threads if wachdog expires. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L430-L434 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.disconnect | python | def disconnect(self):
_LOGGING.debug('Disconnecting from stream: %s', self.name)
self.kill_thrd.set()
self.thrd.join()
_LOGGING.debug('Event stream thread for %s is stopped', self.name)
self.kill_thrd.clear() | Disconnect from event stream. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L436-L442 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.alert_stream | python | def alert_stream(self, reset_event, kill_event):
_LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
start_event = False
parse_string = ""
fail_count = 0
url = '%s/ISAPI/Event/notification/alertStream' % self.root_url
# pylint: disable=too-many-neste... | Open event stream. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L449-L531 | [
"def update_stale(self):\n \"\"\"Update stale active statuses\"\"\"\n # Some events don't post an inactive XML, only active.\n # If we don't get an active update for 5 seconds we can\n # assume the event is no longer active and update accordingly.\n for etype, echannels in self.event_states.items():\... | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.process_stream | python | def process_stream(self, tree):
try:
etype = SENSOR_MAP[tree.find(
self.element_query('eventType')).text.lower()]
estate = tree.find(
self.element_query('eventState')).text
echid = tree.find(
self.element_query('channelID'))
... | Process incoming event stream packets. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L533-L571 | [
"def element_query(self, element):\n \"\"\"Build tree query for a given element.\"\"\"\n return '{%s}%s' % (self.namespace, element)\n",
"def publish_changes(self, etype, echid):\n \"\"\"Post updates for specified event type.\"\"\"\n _LOGGING.debug('%s Update: %s, %s',\n self.name, e... | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.update_stale | python | def update_stale(self):
# Some events don't post an inactive XML, only active.
# If we don't get an active update for 5 seconds we can
# assume the event is no longer active and update accordingly.
for etype, echannels in self.event_states.items():
for eprop in echannels:
... | Update stale active statuses | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L573-L590 | [
"def publish_changes(self, etype, echid):\n \"\"\"Post updates for specified event type.\"\"\"\n _LOGGING.debug('%s Update: %s, %s',\n self.name, etype, self.fetch_attributes(etype, echid))\n signal = 'ValueChanged.{}'.format(self.cam_id)\n sender = '{}.{}'.format(etype, echid)\n if... | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.publish_changes | python | def publish_changes(self, etype, echid):
_LOGGING.debug('%s Update: %s, %s',
self.name, etype, self.fetch_attributes(etype, echid))
signal = 'ValueChanged.{}'.format(self.cam_id)
sender = '{}.{}'.format(etype, echid)
if dispatcher:
dispatcher.send(signa... | Post updates for specified event type. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L592-L601 | [
"def _do_update_callback(self, msg):\n \"\"\"Call registered callback functions.\"\"\"\n for callback, sensor in self._updateCallbacks:\n if sensor == msg:\n _LOGGING.debug('Update callback %s for sensor %s',\n callback, sensor)\n callback(msg)\n",
"def... | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.fetch_attributes | python | def fetch_attributes(self, event, channel):
try:
for sensor in self.event_states[event]:
if sensor[1] == int(channel):
return sensor
except KeyError:
return None | Returns attribute list for a given event/channel. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L603-L610 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/hikvision.py | HikCamera.update_attributes | python | def update_attributes(self, event, channel, attr):
try:
for i, sensor in enumerate(self.event_states[event]):
if sensor[1] == int(channel):
self.event_states[event][i] = attr
except KeyError:
_LOGGING.debug('Error updating attributes for: (%s, ... | Update attribute list for current event/channel. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L612-L620 | null | class HikCamera(object):
"""Creates a new Hikvision api device."""
def __init__(self, host=None, port=DEFAULT_PORT,
usr=None, pwd=None):
"""Initialize device."""
_LOGGING.debug("pyHik %s initializing new hikvision device at: %s",
__version__, host)
... |
mezz64/pyHik | pyhik/watchdog.py | Watchdog.start | python | def start(self):
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return | Starts the watchdog timer. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/watchdog.py#L21-L26 | null | class Watchdog(object):
""" Watchdog timer class. """
def __init__(self, timeout, handler):
""" Initialize watchdog variables. """
self.time = timeout
self.handler = handler
return
def pet(self):
""" Reset watchdog timer. """
self.stop()
self.start(... |
mezz64/pyHik | examples/basic_usage.py | main | python | def main():
"""Main function"""
cam = HikCamObject('http://XXX.XXX.XXX.XXX', 80, 'user', 'password')
entities = []
for sensor, channel_list in cam.sensors.items():
for channel in channel_list:
entities.append(HikSensor(sensor, channel[1], cam)) | Main function | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L97-L105 | null | """
Sample program for hikvision api.
"""
import logging
import pyhik.hikvision as hikvision
logging.basicConfig(filename='out.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
class HikCamObject(object):
"""Representation of HIk camera.... |
mezz64/pyHik | examples/basic_usage.py | HikCamObject.flip_motion | python | def flip_motion(self, value):
"""Toggle motion detection"""
if value:
self.cam.enable_motion_detection()
else:
self.cam.disable_motion_detection() | Toggle motion detection | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L47-L52 | null | class HikCamObject(object):
"""Representation of HIk camera."""
def __init__(self, url, port, user, passw):
"""initalize camera"""
# Establish camera
self.cam = hikvision.HikCamera(url, port, user, passw)
self._name = self.cam.get_name
self.motion = self.cam.current_mo... |
mezz64/pyHik | examples/basic_usage.py | HikSensor.update_callback | python | def update_callback(self, msg):
""" get updates. """
print('Callback: {}'.format(msg))
print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update())) | get updates. | train | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L91-L94 | [
"def _sensor_state(self):\n \"\"\"Extract sensor state.\"\"\"\n return self._cam.get_attributes(self._sensor, self._channel)[0]\n",
"def _sensor_last_update(self):\n \"\"\"Extract sensor last update time.\"\"\"\n return self._cam.get_attributes(self._sensor, self._channel)[3]\n"
] | class HikSensor(object):
""" Hik camera sensor."""
def __init__(self, sensor, channel, cam):
"""Init"""
self._cam = cam
self._name = "{} {} {}".format(self._cam.cam.name, sensor, channel)
self._id = "{}.{}.{}".format(self._cam.cam.cam_id, sensor, channel)
self._sensor = ... |
taxjar/taxjar-python | taxjar/client.py | Client.rates_for_location | python | def rates_for_location(self, postal_code, location_deets=None):
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request) | Shows the sales tax rates for a given location. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L31-L34 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.tax_for_order | python | def tax_for_order(self, order_deets):
request = self._post('taxes', order_deets)
return self.responder(request) | Shows the sales tax that should be collected for a given order. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L36-L39 | [
"def _post(self, endpoint, data):\n return self._request(requests.post, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.list_orders | python | def list_orders(self, params=None):
request = self._get('transactions/orders', params)
return self.responder(request) | Lists existing order transactions. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L41-L44 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.show_order | python | def show_order(self, order_id):
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request) | Shows an existing order transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L46-L49 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.create_order | python | def create_order(self, order_deets):
request = self._post('transactions/orders', order_deets)
return self.responder(request) | Creates a new order transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L51-L54 | [
"def _post(self, endpoint, data):\n return self._request(requests.post, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.update_order | python | def update_order(self, order_id, order_deets):
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request) | Updates an existing order transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L56-L59 | [
"def _put(self, endpoint, data):\n return self._request(requests.put, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.delete_order | python | def delete_order(self, order_id):
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request) | Deletes an existing order transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L61-L64 | [
"def _delete(self, endpoint):\n return self._request(requests.delete, endpoint)\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.list_refunds | python | def list_refunds(self, params=None):
request = self._get('transactions/refunds', params)
return self.responder(request) | Lists existing refund transactions. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L66-L69 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.show_refund | python | def show_refund(self, refund_id):
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request) | Shows an existing refund transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L71-L74 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.create_refund | python | def create_refund(self, refund_deets):
request = self._post('transactions/refunds', refund_deets)
return self.responder(request) | Creates a new refund transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L76-L79 | [
"def _post(self, endpoint, data):\n return self._request(requests.post, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.update_refund | python | def update_refund(self, refund_id, refund_deets):
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request) | Updates an existing refund transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L81-L84 | [
"def _put(self, endpoint, data):\n return self._request(requests.put, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.delete_refund | python | def delete_refund(self, refund_id):
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request) | Deletes an existing refund transaction. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L86-L89 | [
"def _delete(self, endpoint):\n return self._request(requests.delete, endpoint)\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.list_customers | python | def list_customers(self, params=None):
request = self._get('customers', params)
return self.responder(request) | Lists existing customers. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L91-L94 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.show_customer | python | def show_customer(self, customer_id):
request = self._get('customers/' + str(customer_id))
return self.responder(request) | Shows an existing customer. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L96-L99 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.create_customer | python | def create_customer(self, customer_deets):
request = self._post('customers', customer_deets)
return self.responder(request) | Creates a new customer. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L101-L104 | [
"def _post(self, endpoint, data):\n return self._request(requests.post, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.update_customer | python | def update_customer(self, customer_id, customer_deets):
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request) | Updates an existing customer. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L106-L109 | [
"def _put(self, endpoint, data):\n return self._request(requests.put, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.delete_customer | python | def delete_customer(self, customer_id):
request = self._delete("customers/" + str(customer_id))
return self.responder(request) | Deletes an existing customer. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L111-L114 | [
"def _delete(self, endpoint):\n return self._request(requests.delete, endpoint)\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.validate_address | python | def validate_address(self, address_deets):
request = self._post('addresses/validate', address_deets)
return self.responder(request) | Validates a customer address and returns back a collection of address matches. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L121-L124 | [
"def _post(self, endpoint, data):\n return self._request(requests.post, endpoint, {'json': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
taxjar/taxjar-python | taxjar/client.py | Client.validate | python | def validate(self, vat_deets):
request = self._get('validation', vat_deets)
return self.responder(request) | Validates an existing VAT identification number against VIES. | train | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L126-L129 | [
"def _get(self, endpoint, data=None):\n if data is None:\n data = {}\n return self._request(requests.get, endpoint, {'params': data})\n"
] | class Client(object):
"""TaxJar Python Client"""
def __init__(self, api_key, api_url="", options=None, responder=TaxJarResponse.from_request):
if options is None:
options = {}
self.api_key = api_key
self.api_url = api_url if api_url else taxjar.DEFAULT_API_URL
self.ap... |
sashahart/vex | vex/options.py | make_arg_parser | python | def make_arg_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
usage="vex [OPTIONS] VIRTUALENV_NAME COMMAND_TO_RUN ...",
)
make = parser.add_argument_group(title='To make a new virtualenv')
make.add_argument(
'-m', '--make',
actio... | Return a standard ArgumentParser object. | train | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/options.py#L5-L90 | null | import argparse
from vex import exceptions
def get_options(argv):
"""Called to parse the given list as command-line arguments.
:returns:
an options object as returned by argparse.
"""
arg_parser = make_arg_parser()
options, unknown = arg_parser.parse_known_args(argv)
if unknown:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.