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 |
|---|---|---|---|---|---|---|---|---|---|
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.check_keyname | python | def check_keyname(self, rule):
keynames = rule.get('keynames')
if not keynames:
self.logdebug('no keynames requirement.\n')
return True
if not isinstance(keynames, list):
keynames = [keynames]
if self.keyname in keynames:
self.logdebug('k... | If a key name is specified, verify it is permitted. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L164-L179 | [
"def logdebug(self, message):\n \"\"\"Log debugging information.\"\"\"\n if self.debug:\n self.log(message)\n"
] | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.check_client_ip | python | def check_client_ip(self, rule):
if not rule.get('from'):
self.logdebug('no "from" requirement.\n')
return True
allow_from = rule.get('from')
if not isinstance(allow_from, list):
allow_from = [allow_from]
client_ip = self.get_client_ip()
if ... | If a client IP is specified, verify it is permitted. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L181-L198 | [
"def get_client_ip(self):\n \"\"\"Return the client IP from the environment.\"\"\"\n\n if self.client_ip:\n return self.client_ip\n\n try:\n client = os.environ.get('SSH_CONNECTION',\n os.environ.get('SSH_CLIENT'))\n self.client_ip = client.split()[0]\n ... | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.get_merged_config | python | def get_merged_config(self):
if self.yamldocs:
return
loadfiles = []
if self.configfile:
loadfiles.append(self.configfile)
if self.configdir:
# Gets list of all non-dotfile files from configdir.
loadfiles.extend(
[f for f ... | Get merged config file.
Returns an open StringIO containing the
merged config file. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L200-L232 | [
"def logdebug(self, message):\n \"\"\"Log debugging information.\"\"\"\n if self.debug:\n self.log(message)\n"
] | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.load | python | def load(self):
try:
merged_configfile = self.get_merged_config()
self.yamldocs = yaml.load(merged_configfile, Loader=Loader)
# Strip out the top level 'None's we get from concatenation.
# Functionally not required, but makes dumps cleaner.
self.yamld... | Load our config, log and raise on error. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L234-L246 | [
"def pretty(thing):\n \"\"\"Return pretty-printable version.\"\"\"\n ppthing = pprint.PrettyPrinter(indent=4)\n return ppthing.pformat(thing)\n",
"def raise_and_log_error(self, error, message):\n \"\"\"Raise error, including message and original traceback.\n\n error: the error to raise\n message... | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.dump_config | python | def dump_config(self):
yaml_content = self.get_merged_config()
print('YAML Configuration\n%s\n' % yaml_content.read())
try:
self.load()
print('Python Configuration\n%s\n' % pretty(self.yamldocs))
except ConfigError:
sys.stderr.write(
'c... | Pretty print the configuration dict to stdout. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L248-L258 | [
"def pretty(thing):\n \"\"\"Return pretty-printable version.\"\"\"\n ppthing = pprint.PrettyPrinter(indent=4)\n return ppthing.pformat(thing)\n",
"def get_merged_config(self):\n \"\"\"Get merged config file.\n\n Returns an open StringIO containing the\n merged config file.\n \"\"\"\n if se... | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.install_key_data | python | def install_key_data(self, keydata, target):
target.seek(0)
contents = target.read()
ssh_opts = 'no-port-forwarding'
if keydata in contents:
raise InstallError('key data already in file - refusing '
'to double-install.\n')
command = '%s... | Install the key data into the open file. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L260-L278 | null | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.install_key | python | def install_key(self, keyfile, authorized_keys):
# Make the directory containing the authorized_keys
# file, if it doesn't exist. (Typically ~/.ssh).
# Ignore errors; we'll fail shortly if we can't
# create the authkeys file.
try:
os.makedirs(os.path.dirname(authoriz... | Install a key into the authorized_keys file. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L280-L294 | [
"def install_key_data(self, keydata, target):\n \"\"\"Install the key data into the open file.\"\"\"\n\n target.seek(0)\n contents = target.read()\n ssh_opts = 'no-port-forwarding'\n if keydata in contents:\n raise InstallError('key data already in file - refusing '\n ... | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.find_match_scp | python | def find_match_scp(self, rule): # pylint: disable-msg=R0911,R0912
orig_list = []
orig_list.extend(self.original_command_list)
binary = orig_list.pop(0)
allowed_binaries = ['scp', '/usr/bin/scp']
if binary not in allowed_binaries:
self.logdebug('skipping scp processi... | Handle scp commands. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L296-L342 | [
"def logdebug(self, message):\n \"\"\"Log debugging information.\"\"\"\n if self.debug:\n self.log(message)\n",
"def log(self, message):\n \"\"\"Log information.\"\"\"\n if self.logfh:\n self.logfh.write(message) # pylint: disable-msg=E1103\n"
] | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.find_match_command | python | def find_match_command(self, rule):
command_string = rule['command']
command_list = command_string.split()
self.logdebug('comparing "%s" to "%s"\n' %
(command_list, self.original_command_list))
if rule.get('allow_trailing_args'):
self.logdebug('allow_t... | Return a matching (possibly munged) command, if found in rule. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L344-L368 | [
"def logdebug(self, message):\n \"\"\"Log debugging information.\"\"\"\n if self.debug:\n self.log(message)\n"
] | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.find_match | python | def find_match(self):
self.load()
for yamldoc in self.yamldocs:
self.logdebug('\nchecking rule """%s"""\n' % yamldoc)
if not yamldoc:
continue
if not self.check_client_ip(yamldoc):
# Rejected - Client IP does not match
... | Load the config and find a matching rule.
returns the results of find_match_command, a dict of
the command and (in the future) other metadata. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L370-L413 | [
"def logdebug(self, message):\n \"\"\"Log debugging information.\"\"\"\n if self.debug:\n self.log(message)\n",
"def check_client_ip(self, rule):\n \"\"\"If a client IP is specified, verify it is permitted.\"\"\"\n\n if not rule.get('from'):\n self.logdebug('no \"from\" requirement.\\n')... | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | authprogs/authprogs.py | AuthProgs.exec_command | python | def exec_command(self):
if not self.original_command_string:
raise SSHEnvironmentError('no SSH command found; '
'interactive shell disallowed.')
command_info = {'from': self.get_client_ip(),
'keyname': self.keyname,
... | Glean the command to run and exec.
On problems, sys.exit.
This method should *never* return. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L415-L446 | [
"def get_client_ip(self):\n \"\"\"Return the client IP from the environment.\"\"\"\n\n if self.client_ip:\n return self.client_ip\n\n try:\n client = os.environ.get('SSH_CONNECTION',\n os.environ.get('SSH_CLIENT'))\n self.client_ip = client.split()[0]\n ... | class AuthProgs(object): # pylint: disable-msg=R0902
"""AuthProgs class"""
def __init__(self, logfile=None, configfile=None,
configdir=None, debug=False, **kwargs):
"""AuthProgs constructor.
kwargs include:
authprogs_binary: path to this binary, when creating
... |
daethnir/authprogs | setup.py | runcmd | python | def runcmd(command, command_input=None, cwd=None):
proc = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd)
(stdout, stderr) = proc.communicate(command_input)
if proc.r... | Run a command, potentially sending stdin, and capturing stdout/err. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/setup.py#L33-L45 | null | #!/usr/bin/env python
"""Authprogs setup.py"""
# pylint: disable-msg=W0511
# pylint: disable-msg=R0904
import authprogs
import os
import shutil
import subprocess
import sys
from setuptools import setup
from setuptools.command.install import install
from setuptools.command.sdist import sdist
# Documents that should... |
daethnir/authprogs | setup.py | Converter.dd_docs | python | def dd_docs(self):
top = os.path.join(os.path.dirname(__file__))
doc = os.path.join(top, 'doc')
# Markdown to ronn to man page
man_md = os.path.join(doc, 'authprogs.md')
man_ronn = os.path.join(doc, 'authprogs.1.ronn')
man_1 = os.path.join(doc, 'authprogs.1')
# ... | Copy and convert various documentation files. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/setup.py#L54-L100 | [
"def runcmd(command, command_input=None, cwd=None):\n \"\"\"Run a command, potentially sending stdin, and capturing stdout/err.\"\"\"\n proc = subprocess.Popen(command, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n ... | class Converter(object):
"""Documentation conversion class."""
def __init__(self):
"""Init."""
self.created = []
def rm_docs(self):
"""Remove converted docs."""
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename)
|
daethnir/authprogs | setup.py | Converter.rm_docs | python | def rm_docs(self):
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename) | Remove converted docs. | train | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/setup.py#L102-L106 | null | class Converter(object):
"""Documentation conversion class."""
def __init__(self):
"""Init."""
self.created = []
def dd_docs(self):
"""Copy and convert various documentation files."""
top = os.path.join(os.path.dirname(__file__))
doc = os.path.join(top, 'doc')
... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.create_ngram_table | python | def create_ngram_table(self, cardinality):
query = "CREATE TABLE IF NOT EXISTS _{0}_gram (".format(cardinality)
unique = ""
for i in reversed(range(cardinality)):
if i != 0:
unique += "word_{0}, ".format(i)
query += "word_{0} TEXT, ".format(i)
... | Creates a table for n-gram of a give cardinality. The table name is
constructed from this parameter, for example for cardinality `2` there
will be a table `_2_gram` created.
Parameters
----------
cardinality : int
The cardinality to create a table for. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L56-L79 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def execute_sql(self, query):\n \"\"\"\n Executes a given query string on an open sqlite database.\n\n \"\"\"\n c = self.con.cursor()\n c.execute(query)\n result = c.fetchall()\n return result\n",
"d... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.create_index | python | def create_index(self, cardinality):
for i in reversed(range(cardinality)):
if i != 0:
query = "CREATE INDEX idx_{0}_gram_{1} ON _{0}_gram(word_{1});".format(cardinality, i)
self.execute_sql(query) | Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L97-L110 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def execute_sql(self, query):\n \"\"\"\n Executes a given query string on an open sqlite database.\n\n \"\"\"\n c = self.con.cursor()\n c.execute(query)\n result = c.fetchall()\n return result\n",
"d... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.ngrams | python | def ngrams(self, with_counts=False):
query = "SELECT "
for i in reversed(range(self.cardinality)):
if i != 0:
query += "word_{0}, ".format(i)
elif i == 0:
query += "word"
if with_counts:
query += ", count"
query += " F... | Returns all ngrams that are in the table.
Parameters
----------
None
Returns
-------
ngrams : generator
A generator for ngram tuples. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L150-L178 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def execute_sql(self, query):\n \"\"\"\n Executes a given query string on an open sqlite database.\n\n \"\"\"\n c = self.con.cursor()\n c.execute(query)\n result = c.fetchall()\n return result\n",
"d... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.ngram_count | python | def ngram_count(self, ngram):
query = "SELECT count FROM _{0}_gram".format(len(ngram))
query += self._build_where_clause(ngram)
query += ";"
result = self.execute_sql(query)
return self._extract_first_integer(result) | Gets the count for a given ngram from the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
Returns
-------
count : int
The count of the ngram. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L185-L206 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def _build_where_clause(self, ngram):\n where_clause = \" WHERE\"\n for i in range(len(ngram)):\n n = re_escape_singlequote.sub(\"''\", ngram[i])\n if i < (len(ngram) - 1):\n where_clause += ... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.insert_ngram | python | def insert_ngram(self, ngram, count):
query = "INSERT INTO _{0}_gram {1};".format(len(ngram),
self._build_values_clause(ngram, count))
self.execute_sql(query) | Inserts a given n-gram with count into the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L225-L239 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def _build_values_clause(self, ngram, count):\n ngram_escaped = []\n for n in ngram:\n ngram_escaped.append(re_escape_singlequote.sub(\"''\", n))\n\n values_clause = \"VALUES('\"\n values_clause += \"', ... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.update_ngram | python | def update_ngram(self, ngram, count):
query = "UPDATE _{0}_gram SET count = {1}".format(len(ngram), count)
query += self._build_where_clause(ngram)
query += ";"
self.execute_sql(query) | Updates a given ngram in the database. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L241-L257 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def _build_where_clause(self, ngram):\n where_clause = \" WHERE\"\n for i in range(len(ngram)):\n n = re_escape_singlequote.sub(\"''\", ngram[i])\n if i < (len(ngram) - 1):\n where_clause += ... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.remove_ngram | python | def remove_ngram(self, ngram):
query = "DELETE FROM _{0}_gram".format(len(ngram))
query += self._build_where_clause(ngram)
query += ";"
self.execute_sql(query) | Removes a given ngram from the databae. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L259-L273 | [
"def execute_sql(self):\n raise NotImplementedError(\"Method must be implemented\")\n",
"def _build_where_clause(self, ngram):\n where_clause = \" WHERE\"\n for i in range(len(ngram)):\n n = re_escape_singlequote.sub(\"''\", ngram[i])\n if i < (len(ngram) - 1):\n where_clause += ... | class DatabaseConnector(object):
"""
Base class for all database connectors.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, dbname, cardinality = 1):
"""
Constructor of the base class DababaseConnector.
Parameters
----------
dbname : str
pa... |
cidles/pressagio | src/pressagio/dbconnector.py | SqliteDatabaseConnector.execute_sql | python | def execute_sql(self, query):
c = self.con.cursor()
c.execute(query)
result = c.fetchall()
return result | Executes a given query string on an open sqlite database. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L381-L389 | null | class SqliteDatabaseConnector(DatabaseConnector):
"""
Database connector for sqlite databases.
"""
def __init__(self, dbname, cardinality = 1):
"""
Constructor for the sqlite database connector.
Parameters
----------
dbname : str
path to the databas... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.create_database | python | def create_database(self):
if not self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
... | Creates an empty database if not exists. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L428-L469 | [
"def _database_exists(self):\n \"\"\"\n Check if the database exists.\n\n \"\"\"\n con = psycopg2.connect(host=self.host, database=\"postgres\",\n user=self.user, password=self.password, port=self.port)\n query_check = \"select datname from pg_catalog.pg_database\"\n query_check += \" where... | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.reset_database | python | def reset_database(self):
if self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
q... | Re-create an empty database. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L472-L486 | [
"def create_database(self):\n \"\"\"\n Creates an empty database if not exists.\n\n \"\"\"\n if not self._database_exists():\n con = psycopg2.connect(host=self.host, database=\"postgres\",\n user=self.user, password=self.password, port=self.port)\n con.set_isolation_level(\n ... | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.create_index | python | def create_index(self, cardinality):
DatabaseConnector.create_index(self, cardinality)
query = "CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
if self.lowercase:
for i in reversed(range(cardinality)):
... | Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L488-L522 | [
"def create_index(self, cardinality):\n \"\"\"\n Create an index for the table with the given cardinality.\n\n Parameters\n ----------\n cardinality : int\n The cardinality to create a index for.\n\n \"\"\"\n for i in reversed(range(cardinality)):\n if i != 0:\n query =... | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.delete_index | python | def delete_index(self, cardinality):
DatabaseConnector.delete_index(self, cardinality)
query = "DROP INDEX IF EXISTS idx_{0}_gram_varchar;".format(cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_normalized_varchar;".format(
cardinality)
... | Delete index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality of the index to delete. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L524-L551 | [
"def delete_index(self, cardinality):\n \"\"\"\n Delete index for the table with the given cardinality.\n\n Parameters\n ----------\n cardinality : int\n The cardinality of the index to delete.\n\n \"\"\"\n for i in reversed(range(cardinality)):\n if i != 0:\n query = \... | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.open_database | python | def open_database(self):
if not self.con:
try:
self.con = psycopg2.connect(host=self.host,
database=self.dbname, user=self.user,
password=self.password, port=self.port)
except psycopg2.Error as e:
print("Error while ... | Opens the sqlite database. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L560-L572 | null | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.execute_sql | python | def execute_sql(self, query):
c = self.con.cursor()
c.execute(query)
result = []
if c.rowcount > 0:
try:
result = c.fetchall()
except psycopg2.ProgrammingError:
pass
return result | Executes a given query string on an open postgres database. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L583-L596 | null | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector._database_exists | python | def _database_exists(self):
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
query_check = "select datname from pg_catalog.pg_database"
query_check += " where datname = '{0}';".format(self.dbname)
c = con.curs... | Check if the database exists. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L601-L615 | null | class PostgresDatabaseConnector(DatabaseConnector):
"""
Database connector for postgres databases.
"""
def __init__(self, dbname, cardinality = 1, host = "localhost", port = 5432,
user = "postgres", password = None, connection = None):
"""
Constructor for the postgres datab... |
cidles/pressagio | src/pressagio/tokenizer.py | Tokenizer.is_blankspace | python | def is_blankspace(self, char):
if len(char) > 1:
raise TypeError("Expected a char.")
if char in self.blankspaces:
return True
return False | Test if a character is a blankspace.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a blankspace, False otherwise. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/tokenizer.py#L56-L75 | null | class Tokenizer(object):
"""
Base class for all tokenizers.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, stream, blankspaces = pressagio.character.blankspaces,
separators = pressagio.character.separators):
"""
Constructor of the Tokenizer base class.
Par... |
cidles/pressagio | src/pressagio/tokenizer.py | Tokenizer.is_separator | python | def is_separator(self, char):
if len(char) > 1:
raise TypeError("Expected a char.")
if char in self.separators:
return True
return False | Test if a character is a separator.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a separator, False otherwise. | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/tokenizer.py#L77-L96 | null | class Tokenizer(object):
"""
Base class for all tokenizers.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, stream, blankspaces = pressagio.character.blankspaces,
separators = pressagio.character.separators):
"""
Constructor of the Tokenizer base class.
Par... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_token | python | def get_token(self):
payload = {
'aud': API_OAUTH,
'exp': time.time()+600, # 10 minutes
'sub': self.email
}
header = {'Content-type':'application/x-www-form-urlencoded'}
assertion = jwt.encode(payload, self.private_key, algorithm='RS256')
ass... | Acquires a token for futher API calls, unless you already have a token this will be the first thing
you do before you use this.
:param email: string, the username for your EinsteinVision service, usually in email form
:para pem_file: string, file containing your Secret key. Copy cont... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L48-L83 | null | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_model_info | python | def get_model_info(self, model_id, token=None, url=API_GET_MODEL_INFO):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url + '/' + model_id
r = requests.get(the_url, headers=h)
return r | Gets information about a specific previously trained model, ie: stats and accuracy
:param model_id: string, model_id previously supplied by the API
returns: requests object | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L93-L103 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_datasets_info | python | def get_datasets_info(self, token=None, url=API_GET_DATASETS_INFO):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url
r = requests.get(the_url, headers=h)
return r | Gets information on all datasets for this account
returns: requests object | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L106-L115 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_url_image_prediction | python | def get_url_image_prediction(self, model_id, picture_url, token=None, url=API_GET_PREDICTION_IMAGE_URL):
auth = 'Bearer ' + self.check_for_token(token)
m = MultipartEncoder(fields={'sampleLocation':picture_url, 'modelId':model_id})
h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content... | Gets a prediction from a supplied picture url based on a previously trained model.
:param model_id: string, once you train a model you'll be given a model id to use.
:param picture_url: string, in the form of a url pointing to a publicly accessible
image file.
returns: re... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L118-L131 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_fileb64_image_prediction | python | def get_fileb64_image_prediction(self, model_id, filename, token=None, url=API_GET_PREDICTION_IMAGE_URL):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url
with open(filename, "rb") as image_file:
enc... | Gets a prediction from a supplied image on your machine, by encoding the image data as b64
and posting to the API.
:param model_id: string, once you train a model you'll be given a model id to use.
:param filename: string, the name of a file to be posted to the api.
retur... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L134-L152 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_b64_image_prediction | python | def get_b64_image_prediction(self, model_id, b64_encoded_string, token=None, url=API_GET_PREDICTION_IMAGE_URL):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url
encoded_string = b64_encoded_string
m... | Gets a prediction from a supplied image enconded as a b64 string, useful when uploading
images to a server backed by this library.
:param model_id: string, once you train a model you'll be given a model id to use.
:param b64_encoded_string: string, a b64 enconded string representatio... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L155-L172 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.create_dataset_synchronous | python | def create_dataset_synchronous(self, file_url, dataset_type='image', token=None, url=API_CREATE_DATASET):
auth = 'Bearer ' + self.check_for_token(token)
m = MultipartEncoder(fields={'type':dataset_type, 'path':file_url})
h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.co... | Creates a dataset so you can train models from it
:param file_url: string, url to an accessible zip file containing the necessary image files
and folder structure indicating the labels to train. See docs online.
:param dataset_type: string, one of the dataset types, available options... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L175-L189 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.train_model | python | def train_model(self, dataset_id, model_name, token=None, url=API_TRAIN_MODEL):
auth = 'Bearer ' + self.check_for_token(token)
m = MultipartEncoder(fields={'name':model_name, 'datasetId':dataset_id})
h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type}
t... | Train a model given a specifi dataset previously created
:param dataset_id: string, the id of a previously created dataset
:param model_name: string, what you will call this model
attention: This may take a while and a response will be returned before the model has
finish... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L192-L206 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_training_status | python | def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url + '/' + model_id
r = requests.get(the_url, headers=h)
return r | Gets status on the training process once you create a model
:param model_id: string, id of the model to check
returns: requests object | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L209-L219 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_models_info_for_dataset | python | def get_models_info_for_dataset(self, dataset_id, token=None, url=API_GET_MODELS):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
if url != API_GET_MODELS:
r = requests.get(the_url, headers=h)
return r
the_u... | Gets metadata on all models available for given dataset id
:param dataset_id: string, previously obtained dataset id
warning: if providing your own url here, also include the dataset_id in the right place
as this method will not include it for you. Otherwise use the dataset_id attrib... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L222-L239 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.create_language_dataset_from_url | python | def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET):
auth = 'Bearer ' + self.check_for_token(token)
dummy_files = {'type': (None, 'text-intent'), 'path':(None, file_url)}
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url
... | Creates a dataset from a publicly accessible file stored in the cloud.
:param file_url: string, in the form of a URL to a file accessible on the cloud.
Popular options include Dropbox, AWS S3, Google Drive.
warning: Google Drive by default gives you a link to a web ui that allows yo... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L242-L257 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.train_language_model_from_dataset | python | def train_language_model_from_dataset(self, dataset_id, name, token=None, url=API_TRAIN_LANGUAGE_MODEL):
auth = 'Bearer ' + self.check_for_token(token)
dummy_files = {'name': (None, name), 'datasetId':(None, dataset_id)}
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = u... | Trains a model given a dataset and its ID.
:param dataset_id: string, the ID for a dataset you created previously.
:param name: string, name for your model.
returns: a request object | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L263-L275 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_language_model_status | python | def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL):
auth = 'Bearer ' + self.check_for_token(token)
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
the_url = url + '/' + model_id
r = requests.get(the_url, headers=h)
return r | Gets the status of your model, including whether the training has finished.
:param model_id: string, the ID for a model you created previously.
returns: a request object | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L278-L288 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.get_language_prediction_from_model | python | def get_language_prediction_from_model(self, model_id, document, token=None, url=API_GET_LANGUAGE_PREDICTION):
auth = 'Bearer ' + self.check_for_token(token)
dummy_files = {'modelId': (None, model_id), 'document':(None, document)}
h = {'Authorization': auth, 'Cache-Control':'no-cache'}
t... | Gets a prediction based on a body of text you send to a trained model you created previously.
:param model_id: string, the ID for a model you created previously.
:param document: string, a body of text to be classified.
returns: a request object | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L291-L303 | [
"def check_for_token(self, token=None): \n if token:\n return token\n else:\n return self.token\n"
] | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.parse_rectlabel_app_output | python | def parse_rectlabel_app_output(self):
# get json files only
files = []
files = [f for f in os.listdir() if f[-5:] == '.json']
if len(files) == 0:
print('No json files found in this directory')
return None
max_boxes = 0
rows = []
... | Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app
parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the
column headers.
Could be usef... | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L306-L364 | null | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.save_parsed_data_to_csv | python | def save_parsed_data_to_csv(self, output_filename='output.csv'):
result = self.parse_rectlabel_app_output()
ff = open(output_filename, 'w', encoding='utf8')
for line in result:
ff.write(line + '\n')
ff.close() | Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files
in the creation of an Object Detection dataset.
:param output_filename string, default makes sense, but for your convenience. | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L367-L379 | [
"def parse_rectlabel_app_output(self):\n \"\"\" Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app\n parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the\n... | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | EinsteinVisionService.XML_save_parsed_data_to_csv | python | def XML_save_parsed_data_to_csv(self, output_filename='output.csv'):
result = self.XML_parse_rectlabel_app_output()
ff = open(output_filename, 'w', encoding='utf8')
for line in result:
ff.write(line + '\n')
ff.close() | Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files
in the creation of an Object Detection dataset.
:param output_filename string, default makes sense, but for your convenience. | train | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L382-L394 | [
"def XML_parse_rectlabel_app_output(self):\n files = []\n files = [f for f in os.listdir() if f[-4:] == '.xml']\n\n max_boxes = 0\n rows = [] \n\n for f in files:\n tree = ET.parse(f)\n root = tree.getroot()\n row = []\n objects = root.findall('object')\n pri... | class EinsteinVisionService:
""" A wrapper for Salesforce's Einstein Vision API.
:param token: string, in case you obtained a token somewhere else and want to use it here.
:param email: string, the username for your Enstein Vision account, not needed if you already have a token
:param rsa_ce... |
snipsco/snipsmanagercore | snipsmanagercore/intent_parser.py | IntentParser.parse | python | def parse(payload, candidate_classes):
for cls in candidate_classes:
intent = cls.parse(payload)
if intent:
return intent
return None | Parse a json response into an intent.
:param payload: a JSON object representing an intent.
:param candidate_classes: a list of classes representing various
intents, each having their own `parse`
method to attempt parsing the JSON obje... | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L14-L29 | null | class IntentParser:
""" Helper class for parsing intents. """
@staticmethod
@staticmethod
def get_intent_name(payload):
""" Return the simple intent name. An intent has the form:
{
"input": "turn the lights green",
"intent": {
"inte... |
snipsco/snipsmanagercore | snipsmanagercore/intent_parser.py | IntentParser.get_slot_value | python | def get_slot_value(payload, slot_name):
if not 'slots' in payload:
return []
slots = []
for candidate in payload['slots']:
if 'slotName' in candidate and candidate['slotName'] == slot_name:
slots.append(candidate)
result = []
for slot in... | Return the parsed value of a slot. An intent has the form:
{
"text": "brew me a cappuccino with 3 sugars tomorrow",
"slots": [
{"value": {"slotName": "coffee_type", "value": "cappuccino"}},
...
]
}
... | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L59-L133 | [
"def parse_instant_time(slot):\n \"\"\" Parse a slot into an InstantTime object.\n\n Sample response:\n\n {\n \"entity\": \"snips/datetime\",\n \"range\": {\n \"end\": 36,\n \"start\": 28\n },\n \"rawValue\": \"tomorrow\",\n \"slotName\": \"weatherForecastStartDatetim... | class IntentParser:
""" Helper class for parsing intents. """
@staticmethod
def parse(payload, candidate_classes):
""" Parse a json response into an intent.
:param payload: a JSON object representing an intent.
:param candidate_classes: a list of classes representing various
... |
snipsco/snipsmanagercore | snipsmanagercore/intent_parser.py | IntentParser.parse_instant_time | python | def parse_instant_time(slot):
date = IntentParser.get_dict_value(slot, ['value', 'value'])
if not date:
return None
date = parse(date)
if not date:
return None
grain = InstantTime.parse_grain(
IntentParser.get_dict_value(slot,
... | Parse a slot into an InstantTime object.
Sample response:
{
"entity": "snips/datetime",
"range": {
"end": 36,
"start": 28
},
"rawValue": "tomorrow",
"slotName": "weatherForecastStartDatetime",
"value": {
"g... | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L136-L169 | [
"def parse_grain(grain):\n \"\"\" Parse a string to a granularity, e.g. \"Day\" to InstantTime.day.\n\n :param grain: a string representing a granularity.\n \"\"\"\n if not grain:\n return InstantTime.day\n if grain.lower() == 'week':\n return InstantTime.week\n return InstantTime.da... | class IntentParser:
""" Helper class for parsing intents. """
@staticmethod
def parse(payload, candidate_classes):
""" Parse a json response into an intent.
:param payload: a JSON object representing an intent.
:param candidate_classes: a list of classes representing various
... |
snipsco/snipsmanagercore | snipsmanagercore/intent_parser.py | IntentParser.parse_time_interval | python | def parse_time_interval(slot):
start = IntentParser.get_dict_value(
slot, ['value', 'from'])
end = IntentParser.get_dict_value(slot, ['value', 'to'])
if not start or not end:
return None
start = parse(start)
end = parse(end)
if not start or not end... | Parse a slot into a TimeInterval object.
Sample response:
{
"entity": "snips/datetime",
"range": {
"end": 42,
"start": 13
},
"rawValue": "between tomorrow and saturday",
"slotName": "weatherForecastStartDatetime",
"val... | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L172-L204 | [
"def get_dict_value(dictionary, path):\n \"\"\" Safely get the value of a dictionary given a key path. For\n instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at\n key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at\n key path ['a', 'b', 'c'] is None.\n\n :param dict... | class IntentParser:
""" Helper class for parsing intents. """
@staticmethod
def parse(payload, candidate_classes):
""" Parse a json response into an intent.
:param payload: a JSON object representing an intent.
:param candidate_classes: a list of classes representing various
... |
snipsco/snipsmanagercore | snipsmanagercore/intent_parser.py | IntentParser.get_dict_value | python | def get_dict_value(dictionary, path):
if len(path) == 0:
return None
temp_dictionary = dictionary
try:
for k in path:
temp_dictionary = temp_dictionary[k]
return temp_dictionary
except (KeyError, TypeError):
pass
ret... | Safely get the value of a dictionary given a key path. For
instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at
key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at
key path ['a', 'b', 'c'] is None.
:param dictionary: a dictionary.
:param path: t... | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L207-L227 | null | class IntentParser:
""" Helper class for parsing intents. """
@staticmethod
def parse(payload, candidate_classes):
""" Parse a json response into an intent.
:param payload: a JSON object representing an intent.
:param candidate_classes: a list of classes representing various
... |
snipsco/snipsmanagercore | snipsmanagercore/tts.py | GTTS.speak | python | def speak(self, sentence):
temp_dir = "/tmp/"
filename = "gtts.mp3"
file_path = "{}/{}".format(temp_dir, filename)
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
def delete_file():
try:
os.remove(file_path)
if not ... | Speak a sentence using Google TTS.
:param sentence: the sentence to speak. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/tts.py#L23-L49 | [
"def play_async(cls, file_path, on_done=None):\n \"\"\" Play an audio file asynchronously.\n\n :param file_path: the path to the file to play.\n :param on_done: callback when audio playback completes.\n \"\"\"\n thread = threading.Thread(\n target=AudioPlayer.play, args=(file_path, on_done,))\... | class GTTS:
""" Google TTS service. """
def __init__(self, locale, logger=None):
""" Initialise the service.
:param locale: the language locale, e.g. "fr" or "en_US".
"""
self.logger = logger
self.locale = locale.split("_")[0]
|
snipsco/snipsmanagercore | snipsmanagercore/instant_time.py | InstantTime.parse_grain | python | def parse_grain(grain):
if not grain:
return InstantTime.day
if grain.lower() == 'week':
return InstantTime.week
return InstantTime.day | Parse a string to a granularity, e.g. "Day" to InstantTime.day.
:param grain: a string representing a granularity. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/instant_time.py#L23-L32 | null | class InstantTime:
""" A representation of a datetime with a given granularity (day, week).
"""
day, week = range(2)
def __init__(self, datetime, granularity=None):
""" Initialisation.
:param datetime: the underlying datetime object
:param granularity: granularity of the datet... |
snipsco/snipsmanagercore | snipsmanagercore/sound_service.py | SoundService.play | python | def play(state):
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off.wav"
elif state == SoundService.State.hotword_detected:
filename = "pad... | Play sound for a given state.
:param state: a State value. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/sound_service.py#L23-L41 | [
"def play_async(cls, file_path, on_done=None):\n \"\"\" Play an audio file asynchronously.\n\n :param file_path: the path to the file to play.\n :param on_done: callback when audio playback completes.\n \"\"\"\n thread = threading.Thread(\n target=AudioPlayer.play, args=(file_path, on_done,))\... | class SoundService:
""" Sound service for playing various state sounds. """
class State:
""" States handled by the sound service. """
none, welcome, goodbye, hotword_detected, asr_text_captured, error = range(
6)
@staticmethod
|
snipsco/snipsmanagercore | snipsmanagercore/thread_handler.py | ThreadHandler.run | python | def run(self, target, args=()):
run_event = threading.Event()
run_event.set()
thread = threading.Thread(target=target, args=args + (run_event, ))
self.thread_pool.append(thread)
self.run_events.append(run_event)
thread.start() | Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/thread_handler.py#L19-L30 | null | class ThreadHandler(Singleton):
""" Thread handler. """
def __init__(self):
""" Initialisation. """
self.thread_pool = []
self.run_events = []
def start_run_loop(self):
""" Start the thread handler, ensuring that everything stops property
when sending a keyboar... |
snipsco/snipsmanagercore | snipsmanagercore/thread_handler.py | ThreadHandler.stop | python | def stop(self):
for run_event in self.run_events:
run_event.clear()
for thread in self.thread_pool:
thread.join() | Stop all functions running in the thread handler. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/thread_handler.py#L42-L48 | null | class ThreadHandler(Singleton):
""" Thread handler. """
def __init__(self):
""" Initialisation. """
self.thread_pool = []
self.run_events = []
def run(self, target, args=()):
""" Run a function in a separate thread.
:param target: the function to run.
:para... |
snipsco/snipsmanagercore | snipsmanagercore/audio_player.py | AudioPlayer.play | python | def play(cls, file_path, on_done=None, logger=None):
pygame.mixer.init()
try:
pygame.mixer.music.load(file_path)
except pygame.error as e:
if logger is not None:
logger.warning(str(e))
return
pygame.mixer.music.play()
while pyg... | Play an audio file.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/audio_player.py#L12-L31 | null | class AudioPlayer:
""" A simple audio player based on pygame. """
@classmethod
@classmethod
def play_async(cls, file_path, on_done=None):
""" Play an audio file asynchronously.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback comple... |
snipsco/snipsmanagercore | snipsmanagercore/audio_player.py | AudioPlayer.play_async | python | def play_async(cls, file_path, on_done=None):
thread = threading.Thread(
target=AudioPlayer.play, args=(file_path, on_done,))
thread.start() | Play an audio file asynchronously.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/audio_player.py#L34-L42 | null | class AudioPlayer:
""" A simple audio player based on pygame. """
@classmethod
def play(cls, file_path, on_done=None, logger=None):
""" Play an audio file.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes.
"""
py... |
snipsco/snipsmanagercore | snipsmanagercore/server.py | Server.start | python | def start(self):
self.thread_handler.run(target=self.start_blocking)
self.thread_handler.start_run_loop() | Start the MQTT client. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/server.py#L72-L75 | null | class Server():
""" Snips core server. """
DIALOGUE_EVENT_STARTED, DIALOGUE_EVENT_ENDED, DIALOGUE_EVENT_QUEUED = range(3)
def __init__(self,
mqtt_hostname,
mqtt_port,
tts_service_id,
locale,
registry,
hand... |
snipsco/snipsmanagercore | snipsmanagercore/server.py | Server.start_blocking | python | def start_blocking(self, run_event):
topics = [("hermes/intent/#", 0), ("hermes/hotword/#", 0), ("hermes/asr/#", 0), ("hermes/nlu/#", 0),
("snipsmanager/#", 0)]
self.log_info("Connecting to {} on port {}".format(self.mqtt_hostname, str(self.mqtt_port)))
retry = 0
whil... | Start the MQTT client, as a blocking method.
:param run_event: a run event object provided by the thread handler. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/server.py#L77-L113 | [
"def log_info(self, message):\n if self.logger is not None:\n self.logger.info(message)\n"
] | class Server():
""" Snips core server. """
DIALOGUE_EVENT_STARTED, DIALOGUE_EVENT_ENDED, DIALOGUE_EVENT_QUEUED = range(3)
def __init__(self,
mqtt_hostname,
mqtt_port,
tts_service_id,
locale,
registry,
hand... |
snipsco/snipsmanagercore | snipsmanagercore/server.py | Server.on_connect | python | def on_connect(self, client, userdata, flags, result_code):
self.log_info("Connected with result code {}".format(result_code))
self.state_handler.set_state(State.welcome) | Callback when the MQTT client is connected.
:param client: the client being connected.
:param userdata: unused.
:param flags: unused.
:param result_code: result code. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/server.py#L116-L125 | [
"def log_info(self, message):\n if self.logger is not None:\n self.logger.info(message)\n"
] | class Server():
""" Snips core server. """
DIALOGUE_EVENT_STARTED, DIALOGUE_EVENT_ENDED, DIALOGUE_EVENT_QUEUED = range(3)
def __init__(self,
mqtt_hostname,
mqtt_port,
tts_service_id,
locale,
registry,
hand... |
snipsco/snipsmanagercore | snipsmanagercore/server.py | Server.on_disconnect | python | def on_disconnect(self, client, userdata, result_code):
self.log_info("Disconnected with result code " + str(result_code))
self.state_handler.set_state(State.goodbye)
time.sleep(5)
self.thread_handler.run(target=self.start_blocking) | Callback when the MQTT client is disconnected. In this case,
the server waits five seconds before trying to reconnected.
:param client: the client being disconnected.
:param userdata: unused.
:param result_code: result code. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/server.py#L128-L139 | [
"def log_info(self, message):\n if self.logger is not None:\n self.logger.info(message)\n"
] | class Server():
""" Snips core server. """
DIALOGUE_EVENT_STARTED, DIALOGUE_EVENT_ENDED, DIALOGUE_EVENT_QUEUED = range(3)
def __init__(self,
mqtt_hostname,
mqtt_port,
tts_service_id,
locale,
registry,
hand... |
snipsco/snipsmanagercore | snipsmanagercore/server.py | Server.on_message | python | def on_message(self, client, userdata, msg):
if msg is None:
return
self.log_info("New message on topic {}".format(msg.topic))
self.log_debug("Payload {}".format(msg.payload))
if msg.payload is None or len(msg.payload) == 0:
pass
if msg.payload:
... | Callback when the MQTT client received a new message.
:param client: the MQTT client.
:param userdata: unused.
:param msg: the MQTT message. | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/server.py#L142-L207 | [
"def log_info(self, message):\n if self.logger is not None:\n self.logger.info(message)\n",
"def log_debug(self, message):\n if self.logger is not None:\n self.logger.debug(message)\n"
] | class Server():
""" Snips core server. """
DIALOGUE_EVENT_STARTED, DIALOGUE_EVENT_ENDED, DIALOGUE_EVENT_QUEUED = range(3)
def __init__(self,
mqtt_hostname,
mqtt_port,
tts_service_id,
locale,
registry,
hand... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.put | python | def put(self, stream, cmd):
if len(self.q) < self.max_size:
if stream['id'] in self.q:
raise QueueDuplicate
p = self.call(stream, cmd)
self.q[stream['id']] = p
else:
raise QueueFull | Spawn a new background process | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L63-L72 | null | class ProcessList(object):
""" Small class to store and handle calls to a given callable """
def __init__(self, f, max_size=10):
""" Create a ProcessList
f : callable for which a process will be spawned for each call to put
max_size : the maximum size of the ProcessList
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.get_finished | python | def get_finished(self):
indices = []
for idf, v in self.q.items():
if v.poll() != None:
indices.append(idf)
for i in indices:
self.q.pop(i)
return indices | Clean up terminated processes and returns the list of their ids | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L74-L83 | null | class ProcessList(object):
""" Small class to store and handle calls to a given callable """
def __init__(self, f, max_size=10):
""" Create a ProcessList
f : callable for which a process will be spawned for each call to put
max_size : the maximum size of the ProcessList
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.get_stdouts | python | def get_stdouts(self):
souts = []
for v in self.q.values():
souts.append(v.stdout)
return souts | Get the list of stdout of each process | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L89-L94 | null | class ProcessList(object):
""" Small class to store and handle calls to a given callable """
def __init__(self, f, max_size=10):
""" Create a ProcessList
f : callable for which a process will be spawned for each call to put
max_size : the maximum size of the ProcessList
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.terminate_process | python | def terminate_process(self, idf):
try:
p = self.q.pop(idf)
p.terminate()
return p
except:
return None | Terminate a process by id | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L96-L103 | null | class ProcessList(object):
""" Small class to store and handle calls to a given callable """
def __init__(self, f, max_size=10):
""" Create a ProcessList
f : callable for which a process will be spawned for each call to put
max_size : the maximum size of the ProcessList
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.terminate | python | def terminate(self):
for w in self.q.values():
try:
w.terminate()
except:
pass
self.q = {} | Terminate all processes | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L105-L113 | null | class ProcessList(object):
""" Small class to store and handle calls to a given callable """
def __init__(self, f, max_size=10):
""" Create a ProcessList
f : callable for which a process will be spawned for each call to put
max_size : the maximum size of the ProcessList
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.init | python | def init(self, s):
# Hide cursor
curses.curs_set(0)
self.s = s
self.s.keypad(1)
self.set_screen_size()
self.pads = {}
self.offsets = {}
self.init_help()
self.init_streams_pad()
self.current_pad = 'streams'
self.set_title(TITLE... | Initialize the text interface | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L217-L244 | [
"def set_screen_size(self):\n \"\"\" Setup screen size and padding\n\n We have need 2 free lines at the top and 2 free lines at the bottom\n\n \"\"\"\n height, width = self.getheightwidth()\n curses.resizeterm(height, width)\n self.pad_x = 0\n self.max_y, self.max_x = (height-1, width-1)\n s... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.getheightwidth | python | def getheightwidth(self):
try:
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
except KeyError:
height, width = struct.unpack(
"hhhh", ioctl(0, termios.TIOCGWINSZ ,"\000"*8))[0:2]
if not height:
return 25, 80
ret... | getwidth() -> (int, int)
Return the height and width of the console in characters
https://groups.google.com/forum/#!msg/comp.lang.python/CpUszNNXUQM/QADpl11Z-nAJ | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L246-L258 | null | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.resize | python | def resize(self, signum, obj):
self.s.clear()
stream_cursor = self.pads['streams'].getyx()[0]
for pad in self.pads.values():
pad.clear()
self.s.refresh()
self.set_screen_size()
self.set_title(TITLE_STRING)
self.init_help()
self.init_streams_pad... | handler for SIGWINCH | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L260-L273 | [
"def set_screen_size(self):\n \"\"\" Setup screen size and padding\n\n We have need 2 free lines at the top and 2 free lines at the bottom\n\n \"\"\"\n height, width = self.getheightwidth()\n curses.resizeterm(height, width)\n self.pad_x = 0\n self.max_y, self.max_x = (height-1, width-1)\n s... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.run | python | def run(self):
# Show stream list
self.show_streams()
while True:
self.s.refresh()
# See if any stream has ended
self.check_stopped_streams()
# Wait on stdin or on the streams output
souts = self.q.get_stdouts()
souts.ap... | Main event loop | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L275-L368 | [
"def show_help(self):\n \"\"\" Redraw Help screen and wait for any input to leave \"\"\"\n self.s.move(1,0)\n self.s.clrtobot()\n self.set_header('Help'.center(self.pad_w))\n self.set_footer(' ESC or \\'q\\' to return to main menu')\n self.s.refresh()\n self.current_pad = 'help'\n self.refre... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_screen_size | python | def set_screen_size(self):
height, width = self.getheightwidth()
curses.resizeterm(height, width)
self.pad_x = 0
self.max_y, self.max_x = (height-1, width-1)
self.pad_h = height-3
self.pad_w = width-2*self.pad_x | Setup screen size and padding
We have need 2 free lines at the top and 2 free lines at the bottom | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L370-L381 | [
"def getheightwidth(self):\n \"\"\" getwidth() -> (int, int)\n\n Return the height and width of the console in characters\n https://groups.google.com/forum/#!msg/comp.lang.python/CpUszNNXUQM/QADpl11Z-nAJ\"\"\"\n try:\n return int(os.environ[\"LINES\"]), int(os.environ[\"COLUMNS\"])\n except Ke... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_title | python | def set_title(self, msg):
self.s.move(0, 0)
self.overwrite_line(msg, curses.A_REVERSE) | Set first header line text | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L388-L391 | [
"def overwrite_line(self, msg, attr=curses.A_NORMAL):\n self.s.clrtoeol()\n self.s.addstr(msg, attr)\n self.s.chgat(attr)\n"
] | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_header | python | def set_header(self, msg):
self.s.move(1, 0)
self.overwrite_line(msg, attr=curses.A_NORMAL) | Set second head line text | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L393-L396 | [
"def overwrite_line(self, msg, attr=curses.A_NORMAL):\n self.s.clrtoeol()\n self.s.addstr(msg, attr)\n self.s.chgat(attr)\n"
] | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_footer | python | def set_footer(self, msg, reverse=True):
self.s.move(self.max_y-1, 0)
if reverse:
self.overwrite_line(msg, attr=curses.A_REVERSE)
else:
self.overwrite_line(msg, attr=curses.A_NORMAL) | Set first footer line text | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L398-L404 | [
"def overwrite_line(self, msg, attr=curses.A_NORMAL):\n self.s.clrtoeol()\n self.s.addstr(msg, attr)\n self.s.chgat(attr)\n"
] | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.show_help | python | def show_help(self):
self.s.move(1,0)
self.s.clrtobot()
self.set_header('Help'.center(self.pad_w))
self.set_footer(' ESC or \'q\' to return to main menu')
self.s.refresh()
self.current_pad = 'help'
self.refresh_current_pad() | Redraw Help screen and wait for any input to leave | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L450-L458 | [
"def set_header(self, msg):\n \"\"\" Set second head line text \"\"\"\n self.s.move(1, 0)\n self.overwrite_line(msg, attr=curses.A_NORMAL)\n",
"def set_footer(self, msg, reverse=True):\n \"\"\" Set first footer line text \"\"\"\n self.s.move(self.max_y-1, 0)\n if reverse:\n self.overwrite... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.init_streams_pad | python | def init_streams_pad(self, start_row=0):
y = 0
pad = curses.newpad(max(1,len(self.filtered_streams)), self.pad_w)
pad.keypad(1)
for s in self.filtered_streams:
pad.addstr(y, 0, self.format_stream_line(s))
y+=1
self.offsets['streams'] = 0
pad.move(s... | Create a curses pad and populate it with a line by stream | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L460-L472 | [
"def format_stream_line(self, stream):\n idf = '{0} '.format(stream['id']).rjust(ID_FIELD_WIDTH)\n name = ' {0}'.format(stream['name'][:NAME_FIELD_WIDTH-2]).ljust(NAME_FIELD_WIDTH)\n res = ' {0}'.format(stream['res'][:RES_FIELD_WIDTH-2]).ljust(RES_FIELD_WIDTH)\n views = '{0} '.format(stream['seen']).r... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.move | python | def move(self, direction, absolute=False, pad_name=None, refresh=True):
# pad in this lists have the current line highlighted
cursor_line = [ 'streams' ]
# pads in this list will be moved screen-wise as opposed to line-wise
# if absolute is set, will go all the way top or all the way d... | Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
Behaviour is affected by cursor_line and scroll_only below
absolute : (bool) | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L516-L580 | [
"def refresh_current_pad(self):\n pad = self.pads[self.current_pad]\n pad.refresh(self.offsets[self.current_pad], 0, 2, self.pad_x, self.pad_h, self.pad_w)\n",
"def redraw_stream_footer(self):\n if not self.no_stream_shown:\n row = self.pads[self.current_pad].getyx()[0]\n s = self.filtered_... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.redraw_current_line | python | def redraw_current_line(self):
if self.no_streams:
return
row = self.pads[self.current_pad].getyx()[0]
s = self.filtered_streams[row]
pad = self.pads['streams']
pad.move(row, 0)
pad.clrtoeol()
pad.addstr(row, 0, self.format_stream_line(s), curses.A_REV... | Redraw the highlighted line | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L594-L606 | [
"def refresh_current_pad(self):\n pad = self.pads[self.current_pad]\n pad.refresh(self.offsets[self.current_pad], 0, 2, self.pad_x, self.pad_h, self.pad_w)\n",
"def format_stream_line(self, stream):\n idf = '{0} '.format(stream['id']).rjust(ID_FIELD_WIDTH)\n name = ' {0}'.format(stream['name'][:NAME_F... | class StreamList(object):
def __init__(self, filename, config, list_streams=False, init_stream_list=None):
""" Init and try to load a stream list, nothing about curses yet """
global TITLE_STRING
self.db_was_read = False
# Open the storage (create it if necessary)
try:
... |
Synerty/peek-plugin-base | peek_plugin_base/server/PeekPlatformServerHttpHookABC.py | PeekPlatformServerHttpHookABC.addServerResource | python | def addServerResource(self, pluginSubPath: bytes, resource: BasicResource) -> None:
pluginSubPath = pluginSubPath.strip(b'/')
self.__rootServerResource.putChild(pluginSubPath, resource) | Add Server Resource
Add a cusotom implementation of a served http resource.
:param pluginSubPath: The resource path where you want to serve this resource.
:param resource: The resource to serve.
:return: None | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/server/PeekPlatformServerHttpHookABC.py#L30-L41 | null | class PeekPlatformServerHttpHookABC(metaclass=ABCMeta):
""" Peek Platform Server HTTP Hook
The methods provided by this class apply to the HTTP service that provides
resources (vortex, etc) beween the server and the agent, worker and client.
These resources will not be availible to the web apps.
... |
Synerty/peek-plugin-base | peek_plugin_base/client/PluginClientEntryHookABC.py | PluginClientEntryHookABC.angularFrontendAppDir | python | def angularFrontendAppDir(self) -> str:
relDir = self._packageCfg.config.plugin.title(require_string)
dir = os.path.join(self._pluginRoot, relDir)
if not os.path.isdir(dir): raise NotADirectoryError(dir)
return dir | Angular Frontend Dir
This directory will be linked into the angular app when it is compiled.
:return: The absolute path of the Angular2 app directory. | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/client/PluginClientEntryHookABC.py#L31-L41 | null | class PluginClientEntryHookABC(PluginCommonEntryHookABC):
def __init__(self, pluginName: str, pluginRootDir: str, platform: PeekClientPlatformHookABC):
PluginCommonEntryHookABC.__init__(self, pluginName=pluginName, pluginRootDir=pluginRootDir)
self._platform = platform
@property
def platfor... |
Synerty/peek-plugin-base | peek_plugin_base/storage/AlembicEnvBase.py | AlembicEnvBase.run | python | def run(self):
connectable = engine_from_config(
self._config.get_section(self._config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
ensureSchemaExists(connectable, self._schemaName)
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/AlembicEnvBase.py#L42-L66 | [
"def ensureSchemaExists(engine, schemaName):\n # Ensure the schema exists\n\n if isinstance(engine.dialect, MSDialect):\n if list(engine.execute(\"SELECT SCHEMA_ID('%s')\" % schemaName))[0][0] is None:\n engine.execute(\"CREATE SCHEMA [%s]\" % schemaName)\n\n elif isinstance(engine.dialec... | class AlembicEnvBase:
def __init__(self, targetMetadata):
from peek_platform.util.LogUtil import setupPeekLogger
setupPeekLogger()
self._config = context.config
self._targetMetadata = targetMetadata
self._schemaName = targetMetadata.schema
def _includeObjectFilter(self,... |
Synerty/peek-plugin-base | peek_plugin_base/server/PeekPlatformAdminHttpHookABC.py | PeekPlatformAdminHttpHookABC.addAdminResource | python | def addAdminResource(self, pluginSubPath: bytes, resource: BasicResource) -> None:
pluginSubPath = pluginSubPath.strip(b'/')
self.__rootAdminResource.putChild(pluginSubPath, resource) | Add Site Resource
Add a cusotom implementation of a served http resource.
:param pluginSubPath: The resource path where you want to serve this resource.
:param resource: The resource to serve.
:return: None | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/server/PeekPlatformAdminHttpHookABC.py#L31-L42 | null | class PeekPlatformAdminHttpHookABC(metaclass=ABCMeta):
""" Peek Platform Site HTTP Hook
The methods provided by this class apply to the HTTP sites served by the
Client service for the mobile and desktop apps, and the Server service for the
admin app.
It is not the HTTP service that provides resour... |
Synerty/peek-plugin-base | peek_plugin_base/client/PeekPlatformMobileHttpHookABC.py | PeekPlatformMobileHttpHookABC.addMobileResource | python | def addMobileResource(self, pluginSubPath: bytes, resource: BasicResource) -> None:
pluginSubPath = pluginSubPath.strip(b'/')
self.__rootMobileResource.putChild(pluginSubPath, resource) | Add Site Resource
Add a cusotom implementation of a served http resource.
:param pluginSubPath: The resource path where you want to serve this resource.
:param resource: The resource to serve.
:return: None | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/client/PeekPlatformMobileHttpHookABC.py#L31-L42 | null | class PeekPlatformMobileHttpHookABC(metaclass=ABCMeta):
""" Peek Platform Site HTTP Hook
The methods provided by this class apply to the HTTP sites served by the
Client service for the mobile and desktop apps, and the Server service for the
admin app.
It is not the HTTP service that provides resou... |
Synerty/peek-plugin-base | peek_plugin_base/worker/CeleryDbConn.py | setConnStringForWindows | python | def setConnStringForWindows():
global _dbConnectString
from peek_platform.file_config.PeekFileConfigABC import PeekFileConfigABC
from peek_platform.file_config.PeekFileConfigSqlAlchemyMixin import \
PeekFileConfigSqlAlchemyMixin
from peek_platform import PeekPlatformConfig
class _WorkerTask... | Set Conn String for Windiws
Windows has a different way of forking processes, which causes the
@worker_process_init.connect signal not to work in "CeleryDbConnInit" | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/worker/CeleryDbConn.py#L20-L40 | null | import logging
import platform
from threading import Lock
from typing import Iterable, Optional
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.orm.session import sessionmaker
from peek_plugin_base.PeekVortexUtil import peekWorkerName
from peek_plugin_base... |
Synerty/peek-plugin-base | peek_plugin_base/worker/CeleryDbConn.py | prefetchDeclarativeIds | python | def prefetchDeclarativeIds(Declarative, count) -> Optional[Iterable[int]]:
return _commonPrefetchDeclarativeIds(
getDbEngine(), _sequenceMutex, Declarative, count
) | Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, especially those using inheritance
* When we need the ID to assign it to a related object that we'... | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/worker/CeleryDbConn.py#L83-L102 | [
"def _commonPrefetchDeclarativeIds(engine, mutex,\n Declarative, count) -> Optional[Iterable[int]]:\n \"\"\" Common Prefetch Declarative IDs\n\n This function is used by the worker and server\n \"\"\"\n if not count:\n logger.debug(\"Count was zero, no range retur... | import logging
import platform
from threading import Lock
from typing import Iterable, Optional
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.orm.session import sessionmaker
from peek_plugin_base.PeekVortexUtil import peekWorkerName
from peek_plugin_base... |
Synerty/peek-plugin-base | peek_plugin_base/client/PeekPlatformDesktopHttpHookABC.py | PeekPlatformDesktopHttpHookABC.addDesktopResource | python | def addDesktopResource(self, pluginSubPath: bytes, resource: BasicResource) -> None:
pluginSubPath = pluginSubPath.strip(b'/')
self.__rootDesktopResource.putChild(pluginSubPath, resource) | Add Site Resource
Add a cusotom implementation of a served http resource.
:param pluginSubPath: The resource path where you want to serve this resource.
:param resource: The resource to serve.
:return: None | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/client/PeekPlatformDesktopHttpHookABC.py#L31-L42 | null | class PeekPlatformDesktopHttpHookABC(metaclass=ABCMeta):
""" Peek Platform Site HTTP Hook
The methods provided by this class apply to the HTTP sites served by the
Client service for the mobile and desktop apps, and the Server service for the
admin app.
It is not the HTTP service that provides reso... |
Synerty/peek-plugin-base | peek_plugin_base/server/PluginServerStorageEntryHookABC.py | PluginServerStorageEntryHookABC._migrateStorageSchema | python | def _migrateStorageSchema(self, metadata: MetaData) -> None:
relDir = self._packageCfg.config.storage.alembicDir(require_string)
alembicDir = os.path.join(self.rootDir, relDir)
if not os.path.isdir(alembicDir): raise NotADirectoryError(alembicDir)
self._dbConn = DbConnection(
... | Initialise the DB
This method is called by the platform between the load() and start() calls.
There should be no need for a plugin to call this method it's self.
:param metadata: the SQLAlchemy metadata for this plugins schema | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/server/PluginServerStorageEntryHookABC.py#L15-L36 | null | class PluginServerStorageEntryHookABC(metaclass=ABCMeta):
@property
def dbSessionCreator(self) -> DbSessionCreator:
""" Database Session
This is a helper property that can be used by the papp to get easy access to
the SQLAlchemy C{Session}
:return: An instance of the sqlalche... |
Synerty/peek-plugin-base | peek_plugin_base/server/PluginServerStorageEntryHookABC.py | PluginServerStorageEntryHookABC.prefetchDeclarativeIds | python | def prefetchDeclarativeIds(self, Declarative, count) -> Deferred:
return self._dbConn.prefetchDeclarativeIds(Declarative=Declarative, count=count) | Get PG Sequence Generator
A PostGreSQL sequence generator returns a chunk of IDs for the given
declarative.
:return: A generator that will provide the IDs
:rtype: an iterator, yielding the numbers to assign | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/server/PluginServerStorageEntryHookABC.py#L62-L72 | null | class PluginServerStorageEntryHookABC(metaclass=ABCMeta):
def _migrateStorageSchema(self, metadata: MetaData) -> None:
""" Initialise the DB
This method is called by the platform between the load() and start() calls.
There should be no need for a plugin to call this method it's self.
... |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | _commonPrefetchDeclarativeIds | python | def _commonPrefetchDeclarativeIds(engine, mutex,
Declarative, count) -> Optional[Iterable[int]]:
if not count:
logger.debug("Count was zero, no range returned")
return
conn = engine.connect()
transaction = conn.begin()
mutex.acquire()
try:
s... | Common Prefetch Declarative IDs
This function is used by the worker and server | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L221-L267 | [
"def isMssqlDialect(engine):\n return isinstance(engine.dialect, MSDialect)\n",
"def isPostGreSQLDialect(engine):\n return isinstance(engine.dialect, PGDialect)\n"
] | import logging
from textwrap import dedent
from threading import Lock
from typing import Optional, Dict, Union, Callable, Iterable
import sqlalchemy_utils
from pytmpdir.Directory import Directory
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine
from sqlalchemy.orm import scoped_session
fr... |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.ormSessionCreator | python | def ormSessionCreator(self) -> DbSessionCreator:
assert self._dbConnectString
if self._ScopedSession:
return self._ScopedSession
self._dbEngine = create_engine(
self._dbConnectString,
**self._dbEngineArgs
)
self._ScopedSession = scoped_sessi... | Get Orm Session
:return: A SQLAlchemy session scoped for the callers thread.. | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L82-L100 | null | class DbConnection:
def __init__(self, dbConnectString: str, metadata: MetaData, alembicDir: str,
dbEngineArgs: Optional[Dict[str, Union[str, int]]] = None,
enableForeignKeys=False, enableCreateAll=True):
""" SQLAlchemy Database Connection
This class takes care of ... |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.migrate | python | def migrate(self) -> None:
assert self.ormSessionCreator, "ormSessionCreator is not defined"
connection = self._dbEngine.connect()
isDbInitialised = self._dbEngine.dialect.has_table(
connection, 'alembic_version',
schema=self._metadata.schema)
connection.close()... | Migrate
Perform a database migration, upgrading to the latest schema level. | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L114-L135 | [
"def checkForeignKeys(self, engine: Engine) -> None:\n \"\"\" Check Foreign Keys\n\n Log any foreign keys that don't have indexes assigned to them.\n This is a performance issue.\n\n \"\"\"\n missing = (sqlalchemy_utils.functions\n .non_indexed_foreign_keys(self._metadata, engine=engine... | class DbConnection:
def __init__(self, dbConnectString: str, metadata: MetaData, alembicDir: str,
dbEngineArgs: Optional[Dict[str, Union[str, int]]] = None,
enableForeignKeys=False, enableCreateAll=True):
""" SQLAlchemy Database Connection
This class takes care of ... |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.checkForeignKeys | python | def checkForeignKeys(self, engine: Engine) -> None:
missing = (sqlalchemy_utils.functions
.non_indexed_foreign_keys(self._metadata, engine=engine))
for table, keys in missing.items():
for key in keys:
logger.warning("Missing index on ForeignKey %s" % key.c... | Check Foreign Keys
Log any foreign keys that don't have indexes assigned to them.
This is a performance issue. | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L137-L149 | null | class DbConnection:
def __init__(self, dbConnectString: str, metadata: MetaData, alembicDir: str,
dbEngineArgs: Optional[Dict[str, Union[str, int]]] = None,
enableForeignKeys=False, enableCreateAll=True):
""" SQLAlchemy Database Connection
This class takes care of ... |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.prefetchDeclarativeIds | python | def prefetchDeclarativeIds(self, Declarative, count) -> DelcarativeIdGen:
return _commonPrefetchDeclarativeIds(
self.dbEngine, self._sequenceMutex, Declarative, count
) | Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, especially those using inheritance
* When we need the ID to assign it to a rel... | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L152-L171 | [
"def _commonPrefetchDeclarativeIds(engine, mutex,\n Declarative, count) -> Optional[Iterable[int]]:\n \"\"\" Common Prefetch Declarative IDs\n\n This function is used by the worker and server\n \"\"\"\n if not count:\n logger.debug(\"Count was zero, no range retur... | class DbConnection:
def __init__(self, dbConnectString: str, metadata: MetaData, alembicDir: str,
dbEngineArgs: Optional[Dict[str, Union[str, int]]] = None,
enableForeignKeys=False, enableCreateAll=True):
""" SQLAlchemy Database Connection
This class takes care of ... |
Synerty/peek-plugin-base | peek_plugin_base/storage/StorageUtil.py | makeOrmValuesSubqueryCondition | python | def makeOrmValuesSubqueryCondition(ormSession, column, values: List[Union[int, str]]):
if isPostGreSQLDialect(ormSession.bind):
return column.in_(values)
if not isMssqlDialect(ormSession.bind):
raise NotImplementedError()
sql = _createMssqlSqlText(values)
sub_qry = ormSession.query(co... | Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/StorageUtil.py#L25-L43 | [
"def isMssqlDialect(engine):\n return isinstance(engine.dialect, MSDialect)\n",
"def isPostGreSQLDialect(engine):\n return isinstance(engine.dialect, PGDialect)\n"
] | from typing import List, Union
from sqlalchemy import text
from peek_plugin_base.storage.AlembicEnvBase import isMssqlDialect, isPostGreSQLDialect
def _createMssqlSqlText(values: List[Union[int, str]]) -> str:
if not values:
name = "peekCsvVarcharToTable" # Either will do
elif isinstance(values[0]... |
Synerty/peek-plugin-base | peek_plugin_base/storage/StorageUtil.py | makeCoreValuesSubqueryCondition | python | def makeCoreValuesSubqueryCondition(engine, column, values: List[Union[int, str]]):
if isPostGreSQLDialect(engine):
return column.in_(values)
if not isMssqlDialect(engine):
raise NotImplementedError()
sql = _createMssqlSqlText(values)
return column.in_(sql) | Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/StorageUtil.py#L46-L62 | [
"def isMssqlDialect(engine):\n return isinstance(engine.dialect, MSDialect)\n",
"def isPostGreSQLDialect(engine):\n return isinstance(engine.dialect, PGDialect)\n"
] | from typing import List, Union
from sqlalchemy import text
from peek_plugin_base.storage.AlembicEnvBase import isMssqlDialect, isPostGreSQLDialect
def _createMssqlSqlText(values: List[Union[int, str]]) -> str:
if not values:
name = "peekCsvVarcharToTable" # Either will do
elif isinstance(values[0]... |
scivision/gridaurora | gridaurora/__init__.py | to_ut1unix | python | def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray:
# keep this order
time = totime(time)
if isinstance(time, (float, int)):
return time
if isinstance(time, (tuple, list, np.ndarray)):
assert isinstance(time[0], datetime), f'expected datetime, not {type(time[0]... | converts time inputs to UT1 seconds since Unix epoch | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/__init__.py#L28-L43 | [
"def totime(time: Union[str, datetime, np.datetime64]) -> np.ndarray:\n time = np.atleast_1d(time)\n\n if isinstance(time[0], (datetime, np.datetime64)):\n pass\n elif isinstance(time[0], str):\n time = np.atleast_1d(list(map(parse, time)))\n\n return time.squeeze()[()]\n"
] | from datetime import datetime, date
from dateutil.parser import parse
import numpy as np
import logging
from typing import Union
def toyearmon(time: datetime) -> int:
# %% date handle
if isinstance(time, (tuple, list, np.ndarray)):
logging.warning(f'taking only first time {time[0]}, would you like mul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.