text stringlengths 18 773k |
|---|
def describe_key_pairs():
"""
Returns all key pairs for region
"""
region_keys = {}
for r in boto3.client('ec2', 'us-west-2').describe_regions()['Regions']:
region = r['RegionName']
client = boto3.client('ec2', region_name=region)
try:
pairs = client.describe_key_... |
def init_app(module, BASE_DIR, **kwargs):
"""
Initalize an app, call this method once from start_app
"""
global app
def init_config():
"""
Load settings module and attach values to the application
config dictionary
"""
if 'FLASK_PHILO_SETTINGS_MODULE' not in ... |
def execute_command(cmd, **kwargs):
"""
execute a console command
"""
cmd_dict = {
c: 'flask_philo.commands_flask_philo.' + c for c
in dir(commands_flask_philo) if not c.startswith('_') and c != 'os' # noqa
}
# loading specific app commands
try:
import console_c... |
def syncdb():
"""
Create tables if they don't exist
"""
from flask_philo.db.postgresql.schema import Base
from flask_philo.db.postgresql.orm import BaseModel # noqa
from flask_philo.db.postgresql.connection import get_pool
for conn_name, conn in get_pool().connections.items():
Base... |
def new(cls, password, rounds):
"""Creates a PasswordHash from the given password."""
if isinstance(password, str):
password = password.encode('utf8')
value = bcrypt.hashpw(password, bcrypt.gensalt(rounds))
return cls(value) |
def _convert(self, value):
"""Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError.
"""
if isinstance(value, P... |
def init_db_conn(
connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None):
"""
Initialize a redis connection by each connection string
defined in the configuration file
"""
rpool = redis.ConnectionPool(
host=HOST, port=PORT, db=DB, password=PASSWORD)
r = redis.Redis(connec... |
def initialize(g, app):
"""
If redis connection parameters are defined in configuration params a
session will be created
"""
if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:
# Initialize connections for console commands
for k, v in app.config['DATABASES']['REDIS... |
def _initialize_from_dict(self, data):
"""
Loads serializer from a request object
"""
self._json = data
self._validate()
for name, value in self._json.items():
if name in self._properties:
if '$ref' in self._properties[name]:
... |
def _initialize_from_model(self, model):
"""
Loads a model from
"""
for name, value in model.__dict__.items():
if name in self._properties:
setattr(self, name, value) |
def update(self):
"""
Finds record and update it based in serializer values
"""
obj = self.__model__.objects.get_for_update(id=self.id)
for name, value in self.__dict__.items():
if name in self._properties:
setattr(obj, name, value)
obj.update(... |
def to_json(self):
"""
Returns a json representation
"""
data = {}
for k, v in self.__dict__.items():
if not k.startswith('_'):
# values not serializable, should be converted to strings
if isinstance(v, datetime):
v ... |
def OPERATING_SYSTEM(stats, info):
"""General information about the operating system.
This is a flag you can pass to `Stats.submit()`.
"""
info.append(('architecture', platform.machine().lower()))
info.append(('distribution',
"%s;%s" % (platform.linux_distribution()[0:2])))
inf... |
def SESSION_TIME(stats, info):
"""Total time of this session.
Reports the time elapsed from the construction of the `Stats` object to
this `submit()` call.
This is a flag you can pass to `Stats.submit()`.
"""
duration = time.time() - stats.started_time
secs = int(duration)
msecs = int(... |
def PYTHON_VERSION(stats, info):
"""Python interpreter version.
This is a flag you can pass to `Stats.submit()`.
"""
# Some versions of Python have a \n in sys.version!
version = sys.version.replace(' \n', ' ').replace('\n', ' ')
python = ';'.join([str(c) for c in sys.version_info] + [version])... |
def read_config(self):
"""Reads the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is read
from the reports' directory.
This should set `self.status` to one of the state constants... |
def write_config(self, enabled):
"""Writes the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is written
in the reports' directory, containing either ``ENABLED`` or
``DISABLED``; i... |
def enable_reporting(self):
"""Call this method to explicitly enable reporting.
The current report will be uploaded, plus the previously recorded ones,
and the configuration will be updated so that future runs also upload
automatically.
"""
if self.status == Stats.ENABLE... |
def disable_reporting(self):
"""Call this method to explicitly disable reporting.
The current report will be discarded, along with the previously
recorded ones that haven't been uploaded. The configuration is updated
so that future runs do not record or upload reports.
"""
... |
def note(self, info):
"""Record some info to the report.
:param info: Dictionary of info to record. Note that previous info
recorded under the same keys will not be overwritten.
"""
if self.recording:
if self.notes is None:
raise ValueError("This repo... |
def submit(self, info, *flags):
"""Finish recording and upload or save the report.
This closes the `Stats` object, no further methods should be called.
The report is either saved, uploaded or discarded, depending on
configuration. If uploading is enabled, previous reports might be
... |
def store(report, address):
"""Stores the report on disk.
"""
now = time.time()
secs = int(now)
msecs = int((now - secs) * 1000)
submitted_date = filename = None # avoids warnings
while True:
submitted_date = '%d.%03d' % (secs, msecs)
filename = 'report_%s.txt' % submitted_d... |
def application(environ, start_response):
"""WSGI interface.
"""
def send_response(status, body):
if not isinstance(body, bytes):
body = body.encode('utf-8')
start_response(status, [('Content-Type', 'text/plain'),
('Content-Length', '%d' % len(bo... |
def read(self, pin):
""" Read the pin state of an input pin.
Make sure you put the pin in input modus with the IODIR* register or direction_* attribute first.
:Example:
>>> expander = MCP23017I2C(gw)
>>> # Read the logic level on pin B3
>>> expander.read('B3')
F... |
def read_port(self, port):
""" Read the pin state of a whole port (8 pins)
:Example:
>>> expander = MCP23017I2C(gw)
>>> # Read pin A0-A7 as a int (A0 and A1 are high)
>>> expander.read_port('A')
3
>>> # Read pin B0-B7 as a int (B2 is high)
>>> expander.r... |
def write(self, pin, value):
""" Set the pin state.
Make sure you put the pin in output mode first.
:param pin: The label for the pin to write to. (Ex. A0)
:param value: Boolean representing the new state
"""
port, pin = self.pin_to_port(pin)
portname = 'A'
... |
def write_port(self, port, value):
""" Use a whole port as a bus and write a byte to it.
:param port: Name of the port ('A' or 'B')
:param value: Value to write (0-255)
"""
if port == 'A':
self.GPIOA = value
elif port == 'B':
self.GPIOB = value
... |
def sync(self):
""" Upload the changed registers to the chip
This will check which register have been changed since the last sync and send them to the chip.
You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or
if you use one of the h... |
def get_pins(self):
""" Get a list containing references to all 16 pins of the chip.
:Example:
>>> expander = MCP23017I2C(gw)
>>> pins = expander.get_pins()
>>> pprint.pprint(pins)
[<GPIOPin A0 on MCP23017I2C>,
<GPIOPin A1 on MCP23017I2C>,
<GPIOPin A2 ... |
def read(self):
""" Get the logic input level for the pin
:return: True if the input is high
"""
m = getattr(self.chip, self.method)
return m(**self.arguments) |
def write(self, value):
""" Set the logic output level for the pin.
:type value: bool
:param value: True for a logic high
"""
if self.inverted:
value = not value
m = getattr(self.chip, self.method)
m(value=value, **self.arguments) |
def init_app(self, app, **kwargs):
"""Initialize application object.
:param app: An instance of :class:`~flask.Flask`.
"""
self.init_config(app)
# Initialize extensions
self.menu_ext.init_app(app)
self.menu = app.extensions['menu']
self.breadcrumbs.init_... |
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
_vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE']
# Sets RequireJS config and SASS binary as well if not already set.
for k in dir(config):
... |
def set_range(self, accel=1, gyro=1):
"""Set the measurement range for the accel and gyro MEMS. Higher range means less resolution.
:param accel: a RANGE_ACCEL_* constant
:param gyro: a RANGE_GYRO_* constant
:Example:
.. code-block:: python
sensor = MPU6050I2C(gat... |
def set_slave_bus_bypass(self, enable):
"""Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly
Dont forget to use wakeup() or else the slave bus is unavailable
:param enable:
:return:
"""
current = self.i2c_read_register(0x... |
def temperature(self):
"""Read the value for the internal temperature sensor.
:returns: Temperature in degree celcius as float
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.temperature()
49.38
"""
if not self.awake:
... |
def acceleration(self):
"""Return the acceleration in G's
:returns: Acceleration for every axis as a tuple
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.acceleration()
(0.6279296875, 0.87890625, 1.1298828125)
"""
if not se... |
def angular_rate(self):
"""Return the angular rate for every axis in degree/second.
:returns: Angular rate for every axis as a tuple
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.angular_rate()
(1.380859375, 1.6318359375, 1.8828125)
... |
def _get_contents(self):
"""Create strings from lazy strings."""
return [
str(value) if is_lazy_string(value) else value
for value in super(LazyNpmBundle, self)._get_contents()
] |
def load_calibration(self):
"""Load factory calibration data from device."""
registers = self.i2c_read_register(0xAA, 22)
(
self.cal['AC1'],
self.cal['AC2'],
self.cal['AC3'],
self.cal['AC4'],
self.cal['AC5'],
self.cal['AC6']... |
def temperature(self):
"""Get the temperature from the sensor.
:returns: The temperature in degree celcius as a float
:example:
>>> sensor = BMP180(gw)
>>> sensor.load_calibration()
>>> sensor.temperature()
21.4
"""
ut = self.get_raw_temp()
... |
def pressure(self):
"""
Get barometric pressure in milibar
:returns: The pressure in milibar as a int
:example:
>>> sensor = BMP180(gw)
>>> sensor.load_calibration()
>>> sensor.pressure()
75216
"""
ut = self.get_raw_temp()
up = ... |
def switch_mode(self, new_mode):
""" Explicitly switch the Bus Pirate mode
:param new_mode: The mode to switch to. Use the buspirate.MODE_* constants
"""
packet = bytearray()
packet.append(new_mode)
self.device.write(packet)
possible_responses = {
sel... |
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None):
""" Set the peripheral config at runtime.
If a parameter is None then the config will not be changed.
:param power: Set to True to enable the power supply or False to disable
:param pullup: Set to True to ena... |
def _set_i2c_speed(self, i2c_speed):
""" Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz'
"""
lower_bits_mapping = {
'400kHz': 3,
'100kHz': 2,
'50kHz': 1,
'5kHz': 0,
}
if i2c_speed not in lower_bits_mapping:
ra... |
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL):
"""
Set the base config for sensor
:param averaging: Sets the numer of samples that are internally averaged
:param datarate: Datarate in hertz
:param mode: one of the MODE_* constants
"""
averaging_con... |
def set_resolution(self, resolution=1090):
"""
Set the resolution of the sensor
The resolution value is the amount of steps recorded in a single Gauss. The possible options are:
======================= ========== =============
Recommended Gauss range Resolution Gauss per bi... |
def gauss(self):
"""
Get the magnetometer values as gauss for each axis as a tuple (x,y,z)
:example:
>>> sensor = HMC5883L(gw)
>>> sensor.gauss()
(16.56, 21.2888, 26.017599999999998)
"""
raw = self.raw()
factors = {
1370: 0.73,
... |
def temperature(self):
""" Get the temperature in degree celcius
"""
result = self.i2c_read(2)
value = struct.unpack('>H', result)[0]
if value < 32768:
return value / 256.0
else:
return (value - 65536) / 256.0 |
def write(self, char):
""" Display a single character on the display
:type char: str or int
:param char: Character to display
"""
char = str(char).lower()
self.segments.write(self.font[char]) |
def get_html_theme_path():
"""
Get the absolute path of the directory containing the theme files.
"""
return os.path.abspath(os.path.dirname(os.path.dirname(__file__))) |
def feedback_form_url(project, page):
"""
Create a URL for feedback on a particular page in a project.
"""
return FEEDBACK_FORM_FMT.format(pageid=quote("{}: {}".format(project, page))) |
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument
"""
Update the page rendering context to include ``feedback_form_url``.
"""
context['feedback_form_url'] = feedback_form_url(app.config.project, pagename) |
def setup(app):
"""
Sphinx extension to update the rendering context with the feedback form URL.
Arguments:
app (Sphinx): Application object for the Sphinx process
Returns:
a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata)
"""
event = 'ht... |
def objectsFromPEM(pemdata):
"""
Load some objects from a PEM.
"""
certificates = []
keys = []
blobs = [b""]
for line in pemdata.split(b"\n"):
if line.startswith(b'-----BEGIN'):
if b'CERTIFICATE' in line:
blobs = certificates
else:
... |
def following_key(key):
"""
Returns the key immediately following the input key - based on the Java implementation found in
org.apache.accumulo.core.data.Key, function followingKey(PartialKey part)
:param key: the key to be followed
:return: a key that immediately follows the input key
"""
i... |
def followingPrefix(prefix):
"""Returns a String that sorts just after all Strings beginning with a prefix"""
prefixBytes = array('B', prefix)
changeIndex = len(prefixBytes) - 1
while (changeIndex >= 0 and prefixBytes[changeIndex] == 0xff ):
changeIndex = changeIndex - 1;
... |
def prefix(rowPrefix):
"""Returns a Range that covers all rows beginning with a prefix"""
fp = Range.followingPrefix(rowPrefix)
return Range(srow=rowPrefix, sinclude=True, erow=fp, einclude=False) |
def add_mutations_and_flush(self, table, muts):
"""
Add mutations to a table without the need to create and manage a batch writer.
"""
if not isinstance(muts, list) and not isinstance(muts, tuple):
muts = [muts]
cells = {}
for mut in muts:
cells.se... |
def remove_constraint(self, table, constraint):
"""
:param table: table name
:param constraint: the constraint number as returned by list_constraints
"""
self.client.removeConstraint(self.login, table, constraint) |
def get_context(self):
"""
A basic override of get_context to ensure that the appropriate proxy
object is returned.
"""
ctx = self._obj.get_context()
return _ContextProxy(ctx, self._factory) |
def login(self, principal, loginProperties):
"""
Parameters:
- principal
- loginProperties
"""
self.send_login(principal, loginProperties)
return self.recv_login() |
def addConstraint(self, login, tableName, constraintClassName):
"""
Parameters:
- login
- tableName
- constraintClassName
"""
self.send_addConstraint(login, tableName, constraintClassName)
return self.recv_addConstraint() |
def addSplits(self, login, tableName, splits):
"""
Parameters:
- login
- tableName
- splits
"""
self.send_addSplits(login, tableName, splits)
self.recv_addSplits() |
def attachIterator(self, login, tableName, setting, scopes):
"""
Parameters:
- login
- tableName
- setting
- scopes
"""
self.send_attachIterator(login, tableName, setting, scopes)
self.recv_attachIterator() |
def checkIteratorConflicts(self, login, tableName, setting, scopes):
"""
Parameters:
- login
- tableName
- setting
- scopes
"""
self.send_checkIteratorConflicts(login, tableName, setting, scopes)
self.recv_checkIteratorConflicts() |
def clearLocatorCache(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_clearLocatorCache(login, tableName)
self.recv_clearLocatorCache() |
def cloneTable(self, login, tableName, newTableName, flush, propertiesToSet, propertiesToExclude):
"""
Parameters:
- login
- tableName
- newTableName
- flush
- propertiesToSet
- propertiesToExclude
"""
self.send_cloneTable(login, tableName, newTableName, flush, propertiesTo... |
def compactTable(self, login, tableName, startRow, endRow, iterators, flush, wait):
"""
Parameters:
- login
- tableName
- startRow
- endRow
- iterators
- flush
- wait
"""
self.send_compactTable(login, tableName, startRow, endRow, iterators, flush, wait)
self.recv_c... |
def cancelCompaction(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_cancelCompaction(login, tableName)
self.recv_cancelCompaction() |
def createTable(self, login, tableName, versioningIter, type):
"""
Parameters:
- login
- tableName
- versioningIter
- type
"""
self.send_createTable(login, tableName, versioningIter, type)
self.recv_createTable() |
def deleteTable(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_deleteTable(login, tableName)
self.recv_deleteTable() |
def deleteRows(self, login, tableName, startRow, endRow):
"""
Parameters:
- login
- tableName
- startRow
- endRow
"""
self.send_deleteRows(login, tableName, startRow, endRow)
self.recv_deleteRows() |
def exportTable(self, login, tableName, exportDir):
"""
Parameters:
- login
- tableName
- exportDir
"""
self.send_exportTable(login, tableName, exportDir)
self.recv_exportTable() |
def flushTable(self, login, tableName, startRow, endRow, wait):
"""
Parameters:
- login
- tableName
- startRow
- endRow
- wait
"""
self.send_flushTable(login, tableName, startRow, endRow, wait)
self.recv_flushTable() |
def getLocalityGroups(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_getLocalityGroups(login, tableName)
return self.recv_getLocalityGroups() |
def getIteratorSetting(self, login, tableName, iteratorName, scope):
"""
Parameters:
- login
- tableName
- iteratorName
- scope
"""
self.send_getIteratorSetting(login, tableName, iteratorName, scope)
return self.recv_getIteratorSetting() |
def getMaxRow(self, login, tableName, auths, startRow, startInclusive, endRow, endInclusive):
"""
Parameters:
- login
- tableName
- auths
- startRow
- startInclusive
- endRow
- endInclusive
"""
self.send_getMaxRow(login, tableName, auths, startRow, startInclusive, endR... |
def getTableProperties(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_getTableProperties(login, tableName)
return self.recv_getTableProperties() |
def getSplits(self, login, tableName, maxSplits):
"""
Parameters:
- login
- tableName
- maxSplits
"""
self.send_getSplits(login, tableName, maxSplits)
return self.recv_getSplits() |
def importDirectory(self, login, tableName, importDir, failureDir, setTime):
"""
Parameters:
- login
- tableName
- importDir
- failureDir
- setTime
"""
self.send_importDirectory(login, tableName, importDir, failureDir, setTime)
self.recv_importDirectory() |
def importTable(self, login, tableName, importDir):
"""
Parameters:
- login
- tableName
- importDir
"""
self.send_importTable(login, tableName, importDir)
self.recv_importTable() |
def listIterators(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_listIterators(login, tableName)
return self.recv_listIterators() |
def listConstraints(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_listConstraints(login, tableName)
return self.recv_listConstraints() |
def mergeTablets(self, login, tableName, startRow, endRow):
"""
Parameters:
- login
- tableName
- startRow
- endRow
"""
self.send_mergeTablets(login, tableName, startRow, endRow)
self.recv_mergeTablets() |
def offlineTable(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_offlineTable(login, tableName)
self.recv_offlineTable() |
def onlineTable(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_onlineTable(login, tableName)
self.recv_onlineTable() |
def removeConstraint(self, login, tableName, constraint):
"""
Parameters:
- login
- tableName
- constraint
"""
self.send_removeConstraint(login, tableName, constraint)
self.recv_removeConstraint() |
def removeIterator(self, login, tableName, iterName, scopes):
"""
Parameters:
- login
- tableName
- iterName
- scopes
"""
self.send_removeIterator(login, tableName, iterName, scopes)
self.recv_removeIterator() |
def removeTableProperty(self, login, tableName, property):
"""
Parameters:
- login
- tableName
- property
"""
self.send_removeTableProperty(login, tableName, property)
self.recv_removeTableProperty() |
def renameTable(self, login, oldTableName, newTableName):
"""
Parameters:
- login
- oldTableName
- newTableName
"""
self.send_renameTable(login, oldTableName, newTableName)
self.recv_renameTable() |
def setLocalityGroups(self, login, tableName, groups):
"""
Parameters:
- login
- tableName
- groups
"""
self.send_setLocalityGroups(login, tableName, groups)
self.recv_setLocalityGroups() |
def setTableProperty(self, login, tableName, property, value):
"""
Parameters:
- login
- tableName
- property
- value
"""
self.send_setTableProperty(login, tableName, property, value)
self.recv_setTableProperty() |
def splitRangeByTablets(self, login, tableName, range, maxSplits):
"""
Parameters:
- login
- tableName
- range
- maxSplits
"""
self.send_splitRangeByTablets(login, tableName, range, maxSplits)
return self.recv_splitRangeByTablets() |
def tableExists(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_tableExists(login, tableName)
return self.recv_tableExists() |
def pingTabletServer(self, login, tserver):
"""
Parameters:
- login
- tserver
"""
self.send_pingTabletServer(login, tserver)
self.recv_pingTabletServer() |
def getActiveScans(self, login, tserver):
"""
Parameters:
- login
- tserver
"""
self.send_getActiveScans(login, tserver)
return self.recv_getActiveScans() |
def getActiveCompactions(self, login, tserver):
"""
Parameters:
- login
- tserver
"""
self.send_getActiveCompactions(login, tserver)
return self.recv_getActiveCompactions() |
def removeProperty(self, login, property):
"""
Parameters:
- login
- property
"""
self.send_removeProperty(login, property)
self.recv_removeProperty() |
def setProperty(self, login, property, value):
"""
Parameters:
- login
- property
- value
"""
self.send_setProperty(login, property, value)
self.recv_setProperty() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.