idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
44,800 | def note ( self , info ) : if self . recording : if self . notes is None : raise ValueError ( "This report has already been submitted" ) self . notes . extend ( self . _to_notes ( info ) ) | Record some info to the report . |
44,801 | def store ( report , address ) : now = time . time ( ) secs = int ( now ) msecs = int ( ( now - secs ) * 1000 ) submitted_date = filename = None 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" | Stores the report on disk . |
44,802 | def application ( environ , start_response ) : 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" ) 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 ) response_body = store ( request_body , environ . get ( 'REMOTE_ADDR' ) ) if not response_body : status = '200 OK' response_body = "stored" else : status = '501 Server Error' return send_response ( status , response_body ) | WSGI interface . |
44,803 | def write ( self , pin , value ) : port , pin = self . pin_to_port ( pin ) portname = 'A' if port == 1 : portname = 'B' self . _update_register ( 'GPIO' + portname , pin , value ) self . sync ( ) | Set the pin state . Make sure you put the pin in output mode first . |
44,804 | def write_port ( self , port , value ) : 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 ( ) | Use a whole port as a bus and write a byte to it . |
44,805 | def sync ( self ) : 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 ) ) | Upload the changed registers to the chip |
44,806 | def get_pins ( self ) : 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 | Get a list containing references to all 16 pins of the chip . |
44,807 | def read ( self ) : m = getattr ( self . chip , self . method ) return m ( ** self . arguments ) | Get the logic input level for the pin |
44,808 | def write ( self , value ) : if self . inverted : value = not value m = getattr ( self . chip , self . method ) m ( value = value , ** self . arguments ) | Set the logic output level for the pin . |
44,809 | def set_range ( self , accel = 1 , gyro = 1 ) : self . i2c_write_register ( 0x1c , accel ) self . i2c_write_register ( 0x1b , gyro ) self . accel_range = accel self . gyro_range = gyro | Set the measurement range for the accel and gyro MEMS . Higher range means less resolution . |
44,810 | def set_slave_bus_bypass ( self , enable ) : current = self . i2c_read_register ( 0x37 , 1 ) [ 0 ] if enable : current |= 0b00000010 else : current &= 0b11111101 self . i2c_write_register ( 0x37 , current ) | Put the aux i2c bus on the MPU - 6050 in bypass mode thus connecting it to the main i2c bus directly |
44,811 | 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 . unpack ( '>h' , raw ) [ 0 ] return round ( ( raw / 340 ) + 36.53 , 2 ) | Read the value for the internal temperature sensor . |
44,812 | 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 , 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 | Return the acceleration in G s |
44,813 | 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 . |
44,814 | def load_calibration ( self ) : 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 ) | Load factory calibration data from device . |
44,815 | def temperature ( self ) : 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 | Get the temperature from the sensor . |
44,816 | def pressure ( self ) : 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 | Get barometric pressure in milibar |
44,817 | def switch_mode ( self , new_mode ) : 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 ) | Explicitly switch the Bus Pirate mode |
44,818 | def set_peripheral ( self , power = None , pullup = None , aux = None , chip_select = None ) : 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 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 ) ) ) | Set the peripheral config at runtime . If a parameter is None then the config will not be changed . |
44,819 | 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_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 ) ) ) | Set I2C speed to one of 400kHz 100kHz 50kHz 5kHz |
44,820 | def config ( self , averaging = 1 , datarate = 15 , mode = MODE_NORMAL ) : 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 ) | Set the base config for sensor |
44,821 | def set_resolution ( self , resolution = 1090 ) : 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 ) | Set the resolution of the sensor |
44,822 | def temperature ( self ) : result = self . i2c_read ( 2 ) value = struct . unpack ( '>H' , result ) [ 0 ] if value < 32768 : return value / 256.0 else : return ( value - 65536 ) / 256.0 | Get the temperature in degree celcius |
44,823 | def write ( self , char ) : char = str ( char ) . lower ( ) self . segments . write ( self . font [ char ] ) | Display a single character on the display |
44,824 | 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 . |
44,825 | 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 . |
44,826 | def update_context ( app , pagename , templatename , context , doctree ) : context [ 'feedback_form_url' ] = feedback_form_url ( app . config . project , pagename ) | Update the page rendering context to include feedback_form_url . |
44,827 | 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 , 'parallel_write_safe' : True , 'version' : __version__ , } | Sphinx extension to update the rendering context with the feedback form URL . |
44,828 | def objectsFromPEM ( pemdata ) : 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 ) | Load some objects from a PEM . |
44,829 | def followingPrefix ( 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 ( ) | Returns a String that sorts just after all Strings beginning with a prefix |
44,830 | 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 |
44,831 | def add_mutations_and_flush ( self , table , muts ) : 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 ) | Add mutations to a table without the need to create and manage a batch writer . |
44,832 | 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 . |
44,833 | def set_relay_on ( self ) : 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 ( ) | Turn the relay on . |
44,834 | def set_relay_off ( self ) : 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 ( ) | Turn the relay off . |
44,835 | def get_consumption ( self ) : self . get_status ( ) try : self . consumption = self . data [ 'power' ] except TypeError : self . consumption = 0 return self . consumption | Get current power consumption in mWh . |
44,836 | def get_temperature ( self ) : 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 ( ) | Get current temperature in celsius . |
44,837 | def eval_fitness ( self , chromosome ) : score = 0 number = self . translator . translate_gene ( chromosome . genes [ 0 ] ) for factor in self . factors : if number % factor == 0 : score += 1 else : score -= 1 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 return score * number / self . max_encoded_val | Convert a 1 - gene chromosome into an integer and calculate its fitness by checking it against each required factor . |
44,838 | def get_status ( self ) : try : request = requests . get ( '{}/{}/' . format ( self . resource , URI ) , timeout = self . timeout ) raw_data = request . json ( ) self . data = raw_data [ self . _mac ] return self . data except ( requests . exceptions . ConnectionError , ValueError ) : raise exceptions . MyStromConnectionError ( ) | Get the details from the bulb . |
44,839 | def get_power ( self ) : self . get_status ( ) try : self . consumption = self . data [ 'power' ] except TypeError : self . consumption = 0 return self . consumption | Get current power . |
44,840 | def get_firmware ( self ) : self . get_status ( ) try : self . firmware = self . data [ 'fw_version' ] except TypeError : self . firmware = 'Unknown' return self . firmware | Get the current firmware version . |
44,841 | def get_brightness ( self ) : self . get_status ( ) try : self . brightness = self . data [ 'color' ] . split ( ';' ) [ - 1 ] except TypeError : self . brightness = 0 return self . brightness | Get current brightness . |
44,842 | def get_transition_time ( self ) : self . get_status ( ) try : self . transition_time = self . data [ 'ramp' ] except TypeError : self . transition_time = 0 return self . transition_time | Get the transition time in ms . |
44,843 | def get_color ( self ) : 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 } | Get current color . |
44,844 | def set_color_hsv ( self , hue , saturation , value ) : 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 ( ) | Turn the bulb on with the given values as HSV . |
44,845 | 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 . |
44,846 | def set_sunrise ( self , duration ) : 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 ) | Turn the bulb on and create a sunrise . |
44,847 | def set_flashing ( self , duration , hsv1 , hsv2 ) : 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 ) | Turn the bulb on flashing with two colors . |
44,848 | def set_off ( self ) : 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 ( ) | Turn the bulb off . |
44,849 | def load_clients ( self , path = None , apis = [ ] ) : 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 | Generate client libraries for the given apis without starting an api server |
44,850 | def load_apis ( self , path , ignore = [ ] , include_crash_api = False ) : 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" ) ignore . append ( 'pym-config' ) 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 ) ) 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' ] self . path_apis = path self . apis = apis return self | Load all swagger files found at the given path except those whose names are in the ignore list |
44,851 | def start ( self , serve = [ ] ) : 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 ) 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 ] , ) ) serve . append ( 'ping' ) compress = Compress ( ) compress . init_app ( app ) not_persistent = [ ] for api_name in self . apis . keys ( ) : if api_name in serve : pass else : not_persistent . append ( api_name ) for api_name , api_path in self . apis . items ( ) : host = None port = None if api_name in serve : 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 ( ) for api_name in self . apis . keys ( ) : if api_name in serve : log . info ( "Spawning api %s" % api_name ) api = getattr ( ApiPool , api_name ) 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 ( ) : log . info ( "Running in a Celery worker - Not starting the Flask app" ) return monitor_init ( app = app , config = conf ) if os . path . basename ( sys . argv [ 0 ] ) == 'gunicorn' : log . info ( "Running in Gunicorn - Not starting the Flask app" ) return app . debug = self . debug app . run ( host = '0.0.0.0' , port = self . port ) | 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 |
44,852 | 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 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 | Create a new Exception class |
44,853 | def responsify ( error ) : 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 ( ) | Take an Error model and return it as a Flask response |
44,854 | 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 |
44,855 | def format_error ( e ) : if isinstance ( e , PyMacaronException ) : return e . to_model ( ) if isinstance ( e , PyMacaronCoreException ) and e . __class__ . __name__ == 'ValidationError' : return ValidationError ( str ( e ) ) . to_model ( ) return UnhandledServerError ( str ( e ) ) . to_model ( ) | Take an exception caught within pymacaron_core and turn it into a bravado - core Error instance |
44,856 | 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 . error_description ) | Take a bravado - core Error model and raise it as an exception |
44,857 | def http_reply ( self ) : 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 | Return a Flask reply object describing this error |
44,858 | def to_model ( self ) : 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 | Return a bravado - core Error instance |
44,859 | 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 . 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 ) | Get a list of metrics . |
44,860 | def mapstr_to_list ( mapstr ) : maplist = [ ] with StringIO ( mapstr ) as infile : for row in infile : maplist . append ( row . strip ( ) ) return maplist | Convert an ASCII map string with rows to a list of strings 1 string per row . |
44,861 | 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 . |
44,862 | def eval_fitness ( self , chromosome ) : sx , sy = self . translator . translate_chromosome ( chromosome ) 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 crops_watered = 0 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 if self . maplist [ sy ] [ sx ] == 'x' : crops_watered -= 1 self . fitness_cache [ chromosome . dna ] = crops_watered return crops_watered | Return the number of plants reached by the sprinkler . |
44,863 | def map_sprinkler ( self , sx , sy , watered_crop = '^' , watered_field = '_' , dry_field = ' ' , dry_crop = 'x' ) : 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' return '\n' . join ( [ '' . join ( row ) for row in maplist ] ) | Return a version of the ASCII map showing reached crop cells . |
44,864 | def index ( request , template_name = "index.html" ) : 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 ) | \ The index view which basically just displays a button and increments a counter . |
44,865 | def get_fitness ( self , chromosome ) : fitness = self . fitness_cache . get ( chromosome . dna ) if fitness is None : fitness = self . eval_fitness ( chromosome ) self . fitness_cache [ chromosome . dna ] = fitness return fitness | Get the fitness score for a chromosome using the cached value if available . |
44,866 | def create_random ( cls , gene_length , n = 1 , gene_class = BinaryGene ) : assert issubclass ( gene_class , BaseGene ) chromosomes = [ ] 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 | Create 1 or more chromosomes with randomly generated DNA . |
44,867 | 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 . |
44,868 | 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 . |
44,869 | def populate_error_report ( data ) : 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 data [ 'call_id' ] = call_id data [ 'call_path' ] = call_path data [ 'is_ec2_instance' ] = is_ec2_instance ( ) user_data = { 'id' : '' , 'is_auth' : 0 , 'ip' : '' , } if stack . top : 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 if ApiPool ( ) . current_server_api : 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 ( ) , } 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 } | Add generic stats to the error report |
44,870 | 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 [ 'tenant_id' ] data = kwargs [ 'jsonbody' ] if 'jsonbody' in kwargs else kwargs body = self . client . create ( url = url_str , json = data ) return body | Create a metric . |
44,871 | def get_json_results ( self , response ) : try : self . most_recent_json = response . json ( ) json_results = response . json ( ) if response . status_code in [ 401 , 403 ] : raise PyMsCognitiveWebSearchException ( "CODE {code}: {message}" . format ( code = response . status_code , message = json_results [ "message" ] ) ) elif response . status_code in [ 429 ] : message = json_results [ 'message' ] try : 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 | Parses the request result and returns the JSON object . Handles all errors . |
44,872 | def search_all ( self , quota = 50 , format = 'json' ) : 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 | 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 |
44,873 | def format_parameters ( params ) : if not params : return { } if len ( params ) == 1 : if params [ 0 ] . find ( ';' ) != - 1 : 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 | Reformat parameters into dict of format expected by the API . |
44,874 | 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 . |
44,875 | def history ( self , ** kwargs ) : 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 | History of a specific alarm . |
44,876 | def history_list ( self , ** kwargs ) : 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 | History list of alarm state . |
44,877 | def do_version ( ) : 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 | Return version details of the running server api |
44,878 | def do_metric_create ( mc , args ) : 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' ) | Create metric . |
44,879 | def do_metric_create_raw ( mc , args ) : 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' ) | Create metric from raw json body . |
44,880 | def do_metric_name_list ( mc , args ) : 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' ] } ) | List names of metrics . |
44,881 | def do_metric_list ( mc , args ) : 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 ) : utils . print_list ( metric , cols , formatters = formatters ) else : metric_list = list ( ) metric_list . append ( metric ) utils . print_list ( metric_list , cols , formatters = formatters ) | List metrics for this tenant . |
44,882 | def do_metric_statistics ( mc , args ) : 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' ] if metric : column_names = metric [ 0 ] [ 'columns' ] for name in column_names : cols . append ( name ) else : 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 ) : utils . print_list ( metric , cols , formatters = formatters ) else : metric_list = list ( ) metric_list . append ( metric ) utils . print_list ( metric_list , cols , formatters = formatters ) | List measurement statistics for the specified metric . |
44,883 | def do_notification_show ( mc , args ) : 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 ) | Describe the notification . |
44,884 | def do_notification_list ( mc , args ) : 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 ) | List notifications for this tenant . |
44,885 | def do_notification_delete ( mc , args ) : 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' ) | Delete notification . |
44,886 | def do_notification_update ( mc , args ) : 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 ) ) | Update notification . |
44,887 | def do_alarm_definition_list ( mc , args ) : 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 ) : utils . print_list ( alarm , cols , formatters = formatters ) else : alarm_list = list ( ) alarm_list . append ( alarm ) utils . print_list ( alarm_list , cols , formatters = formatters ) | List alarm definitions for this tenant . |
44,888 | def do_alarm_definition_delete ( mc , args ) : 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' ) | Delete the alarm definition . |
44,889 | def do_alarm_definition_update ( mc , args ) : 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 ) ) | Update the alarm definition . |
44,890 | def do_alarm_definition_patch ( mc , args ) : 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 ) ) | Patch the alarm definition . |
44,891 | def do_alarm_show ( mc , args ) : 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 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 ) | Describe the alarm . |
44,892 | def do_alarm_update ( mc , args ) : 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 ) ) | Update the alarm state . |
44,893 | def do_alarm_delete ( mc , args ) : 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' ) | Delete the alarm . |
44,894 | def do_alarm_count ( mc , args ) : 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 ) | Count alarms . |
44,895 | def do_alarm_history ( mc , args ) : 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 ) | Alarm state transition history . |
44,896 | def do_alarm_history_list ( mc , args ) : 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 ) | List alarms state history . |
44,897 | def do_notification_type_list ( mc , args ) : 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" ] , formatters = formatters ) | List notification types supported by monasca . |
44,898 | def add_auth ( f ) : 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 | A decorator that adds the authentication header to requests arguments |
44,899 | 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 ( 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 | Generate a new JWT token for this user_id . Default expiration date is 1 year from creation time |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.