repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
remram44/usagestats
usagestats.py
Stats.note
def note(self, info): """Record some info to the report. :param info: Dictionary of info to record. Note that previous info recorded under the same keys will not be overwritten. """ if self.recording: if self.notes is None: raise ValueError("This report has already been submitted") self.notes.extend(self._to_notes(info))
python
def note(self, info): """Record some info to the report. :param info: Dictionary of info to record. Note that previous info recorded under the same keys will not be overwritten. """ if self.recording: if self.notes is None: raise ValueError("This report has already been submitted") self.notes.extend(self._to_notes(info))
[ "def", "note", "(", "self", ",", "info", ")", ":", "if", "self", ".", "recording", ":", "if", "self", ".", "notes", "is", "None", ":", "raise", "ValueError", "(", "\"This report has already been submitted\"", ")", "self", ".", "notes", ".", "extend", "(", ...
Record some info to the report. :param info: Dictionary of info to record. Note that previous info recorded under the same keys will not be overwritten.
[ "Record", "some", "info", "to", "the", "report", "." ]
6ffd1a51d81d1b4570916c1594aee6a98089fa71
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L282-L291
train
44,800
remram44/usagestats
wsgi/usagestats_server.py
store
def store(report, address): """Stores the report on disk. """ now = time.time() secs = int(now) msecs = int((now - secs) * 1000) submitted_date = filename = None # avoids warnings while True: submitted_date = '%d.%03d' % (secs, msecs) filename = 'report_%s.txt' % submitted_date filename = os.path.join(DESTINATION, filename) if not os.path.exists(filename): break msecs += 1 lines = [l for l in report.split(b'\n') if l] for line in lines: if line.startswith(b'date:'): date = line[5:] if date_format.match(date): with open(filename, 'wb') as fp: if not isinstance(address, bytes): address = address.encode('ascii') fp.write(b'submitted_from:' + address + b'\n') fp.write(('submitted_date:%s\n' % submitted_date) .encode('ascii')) fp.write(report) return None else: return "invalid date" return "missing date field"
python
def store(report, address): """Stores the report on disk. """ now = time.time() secs = int(now) msecs = int((now - secs) * 1000) submitted_date = filename = None # avoids warnings while True: submitted_date = '%d.%03d' % (secs, msecs) filename = 'report_%s.txt' % submitted_date filename = os.path.join(DESTINATION, filename) if not os.path.exists(filename): break msecs += 1 lines = [l for l in report.split(b'\n') if l] for line in lines: if line.startswith(b'date:'): date = line[5:] if date_format.match(date): with open(filename, 'wb') as fp: if not isinstance(address, bytes): address = address.encode('ascii') fp.write(b'submitted_from:' + address + b'\n') fp.write(('submitted_date:%s\n' % submitted_date) .encode('ascii')) fp.write(report) return None else: return "invalid date" return "missing date field"
[ "def", "store", "(", "report", ",", "address", ")", ":", "now", "=", "time", ".", "time", "(", ")", "secs", "=", "int", "(", "now", ")", "msecs", "=", "int", "(", "(", "now", "-", "secs", ")", "*", "1000", ")", "submitted_date", "=", "filename", ...
Stores the report on disk.
[ "Stores", "the", "report", "on", "disk", "." ]
6ffd1a51d81d1b4570916c1594aee6a98089fa71
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/wsgi/usagestats_server.py#L17-L47
train
44,801
remram44/usagestats
wsgi/usagestats_server.py
application
def application(environ, start_response): """WSGI interface. """ def send_response(status, body): if not isinstance(body, bytes): body = body.encode('utf-8') start_response(status, [('Content-Type', 'text/plain'), ('Content-Length', '%d' % len(body))]) return [body] if environ['REQUEST_METHOD'] != 'POST': return send_response('403 Forbidden', "invalid request") # Gets the posted input try: request_body_size = int(environ['CONTENT_LENGTH']) except (KeyError, ValueError): return send_response('400 Bad Request', "invalid content length") if request_body_size > MAX_SIZE: return send_response('403 Forbidden', "report too big") request_body = environ['wsgi.input'].read(request_body_size) # Tries to store response_body = store(request_body, environ.get('REMOTE_ADDR')) if not response_body: status = '200 OK' response_body = "stored" else: status = '501 Server Error' # Sends the response return send_response(status, response_body)
python
def application(environ, start_response): """WSGI interface. """ def send_response(status, body): if not isinstance(body, bytes): body = body.encode('utf-8') start_response(status, [('Content-Type', 'text/plain'), ('Content-Length', '%d' % len(body))]) return [body] if environ['REQUEST_METHOD'] != 'POST': return send_response('403 Forbidden', "invalid request") # Gets the posted input try: request_body_size = int(environ['CONTENT_LENGTH']) except (KeyError, ValueError): return send_response('400 Bad Request', "invalid content length") if request_body_size > MAX_SIZE: return send_response('403 Forbidden', "report too big") request_body = environ['wsgi.input'].read(request_body_size) # Tries to store response_body = store(request_body, environ.get('REMOTE_ADDR')) if not response_body: status = '200 OK' response_body = "stored" else: status = '501 Server Error' # Sends the response return send_response(status, response_body)
[ "def", "application", "(", "environ", ",", "start_response", ")", ":", "def", "send_response", "(", "status", ",", "body", ")", ":", "if", "not", "isinstance", "(", "body", ",", "bytes", ")", ":", "body", "=", "body", ".", "encode", "(", "'utf-8'", ")"...
WSGI interface.
[ "WSGI", "interface", "." ]
6ffd1a51d81d1b4570916c1594aee6a98089fa71
https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/wsgi/usagestats_server.py#L50-L83
train
44,802
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.write
def write(self, pin, value): """ Set the pin state. Make sure you put the pin in output mode first. :param pin: The label for the pin to write to. (Ex. A0) :param value: Boolean representing the new state """ port, pin = self.pin_to_port(pin) portname = 'A' if port == 1: portname = 'B' self._update_register('GPIO' + portname, pin, value) self.sync()
python
def write(self, pin, value): """ Set the pin state. Make sure you put the pin in output mode first. :param pin: The label for the pin to write to. (Ex. A0) :param value: Boolean representing the new state """ port, pin = self.pin_to_port(pin) portname = 'A' if port == 1: portname = 'B' self._update_register('GPIO' + portname, pin, value) self.sync()
[ "def", "write", "(", "self", ",", "pin", ",", "value", ")", ":", "port", ",", "pin", "=", "self", ".", "pin_to_port", "(", "pin", ")", "portname", "=", "'A'", "if", "port", "==", "1", ":", "portname", "=", "'B'", "self", ".", "_update_register", "(...
Set the pin state. Make sure you put the pin in output mode first. :param pin: The label for the pin to write to. (Ex. A0) :param value: Boolean representing the new state
[ "Set", "the", "pin", "state", ".", "Make", "sure", "you", "put", "the", "pin", "in", "output", "mode", "first", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L187-L199
train
44,803
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.write_port
def write_port(self, port, value): """ Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255) """ if port == 'A': self.GPIOA = value elif port == 'B': self.GPIOB = value else: raise AttributeError('Port {} does not exist, use A or B'.format(port)) self.sync()
python
def write_port(self, port, value): """ Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255) """ if port == 'A': self.GPIOA = value elif port == 'B': self.GPIOB = value else: raise AttributeError('Port {} does not exist, use A or B'.format(port)) self.sync()
[ "def", "write_port", "(", "self", ",", "port", ",", "value", ")", ":", "if", "port", "==", "'A'", ":", "self", ".", "GPIOA", "=", "value", "elif", "port", "==", "'B'", ":", "self", ".", "GPIOB", "=", "value", "else", ":", "raise", "AttributeError", ...
Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255)
[ "Use", "a", "whole", "port", "as", "a", "bus", "and", "write", "a", "byte", "to", "it", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L201-L213
train
44,804
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.sync
def sync(self): """ Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the helper attributes (mcp23017.direction_A0 for example) """ registers = { 0x00: 'IODIRA', 0x01: 'IODIRB', 0x02: 'IPOLA', 0x03: 'IPOLB', 0x04: 'GPINTENA', 0x05: 'GPINTENB', 0x0C: 'GPPUA', 0x0D: 'GPPUB', 0x12: 'GPIOA', 0x13: 'GPIOB' } for reg in registers: name = registers[reg] if getattr(self, name) != getattr(self, '_' + name): self.i2c_write_register(reg, [getattr(self, name)]) setattr(self, '_' + name, getattr(self, name))
python
def sync(self): """ Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the helper attributes (mcp23017.direction_A0 for example) """ registers = { 0x00: 'IODIRA', 0x01: 'IODIRB', 0x02: 'IPOLA', 0x03: 'IPOLB', 0x04: 'GPINTENA', 0x05: 'GPINTENB', 0x0C: 'GPPUA', 0x0D: 'GPPUB', 0x12: 'GPIOA', 0x13: 'GPIOB' } for reg in registers: name = registers[reg] if getattr(self, name) != getattr(self, '_' + name): self.i2c_write_register(reg, [getattr(self, name)]) setattr(self, '_' + name, getattr(self, name))
[ "def", "sync", "(", "self", ")", ":", "registers", "=", "{", "0x00", ":", "'IODIRA'", ",", "0x01", ":", "'IODIRB'", ",", "0x02", ":", "'IPOLA'", ",", "0x03", ":", "'IPOLB'", ",", "0x04", ":", "'GPINTENA'", ",", "0x05", ":", "'GPINTENB'", ",", "0x0C",...
Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the helper attributes (mcp23017.direction_A0 for example)
[ "Upload", "the", "changed", "registers", "to", "the", "chip" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L215-L238
train
44,805
MartijnBraam/pyElectronics
electronics/devices/mcp23017.py
MCP23017I2C.get_pins
def get_pins(self): """ Get a list containing references to all 16 pins of the chip. :Example: >>> expander = MCP23017I2C(gw) >>> pins = expander.get_pins() >>> pprint.pprint(pins) [<GPIOPin A0 on MCP23017I2C>, <GPIOPin A1 on MCP23017I2C>, <GPIOPin A2 on MCP23017I2C>, <GPIOPin A3 on MCP23017I2C>, <GPIOPin A4 on MCP23017I2C>, <GPIOPin A5 on MCP23017I2C>, <GPIOPin A6 on MCP23017I2C>, <GPIOPin B0 on MCP23017I2C>, <GPIOPin B1 on MCP23017I2C>, <GPIOPin B2 on MCP23017I2C>, <GPIOPin B3 on MCP23017I2C>, <GPIOPin B4 on MCP23017I2C>, <GPIOPin B5 on MCP23017I2C>, <GPIOPin B6 on MCP23017I2C>] """ result = [] for a in range(0, 7): result.append(GPIOPin(self, '_action', {'pin': 'A{}'.format(a)}, name='A{}'.format(a))) for b in range(0, 7): result.append(GPIOPin(self, '_action', {'pin': 'B{}'.format(b)}, name='B{}'.format(b))) return result
python
def get_pins(self): """ Get a list containing references to all 16 pins of the chip. :Example: >>> expander = MCP23017I2C(gw) >>> pins = expander.get_pins() >>> pprint.pprint(pins) [<GPIOPin A0 on MCP23017I2C>, <GPIOPin A1 on MCP23017I2C>, <GPIOPin A2 on MCP23017I2C>, <GPIOPin A3 on MCP23017I2C>, <GPIOPin A4 on MCP23017I2C>, <GPIOPin A5 on MCP23017I2C>, <GPIOPin A6 on MCP23017I2C>, <GPIOPin B0 on MCP23017I2C>, <GPIOPin B1 on MCP23017I2C>, <GPIOPin B2 on MCP23017I2C>, <GPIOPin B3 on MCP23017I2C>, <GPIOPin B4 on MCP23017I2C>, <GPIOPin B5 on MCP23017I2C>, <GPIOPin B6 on MCP23017I2C>] """ result = [] for a in range(0, 7): result.append(GPIOPin(self, '_action', {'pin': 'A{}'.format(a)}, name='A{}'.format(a))) for b in range(0, 7): result.append(GPIOPin(self, '_action', {'pin': 'B{}'.format(b)}, name='B{}'.format(b))) return result
[ "def", "get_pins", "(", "self", ")", ":", "result", "=", "[", "]", "for", "a", "in", "range", "(", "0", ",", "7", ")", ":", "result", ".", "append", "(", "GPIOPin", "(", "self", ",", "'_action'", ",", "{", "'pin'", ":", "'A{}'", ".", "format", ...
Get a list containing references to all 16 pins of the chip. :Example: >>> expander = MCP23017I2C(gw) >>> pins = expander.get_pins() >>> pprint.pprint(pins) [<GPIOPin A0 on MCP23017I2C>, <GPIOPin A1 on MCP23017I2C>, <GPIOPin A2 on MCP23017I2C>, <GPIOPin A3 on MCP23017I2C>, <GPIOPin A4 on MCP23017I2C>, <GPIOPin A5 on MCP23017I2C>, <GPIOPin A6 on MCP23017I2C>, <GPIOPin B0 on MCP23017I2C>, <GPIOPin B1 on MCP23017I2C>, <GPIOPin B2 on MCP23017I2C>, <GPIOPin B3 on MCP23017I2C>, <GPIOPin B4 on MCP23017I2C>, <GPIOPin B5 on MCP23017I2C>, <GPIOPin B6 on MCP23017I2C>]
[ "Get", "a", "list", "containing", "references", "to", "all", "16", "pins", "of", "the", "chip", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mcp23017.py#L260-L290
train
44,806
MartijnBraam/pyElectronics
electronics/pin.py
DigitalInputPin.read
def read(self): """ Get the logic input level for the pin :return: True if the input is high """ m = getattr(self.chip, self.method) return m(**self.arguments)
python
def read(self): """ Get the logic input level for the pin :return: True if the input is high """ m = getattr(self.chip, self.method) return m(**self.arguments)
[ "def", "read", "(", "self", ")", ":", "m", "=", "getattr", "(", "self", ".", "chip", ",", "self", ".", "method", ")", "return", "m", "(", "*", "*", "self", ".", "arguments", ")" ]
Get the logic input level for the pin :return: True if the input is high
[ "Get", "the", "logic", "input", "level", "for", "the", "pin" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/pin.py#L29-L35
train
44,807
MartijnBraam/pyElectronics
electronics/pin.py
GPIOPin.write
def write(self, value): """ Set the logic output level for the pin. :type value: bool :param value: True for a logic high """ if self.inverted: value = not value m = getattr(self.chip, self.method) m(value=value, **self.arguments)
python
def write(self, value): """ Set the logic output level for the pin. :type value: bool :param value: True for a logic high """ if self.inverted: value = not value m = getattr(self.chip, self.method) m(value=value, **self.arguments)
[ "def", "write", "(", "self", ",", "value", ")", ":", "if", "self", ".", "inverted", ":", "value", "=", "not", "value", "m", "=", "getattr", "(", "self", ".", "chip", ",", "self", ".", "method", ")", "m", "(", "value", "=", "value", ",", "*", "*...
Set the logic output level for the pin. :type value: bool :param value: True for a logic high
[ "Set", "the", "logic", "output", "level", "for", "the", "pin", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/pin.py#L72-L81
train
44,808
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.set_range
def set_range(self, accel=1, gyro=1): """Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range( accel=MPU6050I2C.RANGE_ACCEL_2G, gyro=MPU6050I2C.RANGE_GYRO_250DEG ) """ self.i2c_write_register(0x1c, accel) self.i2c_write_register(0x1b, gyro) self.accel_range = accel self.gyro_range = gyro
python
def set_range(self, accel=1, gyro=1): """Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range( accel=MPU6050I2C.RANGE_ACCEL_2G, gyro=MPU6050I2C.RANGE_GYRO_250DEG ) """ self.i2c_write_register(0x1c, accel) self.i2c_write_register(0x1b, gyro) self.accel_range = accel self.gyro_range = gyro
[ "def", "set_range", "(", "self", ",", "accel", "=", "1", ",", "gyro", "=", "1", ")", ":", "self", ".", "i2c_write_register", "(", "0x1c", ",", "accel", ")", "self", ".", "i2c_write_register", "(", "0x1b", ",", "gyro", ")", "self", ".", "accel_range", ...
Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range( accel=MPU6050I2C.RANGE_ACCEL_2G, gyro=MPU6050I2C.RANGE_GYRO_250DEG )
[ "Set", "the", "measurement", "range", "for", "the", "accel", "and", "gyro", "MEMS", ".", "Higher", "range", "means", "less", "resolution", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L55-L75
train
44,809
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.set_slave_bus_bypass
def set_slave_bus_bypass(self, enable): """Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly Dont forget to use wakeup() or else the slave bus is unavailable :param enable: :return: """ current = self.i2c_read_register(0x37, 1)[0] if enable: current |= 0b00000010 else: current &= 0b11111101 self.i2c_write_register(0x37, current)
python
def set_slave_bus_bypass(self, enable): """Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly Dont forget to use wakeup() or else the slave bus is unavailable :param enable: :return: """ current = self.i2c_read_register(0x37, 1)[0] if enable: current |= 0b00000010 else: current &= 0b11111101 self.i2c_write_register(0x37, current)
[ "def", "set_slave_bus_bypass", "(", "self", ",", "enable", ")", ":", "current", "=", "self", ".", "i2c_read_register", "(", "0x37", ",", "1", ")", "[", "0", "]", "if", "enable", ":", "current", "|=", "0b00000010", "else", ":", "current", "&=", "0b1111110...
Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly Dont forget to use wakeup() or else the slave bus is unavailable :param enable: :return:
[ "Put", "the", "aux", "i2c", "bus", "on", "the", "MPU", "-", "6050", "in", "bypass", "mode", "thus", "connecting", "it", "to", "the", "main", "i2c", "bus", "directly" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L77-L89
train
44,810
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.temperature
def temperature(self): """Read the value for the internal temperature sensor. :returns: Temperature in degree celcius as float :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.temperature() 49.38 """ if not self.awake: raise Exception("MPU6050 is in sleep mode, use wakeup()") raw = self.i2c_read_register(0x41, 2) raw = struct.unpack('>h', raw)[0] return round((raw / 340) + 36.53, 2)
python
def temperature(self): """Read the value for the internal temperature sensor. :returns: Temperature in degree celcius as float :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.temperature() 49.38 """ if not self.awake: raise Exception("MPU6050 is in sleep mode, use wakeup()") raw = self.i2c_read_register(0x41, 2) raw = struct.unpack('>h', raw)[0] return round((raw / 340) + 36.53, 2)
[ "def", "temperature", "(", "self", ")", ":", "if", "not", "self", ".", "awake", ":", "raise", "Exception", "(", "\"MPU6050 is in sleep mode, use wakeup()\"", ")", "raw", "=", "self", ".", "i2c_read_register", "(", "0x41", ",", "2", ")", "raw", "=", "struct",...
Read the value for the internal temperature sensor. :returns: Temperature in degree celcius as float :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.temperature() 49.38
[ "Read", "the", "value", "for", "the", "internal", "temperature", "sensor", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L101-L118
train
44,811
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
MPU6050I2C.acceleration
def acceleration(self): """Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125) """ if not self.awake: raise Exception("MPU6050 is in sleep mode, use wakeup()") raw = self.i2c_read_register(0x3B, 6) x, y, z = struct.unpack('>HHH', raw) scales = { self.RANGE_ACCEL_2G: 16384, self.RANGE_ACCEL_4G: 8192, self.RANGE_ACCEL_8G: 4096, self.RANGE_ACCEL_16G: 2048 } scale = scales[self.accel_range] return x / scale, y / scale, z / scale
python
def acceleration(self): """Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125) """ if not self.awake: raise Exception("MPU6050 is in sleep mode, use wakeup()") raw = self.i2c_read_register(0x3B, 6) x, y, z = struct.unpack('>HHH', raw) scales = { self.RANGE_ACCEL_2G: 16384, self.RANGE_ACCEL_4G: 8192, self.RANGE_ACCEL_8G: 4096, self.RANGE_ACCEL_16G: 2048 } scale = scales[self.accel_range] return x / scale, y / scale, z / scale
[ "def", "acceleration", "(", "self", ")", ":", "if", "not", "self", ".", "awake", ":", "raise", "Exception", "(", "\"MPU6050 is in sleep mode, use wakeup()\"", ")", "raw", "=", "self", ".", "i2c_read_register", "(", "0x3B", ",", "6", ")", "x", ",", "y", ","...
Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125)
[ "Return", "the", "acceleration", "in", "G", "s" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L120-L144
train
44,812
inveniosoftware/invenio-theme
invenio_theme/bundles.py
LazyNpmBundle._get_contents
def _get_contents(self): """Create strings from lazy strings.""" return [ str(value) if is_lazy_string(value) else value for value in super(LazyNpmBundle, self)._get_contents() ]
python
def _get_contents(self): """Create strings from lazy strings.""" return [ str(value) if is_lazy_string(value) else value for value in super(LazyNpmBundle, self)._get_contents() ]
[ "def", "_get_contents", "(", "self", ")", ":", "return", "[", "str", "(", "value", ")", "if", "is_lazy_string", "(", "value", ")", "else", "value", "for", "value", "in", "super", "(", "LazyNpmBundle", ",", "self", ")", ".", "_get_contents", "(", ")", "...
Create strings from lazy strings.
[ "Create", "strings", "from", "lazy", "strings", "." ]
4e07607b1a40805df1d8e4ab9cc2afd728579ca9
https://github.com/inveniosoftware/invenio-theme/blob/4e07607b1a40805df1d8e4ab9cc2afd728579ca9/invenio_theme/bundles.py#L33-L38
train
44,813
MartijnBraam/pyElectronics
electronics/devices/bmp180.py
BMP180.load_calibration
def load_calibration(self): """Load factory calibration data from device.""" registers = self.i2c_read_register(0xAA, 22) ( self.cal['AC1'], self.cal['AC2'], self.cal['AC3'], self.cal['AC4'], self.cal['AC5'], self.cal['AC6'], self.cal['B1'], self.cal['B2'], self.cal['MB'], self.cal['MC'], self.cal['MD'] ) = struct.unpack('>hhhHHHhhhhh', registers)
python
def load_calibration(self): """Load factory calibration data from device.""" registers = self.i2c_read_register(0xAA, 22) ( self.cal['AC1'], self.cal['AC2'], self.cal['AC3'], self.cal['AC4'], self.cal['AC5'], self.cal['AC6'], self.cal['B1'], self.cal['B2'], self.cal['MB'], self.cal['MC'], self.cal['MD'] ) = struct.unpack('>hhhHHHhhhhh', registers)
[ "def", "load_calibration", "(", "self", ")", ":", "registers", "=", "self", ".", "i2c_read_register", "(", "0xAA", ",", "22", ")", "(", "self", ".", "cal", "[", "'AC1'", "]", ",", "self", ".", "cal", "[", "'AC2'", "]", ",", "self", ".", "cal", "[",...
Load factory calibration data from device.
[ "Load", "factory", "calibration", "data", "from", "device", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/bmp180.py#L59-L74
train
44,814
MartijnBraam/pyElectronics
electronics/devices/bmp180.py
BMP180.temperature
def temperature(self): """Get the temperature from the sensor. :returns: The temperature in degree celcius as a float :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.temperature() 21.4 """ ut = self.get_raw_temp() x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15 x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD']) b5 = x1 + x2 return ((b5 + 8) >> 4) / 10
python
def temperature(self): """Get the temperature from the sensor. :returns: The temperature in degree celcius as a float :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.temperature() 21.4 """ ut = self.get_raw_temp() x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15 x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD']) b5 = x1 + x2 return ((b5 + 8) >> 4) / 10
[ "def", "temperature", "(", "self", ")", ":", "ut", "=", "self", ".", "get_raw_temp", "(", ")", "x1", "=", "(", "(", "ut", "-", "self", ".", "cal", "[", "'AC6'", "]", ")", "*", "self", ".", "cal", "[", "'AC5'", "]", ")", ">>", "15", "x2", "=",...
Get the temperature from the sensor. :returns: The temperature in degree celcius as a float :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.temperature() 21.4
[ "Get", "the", "temperature", "from", "the", "sensor", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/bmp180.py#L87-L104
train
44,815
MartijnBraam/pyElectronics
electronics/devices/bmp180.py
BMP180.pressure
def pressure(self): """ Get barometric pressure in milibar :returns: The pressure in milibar as a int :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.pressure() 75216 """ ut = self.get_raw_temp() up = self.get_raw_pressure() x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15 x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD']) b5 = x1 + x2 b6 = b5 - 4000 x1 = (self.cal['B2'] * (b6 * b6) >> 12) >> 11 x2 = (self.cal['AC2'] * b6) >> 11 x3 = x1 + x2 b3 = (((self.cal['AC1'] * 4 + x3) << self.mode) + 2) // 4 x1 = (self.cal['AC3'] * b6) >> 13 x2 = (self.cal['B1'] * ((b6 * b6) >> 12)) >> 16 x3 = ((x1 + x2) + 2) >> 2 b4 = (self.cal['AC4'] * (x3 + 32768)) >> 15 b7 = (up - b3) * (50000 >> self.mode) if b7 < 0x80000000: p = (b7 * 2) // b4 else: p = (b7 // b4) * 2 x1 = (p >> 8) * (p >> 8) x1 = (x1 * 3038) >> 16 x2 = (-7357 * p) >> 16 p += (x1 + x2 + 3791) >> 4 return p
python
def pressure(self): """ Get barometric pressure in milibar :returns: The pressure in milibar as a int :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.pressure() 75216 """ ut = self.get_raw_temp() up = self.get_raw_pressure() x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15 x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD']) b5 = x1 + x2 b6 = b5 - 4000 x1 = (self.cal['B2'] * (b6 * b6) >> 12) >> 11 x2 = (self.cal['AC2'] * b6) >> 11 x3 = x1 + x2 b3 = (((self.cal['AC1'] * 4 + x3) << self.mode) + 2) // 4 x1 = (self.cal['AC3'] * b6) >> 13 x2 = (self.cal['B1'] * ((b6 * b6) >> 12)) >> 16 x3 = ((x1 + x2) + 2) >> 2 b4 = (self.cal['AC4'] * (x3 + 32768)) >> 15 b7 = (up - b3) * (50000 >> self.mode) if b7 < 0x80000000: p = (b7 * 2) // b4 else: p = (b7 // b4) * 2 x1 = (p >> 8) * (p >> 8) x1 = (x1 * 3038) >> 16 x2 = (-7357 * p) >> 16 p += (x1 + x2 + 3791) >> 4 return p
[ "def", "pressure", "(", "self", ")", ":", "ut", "=", "self", ".", "get_raw_temp", "(", ")", "up", "=", "self", ".", "get_raw_pressure", "(", ")", "x1", "=", "(", "(", "ut", "-", "self", ".", "cal", "[", "'AC6'", "]", ")", "*", "self", ".", "cal...
Get barometric pressure in milibar :returns: The pressure in milibar as a int :example: >>> sensor = BMP180(gw) >>> sensor.load_calibration() >>> sensor.pressure() 75216
[ "Get", "barometric", "pressure", "in", "milibar" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/bmp180.py#L106-L143
train
44,816
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
BusPirate.switch_mode
def switch_mode(self, new_mode): """ Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants """ packet = bytearray() packet.append(new_mode) self.device.write(packet) possible_responses = { self.MODE_I2C: b'I2C1', self.MODE_RAW: b'BBIO1', self.MODE_SPI: b'API1', self.MODE_UART: b'ART1', self.MODE_ONEWIRE: b'1W01' } expected = possible_responses[new_mode] response = self.device.read(4) if response != expected: raise Exception('Could not switch mode') self.mode = new_mode self.set_peripheral() if self.i2c_speed: self._set_i2c_speed(self.i2c_speed)
python
def switch_mode(self, new_mode): """ Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants """ packet = bytearray() packet.append(new_mode) self.device.write(packet) possible_responses = { self.MODE_I2C: b'I2C1', self.MODE_RAW: b'BBIO1', self.MODE_SPI: b'API1', self.MODE_UART: b'ART1', self.MODE_ONEWIRE: b'1W01' } expected = possible_responses[new_mode] response = self.device.read(4) if response != expected: raise Exception('Could not switch mode') self.mode = new_mode self.set_peripheral() if self.i2c_speed: self._set_i2c_speed(self.i2c_speed)
[ "def", "switch_mode", "(", "self", ",", "new_mode", ")", ":", "packet", "=", "bytearray", "(", ")", "packet", ".", "append", "(", "new_mode", ")", "self", ".", "device", ".", "write", "(", "packet", ")", "possible_responses", "=", "{", "self", ".", "MO...
Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants
[ "Explicitly", "switch", "the", "Bus", "Pirate", "mode" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L79-L101
train
44,817
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
BusPirate.set_peripheral
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to enable the internal pull-up resistors. False to disable :param aux: Set the AUX pin output state :param chip_select: Set the CS pin output state """ if power is not None: self.power = power if pullup is not None: self.pullup = pullup if aux is not None: self.aux = aux if chip_select is not None: self.chip_select = chip_select # Set peripheral status peripheral_byte = 64 if self.chip_select: peripheral_byte |= 0x01 if self.aux: peripheral_byte |= 0x02 if self.pullup: peripheral_byte |= 0x04 if self.power: peripheral_byte |= 0x08 self.device.write(bytearray([peripheral_byte])) response = self.device.read(1) if response != b"\x01": raise Exception("Setting peripheral failed. Received: {}".format(repr(response)))
python
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to enable the internal pull-up resistors. False to disable :param aux: Set the AUX pin output state :param chip_select: Set the CS pin output state """ if power is not None: self.power = power if pullup is not None: self.pullup = pullup if aux is not None: self.aux = aux if chip_select is not None: self.chip_select = chip_select # Set peripheral status peripheral_byte = 64 if self.chip_select: peripheral_byte |= 0x01 if self.aux: peripheral_byte |= 0x02 if self.pullup: peripheral_byte |= 0x04 if self.power: peripheral_byte |= 0x08 self.device.write(bytearray([peripheral_byte])) response = self.device.read(1) if response != b"\x01": raise Exception("Setting peripheral failed. Received: {}".format(repr(response)))
[ "def", "set_peripheral", "(", "self", ",", "power", "=", "None", ",", "pullup", "=", "None", ",", "aux", "=", "None", ",", "chip_select", "=", "None", ")", ":", "if", "power", "is", "not", "None", ":", "self", ".", "power", "=", "power", "if", "pul...
Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to enable the internal pull-up resistors. False to disable :param aux: Set the AUX pin output state :param chip_select: Set the CS pin output state
[ "Set", "the", "peripheral", "config", "at", "runtime", ".", "If", "a", "parameter", "is", "None", "then", "the", "config", "will", "not", "be", "changed", "." ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L103-L134
train
44,818
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
BusPirate._set_i2c_speed
def _set_i2c_speed(self, i2c_speed): """ Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz' """ lower_bits_mapping = { '400kHz': 3, '100kHz': 2, '50kHz': 1, '5kHz': 0, } if i2c_speed not in lower_bits_mapping: raise ValueError('Invalid i2c_speed') speed_byte = 0b01100000 | lower_bits_mapping[i2c_speed] self.device.write(bytearray([speed_byte])) response = self.device.read(1) if response != b"\x01": raise Exception("Changing I2C speed failed. Received: {}".format(repr(response)))
python
def _set_i2c_speed(self, i2c_speed): """ Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz' """ lower_bits_mapping = { '400kHz': 3, '100kHz': 2, '50kHz': 1, '5kHz': 0, } if i2c_speed not in lower_bits_mapping: raise ValueError('Invalid i2c_speed') speed_byte = 0b01100000 | lower_bits_mapping[i2c_speed] self.device.write(bytearray([speed_byte])) response = self.device.read(1) if response != b"\x01": raise Exception("Changing I2C speed failed. Received: {}".format(repr(response)))
[ "def", "_set_i2c_speed", "(", "self", ",", "i2c_speed", ")", ":", "lower_bits_mapping", "=", "{", "'400kHz'", ":", "3", ",", "'100kHz'", ":", "2", ",", "'50kHz'", ":", "1", ",", "'5kHz'", ":", "0", ",", "}", "if", "i2c_speed", "not", "in", "lower_bits_...
Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz'
[ "Set", "I2C", "speed", "to", "one", "of", "400kHz", "100kHz", "50kHz", "5kHz" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L211-L226
train
44,819
MartijnBraam/pyElectronics
electronics/devices/hmc5883l.py
HMC5883L.config
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL): """ Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants """ averaging_conf = { 1: 0, 2: 1, 4: 2, 8: 3 } if averaging not in averaging_conf.keys(): raise Exception('Averaging should be one of: 1,2,4,8') datarates = { 0.75: 0, 1.5: 1, 3: 2, 7.5: 4, 15: 5, 30: 6, 75: 7 } if datarate not in datarates.keys(): raise Exception( 'Datarate of {} Hz is not support choose one of: {}'.format(datarate, ', '.join(datarates.keys()))) config_a = 0 config_a &= averaging_conf[averaging] << 5 config_a &= datarates[datarate] << 2 config_a &= mode self.i2c_write_register(0x00, config_a)
python
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL): """ Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants """ averaging_conf = { 1: 0, 2: 1, 4: 2, 8: 3 } if averaging not in averaging_conf.keys(): raise Exception('Averaging should be one of: 1,2,4,8') datarates = { 0.75: 0, 1.5: 1, 3: 2, 7.5: 4, 15: 5, 30: 6, 75: 7 } if datarate not in datarates.keys(): raise Exception( 'Datarate of {} Hz is not support choose one of: {}'.format(datarate, ', '.join(datarates.keys()))) config_a = 0 config_a &= averaging_conf[averaging] << 5 config_a &= datarates[datarate] << 2 config_a &= mode self.i2c_write_register(0x00, config_a)
[ "def", "config", "(", "self", ",", "averaging", "=", "1", ",", "datarate", "=", "15", ",", "mode", "=", "MODE_NORMAL", ")", ":", "averaging_conf", "=", "{", "1", ":", "0", ",", "2", ":", "1", ",", "4", ":", "2", ",", "8", ":", "3", "}", "if",...
Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants
[ "Set", "the", "base", "config", "for", "sensor" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/hmc5883l.py#L37-L72
train
44,820
MartijnBraam/pyElectronics
electronics/devices/hmc5883l.py
HMC5883L.set_resolution
def set_resolution(self, resolution=1090): """ Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss. The possible options are: ======================= ========== ============= Recommended Gauss range Resolution Gauss per bit ======================= ========== ============= 0.88 Ga 1370 0.73 mGa 1.3 Ga 1090 0.92 mGa 1.9 Ga 820 1.22 mGa 2.5 Ga 660 1.52 mGa 4.0 Ga 440 2.27 mGa 4.7 Ga 390 2.56 mGa 5.6 Ga 330 3.03 mGa 8.1 Ga 230 4.35 mGa ======================= ========== ============= :param resolution: The resolution of the sensor """ options = { 1370: 0, 1090: 1, 820: 2, 660: 3, 440: 4, 390: 5, 330: 6, 230: 7 } if resolution not in options.keys(): raise Exception('Resolution of {} steps is not supported'.format(resolution)) self.resolution = resolution config_b = 0 config_b &= options[resolution] << 5 self.i2c_write_register(0x01, config_b)
python
def set_resolution(self, resolution=1090): """ Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss. The possible options are: ======================= ========== ============= Recommended Gauss range Resolution Gauss per bit ======================= ========== ============= 0.88 Ga 1370 0.73 mGa 1.3 Ga 1090 0.92 mGa 1.9 Ga 820 1.22 mGa 2.5 Ga 660 1.52 mGa 4.0 Ga 440 2.27 mGa 4.7 Ga 390 2.56 mGa 5.6 Ga 330 3.03 mGa 8.1 Ga 230 4.35 mGa ======================= ========== ============= :param resolution: The resolution of the sensor """ options = { 1370: 0, 1090: 1, 820: 2, 660: 3, 440: 4, 390: 5, 330: 6, 230: 7 } if resolution not in options.keys(): raise Exception('Resolution of {} steps is not supported'.format(resolution)) self.resolution = resolution config_b = 0 config_b &= options[resolution] << 5 self.i2c_write_register(0x01, config_b)
[ "def", "set_resolution", "(", "self", ",", "resolution", "=", "1090", ")", ":", "options", "=", "{", "1370", ":", "0", ",", "1090", ":", "1", ",", "820", ":", "2", ",", "660", ":", "3", ",", "440", ":", "4", ",", "390", ":", "5", ",", "330", ...
Set the resolution of the sensor The resolution value is the amount of steps recorded in a single Gauss. The possible options are: ======================= ========== ============= Recommended Gauss range Resolution Gauss per bit ======================= ========== ============= 0.88 Ga 1370 0.73 mGa 1.3 Ga 1090 0.92 mGa 1.9 Ga 820 1.22 mGa 2.5 Ga 660 1.52 mGa 4.0 Ga 440 2.27 mGa 4.7 Ga 390 2.56 mGa 5.6 Ga 330 3.03 mGa 8.1 Ga 230 4.35 mGa ======================= ========== ============= :param resolution: The resolution of the sensor
[ "Set", "the", "resolution", "of", "the", "sensor" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/hmc5883l.py#L74-L113
train
44,821
MartijnBraam/pyElectronics
electronics/devices/lm75.py
LM75.temperature
def temperature(self): """ Get the temperature in degree celcius """ result = self.i2c_read(2) value = struct.unpack('>H', result)[0] if value < 32768: return value / 256.0 else: return (value - 65536) / 256.0
python
def temperature(self): """ Get the temperature in degree celcius """ result = self.i2c_read(2) value = struct.unpack('>H', result)[0] if value < 32768: return value / 256.0 else: return (value - 65536) / 256.0
[ "def", "temperature", "(", "self", ")", ":", "result", "=", "self", ".", "i2c_read", "(", "2", ")", "value", "=", "struct", ".", "unpack", "(", "'>H'", ",", "result", ")", "[", "0", "]", "if", "value", "<", "32768", ":", "return", "value", "/", "...
Get the temperature in degree celcius
[ "Get", "the", "temperature", "in", "degree", "celcius" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/lm75.py#L29-L38
train
44,822
MartijnBraam/pyElectronics
electronics/devices/segmentdisplay.py
SegmentDisplayGPIO.write
def write(self, char): """ Display a single character on the display :type char: str or int :param char: Character to display """ char = str(char).lower() self.segments.write(self.font[char])
python
def write(self, char): """ Display a single character on the display :type char: str or int :param char: Character to display """ char = str(char).lower() self.segments.write(self.font[char])
[ "def", "write", "(", "self", ",", "char", ")", ":", "char", "=", "str", "(", "char", ")", ".", "lower", "(", ")", "self", ".", "segments", ".", "write", "(", "self", ".", "font", "[", "char", "]", ")" ]
Display a single character on the display :type char: str or int :param char: Character to display
[ "Display", "a", "single", "character", "on", "the", "display" ]
a20878c9fa190135f1e478e9ea0b54ca43ff308e
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/segmentdisplay.py#L205-L212
train
44,823
edx/edx-sphinx-theme
edx_theme/__init__.py
get_html_theme_path
def get_html_theme_path(): """ Get the absolute path of the directory containing the theme files. """ return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
python
def get_html_theme_path(): """ Get the absolute path of the directory containing the theme files. """ return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
[ "def", "get_html_theme_path", "(", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")" ]
Get the absolute path of the directory containing the theme files.
[ "Get", "the", "absolute", "path", "of", "the", "directory", "containing", "the", "theme", "files", "." ]
0abdc8c64ca1453f571a45f4603a6b2907a34378
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L24-L28
train
44,824
edx/edx-sphinx-theme
edx_theme/__init__.py
feedback_form_url
def feedback_form_url(project, page): """ Create a URL for feedback on a particular page in a project. """ return FEEDBACK_FORM_FMT.format(pageid=quote("{}: {}".format(project, page)))
python
def feedback_form_url(project, page): """ Create a URL for feedback on a particular page in a project. """ return FEEDBACK_FORM_FMT.format(pageid=quote("{}: {}".format(project, page)))
[ "def", "feedback_form_url", "(", "project", ",", "page", ")", ":", "return", "FEEDBACK_FORM_FMT", ".", "format", "(", "pageid", "=", "quote", "(", "\"{}: {}\"", ".", "format", "(", "project", ",", "page", ")", ")", ")" ]
Create a URL for feedback on a particular page in a project.
[ "Create", "a", "URL", "for", "feedback", "on", "a", "particular", "page", "in", "a", "project", "." ]
0abdc8c64ca1453f571a45f4603a6b2907a34378
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L31-L35
train
44,825
edx/edx-sphinx-theme
edx_theme/__init__.py
update_context
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument """ Update the page rendering context to include ``feedback_form_url``. """ context['feedback_form_url'] = feedback_form_url(app.config.project, pagename)
python
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument """ Update the page rendering context to include ``feedback_form_url``. """ context['feedback_form_url'] = feedback_form_url(app.config.project, pagename)
[ "def", "update_context", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "# pylint: disable=unused-argument", "context", "[", "'feedback_form_url'", "]", "=", "feedback_form_url", "(", "app", ".", "config", ".", "project...
Update the page rendering context to include ``feedback_form_url``.
[ "Update", "the", "page", "rendering", "context", "to", "include", "feedback_form_url", "." ]
0abdc8c64ca1453f571a45f4603a6b2907a34378
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L38-L42
train
44,826
edx/edx-sphinx-theme
edx_theme/__init__.py
setup
def setup(app): """ Sphinx extension to update the rendering context with the feedback form URL. Arguments: app (Sphinx): Application object for the Sphinx process Returns: a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata) """ event = 'html-page-context' if six.PY3 else b'html-page-context' app.connect(event, update_context) return { 'parallel_read_safe': True, 'parallel_write_safe': True, 'version': __version__, }
python
def setup(app): """ Sphinx extension to update the rendering context with the feedback form URL. Arguments: app (Sphinx): Application object for the Sphinx process Returns: a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata) """ event = 'html-page-context' if six.PY3 else b'html-page-context' app.connect(event, update_context) return { 'parallel_read_safe': True, 'parallel_write_safe': True, 'version': __version__, }
[ "def", "setup", "(", "app", ")", ":", "event", "=", "'html-page-context'", "if", "six", ".", "PY3", "else", "b'html-page-context'", "app", ".", "connect", "(", "event", ",", "update_context", ")", "return", "{", "'parallel_read_safe'", ":", "True", ",", "'pa...
Sphinx extension to update the rendering context with the feedback form URL. Arguments: app (Sphinx): Application object for the Sphinx process Returns: a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata)
[ "Sphinx", "extension", "to", "update", "the", "rendering", "context", "with", "the", "feedback", "form", "URL", "." ]
0abdc8c64ca1453f571a45f4603a6b2907a34378
https://github.com/edx/edx-sphinx-theme/blob/0abdc8c64ca1453f571a45f4603a6b2907a34378/edx_theme/__init__.py#L45-L62
train
44,827
glyph/txsni
txsni/only_noticed_pypi_pem_after_i_wrote_this.py
objectsFromPEM
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: blobs = keys blobs.append(b'') blobs[-1] += line blobs[-1] += b'\n' keys = [KeyPair.load(key, FILETYPE_PEM) for key in keys] certificates = [Certificate.loadPEM(certificate) for certificate in certificates] return PEMObjects(keys=keys, certificates=certificates)
python
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: blobs = keys blobs.append(b'') blobs[-1] += line blobs[-1] += b'\n' keys = [KeyPair.load(key, FILETYPE_PEM) for key in keys] certificates = [Certificate.loadPEM(certificate) for certificate in certificates] return PEMObjects(keys=keys, certificates=certificates)
[ "def", "objectsFromPEM", "(", "pemdata", ")", ":", "certificates", "=", "[", "]", "keys", "=", "[", "]", "blobs", "=", "[", "b\"\"", "]", "for", "line", "in", "pemdata", ".", "split", "(", "b\"\\n\"", ")", ":", "if", "line", ".", "startswith", "(", ...
Load some objects from a PEM.
[ "Load", "some", "objects", "from", "a", "PEM", "." ]
5014c141a7acef63e20fcf6c36fa07f0cd754ce1
https://github.com/glyph/txsni/blob/5014c141a7acef63e20fcf6c36fa07f0cd754ce1/txsni/only_noticed_pypi_pem_after_i_wrote_this.py#L9-L28
train
44,828
revelc/pyaccumulo
pyaccumulo/__init__.py
Range.followingPrefix
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; if(changeIndex < 0): return None newBytes = array('B', prefix[0:changeIndex + 1]) newBytes[changeIndex] = newBytes[changeIndex] + 1 return newBytes.tostring()
python
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; if(changeIndex < 0): return None newBytes = array('B', prefix[0:changeIndex + 1]) newBytes[changeIndex] = newBytes[changeIndex] + 1 return newBytes.tostring()
[ "def", "followingPrefix", "(", "prefix", ")", ":", "prefixBytes", "=", "array", "(", "'B'", ",", "prefix", ")", "changeIndex", "=", "len", "(", "prefixBytes", ")", "-", "1", "while", "(", "changeIndex", ">=", "0", "and", "prefixBytes", "[", "changeIndex", ...
Returns a String that sorts just after all Strings beginning with a prefix
[ "Returns", "a", "String", "that", "sorts", "just", "after", "all", "Strings", "beginning", "with", "a", "prefix" ]
8adcf535bb82ba69c749efce785c9efc487e85de
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/__init__.py#L100-L111
train
44,829
revelc/pyaccumulo
pyaccumulo/__init__.py
Range.prefix
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)
python
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", "prefix", "(", "rowPrefix", ")", ":", "fp", "=", "Range", ".", "followingPrefix", "(", "rowPrefix", ")", "return", "Range", "(", "srow", "=", "rowPrefix", ",", "sinclude", "=", "True", ",", "erow", "=", "fp", ",", "einclude", "=", "False", ")" ]
Returns a Range that covers all rows beginning with a prefix
[ "Returns", "a", "Range", "that", "covers", "all", "rows", "beginning", "with", "a", "prefix" ]
8adcf535bb82ba69c749efce785c9efc487e85de
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/__init__.py#L114-L117
train
44,830
revelc/pyaccumulo
pyaccumulo/__init__.py
Accumulo.add_mutations_and_flush
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.setdefault(mut.row, []).extend(mut.updates) self.client.updateAndFlush(self.login, table, cells)
python
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.setdefault(mut.row, []).extend(mut.updates) self.client.updateAndFlush(self.login, table, cells)
[ "def", "add_mutations_and_flush", "(", "self", ",", "table", ",", "muts", ")", ":", "if", "not", "isinstance", "(", "muts", ",", "list", ")", "and", "not", "isinstance", "(", "muts", ",", "tuple", ")", ":", "muts", "=", "[", "muts", "]", "cells", "="...
Add mutations to a table without the need to create and manage a batch writer.
[ "Add", "mutations", "to", "a", "table", "without", "the", "need", "to", "create", "and", "manage", "a", "batch", "writer", "." ]
8adcf535bb82ba69c749efce785c9efc487e85de
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/__init__.py#L271-L280
train
44,831
glyph/txsni
txsni/snimap.py
_ConnectionProxy.get_context
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)
python
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", "get_context", "(", "self", ")", ":", "ctx", "=", "self", ".", "_obj", ".", "get_context", "(", ")", "return", "_ContextProxy", "(", "ctx", ",", "self", ".", "_factory", ")" ]
A basic override of get_context to ensure that the appropriate proxy object is returned.
[ "A", "basic", "override", "of", "get_context", "to", "ensure", "that", "the", "appropriate", "proxy", "object", "is", "returned", "." ]
5014c141a7acef63e20fcf6c36fa07f0cd754ce1
https://github.com/glyph/txsni/blob/5014c141a7acef63e20fcf6c36fa07f0cd754ce1/txsni/snimap.py#L56-L62
train
44,832
fabaff/python-mystrom
pymystrom/switch.py
MyStromPlug.set_relay_on
def set_relay_on(self): """Turn the relay on.""" if not self.get_relay_state(): try: request = requests.get( '{}/relay'.format(self.resource), params={'state': '1'}, timeout=self.timeout) if request.status_code == 200: self.data['relay'] = True except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
python
def set_relay_on(self): """Turn the relay on.""" if not self.get_relay_state(): try: request = requests.get( '{}/relay'.format(self.resource), params={'state': '1'}, timeout=self.timeout) if request.status_code == 200: self.data['relay'] = True except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
[ "def", "set_relay_on", "(", "self", ")", ":", "if", "not", "self", ".", "get_relay_state", "(", ")", ":", "try", ":", "request", "=", "requests", ".", "get", "(", "'{}/relay'", ".", "format", "(", "self", ".", "resource", ")", ",", "params", "=", "{"...
Turn the relay on.
[ "Turn", "the", "relay", "on", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/switch.py#L23-L33
train
44,833
fabaff/python-mystrom
pymystrom/switch.py
MyStromPlug.set_relay_off
def set_relay_off(self): """Turn the relay off.""" if self.get_relay_state(): try: request = requests.get( '{}/relay'.format(self.resource), params={'state': '0'}, timeout=self.timeout) if request.status_code == 200: self.data['relay'] = False except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
python
def set_relay_off(self): """Turn the relay off.""" if self.get_relay_state(): try: request = requests.get( '{}/relay'.format(self.resource), params={'state': '0'}, timeout=self.timeout) if request.status_code == 200: self.data['relay'] = False except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
[ "def", "set_relay_off", "(", "self", ")", ":", "if", "self", ".", "get_relay_state", "(", ")", ":", "try", ":", "request", "=", "requests", ".", "get", "(", "'{}/relay'", ".", "format", "(", "self", ".", "resource", ")", ",", "params", "=", "{", "'st...
Turn the relay off.
[ "Turn", "the", "relay", "off", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/switch.py#L35-L45
train
44,834
fabaff/python-mystrom
pymystrom/switch.py
MyStromPlug.get_consumption
def get_consumption(self): """Get current power consumption in mWh.""" self.get_status() try: self.consumption = self.data['power'] except TypeError: self.consumption = 0 return self.consumption
python
def get_consumption(self): """Get current power consumption in mWh.""" self.get_status() try: self.consumption = self.data['power'] except TypeError: self.consumption = 0 return self.consumption
[ "def", "get_consumption", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "consumption", "=", "self", ".", "data", "[", "'power'", "]", "except", "TypeError", ":", "self", ".", "consumption", "=", "0", "return", "se...
Get current power consumption in mWh.
[ "Get", "current", "power", "consumption", "in", "mWh", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/switch.py#L67-L75
train
44,835
fabaff/python-mystrom
pymystrom/switch.py
MyStromPlug.get_temperature
def get_temperature(self): """Get current temperature in celsius.""" try: request = requests.get( '{}/temp'.format(self.resource), timeout=self.timeout, allow_redirects=False) self.temperature = request.json()['compensated'] return self.temperature except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError() except ValueError: raise exceptions.MyStromNotVersionTwoSwitch()
python
def get_temperature(self): """Get current temperature in celsius.""" try: request = requests.get( '{}/temp'.format(self.resource), timeout=self.timeout, allow_redirects=False) self.temperature = request.json()['compensated'] return self.temperature except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError() except ValueError: raise exceptions.MyStromNotVersionTwoSwitch()
[ "def", "get_temperature", "(", "self", ")", ":", "try", ":", "request", "=", "requests", ".", "get", "(", "'{}/temp'", ".", "format", "(", "self", ".", "resource", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "allow_redirects", "=", "False", ...
Get current temperature in celsius.
[ "Get", "current", "temperature", "in", "celsius", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/switch.py#L77-L87
train
44,836
mdscruggs/ga
ga/examples/biggest_multiple.py
BiggestMultipleGA.eval_fitness
def eval_fitness(self, chromosome): """ Convert a 1-gene chromosome into an integer and calculate its fitness by checking it against each required factor. return: fitness value """ score = 0 number = self.translator.translate_gene(chromosome.genes[0]) for factor in self.factors: if number % factor == 0: score += 1 else: score -= 1 # check for optimal solution if score == len(self.factors): min_product = functools.reduce(lambda a,b: a * b, self.factors) if number + min_product > self.max_encoded_val: print("Found best solution:", number) self.found_best = True # scale number of factors achieved/missed by ratio of # the solution number to the maximum possible integer # represented by binary strings of the given length return score * number / self.max_encoded_val
python
def eval_fitness(self, chromosome): """ Convert a 1-gene chromosome into an integer and calculate its fitness by checking it against each required factor. return: fitness value """ score = 0 number = self.translator.translate_gene(chromosome.genes[0]) for factor in self.factors: if number % factor == 0: score += 1 else: score -= 1 # check for optimal solution if score == len(self.factors): min_product = functools.reduce(lambda a,b: a * b, self.factors) if number + min_product > self.max_encoded_val: print("Found best solution:", number) self.found_best = True # scale number of factors achieved/missed by ratio of # the solution number to the maximum possible integer # represented by binary strings of the given length return score * number / self.max_encoded_val
[ "def", "eval_fitness", "(", "self", ",", "chromosome", ")", ":", "score", "=", "0", "number", "=", "self", ".", "translator", ".", "translate_gene", "(", "chromosome", ".", "genes", "[", "0", "]", ")", "for", "factor", "in", "self", ".", "factors", ":"...
Convert a 1-gene chromosome into an integer and calculate its fitness by checking it against each required factor. return: fitness value
[ "Convert", "a", "1", "-", "gene", "chromosome", "into", "an", "integer", "and", "calculate", "its", "fitness", "by", "checking", "it", "against", "each", "required", "factor", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/biggest_multiple.py#L43-L71
train
44,837
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.get_status
def get_status(self): """Get the details from the bulb.""" try: request = requests.get( '{}/{}/'.format(self.resource, URI), timeout=self.timeout) raw_data = request.json() # Doesn't always work !!!!! #self._mac = next(iter(self.raw_data)) self.data = raw_data[self._mac] return self.data except (requests.exceptions.ConnectionError, ValueError): raise exceptions.MyStromConnectionError()
python
def get_status(self): """Get the details from the bulb.""" try: request = requests.get( '{}/{}/'.format(self.resource, URI), timeout=self.timeout) raw_data = request.json() # Doesn't always work !!!!! #self._mac = next(iter(self.raw_data)) self.data = raw_data[self._mac] return self.data except (requests.exceptions.ConnectionError, ValueError): raise exceptions.MyStromConnectionError()
[ "def", "get_status", "(", "self", ")", ":", "try", ":", "request", "=", "requests", ".", "get", "(", "'{}/{}/'", ".", "format", "(", "self", ".", "resource", ",", "URI", ")", ",", "timeout", "=", "self", ".", "timeout", ")", "raw_data", "=", "request...
Get the details from the bulb.
[ "Get", "the", "details", "from", "the", "bulb", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L31-L42
train
44,838
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.get_power
def get_power(self): """Get current power.""" self.get_status() try: self.consumption = self.data['power'] except TypeError: self.consumption = 0 return self.consumption
python
def get_power(self): """Get current power.""" self.get_status() try: self.consumption = self.data['power'] except TypeError: self.consumption = 0 return self.consumption
[ "def", "get_power", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "consumption", "=", "self", ".", "data", "[", "'power'", "]", "except", "TypeError", ":", "self", ".", "consumption", "=", "0", "return", "self", ...
Get current power.
[ "Get", "current", "power", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L54-L62
train
44,839
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.get_firmware
def get_firmware(self): """Get the current firmware version.""" self.get_status() try: self.firmware = self.data['fw_version'] except TypeError: self.firmware = 'Unknown' return self.firmware
python
def get_firmware(self): """Get the current firmware version.""" self.get_status() try: self.firmware = self.data['fw_version'] except TypeError: self.firmware = 'Unknown' return self.firmware
[ "def", "get_firmware", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "firmware", "=", "self", ".", "data", "[", "'fw_version'", "]", "except", "TypeError", ":", "self", ".", "firmware", "=", "'Unknown'", "return", ...
Get the current firmware version.
[ "Get", "the", "current", "firmware", "version", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L64-L72
train
44,840
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.get_brightness
def get_brightness(self): """Get current brightness.""" self.get_status() try: self.brightness = self.data['color'].split(';')[-1] except TypeError: self.brightness = 0 return self.brightness
python
def get_brightness(self): """Get current brightness.""" self.get_status() try: self.brightness = self.data['color'].split(';')[-1] except TypeError: self.brightness = 0 return self.brightness
[ "def", "get_brightness", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "brightness", "=", "self", ".", "data", "[", "'color'", "]", ".", "split", "(", "';'", ")", "[", "-", "1", "]", "except", "TypeError", ":"...
Get current brightness.
[ "Get", "current", "brightness", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L74-L82
train
44,841
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.get_transition_time
def get_transition_time(self): """Get the transition time in ms.""" self.get_status() try: self.transition_time = self.data['ramp'] except TypeError: self.transition_time = 0 return self.transition_time
python
def get_transition_time(self): """Get the transition time in ms.""" self.get_status() try: self.transition_time = self.data['ramp'] except TypeError: self.transition_time = 0 return self.transition_time
[ "def", "get_transition_time", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "transition_time", "=", "self", ".", "data", "[", "'ramp'", "]", "except", "TypeError", ":", "self", ".", "transition_time", "=", "0", "ret...
Get the transition time in ms.
[ "Get", "the", "transition", "time", "in", "ms", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L84-L92
train
44,842
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.get_color
def get_color(self): """Get current color.""" self.get_status() try: self.color = self.data['color'] self.mode = self.data['mode'] except TypeError: self.color = 0 self.mode = '' return {'color': self.color, 'mode': self.mode}
python
def get_color(self): """Get current color.""" self.get_status() try: self.color = self.data['color'] self.mode = self.data['mode'] except TypeError: self.color = 0 self.mode = '' return {'color': self.color, 'mode': self.mode}
[ "def", "get_color", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "color", "=", "self", ".", "data", "[", "'color'", "]", "self", ".", "mode", "=", "self", ".", "data", "[", "'mode'", "]", "except", "TypeError...
Get current color.
[ "Get", "current", "color", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L94-L104
train
44,843
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.set_color_hsv
def set_color_hsv(self, hue, saturation, value): """Turn the bulb on with the given values as HSV.""" try: data = "action=on&color={};{};{}".format(hue, saturation, value) request = requests.post( '{}/{}/{}'.format(self.resource, URI, self._mac), data=data, timeout=self.timeout) if request.status_code == 200: self.data['on'] = True except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
python
def set_color_hsv(self, hue, saturation, value): """Turn the bulb on with the given values as HSV.""" try: data = "action=on&color={};{};{}".format(hue, saturation, value) request = requests.post( '{}/{}/{}'.format(self.resource, URI, self._mac), data=data, timeout=self.timeout) if request.status_code == 200: self.data['on'] = True except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
[ "def", "set_color_hsv", "(", "self", ",", "hue", ",", "saturation", ",", "value", ")", ":", "try", ":", "data", "=", "\"action=on&color={};{};{}\"", ".", "format", "(", "hue", ",", "saturation", ",", "value", ")", "request", "=", "requests", ".", "post", ...
Turn the bulb on with the given values as HSV.
[ "Turn", "the", "bulb", "on", "with", "the", "given", "values", "as", "HSV", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L139-L149
train
44,844
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.set_rainbow
def set_rainbow(self, duration): """Turn the bulb on and create a rainbow.""" for i in range(0, 359): self.set_color_hsv(i, 100, 100) time.sleep(duration/359)
python
def set_rainbow(self, duration): """Turn the bulb on and create a rainbow.""" for i in range(0, 359): self.set_color_hsv(i, 100, 100) time.sleep(duration/359)
[ "def", "set_rainbow", "(", "self", ",", "duration", ")", ":", "for", "i", "in", "range", "(", "0", ",", "359", ")", ":", "self", ".", "set_color_hsv", "(", "i", ",", "100", ",", "100", ")", "time", ".", "sleep", "(", "duration", "/", "359", ")" ]
Turn the bulb on and create a rainbow.
[ "Turn", "the", "bulb", "on", "and", "create", "a", "rainbow", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L155-L159
train
44,845
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.set_sunrise
def set_sunrise(self, duration): """Turn the bulb on and create a sunrise.""" self.set_transition_time(duration/100) for i in range(0, duration): try: data = "action=on&color=3;{}".format(i) request = requests.post( '{}/{}/{}'.format(self.resource, URI, self._mac), data=data, timeout=self.timeout) if request.status_code == 200: self.data['on'] = True except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError() time.sleep(duration/100)
python
def set_sunrise(self, duration): """Turn the bulb on and create a sunrise.""" self.set_transition_time(duration/100) for i in range(0, duration): try: data = "action=on&color=3;{}".format(i) request = requests.post( '{}/{}/{}'.format(self.resource, URI, self._mac), data=data, timeout=self.timeout) if request.status_code == 200: self.data['on'] = True except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError() time.sleep(duration/100)
[ "def", "set_sunrise", "(", "self", ",", "duration", ")", ":", "self", ".", "set_transition_time", "(", "duration", "/", "100", ")", "for", "i", "in", "range", "(", "0", ",", "duration", ")", ":", "try", ":", "data", "=", "\"action=on&color=3;{}\"", ".", ...
Turn the bulb on and create a sunrise.
[ "Turn", "the", "bulb", "on", "and", "create", "a", "sunrise", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L161-L174
train
44,846
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.set_flashing
def set_flashing(self, duration, hsv1, hsv2): """Turn the bulb on, flashing with two colors.""" self.set_transition_time(100) for step in range(0, int(duration/2)): self.set_color_hsv(hsv1[0], hsv1[1], hsv1[2]) time.sleep(1) self.set_color_hsv(hsv2[0], hsv2[1], hsv2[2]) time.sleep(1)
python
def set_flashing(self, duration, hsv1, hsv2): """Turn the bulb on, flashing with two colors.""" self.set_transition_time(100) for step in range(0, int(duration/2)): self.set_color_hsv(hsv1[0], hsv1[1], hsv1[2]) time.sleep(1) self.set_color_hsv(hsv2[0], hsv2[1], hsv2[2]) time.sleep(1)
[ "def", "set_flashing", "(", "self", ",", "duration", ",", "hsv1", ",", "hsv2", ")", ":", "self", ".", "set_transition_time", "(", "100", ")", "for", "step", "in", "range", "(", "0", ",", "int", "(", "duration", "/", "2", ")", ")", ":", "self", ".",...
Turn the bulb on, flashing with two colors.
[ "Turn", "the", "bulb", "on", "flashing", "with", "two", "colors", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L176-L183
train
44,847
fabaff/python-mystrom
pymystrom/bulb.py
MyStromBulb.set_off
def set_off(self): """Turn the bulb off.""" try: request = requests.post( '{}/{}/{}/'.format(self.resource, URI, self._mac), data={'action': 'off'}, timeout=self.timeout) if request.status_code == 200: pass except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
python
def set_off(self): """Turn the bulb off.""" try: request = requests.post( '{}/{}/{}/'.format(self.resource, URI, self._mac), data={'action': 'off'}, timeout=self.timeout) if request.status_code == 200: pass except requests.exceptions.ConnectionError: raise exceptions.MyStromConnectionError()
[ "def", "set_off", "(", "self", ")", ":", "try", ":", "request", "=", "requests", ".", "post", "(", "'{}/{}/{}/'", ".", "format", "(", "self", ".", "resource", ",", "URI", ",", "self", ".", "_mac", ")", ",", "data", "=", "{", "'action'", ":", "'off'...
Turn the bulb off.
[ "Turn", "the", "bulb", "off", "." ]
86410f8952104651ef76ad37c84c29740c50551e
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L196-L205
train
44,848
pymacaron/pymacaron
pymacaron/__init__.py
API.load_clients
def load_clients(self, path=None, apis=[]): """Generate client libraries for the given apis, without starting an api server""" if not path: raise Exception("Missing path to api swagger files") if type(apis) is not list: raise Exception("'apis' should be a list of api names") if len(apis) == 0: raise Exception("'apis' is an empty list - Expected at least one api name") for api_name in apis: api_path = os.path.join(path, '%s.yaml' % api_name) if not os.path.isfile(api_path): raise Exception("Cannot find swagger specification at %s" % api_path) log.info("Loading api %s from %s" % (api_name, api_path)) ApiPool.add( api_name, yaml_path=api_path, timeout=self.timeout, error_callback=self.error_callback, formats=self.formats, do_persist=False, local=False, ) return self
python
def load_clients(self, path=None, apis=[]): """Generate client libraries for the given apis, without starting an api server""" if not path: raise Exception("Missing path to api swagger files") if type(apis) is not list: raise Exception("'apis' should be a list of api names") if len(apis) == 0: raise Exception("'apis' is an empty list - Expected at least one api name") for api_name in apis: api_path = os.path.join(path, '%s.yaml' % api_name) if not os.path.isfile(api_path): raise Exception("Cannot find swagger specification at %s" % api_path) log.info("Loading api %s from %s" % (api_name, api_path)) ApiPool.add( api_name, yaml_path=api_path, timeout=self.timeout, error_callback=self.error_callback, formats=self.formats, do_persist=False, local=False, ) return self
[ "def", "load_clients", "(", "self", ",", "path", "=", "None", ",", "apis", "=", "[", "]", ")", ":", "if", "not", "path", ":", "raise", "Exception", "(", "\"Missing path to api swagger files\"", ")", "if", "type", "(", "apis", ")", "is", "not", "list", ...
Generate client libraries for the given apis, without starting an api server
[ "Generate", "client", "libraries", "for", "the", "given", "apis", "without", "starting", "an", "api", "server" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/__init__.py#L53-L81
train
44,849
pymacaron/pymacaron
pymacaron/__init__.py
API.load_apis
def load_apis(self, path, ignore=[], include_crash_api=False): """Load all swagger files found at the given path, except those whose names are in the 'ignore' list""" if not path: raise Exception("Missing path to api swagger files") if type(ignore) is not list: raise Exception("'ignore' should be a list of api names") # Always ignore pym-config.yaml ignore.append('pym-config') # Find all swagger apis under 'path' apis = {} log.debug("Searching path %s" % path) for root, dirs, files in os.walk(path): for f in files: if f.endswith('.yaml'): api_name = f.replace('.yaml', '') if api_name in ignore: log.info("Ignoring api %s" % api_name) continue apis[api_name] = os.path.join(path, f) log.debug("Found api %s in %s" % (api_name, f)) # And add pymacaron's default ping and crash apis for name in ['ping', 'crash']: yaml_path = pkg_resources.resource_filename(__name__, 'pymacaron/%s.yaml' % name) if not os.path.isfile(yaml_path): yaml_path = os.path.join(os.path.dirname(sys.modules[__name__].__file__), '%s.yaml' % name) apis[name] = yaml_path if not include_crash_api: del apis['crash'] # Save found apis self.path_apis = path self.apis = apis return self
python
def load_apis(self, path, ignore=[], include_crash_api=False): """Load all swagger files found at the given path, except those whose names are in the 'ignore' list""" if not path: raise Exception("Missing path to api swagger files") if type(ignore) is not list: raise Exception("'ignore' should be a list of api names") # Always ignore pym-config.yaml ignore.append('pym-config') # Find all swagger apis under 'path' apis = {} log.debug("Searching path %s" % path) for root, dirs, files in os.walk(path): for f in files: if f.endswith('.yaml'): api_name = f.replace('.yaml', '') if api_name in ignore: log.info("Ignoring api %s" % api_name) continue apis[api_name] = os.path.join(path, f) log.debug("Found api %s in %s" % (api_name, f)) # And add pymacaron's default ping and crash apis for name in ['ping', 'crash']: yaml_path = pkg_resources.resource_filename(__name__, 'pymacaron/%s.yaml' % name) if not os.path.isfile(yaml_path): yaml_path = os.path.join(os.path.dirname(sys.modules[__name__].__file__), '%s.yaml' % name) apis[name] = yaml_path if not include_crash_api: del apis['crash'] # Save found apis self.path_apis = path self.apis = apis return self
[ "def", "load_apis", "(", "self", ",", "path", ",", "ignore", "=", "[", "]", ",", "include_crash_api", "=", "False", ")", ":", "if", "not", "path", ":", "raise", "Exception", "(", "\"Missing path to api swagger files\"", ")", "if", "type", "(", "ignore", ")...
Load all swagger files found at the given path, except those whose names are in the 'ignore' list
[ "Load", "all", "swagger", "files", "found", "at", "the", "given", "path", "except", "those", "whose", "names", "are", "in", "the", "ignore", "list" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/__init__.py#L84-L127
train
44,850
pymacaron/pymacaron
pymacaron/__init__.py
API.start
def start(self, serve=[]): """Load all apis, either as local apis served by the flask app, or as remote apis to be called from whithin the app's endpoints, then start the app server""" # Check arguments if type(serve) is str: serve = [serve] elif type(serve) is list: pass else: raise Exception("'serve' should be an api name or a list of api names") if len(serve) == 0: raise Exception("You must specify at least one api to serve") for api_name in serve: if api_name not in self.apis: raise Exception("Can't find %s.yaml (swagger file) in the api directory %s" % (api_name, self.path_apis)) app = self.app app.secret_key = os.urandom(24) # Initialize JWT config conf = get_config() if hasattr(conf, 'jwt_secret'): log.info("Set JWT parameters to issuer=%s audience=%s secret=%s***" % ( conf.jwt_issuer, conf.jwt_audience, conf.jwt_secret[0:8], )) # Always serve the ping api serve.append('ping') # Let's compress returned data when possible compress = Compress() compress.init_app(app) # All apis that are not served locally are not persistent not_persistent = [] for api_name in self.apis.keys(): if api_name in serve: pass else: not_persistent.append(api_name) # Now load those apis into the ApiPool for api_name, api_path in self.apis.items(): host = None port = None if api_name in serve: # We are serving this api locally: override the host:port specified in the swagger spec host = self.host port = self.port do_persist = True if api_name not in not_persistent else False local = True if api_name in serve else False log.info("Loading api %s from %s (persist: %s)" % (api_name, api_path, do_persist)) ApiPool.add( api_name, yaml_path=api_path, timeout=self.timeout, error_callback=self.error_callback, formats=self.formats, do_persist=do_persist, host=host, port=port, local=local, ) ApiPool.merge() # Now spawn flask routes for all endpoints for api_name in self.apis.keys(): if api_name in serve: log.info("Spawning api %s" % api_name) api = getattr(ApiPool, api_name) # Spawn api and wrap every endpoint in a crash handler that # catches replies and reports errors api.spawn_api(app, decorator=generate_crash_handler_decorator(self.error_decorator)) log.debug("Argv is [%s]" % ' '.join(sys.argv)) if 'celery' in sys.argv[0].lower(): # This code is loading in a celery server - Don't start the actual flask app. log.info("Running in a Celery worker - Not starting the Flask app") return # Initialize monitoring, if any is defined monitor_init(app=app, config=conf) if os.path.basename(sys.argv[0]) == 'gunicorn': # Gunicorn takes care of spawning workers log.info("Running in Gunicorn - Not starting the Flask app") return # Debug mode is the default when not running via gunicorn app.debug = self.debug app.run(host='0.0.0.0', port=self.port)
python
def start(self, serve=[]): """Load all apis, either as local apis served by the flask app, or as remote apis to be called from whithin the app's endpoints, then start the app server""" # Check arguments if type(serve) is str: serve = [serve] elif type(serve) is list: pass else: raise Exception("'serve' should be an api name or a list of api names") if len(serve) == 0: raise Exception("You must specify at least one api to serve") for api_name in serve: if api_name not in self.apis: raise Exception("Can't find %s.yaml (swagger file) in the api directory %s" % (api_name, self.path_apis)) app = self.app app.secret_key = os.urandom(24) # Initialize JWT config conf = get_config() if hasattr(conf, 'jwt_secret'): log.info("Set JWT parameters to issuer=%s audience=%s secret=%s***" % ( conf.jwt_issuer, conf.jwt_audience, conf.jwt_secret[0:8], )) # Always serve the ping api serve.append('ping') # Let's compress returned data when possible compress = Compress() compress.init_app(app) # All apis that are not served locally are not persistent not_persistent = [] for api_name in self.apis.keys(): if api_name in serve: pass else: not_persistent.append(api_name) # Now load those apis into the ApiPool for api_name, api_path in self.apis.items(): host = None port = None if api_name in serve: # We are serving this api locally: override the host:port specified in the swagger spec host = self.host port = self.port do_persist = True if api_name not in not_persistent else False local = True if api_name in serve else False log.info("Loading api %s from %s (persist: %s)" % (api_name, api_path, do_persist)) ApiPool.add( api_name, yaml_path=api_path, timeout=self.timeout, error_callback=self.error_callback, formats=self.formats, do_persist=do_persist, host=host, port=port, local=local, ) ApiPool.merge() # Now spawn flask routes for all endpoints for api_name in self.apis.keys(): if api_name in serve: log.info("Spawning api %s" % api_name) api = getattr(ApiPool, api_name) # Spawn api and wrap every endpoint in a crash handler that # catches replies and reports errors api.spawn_api(app, decorator=generate_crash_handler_decorator(self.error_decorator)) log.debug("Argv is [%s]" % ' '.join(sys.argv)) if 'celery' in sys.argv[0].lower(): # This code is loading in a celery server - Don't start the actual flask app. log.info("Running in a Celery worker - Not starting the Flask app") return # Initialize monitoring, if any is defined monitor_init(app=app, config=conf) if os.path.basename(sys.argv[0]) == 'gunicorn': # Gunicorn takes care of spawning workers log.info("Running in Gunicorn - Not starting the Flask app") return # Debug mode is the default when not running via gunicorn app.debug = self.debug app.run(host='0.0.0.0', port=self.port)
[ "def", "start", "(", "self", ",", "serve", "=", "[", "]", ")", ":", "# Check arguments", "if", "type", "(", "serve", ")", "is", "str", ":", "serve", "=", "[", "serve", "]", "elif", "type", "(", "serve", ")", "is", "list", ":", "pass", "else", ":"...
Load all apis, either as local apis served by the flask app, or as remote apis to be called from whithin the app's endpoints, then start the app server
[ "Load", "all", "apis", "either", "as", "local", "apis", "served", "by", "the", "flask", "app", "or", "as", "remote", "apis", "to", "be", "called", "from", "whithin", "the", "app", "s", "endpoints", "then", "start", "the", "app", "server" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/__init__.py#L177-L279
train
44,851
pymacaron/pymacaron
pymacaron/exceptions.py
add_error
def add_error(name=None, code=None, status=None): """Create a new Exception class""" if not name or not status or not code: raise Exception("Can't create Exception class %s: you must set both name, status and code" % name) myexception = type(name, (PyMacaronException, ), {"code": code, "status": status}) globals()[name] = myexception if code in code_to_class: raise Exception("ERROR! Exception %s is already defined." % code) code_to_class[code] = myexception return myexception
python
def add_error(name=None, code=None, status=None): """Create a new Exception class""" if not name or not status or not code: raise Exception("Can't create Exception class %s: you must set both name, status and code" % name) myexception = type(name, (PyMacaronException, ), {"code": code, "status": status}) globals()[name] = myexception if code in code_to_class: raise Exception("ERROR! Exception %s is already defined." % code) code_to_class[code] = myexception return myexception
[ "def", "add_error", "(", "name", "=", "None", ",", "code", "=", "None", ",", "status", "=", "None", ")", ":", "if", "not", "name", "or", "not", "status", "or", "not", "code", ":", "raise", "Exception", "(", "\"Can't create Exception class %s: you must set bo...
Create a new Exception class
[ "Create", "a", "new", "Exception", "class" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L72-L81
train
44,852
pymacaron/pymacaron
pymacaron/exceptions.py
responsify
def responsify(error): """Take an Error model and return it as a Flask response""" assert str(type(error).__name__) == 'Error' if error.error in code_to_class: e = code_to_class[error.error](error.error_description) if error.error_id: e.error_id = error.error_id if error.user_message: e.user_message = error.user_message return e.http_reply() elif isinstance(error, PyMacaronException): return error.http_reply() else: return PyMacaronException("Caught un-mapped error: %s" % error).http_reply()
python
def responsify(error): """Take an Error model and return it as a Flask response""" assert str(type(error).__name__) == 'Error' if error.error in code_to_class: e = code_to_class[error.error](error.error_description) if error.error_id: e.error_id = error.error_id if error.user_message: e.user_message = error.user_message return e.http_reply() elif isinstance(error, PyMacaronException): return error.http_reply() else: return PyMacaronException("Caught un-mapped error: %s" % error).http_reply()
[ "def", "responsify", "(", "error", ")", ":", "assert", "str", "(", "type", "(", "error", ")", ".", "__name__", ")", "==", "'Error'", "if", "error", ".", "error", "in", "code_to_class", ":", "e", "=", "code_to_class", "[", "error", ".", "error", "]", ...
Take an Error model and return it as a Flask response
[ "Take", "an", "Error", "model", "and", "return", "it", "as", "a", "Flask", "response" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L94-L107
train
44,853
pymacaron/pymacaron
pymacaron/exceptions.py
is_error
def is_error(o): """True if o is an instance of a swagger Error model or a flask Response of an error model""" if hasattr(o, 'error') and hasattr(o, 'error_description') and hasattr(o, 'status'): return True return False
python
def is_error(o): """True if o is an instance of a swagger Error model or a flask Response of an error model""" if hasattr(o, 'error') and hasattr(o, 'error_description') and hasattr(o, 'status'): return True return False
[ "def", "is_error", "(", "o", ")", ":", "if", "hasattr", "(", "o", ",", "'error'", ")", "and", "hasattr", "(", "o", ",", "'error_description'", ")", "and", "hasattr", "(", "o", ",", "'status'", ")", ":", "return", "True", "return", "False" ]
True if o is an instance of a swagger Error model or a flask Response of an error model
[ "True", "if", "o", "is", "an", "instance", "of", "a", "swagger", "Error", "model", "or", "a", "flask", "Response", "of", "an", "error", "model" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L110-L115
train
44,854
pymacaron/pymacaron
pymacaron/exceptions.py
format_error
def format_error(e): """Take an exception caught within pymacaron_core and turn it into a bravado-core Error instance """ if isinstance(e, PyMacaronException): return e.to_model() if isinstance(e, PyMacaronCoreException) and e.__class__.__name__ == 'ValidationError': return ValidationError(str(e)).to_model() # Turn this exception into a PyMacaron Error model return UnhandledServerError(str(e)).to_model()
python
def format_error(e): """Take an exception caught within pymacaron_core and turn it into a bravado-core Error instance """ if isinstance(e, PyMacaronException): return e.to_model() if isinstance(e, PyMacaronCoreException) and e.__class__.__name__ == 'ValidationError': return ValidationError(str(e)).to_model() # Turn this exception into a PyMacaron Error model return UnhandledServerError(str(e)).to_model()
[ "def", "format_error", "(", "e", ")", ":", "if", "isinstance", "(", "e", ",", "PyMacaronException", ")", ":", "return", "e", ".", "to_model", "(", ")", "if", "isinstance", "(", "e", ",", "PyMacaronCoreException", ")", "and", "e", ".", "__class__", ".", ...
Take an exception caught within pymacaron_core and turn it into a bravado-core Error instance
[ "Take", "an", "exception", "caught", "within", "pymacaron_core", "and", "turn", "it", "into", "a", "bravado", "-", "core", "Error", "instance" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L118-L130
train
44,855
pymacaron/pymacaron
pymacaron/exceptions.py
raise_error
def raise_error(e): """Take a bravado-core Error model and raise it as an exception""" code = e.error if code in code_to_class: raise code_to_class[code](e.error_description) else: raise InternalServerError(e.error_description)
python
def raise_error(e): """Take a bravado-core Error model and raise it as an exception""" code = e.error if code in code_to_class: raise code_to_class[code](e.error_description) else: raise InternalServerError(e.error_description)
[ "def", "raise_error", "(", "e", ")", ":", "code", "=", "e", ".", "error", "if", "code", "in", "code_to_class", ":", "raise", "code_to_class", "[", "code", "]", "(", "e", ".", "error_description", ")", "else", ":", "raise", "InternalServerError", "(", "e"...
Take a bravado-core Error model and raise it as an exception
[ "Take", "a", "bravado", "-", "core", "Error", "model", "and", "raise", "it", "as", "an", "exception" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L133-L139
train
44,856
pymacaron/pymacaron
pymacaron/exceptions.py
PyMacaronException.http_reply
def http_reply(self): """Return a Flask reply object describing this error""" data = { 'status': self.status, 'error': self.code.upper(), 'error_description': str(self) } if self.error_caught: data['error_caught'] = pformat(self.error_caught) if self.error_id: data['error_id'] = self.error_id if self.user_message: data['user_message'] = self.user_message r = jsonify(data) r.status_code = self.status if str(self.status) != "200": log.warn("ERROR: caught error %s %s [%s]" % (self.status, self.code, str(self))) return r
python
def http_reply(self): """Return a Flask reply object describing this error""" data = { 'status': self.status, 'error': self.code.upper(), 'error_description': str(self) } if self.error_caught: data['error_caught'] = pformat(self.error_caught) if self.error_id: data['error_id'] = self.error_id if self.user_message: data['user_message'] = self.user_message r = jsonify(data) r.status_code = self.status if str(self.status) != "200": log.warn("ERROR: caught error %s %s [%s]" % (self.status, self.code, str(self))) return r
[ "def", "http_reply", "(", "self", ")", ":", "data", "=", "{", "'status'", ":", "self", ".", "status", ",", "'error'", ":", "self", ".", "code", ".", "upper", "(", ")", ",", "'error_description'", ":", "str", "(", "self", ")", "}", "if", "self", "."...
Return a Flask reply object describing this error
[ "Return", "a", "Flask", "reply", "object", "describing", "this", "error" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L26-L49
train
44,857
pymacaron/pymacaron
pymacaron/exceptions.py
PyMacaronException.to_model
def to_model(self): """Return a bravado-core Error instance""" e = ApiPool().current_server_api.model.Error( status=self.status, error=self.code.upper(), error_description=str(self), ) if self.error_id: e.error_id = self.error_id if self.user_message: e.user_message = self.user_message if self.error_caught: e.error_caught = pformat(self.error_caught) return e
python
def to_model(self): """Return a bravado-core Error instance""" e = ApiPool().current_server_api.model.Error( status=self.status, error=self.code.upper(), error_description=str(self), ) if self.error_id: e.error_id = self.error_id if self.user_message: e.user_message = self.user_message if self.error_caught: e.error_caught = pformat(self.error_caught) return e
[ "def", "to_model", "(", "self", ")", ":", "e", "=", "ApiPool", "(", ")", ".", "current_server_api", ".", "model", ".", "Error", "(", "status", "=", "self", ".", "status", ",", "error", "=", "self", ".", "code", ".", "upper", "(", ")", ",", "error_d...
Return a bravado-core Error instance
[ "Return", "a", "bravado", "-", "core", "Error", "instance" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/exceptions.py#L51-L64
train
44,858
openstack/python-monascaclient
monascaclient/common/monasca_manager.py
MonascaManager._list
def _list(self, path, dim_key=None, **kwargs): """Get a list of metrics.""" url_str = self.base_url + path if dim_key and dim_key in kwargs: dim_str = self.get_dimensions_url_string(kwargs[dim_key]) kwargs[dim_key] = dim_str if kwargs: url_str += '?%s' % parse.urlencode(kwargs, True) body = self.client.list( path=url_str ) return self._parse_body(body)
python
def _list(self, path, dim_key=None, **kwargs): """Get a list of metrics.""" url_str = self.base_url + path if dim_key and dim_key in kwargs: dim_str = self.get_dimensions_url_string(kwargs[dim_key]) kwargs[dim_key] = dim_str if kwargs: url_str += '?%s' % parse.urlencode(kwargs, True) body = self.client.list( path=url_str ) return self._parse_body(body)
[ "def", "_list", "(", "self", ",", "path", ",", "dim_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url_str", "=", "self", ".", "base_url", "+", "path", "if", "dim_key", "and", "dim_key", "in", "kwargs", ":", "dim_str", "=", "self", ".", "ge...
Get a list of metrics.
[ "Get", "a", "list", "of", "metrics", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/common/monasca_manager.py#L37-L51
train
44,859
mdscruggs/ga
ga/examples/irrigation.py
mapstr_to_list
def mapstr_to_list(mapstr): """ Convert an ASCII map string with rows to a list of strings, 1 string per row. """ maplist = [] with StringIO(mapstr) as infile: for row in infile: maplist.append(row.strip()) return maplist
python
def mapstr_to_list(mapstr): """ Convert an ASCII map string with rows to a list of strings, 1 string per row. """ maplist = [] with StringIO(mapstr) as infile: for row in infile: maplist.append(row.strip()) return maplist
[ "def", "mapstr_to_list", "(", "mapstr", ")", ":", "maplist", "=", "[", "]", "with", "StringIO", "(", "mapstr", ")", "as", "infile", ":", "for", "row", "in", "infile", ":", "maplist", ".", "append", "(", "row", ".", "strip", "(", ")", ")", "return", ...
Convert an ASCII map string with rows to a list of strings, 1 string per row.
[ "Convert", "an", "ASCII", "map", "string", "with", "rows", "to", "a", "list", "of", "strings", "1", "string", "per", "row", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L67-L75
train
44,860
mdscruggs/ga
ga/examples/irrigation.py
sprinkler_reaches_cell
def sprinkler_reaches_cell(x, y, sx, sy, r): """ Return whether a cell is within the radius of the sprinkler. x: column index of cell y: row index of cell sx: column index of sprinkler sy: row index of sprinkler r: sprinkler radius """ dx = sx - x dy = sy - y return math.sqrt(dx ** 2 + dy ** 2) <= r
python
def sprinkler_reaches_cell(x, y, sx, sy, r): """ Return whether a cell is within the radius of the sprinkler. x: column index of cell y: row index of cell sx: column index of sprinkler sy: row index of sprinkler r: sprinkler radius """ dx = sx - x dy = sy - y return math.sqrt(dx ** 2 + dy ** 2) <= r
[ "def", "sprinkler_reaches_cell", "(", "x", ",", "y", ",", "sx", ",", "sy", ",", "r", ")", ":", "dx", "=", "sx", "-", "x", "dy", "=", "sy", "-", "y", "return", "math", ".", "sqrt", "(", "dx", "**", "2", "+", "dy", "**", "2", ")", "<=", "r" ]
Return whether a cell is within the radius of the sprinkler. x: column index of cell y: row index of cell sx: column index of sprinkler sy: row index of sprinkler r: sprinkler radius
[ "Return", "whether", "a", "cell", "is", "within", "the", "radius", "of", "the", "sprinkler", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L78-L90
train
44,861
mdscruggs/ga
ga/examples/irrigation.py
IrrigationGA.eval_fitness
def eval_fitness(self, chromosome): """ Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map. """ # convert DNA to represented sprinkler coordinates sx, sy = self.translator.translate_chromosome(chromosome) # check for invalid points penalty = 0 if sx >= self.w: penalty += self.w * self.h if sy >= self.h: penalty += self.w * self.h if penalty > 0: self.fitness_cache[chromosome.dna] = -penalty return -penalty # calculate number of crop cells watered by sprinkler crops_watered = 0 # check bounding box around sprinkler for crop cells # circle guaranteed to be within square with side length 2*r around sprinkler row_start_idx = max(0, sy - self.r) row_end_idx = min(sy + self.r + 1, self.h) col_start_idx = max(0, sx - self.r) col_end_idx = min(sx + self.r + 1, self.w) for y, row in enumerate(self.maplist[row_start_idx:row_end_idx], row_start_idx): for x, cell in enumerate(row[col_start_idx:col_end_idx], col_start_idx): if cell == 'x' and sprinkler_reaches_cell(x, y, sx, sy, self.r): crops_watered += 1 # reduce score by 1 if sprinkler placed on a crop cell if self.maplist[sy][sx] == 'x': crops_watered -= 1 self.fitness_cache[chromosome.dna] = crops_watered return crops_watered
python
def eval_fitness(self, chromosome): """ Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map. """ # convert DNA to represented sprinkler coordinates sx, sy = self.translator.translate_chromosome(chromosome) # check for invalid points penalty = 0 if sx >= self.w: penalty += self.w * self.h if sy >= self.h: penalty += self.w * self.h if penalty > 0: self.fitness_cache[chromosome.dna] = -penalty return -penalty # calculate number of crop cells watered by sprinkler crops_watered = 0 # check bounding box around sprinkler for crop cells # circle guaranteed to be within square with side length 2*r around sprinkler row_start_idx = max(0, sy - self.r) row_end_idx = min(sy + self.r + 1, self.h) col_start_idx = max(0, sx - self.r) col_end_idx = min(sx + self.r + 1, self.w) for y, row in enumerate(self.maplist[row_start_idx:row_end_idx], row_start_idx): for x, cell in enumerate(row[col_start_idx:col_end_idx], col_start_idx): if cell == 'x' and sprinkler_reaches_cell(x, y, sx, sy, self.r): crops_watered += 1 # reduce score by 1 if sprinkler placed on a crop cell if self.maplist[sy][sx] == 'x': crops_watered -= 1 self.fitness_cache[chromosome.dna] = crops_watered return crops_watered
[ "def", "eval_fitness", "(", "self", ",", "chromosome", ")", ":", "# convert DNA to represented sprinkler coordinates", "sx", ",", "sy", "=", "self", ".", "translator", ".", "translate_chromosome", "(", "chromosome", ")", "# check for invalid points", "penalty", "=", "...
Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map.
[ "Return", "the", "number", "of", "plants", "reached", "by", "the", "sprinkler", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L118-L158
train
44,862
mdscruggs/ga
ga/examples/irrigation.py
IrrigationGA.map_sprinkler
def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'): """ Return a version of the ASCII map showing reached crop cells. """ # convert strings (rows) to lists of characters for easier map editing maplist = [list(s) for s in self.maplist] for y, row in enumerate(maplist): for x, cell in enumerate(row): if sprinkler_reaches_cell(x, y, sx, sy, self.r): if cell == 'x': cell = watered_crop else: cell = watered_field else: cell = dry_crop if cell == 'x' else dry_field maplist[y][x] = cell maplist[sy][sx] = 'O' # sprinkler return '\n'.join([''.join(row) for row in maplist])
python
def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'): """ Return a version of the ASCII map showing reached crop cells. """ # convert strings (rows) to lists of characters for easier map editing maplist = [list(s) for s in self.maplist] for y, row in enumerate(maplist): for x, cell in enumerate(row): if sprinkler_reaches_cell(x, y, sx, sy, self.r): if cell == 'x': cell = watered_crop else: cell = watered_field else: cell = dry_crop if cell == 'x' else dry_field maplist[y][x] = cell maplist[sy][sx] = 'O' # sprinkler return '\n'.join([''.join(row) for row in maplist])
[ "def", "map_sprinkler", "(", "self", ",", "sx", ",", "sy", ",", "watered_crop", "=", "'^'", ",", "watered_field", "=", "'_'", ",", "dry_field", "=", "' '", ",", "dry_crop", "=", "'x'", ")", ":", "# convert strings (rows) to lists of characters for easier map editi...
Return a version of the ASCII map showing reached crop cells.
[ "Return", "a", "version", "of", "the", "ASCII", "map", "showing", "reached", "crop", "cells", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L160-L181
train
44,863
brejoc/django-intercoolerjs
demo/counter/views.py
index
def index(request, template_name="index.html"): """\ The index view, which basically just displays a button and increments a counter. """ if request.GET.get('ic-request'): counter, created = Counter.objects.get_or_create(pk=1) counter.value += 1 counter.save() else: counter, created = Counter.objects.get_or_create(pk=1) print(counter.value) context = dict( value=counter.value, ) return render(request, template_name, context=context)
python
def index(request, template_name="index.html"): """\ The index view, which basically just displays a button and increments a counter. """ if request.GET.get('ic-request'): counter, created = Counter.objects.get_or_create(pk=1) counter.value += 1 counter.save() else: counter, created = Counter.objects.get_or_create(pk=1) print(counter.value) context = dict( value=counter.value, ) return render(request, template_name, context=context)
[ "def", "index", "(", "request", ",", "template_name", "=", "\"index.html\"", ")", ":", "if", "request", ".", "GET", ".", "get", "(", "'ic-request'", ")", ":", "counter", ",", "created", "=", "Counter", ".", "objects", ".", "get_or_create", "(", "pk", "="...
\ The index view, which basically just displays a button and increments a counter.
[ "\\", "The", "index", "view", "which", "basically", "just", "displays", "a", "button", "and", "increments", "a", "counter", "." ]
cc92b914204bfcb9eae3dc658e2063dff67636fc
https://github.com/brejoc/django-intercoolerjs/blob/cc92b914204bfcb9eae3dc658e2063dff67636fc/demo/counter/views.py#L6-L21
train
44,864
mdscruggs/ga
ga/algorithms.py
BaseGeneticAlgorithm.get_fitness
def get_fitness(self, chromosome): """ Get the fitness score for a chromosome, using the cached value if available. """ fitness = self.fitness_cache.get(chromosome.dna) if fitness is None: fitness = self.eval_fitness(chromosome) self.fitness_cache[chromosome.dna] = fitness return fitness
python
def get_fitness(self, chromosome): """ Get the fitness score for a chromosome, using the cached value if available. """ fitness = self.fitness_cache.get(chromosome.dna) if fitness is None: fitness = self.eval_fitness(chromosome) self.fitness_cache[chromosome.dna] = fitness return fitness
[ "def", "get_fitness", "(", "self", ",", "chromosome", ")", ":", "fitness", "=", "self", ".", "fitness_cache", ".", "get", "(", "chromosome", ".", "dna", ")", "if", "fitness", "is", "None", ":", "fitness", "=", "self", ".", "eval_fitness", "(", "chromosom...
Get the fitness score for a chromosome, using the cached value if available.
[ "Get", "the", "fitness", "score", "for", "a", "chromosome", "using", "the", "cached", "value", "if", "available", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/algorithms.py#L77-L85
train
44,865
mdscruggs/ga
ga/chromosomes.py
Chromosome.create_random
def create_random(cls, gene_length, n=1, gene_class=BinaryGene): """ Create 1 or more chromosomes with randomly generated DNA. gene_length: int (or sequence of ints) describing gene DNA length n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes return: new chromosome """ assert issubclass(gene_class, BaseGene) chromosomes = [] # when gene_length is scalar, convert to a list to keep subsequent code simple if not hasattr(gene_length, '__iter__'): gene_length = [gene_length] for _ in range(n): genes = [gene_class.create_random(length) for length in gene_length] chromosomes.append(cls(genes)) if n == 1: return chromosomes[0] else: return chromosomes
python
def create_random(cls, gene_length, n=1, gene_class=BinaryGene): """ Create 1 or more chromosomes with randomly generated DNA. gene_length: int (or sequence of ints) describing gene DNA length n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes return: new chromosome """ assert issubclass(gene_class, BaseGene) chromosomes = [] # when gene_length is scalar, convert to a list to keep subsequent code simple if not hasattr(gene_length, '__iter__'): gene_length = [gene_length] for _ in range(n): genes = [gene_class.create_random(length) for length in gene_length] chromosomes.append(cls(genes)) if n == 1: return chromosomes[0] else: return chromosomes
[ "def", "create_random", "(", "cls", ",", "gene_length", ",", "n", "=", "1", ",", "gene_class", "=", "BinaryGene", ")", ":", "assert", "issubclass", "(", "gene_class", ",", "BaseGene", ")", "chromosomes", "=", "[", "]", "# when gene_length is scalar, convert to a...
Create 1 or more chromosomes with randomly generated DNA. gene_length: int (or sequence of ints) describing gene DNA length n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes return: new chromosome
[ "Create", "1", "or", "more", "chromosomes", "with", "randomly", "generated", "DNA", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L12-L36
train
44,866
mdscruggs/ga
ga/chromosomes.py
Chromosome.copy
def copy(self): """ Return a new instance of this chromosome by copying its genes. """ genes = [g.copy() for g in self.genes] return type(self)(genes)
python
def copy(self): """ Return a new instance of this chromosome by copying its genes. """ genes = [g.copy() for g in self.genes] return type(self)(genes)
[ "def", "copy", "(", "self", ")", ":", "genes", "=", "[", "g", ".", "copy", "(", ")", "for", "g", "in", "self", ".", "genes", "]", "return", "type", "(", "self", ")", "(", "genes", ")" ]
Return a new instance of this chromosome by copying its genes.
[ "Return", "a", "new", "instance", "of", "this", "chromosome", "by", "copying", "its", "genes", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L127-L130
train
44,867
mdscruggs/ga
ga/chromosomes.py
ReorderingSetChromosome.check_genes
def check_genes(self): """ Assert that every DNA choice is represented by exactly one gene. """ gene_dna_set = set([g.dna for g in self.genes]) assert gene_dna_set == self.dna_choices_set
python
def check_genes(self): """ Assert that every DNA choice is represented by exactly one gene. """ gene_dna_set = set([g.dna for g in self.genes]) assert gene_dna_set == self.dna_choices_set
[ "def", "check_genes", "(", "self", ")", ":", "gene_dna_set", "=", "set", "(", "[", "g", ".", "dna", "for", "g", "in", "self", ".", "genes", "]", ")", "assert", "gene_dna_set", "==", "self", ".", "dna_choices_set" ]
Assert that every DNA choice is represented by exactly one gene.
[ "Assert", "that", "every", "DNA", "choice", "is", "represented", "by", "exactly", "one", "gene", "." ]
adac7a004e5e22d888e44ab39f313064c3803b38
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L160-L163
train
44,868
pymacaron/pymacaron
pymacaron/crash.py
populate_error_report
def populate_error_report(data): """Add generic stats to the error report""" # Did pymacaron_core set a call_id and call_path? call_id, call_path = '', '' if hasattr(stack.top, 'call_id'): call_id = stack.top.call_id if hasattr(stack.top, 'call_path'): call_path = stack.top.call_path # Unique ID associated to all responses associated to a given # call to apis, across all micro-services data['call_id'] = call_id data['call_path'] = call_path # Are we in aws? data['is_ec2_instance'] = is_ec2_instance() # If user is authenticated, get her id user_data = { 'id': '', 'is_auth': 0, 'ip': '', } if stack.top: # We are in a request context user_data['ip'] = request.remote_addr if 'X-Forwarded-For' in request.headers: user_data['forwarded_ip'] = request.headers.get('X-Forwarded-For', '') if 'User-Agent' in request.headers: user_data['user_agent'] = request.headers.get('User-Agent', '') if hasattr(stack.top, 'current_user'): user_data['is_auth'] = 1 user_data['id'] = stack.top.current_user.get('sub', '') for k in ('name', 'email', 'is_expert', 'is_admin', 'is_support', 'is_tester', 'language'): v = stack.top.current_user.get(k, None) if v: user_data[k] = v data['user'] = user_data # Is the current code running as a server? if ApiPool().current_server_api: # Server info server = request.base_url server = server.replace('http://', '') server = server.replace('https://', '') server = server.split('/')[0] parts = server.split(':') fqdn = parts[0] port = parts[1] if len(parts) == 2 else '' data['server'] = { 'fqdn': fqdn, 'port': port, 'api_name': ApiPool().current_server_name, 'api_version': ApiPool().current_server_api.get_version(), } # Endpoint data data['endpoint'] = { 'id': "%s %s %s" % (ApiPool().current_server_name, request.method, request.path), 'url': request.url, 'base_url': request.base_url, 'path': request.path, 'method': request.method }
python
def populate_error_report(data): """Add generic stats to the error report""" # Did pymacaron_core set a call_id and call_path? call_id, call_path = '', '' if hasattr(stack.top, 'call_id'): call_id = stack.top.call_id if hasattr(stack.top, 'call_path'): call_path = stack.top.call_path # Unique ID associated to all responses associated to a given # call to apis, across all micro-services data['call_id'] = call_id data['call_path'] = call_path # Are we in aws? data['is_ec2_instance'] = is_ec2_instance() # If user is authenticated, get her id user_data = { 'id': '', 'is_auth': 0, 'ip': '', } if stack.top: # We are in a request context user_data['ip'] = request.remote_addr if 'X-Forwarded-For' in request.headers: user_data['forwarded_ip'] = request.headers.get('X-Forwarded-For', '') if 'User-Agent' in request.headers: user_data['user_agent'] = request.headers.get('User-Agent', '') if hasattr(stack.top, 'current_user'): user_data['is_auth'] = 1 user_data['id'] = stack.top.current_user.get('sub', '') for k in ('name', 'email', 'is_expert', 'is_admin', 'is_support', 'is_tester', 'language'): v = stack.top.current_user.get(k, None) if v: user_data[k] = v data['user'] = user_data # Is the current code running as a server? if ApiPool().current_server_api: # Server info server = request.base_url server = server.replace('http://', '') server = server.replace('https://', '') server = server.split('/')[0] parts = server.split(':') fqdn = parts[0] port = parts[1] if len(parts) == 2 else '' data['server'] = { 'fqdn': fqdn, 'port': port, 'api_name': ApiPool().current_server_name, 'api_version': ApiPool().current_server_api.get_version(), } # Endpoint data data['endpoint'] = { 'id': "%s %s %s" % (ApiPool().current_server_name, request.method, request.path), 'url': request.url, 'base_url': request.base_url, 'path': request.path, 'method': request.method }
[ "def", "populate_error_report", "(", "data", ")", ":", "# Did pymacaron_core set a call_id and call_path?", "call_id", ",", "call_path", "=", "''", ",", "''", "if", "hasattr", "(", "stack", ".", "top", ",", "'call_id'", ")", ":", "call_id", "=", "stack", ".", ...
Add generic stats to the error report
[ "Add", "generic", "stats", "to", "the", "error", "report" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/crash.py#L126-L196
train
44,869
openstack/python-monascaclient
monascaclient/v2_0/metrics.py
MetricsManager.create
def create(self, **kwargs): """Create a metric.""" url_str = self.base_url if 'tenant_id' in kwargs: url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id'] del kwargs['tenant_id'] data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs body = self.client.create(url=url_str, json=data) return body
python
def create(self, **kwargs): """Create a metric.""" url_str = self.base_url if 'tenant_id' in kwargs: url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id'] del kwargs['tenant_id'] data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs body = self.client.create(url=url_str, json=data) return body
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url_str", "=", "self", ".", "base_url", "if", "'tenant_id'", "in", "kwargs", ":", "url_str", "=", "url_str", "+", "'?tenant_id=%s'", "%", "kwargs", "[", "'tenant_id'", "]", "del", "kwargs"...
Create a metric.
[ "Create", "a", "metric", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/metrics.py#L23-L32
train
44,870
tristantao/py-ms-cognitive
py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py
PyMsCognitiveSearch.get_json_results
def get_json_results(self, response): ''' Parses the request result and returns the JSON object. Handles all errors. ''' try: # return the proper JSON object, or error code if request didn't go through. self.most_recent_json = response.json() json_results = response.json() if response.status_code in [401, 403]: #401 is invalid key, 403 is out of monthly quota. raise PyMsCognitiveWebSearchException("CODE {code}: {message}".format(code=response.status_code,message=json_results["message"]) ) elif response.status_code in [429]: #429 means try again in x seconds. message = json_results['message'] try: # extract time out seconds from response timeout = int(re.search('in (.+?) seconds', message).group(1)) + 1 print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout)) time.sleep(timeout) except (AttributeError, ValueError) as e: if not self.silent_fail: raise PyMsCognitiveWebSearchException("CODE 429. Failed to auto-sleep: {message}".format(code=response.status_code,message=json_results["message"]) ) else: print ("CODE 429. Failed to auto-sleep: {message}. Trying again in 5 seconds.".format(code=response.status_code,message=json_results["message"])) time.sleep(5) except ValueError as vE: if not self.silent_fail: raise PyMsCognitiveWebSearchException("Request returned with code %s, error msg: %s" % (r.status_code, r.text)) else: print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text)) time.sleep(5) return json_results
python
def get_json_results(self, response): ''' Parses the request result and returns the JSON object. Handles all errors. ''' try: # return the proper JSON object, or error code if request didn't go through. self.most_recent_json = response.json() json_results = response.json() if response.status_code in [401, 403]: #401 is invalid key, 403 is out of monthly quota. raise PyMsCognitiveWebSearchException("CODE {code}: {message}".format(code=response.status_code,message=json_results["message"]) ) elif response.status_code in [429]: #429 means try again in x seconds. message = json_results['message'] try: # extract time out seconds from response timeout = int(re.search('in (.+?) seconds', message).group(1)) + 1 print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout)) time.sleep(timeout) except (AttributeError, ValueError) as e: if not self.silent_fail: raise PyMsCognitiveWebSearchException("CODE 429. Failed to auto-sleep: {message}".format(code=response.status_code,message=json_results["message"]) ) else: print ("CODE 429. Failed to auto-sleep: {message}. Trying again in 5 seconds.".format(code=response.status_code,message=json_results["message"])) time.sleep(5) except ValueError as vE: if not self.silent_fail: raise PyMsCognitiveWebSearchException("Request returned with code %s, error msg: %s" % (r.status_code, r.text)) else: print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text)) time.sleep(5) return json_results
[ "def", "get_json_results", "(", "self", ",", "response", ")", ":", "try", ":", "# return the proper JSON object, or error code if request didn't go through.", "self", ".", "most_recent_json", "=", "response", ".", "json", "(", ")", "json_results", "=", "response", ".", ...
Parses the request result and returns the JSON object. Handles all errors.
[ "Parses", "the", "request", "result", "and", "returns", "the", "JSON", "object", ".", "Handles", "all", "errors", "." ]
8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7
https://github.com/tristantao/py-ms-cognitive/blob/8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7/py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py#L38-L67
train
44,871
tristantao/py-ms-cognitive
py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py
PyMsCognitiveSearch.search_all
def search_all(self, quota=50, format='json'): ''' Returns a single list containing up to 'limit' Result objects Will keep requesting until quota is met Will also truncate extra results to return exactly the given quota ''' quota_left = quota results = [] while quota_left > 0: more_results = self._search(quota_left, format) if not more_results: break results += more_results quota_left = quota_left - len(more_results) time.sleep(1) results = results[0:quota] return results
python
def search_all(self, quota=50, format='json'): ''' Returns a single list containing up to 'limit' Result objects Will keep requesting until quota is met Will also truncate extra results to return exactly the given quota ''' quota_left = quota results = [] while quota_left > 0: more_results = self._search(quota_left, format) if not more_results: break results += more_results quota_left = quota_left - len(more_results) time.sleep(1) results = results[0:quota] return results
[ "def", "search_all", "(", "self", ",", "quota", "=", "50", ",", "format", "=", "'json'", ")", ":", "quota_left", "=", "quota", "results", "=", "[", "]", "while", "quota_left", ">", "0", ":", "more_results", "=", "self", ".", "_search", "(", "quota_left...
Returns a single list containing up to 'limit' Result objects Will keep requesting until quota is met Will also truncate extra results to return exactly the given quota
[ "Returns", "a", "single", "list", "containing", "up", "to", "limit", "Result", "objects", "Will", "keep", "requesting", "until", "quota", "is", "met", "Will", "also", "truncate", "extra", "results", "to", "return", "exactly", "the", "given", "quota" ]
8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7
https://github.com/tristantao/py-ms-cognitive/blob/8f4b10df1b4bf1f2c9af64218cfcdc35176b75e7/py_ms_cognitive/py_ms_cognitive_search/py_ms_cognitive_search.py#L73-L89
train
44,872
openstack/python-monascaclient
monascaclient/common/utils.py
format_parameters
def format_parameters(params): '''Reformat parameters into dict of format expected by the API.''' if not params: return {} # expect multiple invocations of --parameters but fall back # to ; delimited if only one --parameters is specified if len(params) == 1: if params[0].find(';') != -1: # found params = params[0].split(';') else: params = params[0].split(',') parameters = {} for p in params: try: (n, v) = p.split('=', 1) except ValueError: msg = '%s(%s). %s.' % ('Malformed parameter', p, 'Use the key=value format') raise exc.CommandError(msg) if n not in parameters: parameters[n] = v else: if not isinstance(parameters[n], list): parameters[n] = [parameters[n]] parameters[n].append(v) return parameters
python
def format_parameters(params): '''Reformat parameters into dict of format expected by the API.''' if not params: return {} # expect multiple invocations of --parameters but fall back # to ; delimited if only one --parameters is specified if len(params) == 1: if params[0].find(';') != -1: # found params = params[0].split(';') else: params = params[0].split(',') parameters = {} for p in params: try: (n, v) = p.split('=', 1) except ValueError: msg = '%s(%s). %s.' % ('Malformed parameter', p, 'Use the key=value format') raise exc.CommandError(msg) if n not in parameters: parameters[n] = v else: if not isinstance(parameters[n], list): parameters[n] = [parameters[n]] parameters[n].append(v) return parameters
[ "def", "format_parameters", "(", "params", ")", ":", "if", "not", "params", ":", "return", "{", "}", "# expect multiple invocations of --parameters but fall back", "# to ; delimited if only one --parameters is specified", "if", "len", "(", "params", ")", "==", "1", ":", ...
Reformat parameters into dict of format expected by the API.
[ "Reformat", "parameters", "into", "dict", "of", "format", "expected", "by", "the", "API", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/common/utils.py#L91-L121
train
44,873
openstack/python-monascaclient
monascaclient/v2_0/alarms.py
AlarmsManager.delete
def delete(self, **kwargs): """Delete a specific alarm.""" url_str = self.base_url + '/%s' % kwargs['alarm_id'] resp = self.client.delete(url_str) return resp
python
def delete(self, **kwargs): """Delete a specific alarm.""" url_str = self.base_url + '/%s' % kwargs['alarm_id'] resp = self.client.delete(url_str) return resp
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url_str", "=", "self", ".", "base_url", "+", "'/%s'", "%", "kwargs", "[", "'alarm_id'", "]", "resp", "=", "self", ".", "client", ".", "delete", "(", "url_str", ")", "return", "resp" ]
Delete a specific alarm.
[ "Delete", "a", "specific", "alarm", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarms.py#L39-L43
train
44,874
openstack/python-monascaclient
monascaclient/v2_0/alarms.py
AlarmsManager.history
def history(self, **kwargs): """History of a specific alarm.""" url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id'] del kwargs['alarm_id'] if kwargs: url_str = url_str + '?%s' % parse.urlencode(kwargs, True) resp = self.client.list(url_str) return resp['elements'] if type(resp) is dict else resp
python
def history(self, **kwargs): """History of a specific alarm.""" url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id'] del kwargs['alarm_id'] if kwargs: url_str = url_str + '?%s' % parse.urlencode(kwargs, True) resp = self.client.list(url_str) return resp['elements'] if type(resp) is dict else resp
[ "def", "history", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url_str", "=", "self", ".", "base_url", "+", "'/%s/state-history'", "%", "kwargs", "[", "'alarm_id'", "]", "del", "kwargs", "[", "'alarm_id'", "]", "if", "kwargs", ":", "url_str", "=", ...
History of a specific alarm.
[ "History", "of", "a", "specific", "alarm", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarms.py#L79-L86
train
44,875
openstack/python-monascaclient
monascaclient/v2_0/alarms.py
AlarmsManager.history_list
def history_list(self, **kwargs): """History list of alarm state.""" url_str = self.base_url + '/state-history/' if 'dimensions' in kwargs: dimstr = self.get_dimensions_url_string(kwargs['dimensions']) kwargs['dimensions'] = dimstr if kwargs: url_str = url_str + '?%s' % parse.urlencode(kwargs, True) resp = self.client.list(url_str) return resp['elements'] if type(resp) is dict else resp
python
def history_list(self, **kwargs): """History list of alarm state.""" url_str = self.base_url + '/state-history/' if 'dimensions' in kwargs: dimstr = self.get_dimensions_url_string(kwargs['dimensions']) kwargs['dimensions'] = dimstr if kwargs: url_str = url_str + '?%s' % parse.urlencode(kwargs, True) resp = self.client.list(url_str) return resp['elements'] if type(resp) is dict else resp
[ "def", "history_list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url_str", "=", "self", ".", "base_url", "+", "'/state-history/'", "if", "'dimensions'", "in", "kwargs", ":", "dimstr", "=", "self", ".", "get_dimensions_url_string", "(", "kwargs", "[", ...
History list of alarm state.
[ "History", "list", "of", "alarm", "state", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarms.py#L88-L97
train
44,876
pymacaron/pymacaron
pymacaron/api.py
do_version
def do_version(): """Return version details of the running server api""" v = ApiPool.ping.model.Version( name=ApiPool().current_server_name, version=ApiPool().current_server_api.get_version(), container=get_container_version(), ) log.info("/version: " + pprint.pformat(v)) return v
python
def do_version(): """Return version details of the running server api""" v = ApiPool.ping.model.Version( name=ApiPool().current_server_name, version=ApiPool().current_server_api.get_version(), container=get_container_version(), ) log.info("/version: " + pprint.pformat(v)) return v
[ "def", "do_version", "(", ")", ":", "v", "=", "ApiPool", ".", "ping", ".", "model", ".", "Version", "(", "name", "=", "ApiPool", "(", ")", ".", "current_server_name", ",", "version", "=", "ApiPool", "(", ")", ".", "current_server_api", ".", "get_version"...
Return version details of the running server api
[ "Return", "version", "details", "of", "the", "running", "server", "api" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/api.py#L27-L35
train
44,877
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_metric_create
def do_metric_create(mc, args): '''Create metric.''' fields = {} fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) fields['timestamp'] = args.time fields['value'] = args.value if args.value_meta: fields['value_meta'] = utils.format_parameters(args.value_meta) if args.project_id: fields['tenant_id'] = args.project_id try: mc.metrics.create(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully created metric')
python
def do_metric_create(mc, args): '''Create metric.''' fields = {} fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) fields['timestamp'] = args.time fields['value'] = args.value if args.value_meta: fields['value_meta'] = utils.format_parameters(args.value_meta) if args.project_id: fields['tenant_id'] = args.project_id try: mc.metrics.create(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully created metric')
[ "def", "do_metric_create", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'name'", "]", "=", "args", ".", "name", "if", "args", ".", "dimensions", ":", "fields", "[", "'dimensions'", "]", "=", "utils", ".", "format_parameter...
Create metric.
[ "Create", "metric", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L72-L89
train
44,878
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_metric_create_raw
def do_metric_create_raw(mc, args): '''Create metric from raw json body.''' try: mc.metrics.create(**args.jsonbody) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully created metric')
python
def do_metric_create_raw(mc, args): '''Create metric from raw json body.''' try: mc.metrics.create(**args.jsonbody) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully created metric')
[ "def", "do_metric_create_raw", "(", "mc", ",", "args", ")", ":", "try", ":", "mc", ".", "metrics", ".", "create", "(", "*", "*", "args", ".", "jsonbody", ")", "except", "(", "osc_exc", ".", "ClientException", ",", "k_exc", ".", "HttpError", ")", "as", ...
Create metric from raw json body.
[ "Create", "metric", "from", "raw", "json", "body", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L95-L102
train
44,879
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_metric_name_list
def do_metric_name_list(mc, args): '''List names of metrics.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.tenant_id: fields['tenant_id'] = args.tenant_id try: metric_names = mc.metrics.list_names(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(metric_names)) return if isinstance(metric_names, list): utils.print_list(metric_names, ['Name'], formatters={'Name': lambda x: x['name']})
python
def do_metric_name_list(mc, args): '''List names of metrics.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.tenant_id: fields['tenant_id'] = args.tenant_id try: metric_names = mc.metrics.list_names(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(metric_names)) return if isinstance(metric_names, list): utils.print_list(metric_names, ['Name'], formatters={'Name': lambda x: x['name']})
[ "def", "do_metric_name_list", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "if", "args", ".", "dimensions", ":", "fields", "[", "'dimensions'", "]", "=", "utils", ".", "format_dimensions_query", "(", "args", ".", "dimensions", ")", "if", "a...
List names of metrics.
[ "List", "names", "of", "metrics", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L119-L140
train
44,880
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_metric_list
def do_metric_list(mc, args): '''List metrics for this tenant.''' fields = {} if args.name: fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.starttime: _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: fields['end_time'] = args.endtime if args.tenant_id: fields['tenant_id'] = args.tenant_id try: metric = mc.metrics.list(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(metric)) return cols = ['name', 'dimensions'] formatters = { 'name': lambda x: x['name'], 'dimensions': lambda x: utils.format_dict(x['dimensions']), } if isinstance(metric, list): # print the list utils.print_list(metric, cols, formatters=formatters) else: # add the dictionary to a list, so print_list works metric_list = list() metric_list.append(metric) utils.print_list( metric_list, cols, formatters=formatters)
python
def do_metric_list(mc, args): '''List metrics for this tenant.''' fields = {} if args.name: fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.starttime: _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: fields['end_time'] = args.endtime if args.tenant_id: fields['tenant_id'] = args.tenant_id try: metric = mc.metrics.list(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(metric)) return cols = ['name', 'dimensions'] formatters = { 'name': lambda x: x['name'], 'dimensions': lambda x: utils.format_dict(x['dimensions']), } if isinstance(metric, list): # print the list utils.print_list(metric, cols, formatters=formatters) else: # add the dictionary to a list, so print_list works metric_list = list() metric_list.append(metric) utils.print_list( metric_list, cols, formatters=formatters)
[ "def", "do_metric_list", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "if", "args", ".", "name", ":", "fields", "[", "'name'", "]", "=", "args", ".", "name", "if", "args", ".", "dimensions", ":", "fields", "[", "'dimensions'", "]", "=...
List metrics for this tenant.
[ "List", "metrics", "for", "this", "tenant", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L164-L206
train
44,881
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_metric_statistics
def do_metric_statistics(mc, args): '''List measurement statistics for the specified metric.''' statistic_types = ['AVG', 'MIN', 'MAX', 'COUNT', 'SUM'] statlist = args.statistics.split(',') for stat in statlist: if stat.upper() not in statistic_types: errmsg = ('Invalid type, not one of [' + ', '.join(statistic_types) + ']') raise osc_exc.CommandError(errmsg) fields = {} fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: fields['end_time'] = args.endtime if args.period: fields['period'] = args.period fields['statistics'] = args.statistics if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.merge_metrics: fields['merge_metrics'] = args.merge_metrics if args.group_by: fields['group_by'] = args.group_by if args.tenant_id: fields['tenant_id'] = args.tenant_id try: metric = mc.metrics.list_statistics(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(metric)) return cols = ['name', 'dimensions'] # add dynamic column names if metric: column_names = metric[0]['columns'] for name in column_names: cols.append(name) else: # when empty set, print_list needs a col cols.append('timestamp') formatters = { 'name': lambda x: x['name'], 'dimensions': lambda x: utils.format_dict(x['dimensions']), 'timestamp': lambda x: format_statistic_timestamp(x['statistics'], x['columns'], 'timestamp'), 'avg': lambda x: format_statistic_value(x['statistics'], x['columns'], 'avg'), 'min': lambda x: format_statistic_value(x['statistics'], x['columns'], 'min'), 'max': lambda x: format_statistic_value(x['statistics'], x['columns'], 'max'), 'count': lambda x: format_statistic_value(x['statistics'], x['columns'], 'count'), 'sum': lambda x: format_statistic_value(x['statistics'], x['columns'], 'sum'), } if isinstance(metric, list): # print the list utils.print_list(metric, cols, formatters=formatters) else: # add the dictionary to a list, so print_list works metric_list = list() metric_list.append(metric) utils.print_list( metric_list, cols, formatters=formatters)
python
def do_metric_statistics(mc, args): '''List measurement statistics for the specified metric.''' statistic_types = ['AVG', 'MIN', 'MAX', 'COUNT', 'SUM'] statlist = args.statistics.split(',') for stat in statlist: if stat.upper() not in statistic_types: errmsg = ('Invalid type, not one of [' + ', '.join(statistic_types) + ']') raise osc_exc.CommandError(errmsg) fields = {} fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: fields['end_time'] = args.endtime if args.period: fields['period'] = args.period fields['statistics'] = args.statistics if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.merge_metrics: fields['merge_metrics'] = args.merge_metrics if args.group_by: fields['group_by'] = args.group_by if args.tenant_id: fields['tenant_id'] = args.tenant_id try: metric = mc.metrics.list_statistics(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(metric)) return cols = ['name', 'dimensions'] # add dynamic column names if metric: column_names = metric[0]['columns'] for name in column_names: cols.append(name) else: # when empty set, print_list needs a col cols.append('timestamp') formatters = { 'name': lambda x: x['name'], 'dimensions': lambda x: utils.format_dict(x['dimensions']), 'timestamp': lambda x: format_statistic_timestamp(x['statistics'], x['columns'], 'timestamp'), 'avg': lambda x: format_statistic_value(x['statistics'], x['columns'], 'avg'), 'min': lambda x: format_statistic_value(x['statistics'], x['columns'], 'min'), 'max': lambda x: format_statistic_value(x['statistics'], x['columns'], 'max'), 'count': lambda x: format_statistic_value(x['statistics'], x['columns'], 'count'), 'sum': lambda x: format_statistic_value(x['statistics'], x['columns'], 'sum'), } if isinstance(metric, list): # print the list utils.print_list(metric, cols, formatters=formatters) else: # add the dictionary to a list, so print_list works metric_list = list() metric_list.append(metric) utils.print_list( metric_list, cols, formatters=formatters)
[ "def", "do_metric_statistics", "(", "mc", ",", "args", ")", ":", "statistic_types", "=", "[", "'AVG'", ",", "'MIN'", ",", "'MAX'", ",", "'COUNT'", ",", "'SUM'", "]", "statlist", "=", "args", ".", "statistics", ".", "split", "(", "','", ")", "for", "sta...
List measurement statistics for the specified metric.
[ "List", "measurement", "statistics", "for", "the", "specified", "metric", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L477-L554
train
44,882
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_notification_show
def do_notification_show(mc, args): '''Describe the notification.''' fields = {} fields['notification_id'] = args.id try: notification = mc.notifications.get(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(notification)) return formatters = { 'name': utils.json_formatter, 'id': utils.json_formatter, 'type': utils.json_formatter, 'address': utils.json_formatter, 'period': utils.json_formatter, 'links': utils.format_dictlist, } utils.print_dict(notification, formatters=formatters)
python
def do_notification_show(mc, args): '''Describe the notification.''' fields = {} fields['notification_id'] = args.id try: notification = mc.notifications.get(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(notification)) return formatters = { 'name': utils.json_formatter, 'id': utils.json_formatter, 'type': utils.json_formatter, 'address': utils.json_formatter, 'period': utils.json_formatter, 'links': utils.format_dictlist, } utils.print_dict(notification, formatters=formatters)
[ "def", "do_notification_show", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'notification_id'", "]", "=", "args", ".", "id", "try", ":", "notification", "=", "mc", ".", "notifications", ".", "get", "(", "*", "*", "fields",...
Describe the notification.
[ "Describe", "the", "notification", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L593-L613
train
44,883
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_notification_list
def do_notification_list(mc, args): '''List notifications for this tenant.''' fields = {} if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.sort_by: sort_by = args.sort_by.split(',') for field in sort_by: field_values = field.lower().split() if len(field_values) > 2: print("Invalid sort_by value {}".format(field)) if field_values[0] not in allowed_notification_sort_by: print("Sort-by field name {} is not in [{}]".format(field_values[0], allowed_notification_sort_by)) return if len(field_values) > 1 and field_values[1] not in ['asc', 'desc']: print("Invalid value {}, must be asc or desc".format(field_values[1])) fields['sort_by'] = args.sort_by try: notification = mc.notifications.list(**fields) except osc_exc.ClientException as he: raise osc_exc.CommandError( 'ClientException code=%s message=%s' % (he.code, he.message)) else: if args.json: print(utils.json_formatter(notification)) return cols = ['name', 'id', 'type', 'address', 'period'] formatters = { 'name': lambda x: x['name'], 'id': lambda x: x['id'], 'type': lambda x: x['type'], 'address': lambda x: x['address'], 'period': lambda x: x['period'], } if isinstance(notification, list): utils.print_list( notification, cols, formatters=formatters) else: notif_list = list() notif_list.append(notification) utils.print_list(notif_list, cols, formatters=formatters)
python
def do_notification_list(mc, args): '''List notifications for this tenant.''' fields = {} if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.sort_by: sort_by = args.sort_by.split(',') for field in sort_by: field_values = field.lower().split() if len(field_values) > 2: print("Invalid sort_by value {}".format(field)) if field_values[0] not in allowed_notification_sort_by: print("Sort-by field name {} is not in [{}]".format(field_values[0], allowed_notification_sort_by)) return if len(field_values) > 1 and field_values[1] not in ['asc', 'desc']: print("Invalid value {}, must be asc or desc".format(field_values[1])) fields['sort_by'] = args.sort_by try: notification = mc.notifications.list(**fields) except osc_exc.ClientException as he: raise osc_exc.CommandError( 'ClientException code=%s message=%s' % (he.code, he.message)) else: if args.json: print(utils.json_formatter(notification)) return cols = ['name', 'id', 'type', 'address', 'period'] formatters = { 'name': lambda x: x['name'], 'id': lambda x: x['id'], 'type': lambda x: x['type'], 'address': lambda x: x['address'], 'period': lambda x: x['period'], } if isinstance(notification, list): utils.print_list( notification, cols, formatters=formatters) else: notif_list = list() notif_list.append(notification) utils.print_list(notif_list, cols, formatters=formatters)
[ "def", "do_notification_list", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "if", "args", ".", "limit", ":", "fields", "[", "'limit'", "]", "=", "args", ".", "limit", "if", "args", ".", "offset", ":", "fields", "[", "'offset'", "]", "...
List notifications for this tenant.
[ "List", "notifications", "for", "this", "tenant", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L625-L673
train
44,884
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_notification_delete
def do_notification_delete(mc, args): '''Delete notification.''' fields = {} fields['notification_id'] = args.id try: mc.notifications.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully deleted notification')
python
def do_notification_delete(mc, args): '''Delete notification.''' fields = {} fields['notification_id'] = args.id try: mc.notifications.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully deleted notification')
[ "def", "do_notification_delete", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'notification_id'", "]", "=", "args", ".", "id", "try", ":", "mc", ".", "notifications", ".", "delete", "(", "*", "*", "fields", ")", "except", ...
Delete notification.
[ "Delete", "notification", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L678-L687
train
44,885
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_notification_update
def do_notification_update(mc, args): '''Update notification.''' fields = {} fields['notification_id'] = args.id fields['name'] = args.name fields['type'] = args.type fields['address'] = args.address if not _validate_notification_period(args.period, args.type.upper()): return fields['period'] = args.period try: notification = mc.notifications.update(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(notification, indent=2))
python
def do_notification_update(mc, args): '''Update notification.''' fields = {} fields['notification_id'] = args.id fields['name'] = args.name fields['type'] = args.type fields['address'] = args.address if not _validate_notification_period(args.period, args.type.upper()): return fields['period'] = args.period try: notification = mc.notifications.update(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(notification, indent=2))
[ "def", "do_notification_update", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'notification_id'", "]", "=", "args", ".", "id", "fields", "[", "'name'", "]", "=", "args", ".", "name", "fields", "[", "'type'", "]", "=", "a...
Update notification.
[ "Update", "notification", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L700-L716
train
44,886
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_definition_list
def do_alarm_definition_list(mc, args): '''List alarm definitions for this tenant.''' fields = {} if args.name: fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.severity: if not _validate_severity(args.severity): return fields['severity'] = args.severity if args.sort_by: sort_by = args.sort_by.split(',') for field in sort_by: field_values = field.split() if len(field_values) > 2: print("Invalid sort_by value {}".format(field)) if field_values[0] not in allowed_definition_sort_by: print("Sort-by field name {} is not in [{}]".format(field_values[0], allowed_definition_sort_by)) return if len(field_values) > 1 and field_values[1] not in ['asc', 'desc']: print("Invalid value {}, must be asc or desc".format(field_values[1])) fields['sort_by'] = args.sort_by if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarm_definitions.list(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(alarm)) return cols = ['name', 'id', 'expression', 'match_by', 'actions_enabled'] formatters = { 'name': lambda x: x['name'], 'id': lambda x: x['id'], 'expression': lambda x: x['expression'], 'match_by': lambda x: utils.format_list(x['match_by']), 'actions_enabled': lambda x: x['actions_enabled'], } if isinstance(alarm, list): # print the list utils.print_list(alarm, cols, formatters=formatters) else: # add the dictionary to a list, so print_list works alarm_list = list() alarm_list.append(alarm) utils.print_list(alarm_list, cols, formatters=formatters)
python
def do_alarm_definition_list(mc, args): '''List alarm definitions for this tenant.''' fields = {} if args.name: fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.severity: if not _validate_severity(args.severity): return fields['severity'] = args.severity if args.sort_by: sort_by = args.sort_by.split(',') for field in sort_by: field_values = field.split() if len(field_values) > 2: print("Invalid sort_by value {}".format(field)) if field_values[0] not in allowed_definition_sort_by: print("Sort-by field name {} is not in [{}]".format(field_values[0], allowed_definition_sort_by)) return if len(field_values) > 1 and field_values[1] not in ['asc', 'desc']: print("Invalid value {}, must be asc or desc".format(field_values[1])) fields['sort_by'] = args.sort_by if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarm_definitions.list(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(alarm)) return cols = ['name', 'id', 'expression', 'match_by', 'actions_enabled'] formatters = { 'name': lambda x: x['name'], 'id': lambda x: x['id'], 'expression': lambda x: x['expression'], 'match_by': lambda x: utils.format_list(x['match_by']), 'actions_enabled': lambda x: x['actions_enabled'], } if isinstance(alarm, list): # print the list utils.print_list(alarm, cols, formatters=formatters) else: # add the dictionary to a list, so print_list works alarm_list = list() alarm_list.append(alarm) utils.print_list(alarm_list, cols, formatters=formatters)
[ "def", "do_alarm_definition_list", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "if", "args", ".", "name", ":", "fields", "[", "'name'", "]", "=", "args", ".", "name", "if", "args", ".", "dimensions", ":", "fields", "[", "'dimensions'", ...
List alarm definitions for this tenant.
[ "List", "alarm", "definitions", "for", "this", "tenant", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L867-L918
train
44,887
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_definition_delete
def do_alarm_definition_delete(mc, args): '''Delete the alarm definition.''' fields = {} fields['alarm_id'] = args.id try: mc.alarm_definitions.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully deleted alarm definition')
python
def do_alarm_definition_delete(mc, args): '''Delete the alarm definition.''' fields = {} fields['alarm_id'] = args.id try: mc.alarm_definitions.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully deleted alarm definition')
[ "def", "do_alarm_definition_delete", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "try", ":", "mc", ".", "alarm_definitions", ".", "delete", "(", "*", "*", "fields", ")", "except",...
Delete the alarm definition.
[ "Delete", "the", "alarm", "definition", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L923-L932
train
44,888
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_definition_update
def do_alarm_definition_update(mc, args): '''Update the alarm definition.''' fields = {} fields['alarm_id'] = args.id fields['name'] = args.name fields['description'] = args.description fields['expression'] = args.expression fields['alarm_actions'] = _arg_split_patch_update(args.alarm_actions) fields['ok_actions'] = _arg_split_patch_update(args.ok_actions) fields['undetermined_actions'] = _arg_split_patch_update(args.undetermined_actions) if args.actions_enabled not in enabled_types: errmsg = ('Invalid value, not one of [' + ', '.join(enabled_types) + ']') print(errmsg) return fields['actions_enabled'] = args.actions_enabled in ['true', 'True'] fields['match_by'] = _arg_split_patch_update(args.match_by) if not _validate_severity(args.severity): return fields['severity'] = args.severity try: alarm = mc.alarm_definitions.update(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(alarm, indent=2))
python
def do_alarm_definition_update(mc, args): '''Update the alarm definition.''' fields = {} fields['alarm_id'] = args.id fields['name'] = args.name fields['description'] = args.description fields['expression'] = args.expression fields['alarm_actions'] = _arg_split_patch_update(args.alarm_actions) fields['ok_actions'] = _arg_split_patch_update(args.ok_actions) fields['undetermined_actions'] = _arg_split_patch_update(args.undetermined_actions) if args.actions_enabled not in enabled_types: errmsg = ('Invalid value, not one of [' + ', '.join(enabled_types) + ']') print(errmsg) return fields['actions_enabled'] = args.actions_enabled in ['true', 'True'] fields['match_by'] = _arg_split_patch_update(args.match_by) if not _validate_severity(args.severity): return fields['severity'] = args.severity try: alarm = mc.alarm_definitions.update(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(alarm, indent=2))
[ "def", "do_alarm_definition_update", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "fields", "[", "'name'", "]", "=", "args", ".", "name", "fields", "[", "'description'", "]", "=", ...
Update the alarm definition.
[ "Update", "the", "alarm", "definition", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L962-L987
train
44,889
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_definition_patch
def do_alarm_definition_patch(mc, args): '''Patch the alarm definition.''' fields = {} fields['alarm_id'] = args.id if args.name: fields['name'] = args.name if args.description: fields['description'] = args.description if args.expression: fields['expression'] = args.expression if args.alarm_actions: fields['alarm_actions'] = _arg_split_patch_update(args.alarm_actions, patch=True) if args.ok_actions: fields['ok_actions'] = _arg_split_patch_update(args.ok_actions, patch=True) if args.undetermined_actions: fields['undetermined_actions'] = _arg_split_patch_update(args.undetermined_actions, patch=True) if args.actions_enabled: if args.actions_enabled not in enabled_types: errmsg = ('Invalid value, not one of [' + ', '.join(enabled_types) + ']') print(errmsg) return fields['actions_enabled'] = args.actions_enabled in ['true', 'True'] if args.severity: if not _validate_severity(args.severity): return fields['severity'] = args.severity try: alarm = mc.alarm_definitions.patch(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(alarm, indent=2))
python
def do_alarm_definition_patch(mc, args): '''Patch the alarm definition.''' fields = {} fields['alarm_id'] = args.id if args.name: fields['name'] = args.name if args.description: fields['description'] = args.description if args.expression: fields['expression'] = args.expression if args.alarm_actions: fields['alarm_actions'] = _arg_split_patch_update(args.alarm_actions, patch=True) if args.ok_actions: fields['ok_actions'] = _arg_split_patch_update(args.ok_actions, patch=True) if args.undetermined_actions: fields['undetermined_actions'] = _arg_split_patch_update(args.undetermined_actions, patch=True) if args.actions_enabled: if args.actions_enabled not in enabled_types: errmsg = ('Invalid value, not one of [' + ', '.join(enabled_types) + ']') print(errmsg) return fields['actions_enabled'] = args.actions_enabled in ['true', 'True'] if args.severity: if not _validate_severity(args.severity): return fields['severity'] = args.severity try: alarm = mc.alarm_definitions.patch(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(alarm, indent=2))
[ "def", "do_alarm_definition_patch", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "if", "args", ".", "name", ":", "fields", "[", "'name'", "]", "=", "args", ".", "name", "if", "...
Patch the alarm definition.
[ "Patch", "the", "alarm", "definition", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1014-L1047
train
44,890
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_show
def do_alarm_show(mc, args): '''Describe the alarm.''' fields = {} fields['alarm_id'] = args.id try: alarm = mc.alarms.get(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(alarm)) return # print out detail of a single alarm formatters = { 'id': utils.json_formatter, 'alarm_definition': utils.json_formatter, 'metrics': utils.json_formatter, 'state': utils.json_formatter, 'links': utils.format_dictlist, } utils.print_dict(alarm, formatters=formatters)
python
def do_alarm_show(mc, args): '''Describe the alarm.''' fields = {} fields['alarm_id'] = args.id try: alarm = mc.alarms.get(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(alarm)) return # print out detail of a single alarm formatters = { 'id': utils.json_formatter, 'alarm_definition': utils.json_formatter, 'metrics': utils.json_formatter, 'state': utils.json_formatter, 'links': utils.format_dictlist, } utils.print_dict(alarm, formatters=formatters)
[ "def", "do_alarm_show", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "try", ":", "alarm", "=", "mc", ".", "alarms", ".", "get", "(", "*", "*", "fields", ")", "except", "(", ...
Describe the alarm.
[ "Describe", "the", "alarm", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1162-L1182
train
44,891
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_update
def do_alarm_update(mc, args): '''Update the alarm state.''' fields = {} fields['alarm_id'] = args.id if args.state.upper() not in state_types: errmsg = ('Invalid state, not one of [' + ', '.join(state_types) + ']') print(errmsg) return fields['state'] = args.state fields['lifecycle_state'] = args.lifecycle_state fields['link'] = args.link try: alarm = mc.alarms.update(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(alarm, indent=2))
python
def do_alarm_update(mc, args): '''Update the alarm state.''' fields = {} fields['alarm_id'] = args.id if args.state.upper() not in state_types: errmsg = ('Invalid state, not one of [' + ', '.join(state_types) + ']') print(errmsg) return fields['state'] = args.state fields['lifecycle_state'] = args.lifecycle_state fields['link'] = args.link try: alarm = mc.alarms.update(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print(jsonutils.dumps(alarm, indent=2))
[ "def", "do_alarm_update", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "if", "args", ".", "state", ".", "upper", "(", ")", "not", "in", "state_types", ":", "errmsg", "=", "(", ...
Update the alarm state.
[ "Update", "the", "alarm", "state", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1193-L1210
train
44,892
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_delete
def do_alarm_delete(mc, args): '''Delete the alarm.''' fields = {} fields['alarm_id'] = args.id try: mc.alarms.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully deleted alarm')
python
def do_alarm_delete(mc, args): '''Delete the alarm.''' fields = {} fields['alarm_id'] = args.id try: mc.alarms.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: print('Successfully deleted alarm')
[ "def", "do_alarm_delete", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "try", ":", "mc", ".", "alarms", ".", "delete", "(", "*", "*", "fields", ")", "except", "(", "osc_exc", ...
Delete the alarm.
[ "Delete", "the", "alarm", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1246-L1255
train
44,893
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_count
def do_alarm_count(mc, args): '''Count alarms.''' fields = {} if args.alarm_definition_id: fields['alarm_definition_id'] = args.alarm_definition_id if args.metric_name: fields['metric_name'] = args.metric_name if args.metric_dimensions: fields['metric_dimensions'] = utils.format_dimensions_query(args.metric_dimensions) if args.state: if args.state.upper() not in state_types: errmsg = ('Invalid state, not one of [' + ', '.join(state_types) + ']') print(errmsg) return fields['state'] = args.state if args.severity: if not _validate_severity(args.severity): return fields['severity'] = args.severity if args.state_updated_start_time: fields['state_updated_start_time'] = args.state_updated_start_time if args.lifecycle_state: fields['lifecycle_state'] = args.lifecycle_state if args.link: fields['link'] = args.link if args.group_by: group_by = args.group_by.split(',') if not set(group_by).issubset(set(group_by_types)): errmsg = ('Invalid group-by, one or more values not in [' + ','.join(group_by_types) + ']') print(errmsg) return fields['group_by'] = args.group_by if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: counts = mc.alarms.count(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(counts)) return cols = counts['columns'] utils.print_list(counts['counts'], [i for i in range(len(cols))], field_labels=cols)
python
def do_alarm_count(mc, args): '''Count alarms.''' fields = {} if args.alarm_definition_id: fields['alarm_definition_id'] = args.alarm_definition_id if args.metric_name: fields['metric_name'] = args.metric_name if args.metric_dimensions: fields['metric_dimensions'] = utils.format_dimensions_query(args.metric_dimensions) if args.state: if args.state.upper() not in state_types: errmsg = ('Invalid state, not one of [' + ', '.join(state_types) + ']') print(errmsg) return fields['state'] = args.state if args.severity: if not _validate_severity(args.severity): return fields['severity'] = args.severity if args.state_updated_start_time: fields['state_updated_start_time'] = args.state_updated_start_time if args.lifecycle_state: fields['lifecycle_state'] = args.lifecycle_state if args.link: fields['link'] = args.link if args.group_by: group_by = args.group_by.split(',') if not set(group_by).issubset(set(group_by_types)): errmsg = ('Invalid group-by, one or more values not in [' + ','.join(group_by_types) + ']') print(errmsg) return fields['group_by'] = args.group_by if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: counts = mc.alarms.count(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(counts)) return cols = counts['columns'] utils.print_list(counts['counts'], [i for i in range(len(cols))], field_labels=cols)
[ "def", "do_alarm_count", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "if", "args", ".", "alarm_definition_id", ":", "fields", "[", "'alarm_definition_id'", "]", "=", "args", ".", "alarm_definition_id", "if", "args", ".", "metric_name", ":", ...
Count alarms.
[ "Count", "alarms", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1315-L1364
train
44,894
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_history
def do_alarm_history(mc, args): '''Alarm state transition history.''' fields = {} fields['alarm_id'] = args.id if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: output_alarm_history(args, alarm)
python
def do_alarm_history(mc, args): '''Alarm state transition history.''' fields = {} fields['alarm_id'] = args.id if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: output_alarm_history(args, alarm)
[ "def", "do_alarm_history", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "if", "args", ".", "limit", ":", "fields", "[", "'limit'", "]", "=", "args", ".", "limit", "if", "args",...
Alarm state transition history.
[ "Alarm", "state", "transition", "history", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1373-L1386
train
44,895
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_alarm_history_list
def do_alarm_history_list(mc, args): '''List alarms state history.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) if args.starttime: _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: fields['end_time'] = args.endtime if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history_list(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: output_alarm_history(args, alarm)
python
def do_alarm_history_list(mc, args): '''List alarms state history.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) if args.starttime: _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: fields['end_time'] = args.endtime if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history_list(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: output_alarm_history(args, alarm)
[ "def", "do_alarm_history_list", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "if", "args", ".", "dimensions", ":", "fields", "[", "'dimensions'", "]", "=", "utils", ".", "format_parameters", "(", "args", ".", "dimensions", ")", "if", "args"...
List alarms state history.
[ "List", "alarms", "state", "history", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1405-L1424
train
44,896
openstack/python-monascaclient
monascaclient/v2_0/shell.py
do_notification_type_list
def do_notification_type_list(mc, args): '''List notification types supported by monasca.''' try: notification_types = mc.notificationtypes.list() except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(notification_types)) return else: formatters = {'types': lambda x: x["type"]} # utils.print_list(notification_types['types'], ["types"], formatters=formatters) utils.print_list(notification_types, ["types"], formatters=formatters)
python
def do_notification_type_list(mc, args): '''List notification types supported by monasca.''' try: notification_types = mc.notificationtypes.list() except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if args.json: print(utils.json_formatter(notification_types)) return else: formatters = {'types': lambda x: x["type"]} # utils.print_list(notification_types['types'], ["types"], formatters=formatters) utils.print_list(notification_types, ["types"], formatters=formatters)
[ "def", "do_notification_type_list", "(", "mc", ",", "args", ")", ":", "try", ":", "notification_types", "=", "mc", ".", "notificationtypes", ".", "list", "(", ")", "except", "(", "osc_exc", ".", "ClientException", ",", "k_exc", ".", "HttpError", ")", "as", ...
List notification types supported by monasca.
[ "List", "notification", "types", "supported", "by", "monasca", "." ]
03b07534145928eb2debad938da033c232dda105
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/shell.py#L1427-L1441
train
44,897
pymacaron/pymacaron
pymacaron/auth.py
add_auth
def add_auth(f): """A decorator that adds the authentication header to requests arguments""" def add_auth_decorator(*args, **kwargs): token = get_user_token() if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Authorization'] = "Bearer %s" % token return f(*args, **kwargs) return add_auth_decorator
python
def add_auth(f): """A decorator that adds the authentication header to requests arguments""" def add_auth_decorator(*args, **kwargs): token = get_user_token() if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Authorization'] = "Bearer %s" % token return f(*args, **kwargs) return add_auth_decorator
[ "def", "add_auth", "(", "f", ")", ":", "def", "add_auth_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "token", "=", "get_user_token", "(", ")", "if", "'headers'", "not", "in", "kwargs", ":", "kwargs", "[", "'headers'", "]", "=", "{...
A decorator that adds the authentication header to requests arguments
[ "A", "decorator", "that", "adds", "the", "authentication", "header", "to", "requests", "arguments" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L44-L54
train
44,898
pymacaron/pymacaron
pymacaron/auth.py
generate_token
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None): """Generate a new JWT token for this user_id. Default expiration date is 1 year from creation time""" assert user_id, "No user_id passed to generate_token()" assert isinstance(data, dict), "generate_token(data=) should be a dictionary" assert get_config().jwt_secret, "No JWT secret configured in pymacaron" if not issuer: issuer = get_config().jwt_issuer assert issuer, "No JWT issuer configured for pymacaron" if expire_in is None: expire_in = get_config().jwt_token_timeout if iat: epoch_now = iat else: epoch_now = to_epoch(timenow()) epoch_end = epoch_now + expire_in data['iss'] = issuer data['sub'] = user_id data['aud'] = get_config().jwt_audience data['exp'] = epoch_end data['iat'] = epoch_now headers = { "typ": "JWT", "alg": "HS256", "iss": issuer, } log.debug("Encoding token with data %s and headers %s (secret:%s****)" % (data, headers, get_config().jwt_secret[0:8])) t = jwt.encode( data, get_config().jwt_secret, headers=headers, ) if type(t) is bytes: t = t.decode("utf-8") return t
python
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None): """Generate a new JWT token for this user_id. Default expiration date is 1 year from creation time""" assert user_id, "No user_id passed to generate_token()" assert isinstance(data, dict), "generate_token(data=) should be a dictionary" assert get_config().jwt_secret, "No JWT secret configured in pymacaron" if not issuer: issuer = get_config().jwt_issuer assert issuer, "No JWT issuer configured for pymacaron" if expire_in is None: expire_in = get_config().jwt_token_timeout if iat: epoch_now = iat else: epoch_now = to_epoch(timenow()) epoch_end = epoch_now + expire_in data['iss'] = issuer data['sub'] = user_id data['aud'] = get_config().jwt_audience data['exp'] = epoch_end data['iat'] = epoch_now headers = { "typ": "JWT", "alg": "HS256", "iss": issuer, } log.debug("Encoding token with data %s and headers %s (secret:%s****)" % (data, headers, get_config().jwt_secret[0:8])) t = jwt.encode( data, get_config().jwt_secret, headers=headers, ) if type(t) is bytes: t = t.decode("utf-8") return t
[ "def", "generate_token", "(", "user_id", ",", "expire_in", "=", "None", ",", "data", "=", "{", "}", ",", "issuer", "=", "None", ",", "iat", "=", "None", ")", ":", "assert", "user_id", ",", "\"No user_id passed to generate_token()\"", "assert", "isinstance", ...
Generate a new JWT token for this user_id. Default expiration date is 1 year from creation time
[ "Generate", "a", "new", "JWT", "token", "for", "this", "user_id", ".", "Default", "expiration", "date", "is", "1", "year", "from", "creation", "time" ]
af244f203f8216108b39d374d46bf8e1813f13d5
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/auth.py#L156-L200
train
44,899