idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
233,200 | def clean_pofile ( pofile_path ) : # Reading in the .po file and saving it again fixes redundancies. pomsgs = pofile ( pofile_path ) # The msgcat tool marks the metadata as fuzzy, but it's ok as it is. pomsgs . metadata_is_fuzzy = False duplicate_entries = [ ] for entry in pomsgs : # Remove line numbers entry . occurrences = [ ( filename , None ) for filename , __ in entry . occurrences ] # Check for merge conflicts. Pick the first, and emit a warning. if 'fuzzy' in entry . flags : # Remove fuzzy from flags entry . flags = [ f for f in entry . flags if f != 'fuzzy' ] # Save a warning message dup_msg = 'Multiple translations found for single string.\n\tString "{0}"\n\tPresent in files {1}' . format ( entry . msgid , [ f for ( f , __ ) in entry . occurrences ] ) duplicate_entries . append ( ( dup_msg , entry . msgstr ) ) # Pick the first entry for msgstr in DUPLICATE_ENTRY_PATTERN . split ( entry . msgstr ) : # Ignore any empty strings that may result from the split call if msgstr : # Set the first one we find to be the right one. Strip to remove extraneous # new lines that exist. entry . msgstr = msgstr . strip ( ) # Raise error if there's new lines starting or ending the id string. if entry . msgid . startswith ( '\n' ) or entry . msgid . endswith ( '\n' ) : raise ValueError ( u'{} starts or ends with a new line character, which is not allowed. ' 'Please fix before continuing. Source string is found in {}' . format ( entry . msgid , entry . occurrences ) . encode ( 'utf-8' ) ) break pomsgs . save ( ) return duplicate_entries | Clean various aspect of a . po file . | 433 | 9 |
233,201 | def new_filename ( original_filename , new_locale ) : orig_file = Path ( original_filename ) new_file = orig_file . parent . parent . parent / new_locale / orig_file . parent . name / orig_file . name return new_file . abspath ( ) | Returns a filename derived from original_filename using new_locale as the locale | 66 | 16 |
233,202 | def run ( self , args ) : configuration = self . configuration source_messages_dir = configuration . source_messages_dir for locale , converter in zip ( configuration . dummy_locales , [ Dummy ( ) , Dummy2 ( ) , ArabicDummy ( ) ] ) : print ( 'Processing source language files into dummy strings, locale "{}"' . format ( locale ) ) for source_file in configuration . source_messages_dir . walkfiles ( '*.po' ) : if args . verbose : print ( ' ' , source_file . relpath ( ) ) make_dummy ( source_messages_dir . joinpath ( source_file ) , locale , converter ) if args . verbose : print ( ) | Generate dummy strings for all source po files . | 160 | 10 |
233,203 | def execute ( command , working_directory = config . BASE_DIR , stderr = sp . STDOUT ) : LOG . info ( "Executing in %s ..." , working_directory ) LOG . info ( command ) sp . check_call ( command , cwd = working_directory , stderr = stderr , shell = True ) | Executes shell command in a given working_directory . Command is a string to pass to the shell . Output is ignored . | 74 | 25 |
233,204 | def remove_file ( filename , verbose = True ) : if verbose : LOG . info ( 'Deleting file %s' , os . path . relpath ( filename , config . BASE_DIR ) ) if not os . path . exists ( filename ) : LOG . warning ( "File does not exist: %s" , os . path . relpath ( filename , config . BASE_DIR ) ) else : os . remove ( filename ) | Attempt to delete filename . log is boolean . If true removal is logged . Log a warning if file does not exist . Logging filenames are relative to config . BASE_DIR to cut down on noise in output . | 95 | 45 |
233,205 | def push ( * resources ) : cmd = 'tx push -s' if resources : for resource in resources : execute ( cmd + ' -r {resource}' . format ( resource = resource ) ) else : execute ( cmd ) | Push translation source English files to Transifex . | 48 | 10 |
233,206 | def pull_all_ltr ( configuration ) : print ( "Pulling all translated LTR languages from transifex..." ) for lang in configuration . ltr_langs : print ( 'rm -rf conf/locale/' + lang ) execute ( 'rm -rf conf/locale/' + lang ) execute ( 'tx pull -l ' + lang ) clean_translated_locales ( configuration , langs = configuration . ltr_langs ) | Pulls all translations - reviewed or not - for LTR languages | 100 | 13 |
233,207 | def pull_all_rtl ( configuration ) : print ( "Pulling all translated RTL languages from transifex..." ) for lang in configuration . rtl_langs : print ( 'rm -rf conf/locale/' + lang ) execute ( 'rm -rf conf/locale/' + lang ) execute ( 'tx pull -l ' + lang ) clean_translated_locales ( configuration , langs = configuration . rtl_langs ) | Pulls all translations - reviewed or not - for RTL languages | 100 | 13 |
233,208 | def clean_translated_locales ( configuration , langs = None ) : if not langs : langs = configuration . translated_locales for locale in langs : clean_locale ( configuration , locale ) | Strips out the warning from all translated po files about being an English source file . | 46 | 18 |
233,209 | def clean_locale ( configuration , locale ) : dirname = configuration . get_messages_dir ( locale ) if not dirname . exists ( ) : # Happens when we have a supported locale that doesn't exist in Transifex return for filename in dirname . files ( '*.po' ) : clean_file ( configuration , dirname . joinpath ( filename ) ) | Strips out the warning from all of a locale s translated po files about being an English source file . Iterates over machine - generated files . | 81 | 30 |
233,210 | def clean_file ( configuration , filename ) : pofile = polib . pofile ( filename ) if pofile . header . find ( EDX_MARKER ) != - 1 : new_header = get_new_header ( configuration , pofile ) new = pofile . header . replace ( EDX_MARKER , new_header ) pofile . header = new pofile . save ( ) | Strips out the warning from a translated po file about being an English source file . Replaces warning with a note about coming from Transifex . | 87 | 31 |
233,211 | def get_new_header ( configuration , pofile ) : team = pofile . metadata . get ( 'Language-Team' , None ) if not team : return TRANSIFEX_HEADER . format ( configuration . TRANSIFEX_URL ) return TRANSIFEX_HEADER . format ( team ) | Insert info about edX into the po file headers | 64 | 10 |
233,212 | def detag_string ( self , string ) : counter = itertools . count ( 0 ) count = lambda m : '<%s>' % next ( counter ) tags = self . tag_pattern . findall ( string ) tags = [ '' . join ( tag ) for tag in tags ] ( new , nfound ) = self . tag_pattern . subn ( count , string ) if len ( tags ) != nfound : raise Exception ( 'tags dont match:' + string ) return ( new , tags ) | Extracts tags from string . | 110 | 7 |
233,213 | def options ( self ) : arg = self . get ( 0 ) if arg . startswith ( '-' ) and not self . is_asking_for_help : return arg [ 1 : ] return '' . join ( x for x in arg if x in 'dgktz' ) | Train tickets query options . | 62 | 5 |
233,214 | def trains ( self ) : for row in self . _rows : train_no = row . get ( 'station_train_code' ) initial = train_no [ 0 ] . lower ( ) if not self . _opts or initial in self . _opts : train = [ # Column: '车次' train_no , # Column: '车站' '\n' . join ( [ colored . green ( row . get ( 'from_station_name' ) ) , colored . red ( row . get ( 'to_station_name' ) ) , ] ) , # Column: '时间' '\n' . join ( [ colored . green ( row . get ( 'start_time' ) ) , colored . red ( row . get ( 'arrive_time' ) ) , ] ) , # Column: '历时' self . _get_duration ( row ) , # Column: '商务' row . get ( 'swz_num' ) , # Column: '一等' row . get ( 'zy_num' ) , # Column: '二等' row . get ( 'ze_num' ) , # Column: '软卧' row . get ( 'rw_num' ) , # Column: '硬卧' row . get ( 'yw_num' ) , # Column: '软座' row . get ( 'rz_num' ) , # Column: '硬座' row . get ( 'yz_num' ) , # Column: '无座' row . get ( 'wz_num' ) ] yield train | Filter rows according to headers | 377 | 5 |
233,215 | def pretty_print ( self ) : pt = PrettyTable ( ) if len ( self ) == 0 : pt . _set_field_names ( [ 'Sorry,' ] ) pt . add_row ( [ TRAIN_NOT_FOUND ] ) else : pt . _set_field_names ( self . headers ) for train in self . trains : pt . add_row ( train ) print ( pt ) | Use PrettyTable to perform formatted outprint . | 87 | 9 |
233,216 | def _valid_date ( self ) : date = self . _parse_date ( self . date ) if not date : exit_after_echo ( INVALID_DATE ) try : date = datetime . strptime ( date , '%Y%m%d' ) except ValueError : exit_after_echo ( INVALID_DATE ) # A valid query date should within 50 days. offset = date - datetime . today ( ) if offset . days not in range ( - 1 , 50 ) : exit_after_echo ( INVALID_DATE ) return datetime . strftime ( date , '%Y-%m-%d' ) | Check and return a valid query date . | 145 | 8 |
233,217 | def _parse_date ( date ) : result = '' . join ( re . findall ( '\d' , date ) ) l = len ( result ) # User only input month and day, eg 6-1, 6.26, 0626... if l in ( 2 , 3 , 4 ) : year = str ( datetime . today ( ) . year ) return year + result # User input full format date, eg 201661, 2016-6-26, 20160626... if l in ( 6 , 7 , 8 ) : return result return '' | Parse from the user input date . | 118 | 8 |
233,218 | def _build_params ( self ) : d = OrderedDict ( ) d [ 'purpose_codes' ] = 'ADULT' d [ 'queryDate' ] = self . _valid_date d [ 'from_station' ] = self . _from_station_telecode d [ 'to_station' ] = self . _to_station_telecode return d | Have no idea why wrong params order can t get data . So use OrderedDict here . | 82 | 20 |
233,219 | def date_range ( self ) : try : days = int ( self . days ) except ValueError : exit_after_echo ( QUERY_DAYS_INVALID ) if days < 1 : exit_after_echo ( QUERY_DAYS_INVALID ) start = datetime . today ( ) end = start + timedelta ( days = days ) return ( datetime . strftime ( start , '%Y-%m-%d' ) , datetime . strftime ( end , '%Y-%m-%d' ) ) | Generate date range according to the days user input . | 120 | 11 |
233,220 | def query ( params ) : r = requests_get ( QUERY_URL , verify = True ) return HospitalCollection ( r . json ( ) , params ) | params is a city name or a city name + hospital name . | 33 | 13 |
233,221 | def cli ( ) : if args . is_asking_for_help : exit_after_echo ( cli . __doc__ , color = None ) elif args . is_querying_lottery : from . lottery import query result = query ( ) elif args . is_querying_movie : from . movies import query result = query ( ) elif args . is_querying_lyric : from . lyrics import query result = query ( args . as_lyric_query_params ) elif args . is_querying_show : from . showes import query result = query ( args . as_show_query_params ) elif args . is_querying_putian_hospital : from . hospitals import query result = query ( args . as_hospital_query_params ) elif args . is_querying_train : from . trains import query result = query ( args . as_train_query_params ) else : exit_after_echo ( show_usage . __doc__ , color = None ) result . pretty_print ( ) | Various information query via command line . | 230 | 7 |
233,222 | def query ( ) : r = requests_get ( QUERY_URL ) try : rows = r . json ( ) [ 'subject_collection_items' ] except ( IndexError , TypeError ) : rows = [ ] return MoviesCollection ( rows ) | Query hot movies infomation from douban . | 53 | 10 |
233,223 | def action_draft ( self ) : for rec in self : if not rec . state == 'cancelled' : raise UserError ( _ ( 'You need to cancel it before reopening.' ) ) if not ( rec . am_i_owner or rec . am_i_approver ) : raise UserError ( _ ( 'You are not authorized to do this.\r\n' 'Only owners or approvers can reopen Change Requests.' ) ) rec . write ( { 'state' : 'draft' } ) | Set a change request as draft | 112 | 6 |
233,224 | def action_to_approve ( self ) : template = self . env . ref ( 'document_page_approval.email_template_new_draft_need_approval' ) approver_gid = self . env . ref ( 'document_page_approval.group_document_approver_user' ) for rec in self : if rec . state != 'draft' : raise UserError ( _ ( "Can't approve pages in '%s' state." ) % rec . state ) if not ( rec . am_i_owner or rec . am_i_approver ) : raise UserError ( _ ( 'You are not authorized to do this.\r\n' 'Only owners or approvers can request approval.' ) ) # request approval if rec . is_approval_required : rec . write ( { 'state' : 'to approve' } ) guids = [ g . id for g in rec . page_id . approver_group_ids ] users = self . env [ 'res.users' ] . search ( [ ( 'groups_id' , 'in' , guids ) , ( 'groups_id' , 'in' , approver_gid . id ) ] ) rec . message_subscribe_users ( [ u . id for u in users ] ) rec . message_post_with_template ( template . id ) else : # auto-approve if approval is not required rec . action_approve ( ) | Set a change request as to approve | 318 | 7 |
233,225 | def action_approve ( self ) : for rec in self : if rec . state not in [ 'draft' , 'to approve' ] : raise UserError ( _ ( "Can't approve page in '%s' state." ) % rec . state ) if not rec . am_i_approver : raise UserError ( _ ( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: ' ) % ', ' . join ( [ g . display_name for g in rec . page_id . approver_group_ids ] ) ) # Update state rec . write ( { 'state' : 'approved' , 'approved_date' : fields . datetime . now ( ) , 'approved_uid' : self . env . uid , } ) # Trigger computed field update rec . page_id . _compute_history_head ( ) # Notify state change rec . message_post ( subtype = 'mt_comment' , body = _ ( 'Change request has been approved by %s.' ) % ( self . env . user . name ) ) # Notify followers a new version is available rec . page_id . message_post ( subtype = 'mt_comment' , body = _ ( 'New version of the document %s approved.' ) % ( rec . page_id . name ) ) | Set a change request as approved . | 295 | 7 |
233,226 | def action_cancel ( self ) : self . write ( { 'state' : 'cancelled' } ) for rec in self : rec . message_post ( subtype = 'mt_comment' , body = _ ( 'Change request <b>%s</b> has been cancelled by %s.' ) % ( rec . display_name , self . env . user . name ) ) | Set a change request as cancelled . | 85 | 7 |
233,227 | def _compute_am_i_owner ( self ) : for rec in self : rec . am_i_owner = ( rec . create_uid == self . env . user ) | Check if current user is the owner | 40 | 7 |
233,228 | def _compute_page_url ( self ) : for page in self : base_url = self . env [ 'ir.config_parameter' ] . sudo ( ) . get_param ( 'web.base.url' , default = 'http://localhost:8069' ) page . page_url = ( '{}/web#db={}&id={}&view_type=form&' 'model=document.page.history' ) . format ( base_url , self . env . cr . dbname , page . id ) | Compute the page url . | 120 | 6 |
233,229 | def _compute_diff ( self ) : history = self . env [ 'document.page.history' ] for rec in self : domain = [ ( 'page_id' , '=' , rec . page_id . id ) , ( 'state' , '=' , 'approved' ) ] if rec . approved_date : domain . append ( ( 'approved_date' , '<' , rec . approved_date ) ) prev = history . search ( domain , limit = 1 , order = 'approved_date DESC' ) if prev : rec . diff = self . getDiff ( prev . id , rec . id ) else : rec . diff = self . getDiff ( False , rec . id ) | Shows a diff between this version and the previous version | 152 | 11 |
233,230 | def action_add_url ( self ) : if not self . env . context . get ( 'active_model' ) : return attachment_obj = self . env [ 'ir.attachment' ] for form in self : url = parse . urlparse ( form . url ) if not url . scheme : url = parse . urlparse ( '%s%s' % ( 'http://' , form . url ) ) for active_id in self . env . context . get ( 'active_ids' , [ ] ) : attachment = { 'name' : form . name , 'type' : 'url' , 'url' : url . geturl ( ) , 'res_id' : active_id , 'res_model' : self . env . context [ 'active_model' ] , } attachment_obj . create ( attachment ) return { 'type' : 'ir.actions.act_close_wizard_and_reload_view' } | Adds the URL with the given name as an ir . attachment record . | 207 | 14 |
233,231 | def _compute_is_approval_required ( self ) : for page in self : res = page . approval_required if page . parent_id : res = res or page . parent_id . is_approval_required page . is_approval_required = res | Check if the document required approval based on his parents . | 60 | 11 |
233,232 | def _compute_approver_group_ids ( self ) : for page in self : res = page . approver_gid if page . parent_id : res = res | page . parent_id . approver_group_ids page . approver_group_ids = res | Compute the approver groups based on his parents . | 62 | 11 |
233,233 | def _compute_am_i_approver ( self ) : for rec in self : rec . am_i_approver = rec . can_user_approve_this_page ( self . env . user ) | Check if the current user can approve changes to this page . | 48 | 12 |
233,234 | def can_user_approve_this_page ( self , user ) : self . ensure_one ( ) # if it's not required, anyone can approve if not self . is_approval_required : return True # if user belongs to 'Knowledge / Manager', he can approve anything if user . has_group ( 'document_page.group_document_manager' ) : return True # to approve, user must have approver rights if not user . has_group ( 'document_page_approval.group_document_approver_user' ) : return False # if there aren't any approver_groups_defined, user can approve if not self . approver_group_ids : return True # to approve, user must belong to any of the approver groups return len ( user . groups_id & self . approver_group_ids ) > 0 | Check if a user can approve this page . | 186 | 9 |
233,235 | def status ( self ) : response = requests . get ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self . locationId , headers = self . client . _headers ( ) # pylint: disable=protected-access ) response . raise_for_status ( ) data = response . json ( ) # Now feed into other elements for gw_data in data [ 'gateways' ] : gateway = self . gateways [ gw_data [ 'gatewayId' ] ] for sys in gw_data [ "temperatureControlSystems" ] : system = gateway . control_systems [ sys [ 'systemId' ] ] system . __dict__ . update ( { 'systemModeStatus' : sys [ 'systemModeStatus' ] , 'activeFaults' : sys [ 'activeFaults' ] } ) if 'dhw' in sys : system . hotwater . __dict__ . update ( sys [ 'dhw' ] ) for zone_data in sys [ "zones" ] : zone = system . zones [ zone_data [ 'name' ] ] zone . __dict__ . update ( zone_data ) return data | Retrieves the location status . | 277 | 7 |
233,236 | def set_dhw_on ( self , until = None ) : if until is None : data = { "Mode" : "PermanentOverride" , "State" : "On" , "UntilTime" : None } else : data = { "Mode" : "TemporaryOverride" , "State" : "On" , "UntilTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_dhw ( data ) | Sets the DHW on until a given time or permanently . | 113 | 13 |
233,237 | def set_dhw_off ( self , until = None ) : if until is None : data = { "Mode" : "PermanentOverride" , "State" : "Off" , "UntilTime" : None } else : data = { "Mode" : "TemporaryOverride" , "State" : "Off" , "UntilTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_dhw ( data ) | Sets the DHW off until a given time or permanently . | 113 | 13 |
233,238 | def schedule ( self ) : response = requests . get ( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % ( self . zone_type , self . zoneId ) , headers = self . client . _headers ( ) # pylint: disable=no-member,protected-access ) response . raise_for_status ( ) mapping = [ ( 'dailySchedules' , 'DailySchedules' ) , ( 'dayOfWeek' , 'DayOfWeek' ) , ( 'temperature' , 'TargetTemperature' ) , ( 'timeOfDay' , 'TimeOfDay' ) , ( 'switchpoints' , 'Switchpoints' ) , ( 'dhwState' , 'DhwState' ) , ] response_data = response . text for from_val , to_val in mapping : response_data = response_data . replace ( from_val , to_val ) data = json . loads ( response_data ) # change the day name string to a number offset (0 = Monday) for day_of_week , schedule in enumerate ( data [ 'DailySchedules' ] ) : schedule [ 'DayOfWeek' ] = day_of_week return data | Gets the schedule for the given zone | 280 | 8 |
233,239 | def set_schedule ( self , zone_info ) : # must only POST json, otherwise server API handler raises exceptions try : json . loads ( zone_info ) except ValueError as error : raise ValueError ( "zone_info must be valid JSON: " , error ) headers = dict ( self . client . _headers ( ) ) # pylint: disable=protected-access headers [ 'Content-Type' ] = 'application/json' response = requests . put ( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % ( self . zone_type , self . zoneId ) , data = zone_info , headers = headers ) response . raise_for_status ( ) return response . json ( ) | Sets the schedule for this zone | 174 | 7 |
233,240 | def temperatures ( self , force_refresh = False ) : self . _populate_full_data ( force_refresh ) for device in self . full_data [ 'devices' ] : set_point = 0 status = "" if 'heatSetpoint' in device [ 'thermostat' ] [ 'changeableValues' ] : set_point = float ( device [ 'thermostat' ] [ 'changeableValues' ] [ "heatSetpoint" ] [ "value" ] ) status = device [ 'thermostat' ] [ 'changeableValues' ] [ "heatSetpoint" ] [ "status" ] else : status = device [ 'thermostat' ] [ 'changeableValues' ] [ 'status' ] yield { 'thermostat' : device [ 'thermostatModelType' ] , 'id' : device [ 'deviceID' ] , 'name' : device [ 'name' ] , 'temp' : float ( device [ 'thermostat' ] [ 'indoorTemperature' ] ) , 'setpoint' : set_point , 'status' : status , 'mode' : device [ 'thermostat' ] [ 'changeableValues' ] [ 'mode' ] } | Retrieve the current details for each zone . Returns a generator . | 265 | 13 |
233,241 | def get_modes ( self , zone ) : self . _populate_full_data ( ) device = self . _get_device ( zone ) return device [ 'thermostat' ] [ 'allowedModes' ] | Returns the set of modes the device can be assigned . | 49 | 11 |
233,242 | def set_temperature ( self , zone , temperature , until = None ) : if until is None : data = { "Value" : temperature , "Status" : "Hold" , "NextTime" : None } else : data = { "Value" : temperature , "Status" : "Temporary" , "NextTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_heat_setpoint ( zone , data ) | Sets the temperature of the given zone . | 112 | 9 |
233,243 | def _set_dhw ( self , status = "Scheduled" , mode = None , next_time = None ) : data = { "Status" : status , "Mode" : mode , "NextTime" : next_time , "SpecialModes" : None , "HeatSetpoint" : None , "CoolSetpoint" : None } self . _populate_full_data ( ) dhw_zone = self . _get_dhw_zone ( ) if dhw_zone is None : raise Exception ( 'No DHW zone reported from API' ) url = ( self . hostname + "/WebAPI/api/devices" "/%s/thermostat/changeableValues" % dhw_zone ) response = self . _do_request ( 'put' , url , json . dumps ( data ) ) task_id = self . _get_task_id ( response ) while self . _get_task_status ( task_id ) != 'Succeeded' : time . sleep ( 1 ) | Set DHW to On Off or Auto either indefinitely or until a specified time . | 223 | 16 |
233,244 | def set_dhw_on ( self , until = None ) : time_until = None if until is None else until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) self . _set_dhw ( status = "Hold" , mode = "DHWOn" , next_time = time_until ) | Set DHW to on either indefinitely or until a specified time . | 81 | 13 |
233,245 | def _headers ( self ) : if not self . access_token or not self . access_token_expires : self . _basic_login ( ) elif datetime . now ( ) > self . access_token_expires - timedelta ( seconds = 30 ) : self . _basic_login ( ) return { 'Accept' : HEADER_ACCEPT , 'Authorization' : 'bearer ' + self . access_token } | Ensure the Authorization Header has a valid Access Token . | 95 | 11 |
233,246 | def _basic_login ( self ) : _LOGGER . debug ( "No/Expired/Invalid access_token, re-authenticating..." ) self . access_token = self . access_token_expires = None if self . refresh_token : _LOGGER . debug ( "Trying refresh_token..." ) credentials = { 'grant_type' : "refresh_token" , 'scope' : "EMEA-V1-Basic EMEA-V1-Anonymous" , 'refresh_token' : self . refresh_token } try : self . _obtain_access_token ( credentials ) except ( requests . HTTPError , KeyError , ValueError ) : _LOGGER . warning ( "Invalid refresh_token, will try user credentials." ) self . refresh_token = None if not self . refresh_token : _LOGGER . debug ( "Trying user credentials..." ) credentials = { 'grant_type' : "password" , 'scope' : "EMEA-V1-Basic EMEA-V1-Anonymous " "EMEA-V1-Get-Current-User-Account" , 'Username' : self . username , 'Password' : self . password } self . _obtain_access_token ( credentials ) _LOGGER . debug ( "refresh_token = %s" , self . refresh_token ) _LOGGER . debug ( "access_token = %s" , self . access_token ) _LOGGER . debug ( "access_token_expires = %s" , self . access_token_expires . strftime ( "%Y-%m-%d %H:%M:%S" ) ) | Obtain a new access token from the vendor . | 367 | 10 |
233,247 | def user_account ( self ) : self . account_info = None url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount' response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) self . account_info = response . json ( ) return self . account_info | Return the user account information . | 87 | 6 |
233,248 | def installation ( self ) : self . locations = [ ] url = ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/installationInfo?userId=%s" "&includeTemperatureControlSystems=True" % self . account_info [ 'userId' ] ) response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) self . installation_info = response . json ( ) self . system_id = ( self . installation_info [ 0 ] [ 'gateways' ] [ 0 ] [ 'temperatureControlSystems' ] [ 0 ] [ 'systemId' ] ) for loc_data in self . installation_info : self . locations . append ( Location ( self , loc_data ) ) return self . installation_info | Return the details of the installation . | 187 | 7 |
233,249 | def full_installation ( self , location = None ) : url = ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self . _get_location ( location ) ) response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) return response . json ( ) | Return the full details of the installation . | 101 | 8 |
233,250 | def gateway ( self ) : url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) return response . json ( ) | Return the detail of the gateway . | 67 | 7 |
233,251 | def temperatures ( self ) : self . location . status ( ) if self . hotwater : yield { 'thermostat' : 'DOMESTIC_HOT_WATER' , 'id' : self . hotwater . dhwId , 'name' : '' , 'temp' : self . hotwater . temperatureStatus [ 'temperature' ] , # pylint: disable=no-member 'setpoint' : '' } for zone in self . _zones : zone_info = { 'thermostat' : 'EMEA_ZONE' , 'id' : zone . zoneId , 'name' : zone . name , 'temp' : None , 'setpoint' : zone . setpointStatus [ 'targetHeatTemperature' ] } if zone . temperatureStatus [ 'isAvailable' ] : zone_info [ 'temp' ] = zone . temperatureStatus [ 'temperature' ] yield zone_info | Return a generator with the details of each zone . | 197 | 10 |
233,252 | def zone_schedules_backup ( self , filename ) : _LOGGER . info ( "Backing up schedules from ControlSystem: %s (%s)..." , self . systemId , self . location . name ) schedules = { } if self . hotwater : _LOGGER . info ( "Retrieving DHW schedule: %s..." , self . hotwater . zoneId ) schedule = self . hotwater . schedule ( ) schedules [ self . hotwater . zoneId ] = { 'name' : 'Domestic Hot Water' , 'schedule' : schedule } for zone in self . _zones : zone_id = zone . zoneId name = zone . name _LOGGER . info ( "Retrieving Zone schedule: %s - %s" , zone_id , name ) schedule = zone . schedule ( ) schedules [ zone_id ] = { 'name' : name , 'schedule' : schedule } schedule_db = json . dumps ( schedules , indent = 4 ) _LOGGER . info ( "Writing to backup file: %s..." , filename ) with open ( filename , 'w' ) as file_output : file_output . write ( schedule_db ) _LOGGER . info ( "Backup completed." ) | Backup all zones on control system to the given file . | 266 | 12 |
233,253 | def zone_schedules_restore ( self , filename ) : _LOGGER . info ( "Restoring schedules to ControlSystem %s (%s)..." , self . systemId , self . location ) _LOGGER . info ( "Reading from backup file: %s..." , filename ) with open ( filename , 'r' ) as file_input : schedule_db = file_input . read ( ) schedules = json . loads ( schedule_db ) for zone_id , zone_schedule in schedules . items ( ) : name = zone_schedule [ 'name' ] zone_info = zone_schedule [ 'schedule' ] _LOGGER . info ( "Restoring schedule for: %s - %s..." , zone_id , name ) if self . hotwater and self . hotwater . zoneId == zone_id : self . hotwater . set_schedule ( json . dumps ( zone_info ) ) else : self . zones_by_id [ zone_id ] . set_schedule ( json . dumps ( zone_info ) ) _LOGGER . info ( "Restore completed." ) | Restore all zones on control system from the given file . | 241 | 12 |
233,254 | def cli ( env , package_keyname , keyword , category ) : table = formatting . Table ( COLUMNS ) manager = ordering . OrderingManager ( env . client ) _filter = { 'items' : { } } if keyword : _filter [ 'items' ] [ 'description' ] = { 'operation' : '*= %s' % keyword } if category : _filter [ 'items' ] [ 'categories' ] = { 'categoryCode' : { 'operation' : '_= %s' % category } } items = manager . list_items ( package_keyname , filter = _filter ) sorted_items = sort_items ( items ) categories = sorted_items . keys ( ) for catname in sorted ( categories ) : for item in sorted_items [ catname ] : table . add_row ( [ catname , item [ 'keyName' ] , item [ 'description' ] , get_price ( item ) ] ) env . fout ( table ) | List package items used for ordering . | 216 | 7 |
233,255 | def sort_items ( items ) : sorted_items = { } for item in items : category = lookup ( item , 'itemCategory' , 'categoryCode' ) if sorted_items . get ( category ) is None : sorted_items [ category ] = [ ] sorted_items [ category ] . append ( item ) return sorted_items | sorts the items into a dictionary of categories with a list of items | 71 | 14 |
233,256 | def cli ( env , sortby , datacenter , number , name , limit ) : mgr = SoftLayer . NetworkManager ( env . client ) table = formatting . Table ( COLUMNS ) table . sortby = sortby vlans = mgr . list_vlans ( datacenter = datacenter , vlan_number = number , name = name , limit = limit ) for vlan in vlans : table . add_row ( [ vlan [ 'id' ] , vlan [ 'vlanNumber' ] , vlan . get ( 'name' ) or formatting . blank ( ) , 'Yes' if vlan [ 'firewallInterfaces' ] else 'No' , utils . lookup ( vlan , 'primaryRouter' , 'datacenter' , 'name' ) , vlan [ 'hardwareCount' ] , vlan [ 'virtualGuestCount' ] , vlan [ 'totalPrimaryIpAddressCount' ] , ] ) env . fout ( table ) | List VLANs . | 220 | 5 |
233,257 | def cli ( env ) : account = env . client [ 'Account' ] nas_accounts = account . getNasNetworkStorage ( mask = 'eventCount,serviceResource[datacenter.name]' ) table = formatting . Table ( [ 'id' , 'datacenter' , 'size' , 'server' ] ) for nas_account in nas_accounts : table . add_row ( [ nas_account [ 'id' ] , utils . lookup ( nas_account , 'serviceResource' , 'datacenter' , 'name' ) or formatting . blank ( ) , formatting . FormattedItem ( nas_account . get ( 'capacityGb' , formatting . blank ( ) ) , "%dGB" % nas_account . get ( 'capacityGb' , 0 ) ) , nas_account . get ( 'serviceResourceBackendIpAddress' , formatting . blank ( ) ) ] ) env . fout ( table ) | List NAS accounts . | 204 | 4 |
233,258 | def get_api_key ( client , username , secret ) : # Try to use a client with username/api key if len ( secret ) == 64 : try : client [ 'Account' ] . getCurrentUser ( ) return secret except SoftLayer . SoftLayerAPIError as ex : if 'invalid api token' not in ex . faultString . lower ( ) : raise else : # Try to use a client with username/password client . authenticate_with_password ( username , secret ) user_record = client [ 'Account' ] . getCurrentUser ( mask = 'id, apiAuthenticationKeys' ) api_keys = user_record [ 'apiAuthenticationKeys' ] if len ( api_keys ) == 0 : return client [ 'User_Customer' ] . addApiAuthenticationKey ( id = user_record [ 'id' ] ) return api_keys [ 0 ] [ 'authenticationKey' ] | Attempts API - Key and password auth to get an API key . | 197 | 13 |
233,259 | def cli ( env ) : username , secret , endpoint_url , timeout = get_user_input ( env ) new_client = SoftLayer . Client ( username = username , api_key = secret , endpoint_url = endpoint_url , timeout = timeout ) api_key = get_api_key ( new_client , username , secret ) path = '~/.softlayer' if env . config_file : path = env . config_file config_path = os . path . expanduser ( path ) env . out ( env . fmt ( config . config_table ( { 'username' : username , 'api_key' : api_key , 'endpoint_url' : endpoint_url , 'timeout' : timeout } ) ) ) if not formatting . confirm ( 'Are you sure you want to write settings ' 'to "%s"?' % config_path , default = True ) : raise exceptions . CLIAbort ( 'Aborted.' ) # Persist the config file. Read the target config file in before # setting the values to avoid clobbering settings parsed_config = utils . configparser . RawConfigParser ( ) parsed_config . read ( config_path ) try : parsed_config . add_section ( 'softlayer' ) except utils . configparser . DuplicateSectionError : pass parsed_config . set ( 'softlayer' , 'username' , username ) parsed_config . set ( 'softlayer' , 'api_key' , api_key ) parsed_config . set ( 'softlayer' , 'endpoint_url' , endpoint_url ) parsed_config . set ( 'softlayer' , 'timeout' , timeout ) config_fd = os . fdopen ( os . open ( config_path , ( os . O_WRONLY | os . O_CREAT | os . O_TRUNC ) , 0o600 ) , 'w' ) try : parsed_config . write ( config_fd ) finally : config_fd . close ( ) env . fout ( "Configuration Updated Successfully" ) | Edit configuration . | 445 | 3 |
233,260 | def cli ( env , * * kwargs ) : mgr = SoftLayer . DedicatedHostManager ( env . client ) tables = [ ] if not kwargs [ 'flavor' ] and not kwargs [ 'datacenter' ] : options = mgr . get_create_options ( ) # Datacenters dc_table = formatting . Table ( [ 'datacenter' , 'value' ] ) dc_table . sortby = 'value' for location in options [ 'locations' ] : dc_table . add_row ( [ location [ 'name' ] , location [ 'key' ] ] ) tables . append ( dc_table ) dh_table = formatting . Table ( [ 'Dedicated Virtual Host Flavor(s)' , 'value' ] ) dh_table . sortby = 'value' for item in options [ 'dedicated_host' ] : dh_table . add_row ( [ item [ 'name' ] , item [ 'key' ] ] ) tables . append ( dh_table ) else : if kwargs [ 'flavor' ] is None or kwargs [ 'datacenter' ] is None : raise exceptions . ArgumentError ( 'Both a flavor and datacenter need ' 'to be passed as arguments ' 'ex. slcli dh create-options -d ' 'ams01 -f ' '56_CORES_X_242_RAM_X_1_4_TB' ) router_opt = mgr . get_router_options ( kwargs [ 'datacenter' ] , kwargs [ 'flavor' ] ) br_table = formatting . Table ( [ 'Available Backend Routers' ] ) for router in router_opt : br_table . add_row ( [ router [ 'hostname' ] ] ) tables . append ( br_table ) env . fout ( formatting . listing ( tables , separator = '\n' ) ) | host order options for a given dedicated host . | 421 | 9 |
233,261 | def cli ( env ) : table = formatting . Table ( [ 'Code' , 'Reason' ] ) table . align [ 'Code' ] = 'r' table . align [ 'Reason' ] = 'l' mgr = SoftLayer . HardwareManager ( env . client ) for code , reason in mgr . get_cancellation_reasons ( ) . items ( ) : table . add_row ( [ code , reason ] ) env . fout ( table ) | Display a list of cancellation reasons . | 103 | 7 |
233,262 | def cli ( env ) : manager = SoftLayer . IPSECManager ( env . client ) contexts = manager . get_tunnel_contexts ( ) table = formatting . Table ( [ 'id' , 'name' , 'friendly name' , 'internal peer IP address' , 'remote peer IP address' , 'created' ] ) for context in contexts : table . add_row ( [ context . get ( 'id' , '' ) , context . get ( 'name' , '' ) , context . get ( 'friendlyName' , '' ) , context . get ( 'internalPeerIpAddress' , '' ) , context . get ( 'customerPeerIpAddress' , '' ) , context . get ( 'createDate' , '' ) ] ) env . fout ( table ) | List IPSec VPN tunnel contexts | 171 | 6 |
233,263 | def cli ( env , columns , sortby , volume_id ) : file_storage_manager = SoftLayer . FileStorageManager ( env . client ) legal_centers = file_storage_manager . get_replication_locations ( volume_id ) if not legal_centers : click . echo ( "No data centers compatible for replication." ) else : table = formatting . KeyValueTable ( columns . columns ) table . sortby = sortby for legal_center in legal_centers : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( legal_center ) ] ) env . fout ( table ) | List suitable replication datacenters for the given volume . | 141 | 11 |
233,264 | def cli ( env , identifier , sortby , cpu , domain , hostname , memory , tag , columns ) : mgr = SoftLayer . DedicatedHostManager ( env . client ) guests = mgr . list_guests ( host_id = identifier , cpus = cpu , hostname = hostname , domain = domain , memory = memory , tags = tag , mask = columns . mask ( ) ) table = formatting . Table ( columns . columns ) table . sortby = sortby for guest in guests : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( guest ) ] ) env . fout ( table ) | List guests which are in a dedicated host server . | 141 | 10 |
233,265 | def cli ( env , identifier , count ) : mgr = SoftLayer . TicketManager ( env . client ) ticket_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'ticket' ) env . fout ( ticket . get_ticket_results ( mgr , ticket_id , update_count = count ) ) | Get details for a ticket . | 74 | 6 |
233,266 | def get_session ( user_agent ) : client = requests . Session ( ) client . headers . update ( { 'Content-Type' : 'application/json' , 'User-Agent' : user_agent , } ) retry = Retry ( connect = 3 , backoff_factor = 3 ) adapter = HTTPAdapter ( max_retries = retry ) client . mount ( 'https://' , adapter ) return client | Sets up urllib sessions | 91 | 7 |
233,267 | def _format_object_mask ( objectmask ) : objectmask = objectmask . strip ( ) if ( not objectmask . startswith ( 'mask' ) and not objectmask . startswith ( '[' ) ) : objectmask = "mask[%s]" % objectmask return objectmask | Format the new style object mask . | 64 | 7 |
233,268 | def client ( self ) : if self . _client is None : self . _client = get_session ( self . user_agent ) return self . _client | Returns client session object | 34 | 4 |
233,269 | def cli ( env , identifier , enable ) : mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) result = env . client [ 'Hardware_Server' ] . toggleManagementInterface ( enable , id = hw_id ) env . fout ( result ) | Toggle the IPMI interface on and off | 82 | 9 |
233,270 | def cli ( env , record_id ) : manager = SoftLayer . DNSManager ( env . client ) if not ( env . skip_confirmations or formatting . no_going_back ( 'yes' ) ) : raise exceptions . CLIAbort ( "Aborted." ) manager . delete_record ( record_id ) | Remove resource record . | 71 | 4 |
233,271 | def cli ( env , sortby , datacenter ) : block_manager = SoftLayer . BlockStorageManager ( env . client ) mask = "mask[serviceResource[datacenter[name]]," "replicationPartners[serviceResource[datacenter[name]]]]" block_volumes = block_manager . list_block_volumes ( datacenter = datacenter , mask = mask ) # cycle through all block volumes and count datacenter occurences. datacenters = dict ( ) for volume in block_volumes : service_resource = volume [ 'serviceResource' ] if 'datacenter' in service_resource : datacenter_name = service_resource [ 'datacenter' ] [ 'name' ] if datacenter_name not in datacenters . keys ( ) : datacenters [ datacenter_name ] = 1 else : datacenters [ datacenter_name ] += 1 table = formatting . KeyValueTable ( DEFAULT_COLUMNS ) table . sortby = sortby for datacenter_name in datacenters : table . add_row ( [ datacenter_name , datacenters [ datacenter_name ] ] ) env . fout ( table ) | List number of block storage volumes per datacenter . | 269 | 11 |
233,272 | def cli ( env , account_id , content_url ) : manager = SoftLayer . CDNManager ( env . client ) manager . load_content ( account_id , content_url ) | Cache one or more files on all edge nodes . | 42 | 10 |
233,273 | def cli ( env , identifier , no_vs , no_hardware ) : mgr = SoftLayer . NetworkManager ( env . client ) vlan_id = helpers . resolve_id ( mgr . resolve_vlan_ids , identifier , 'VLAN' ) vlan = mgr . get_vlan ( vlan_id ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , vlan [ 'id' ] ] ) table . add_row ( [ 'number' , vlan [ 'vlanNumber' ] ] ) table . add_row ( [ 'datacenter' , vlan [ 'primaryRouter' ] [ 'datacenter' ] [ 'longName' ] ] ) table . add_row ( [ 'primary_router' , vlan [ 'primaryRouter' ] [ 'fullyQualifiedDomainName' ] ] ) table . add_row ( [ 'firewall' , 'Yes' if vlan [ 'firewallInterfaces' ] else 'No' ] ) subnets = [ ] for subnet in vlan . get ( 'subnets' , [ ] ) : subnet_table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) subnet_table . align [ 'name' ] = 'r' subnet_table . align [ 'value' ] = 'l' subnet_table . add_row ( [ 'id' , subnet [ 'id' ] ] ) subnet_table . add_row ( [ 'identifier' , subnet [ 'networkIdentifier' ] ] ) subnet_table . add_row ( [ 'netmask' , subnet [ 'netmask' ] ] ) subnet_table . add_row ( [ 'gateway' , subnet . get ( 'gateway' , '-' ) ] ) subnet_table . add_row ( [ 'type' , subnet [ 'subnetType' ] ] ) subnet_table . add_row ( [ 'usable ips' , subnet [ 'usableIpAddressCount' ] ] ) subnets . append ( subnet_table ) table . add_row ( [ 'subnets' , subnets ] ) server_columns = [ 'hostname' , 'domain' , 'public_ip' , 'private_ip' ] if not no_vs : if vlan . get ( 'virtualGuests' ) : vs_table = formatting . KeyValueTable ( server_columns ) for vsi in vlan [ 'virtualGuests' ] : vs_table . add_row ( [ vsi . get ( 'hostname' ) , vsi . get ( 'domain' ) , vsi . get ( 'primaryIpAddress' ) , vsi . get ( 'primaryBackendIpAddress' ) ] ) table . add_row ( [ 'vs' , vs_table ] ) else : table . add_row ( [ 'vs' , 'none' ] ) if not no_hardware : if vlan . get ( 'hardware' ) : hw_table = formatting . Table ( server_columns ) for hardware in vlan [ 'hardware' ] : hw_table . add_row ( [ hardware . get ( 'hostname' ) , hardware . get ( 'domain' ) , hardware . get ( 'primaryIpAddress' ) , hardware . get ( 'primaryBackendIpAddress' ) ] ) table . add_row ( [ 'hardware' , hw_table ] ) else : table . add_row ( [ 'hardware' , 'none' ] ) env . fout ( table ) | Get details about a VLAN . | 833 | 7 |
233,274 | def cli ( env , volume_id , lun_id ) : block_storage_manager = SoftLayer . BlockStorageManager ( env . client ) res = block_storage_manager . create_or_update_lun_id ( volume_id , lun_id ) if 'value' in res and lun_id == res [ 'value' ] : click . echo ( 'Block volume with id %s is reporting LUN ID %s' % ( res [ 'volumeId' ] , res [ 'value' ] ) ) else : click . echo ( 'Failed to confirm the new LUN ID on volume %s' % ( volume_id ) ) | Set the LUN ID on an existing block storage volume . | 142 | 12 |
233,275 | def cli ( env , identifier ) : mgr = SoftLayer . LoadBalancerManager ( env . client ) _ , loadbal_id = loadbal . parse_id ( identifier ) load_balancer = mgr . get_local_lb ( loadbal_id ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'l' table . align [ 'value' ] = 'l' table . add_row ( [ 'ID' , 'local:%s' % load_balancer [ 'id' ] ] ) table . add_row ( [ 'IP Address' , load_balancer [ 'ipAddress' ] [ 'ipAddress' ] ] ) name = load_balancer [ 'loadBalancerHardware' ] [ 0 ] [ 'datacenter' ] [ 'name' ] table . add_row ( [ 'Datacenter' , name ] ) table . add_row ( [ 'Connections limit' , load_balancer [ 'connectionLimit' ] ] ) table . add_row ( [ 'Dedicated' , load_balancer [ 'dedicatedFlag' ] ] ) table . add_row ( [ 'HA' , load_balancer [ 'highAvailabilityFlag' ] ] ) table . add_row ( [ 'SSL Enabled' , load_balancer [ 'sslEnabledFlag' ] ] ) table . add_row ( [ 'SSL Active' , load_balancer [ 'sslActiveFlag' ] ] ) index0 = 1 for virtual_server in load_balancer [ 'virtualServers' ] : for group in virtual_server [ 'serviceGroups' ] : service_group_table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . add_row ( [ 'Service Group %s' % index0 , service_group_table ] ) index0 += 1 service_group_table . add_row ( [ 'Guest ID' , virtual_server [ 'id' ] ] ) service_group_table . add_row ( [ 'Port' , virtual_server [ 'port' ] ] ) service_group_table . add_row ( [ 'Allocation' , '%s %%' % virtual_server [ 'allocation' ] ] ) service_group_table . add_row ( [ 'Routing Type' , '%s:%s' % ( group [ 'routingTypeId' ] , group [ 'routingType' ] [ 'name' ] ) ] ) service_group_table . add_row ( [ 'Routing Method' , '%s:%s' % ( group [ 'routingMethodId' ] , group [ 'routingMethod' ] [ 'name' ] ) ] ) index1 = 1 for service in group [ 'services' ] : service_table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) service_group_table . add_row ( [ 'Service %s' % index1 , service_table ] ) index1 += 1 health_check = service [ 'healthChecks' ] [ 0 ] service_table . add_row ( [ 'Service ID' , service [ 'id' ] ] ) service_table . add_row ( [ 'IP Address' , service [ 'ipAddress' ] [ 'ipAddress' ] ] ) service_table . add_row ( [ 'Port' , service [ 'port' ] ] ) service_table . add_row ( [ 'Health Check' , '%s:%s' % ( health_check [ 'healthCheckTypeId' ] , health_check [ 'type' ] [ 'name' ] ) ] ) service_table . add_row ( [ 'Weight' , service [ 'groupReferences' ] [ 0 ] [ 'weight' ] ] ) service_table . add_row ( [ 'Enabled' , service [ 'enabled' ] ] ) service_table . add_row ( [ 'Status' , service [ 'status' ] ] ) env . fout ( table ) | Get Load balancer details . | 883 | 6 |
233,276 | def cli ( env , format = 'table' , config = None , verbose = 0 , proxy = None , really = False , demo = False , * * kwargs ) : # Populate environement with client and set it as the context object env . skip_confirmations = really env . config_file = config env . format = format env . ensure_client ( config_file = config , is_demo = demo , proxy = proxy ) env . vars [ '_start' ] = time . time ( ) logger = logging . getLogger ( ) if demo is False : logger . addHandler ( logging . StreamHandler ( ) ) else : # This section is for running CLI tests. logging . getLogger ( "urllib3" ) . setLevel ( logging . WARNING ) logger . addHandler ( logging . NullHandler ( ) ) logger . setLevel ( DEBUG_LOGGING_MAP . get ( verbose , logging . DEBUG ) ) env . vars [ '_timings' ] = SoftLayer . DebugTransport ( env . client . transport ) env . client . transport = env . vars [ '_timings' ] | Main click CLI entry - point . | 250 | 7 |
233,277 | def output_diagnostics ( env , result , verbose = 0 , * * kwargs ) : if verbose > 0 : diagnostic_table = formatting . Table ( [ 'name' , 'value' ] ) diagnostic_table . add_row ( [ 'execution_time' , '%fs' % ( time . time ( ) - START_TIME ) ] ) api_call_value = [ ] for call in env . client . transport . get_last_calls ( ) : api_call_value . append ( "%s::%s (%fs)" % ( call . service , call . method , call . end_time - call . start_time ) ) diagnostic_table . add_row ( [ 'api_calls' , api_call_value ] ) diagnostic_table . add_row ( [ 'version' , consts . USER_AGENT ] ) diagnostic_table . add_row ( [ 'python_version' , sys . version ] ) diagnostic_table . add_row ( [ 'library_location' , os . path . dirname ( SoftLayer . __file__ ) ] ) env . err ( env . fmt ( diagnostic_table ) ) if verbose > 1 : for call in env . client . transport . get_last_calls ( ) : call_table = formatting . Table ( [ '' , '{}::{}' . format ( call . service , call . method ) ] ) nice_mask = '' if call . mask is not None : nice_mask = call . mask call_table . add_row ( [ 'id' , call . identifier ] ) call_table . add_row ( [ 'mask' , nice_mask ] ) call_table . add_row ( [ 'filter' , call . filter ] ) call_table . add_row ( [ 'limit' , call . limit ] ) call_table . add_row ( [ 'offset' , call . offset ] ) env . err ( env . fmt ( call_table ) ) if verbose > 2 : for call in env . client . transport . get_last_calls ( ) : env . err ( env . client . transport . print_reproduceable ( call ) ) | Output diagnostic information . | 477 | 4 |
233,278 | def main ( reraise_exceptions = False , * * kwargs ) : exit_status = 0 try : cli . main ( * * kwargs ) except SoftLayer . SoftLayerAPIError as ex : if 'invalid api token' in ex . faultString . lower ( ) : print ( "Authentication Failed: To update your credentials, use 'slcli config setup'" ) exit_status = 1 else : print ( str ( ex ) ) exit_status = 1 except SoftLayer . SoftLayerError as ex : print ( str ( ex ) ) exit_status = 1 except exceptions . CLIAbort as ex : print ( str ( ex . message ) ) exit_status = ex . code except Exception : if reraise_exceptions : raise import traceback print ( "An unexpected error has occured:" ) print ( str ( traceback . format_exc ( ) ) ) print ( "Feel free to report this error as it is likely a bug:" ) print ( " https://github.com/softlayer/softlayer-python/issues" ) print ( "The following snippet should be able to reproduce the error" ) exit_status = 1 sys . exit ( exit_status ) | Main program . Catches several common errors and displays them nicely . | 255 | 13 |
233,279 | def cli ( env , volume_id , hardware_id , virtual_id , ip_address_id , ip_address ) : block_manager = SoftLayer . BlockStorageManager ( env . client ) ip_address_id_list = list ( ip_address_id ) # Convert actual IP Addresses to their SoftLayer ids if ip_address is not None : network_manager = SoftLayer . NetworkManager ( env . client ) for ip_address_value in ip_address : ip_address_object = network_manager . ip_lookup ( ip_address_value ) ip_address_id_list . append ( ip_address_object [ 'id' ] ) block_manager . deauthorize_host_to_volume ( volume_id , hardware_id , virtual_id , ip_address_id_list ) # If no exception was raised, the command succeeded click . echo ( 'Access to %s was revoked for the specified hosts' % volume_id ) | Revokes authorization for hosts accessing a given volume | 212 | 9 |
233,280 | def cli ( env , identifier , allocation , port , routing_type , routing_method ) : mgr = SoftLayer . LoadBalancerManager ( env . client ) _ , loadbal_id = loadbal . parse_id ( identifier ) mgr . add_service_group ( loadbal_id , allocation = allocation , port = port , routing_type = routing_type , routing_method = routing_method ) env . fout ( 'Load balancer service group is being added!' ) | Adds a new load_balancer service . | 106 | 9 |
233,281 | def cli ( env , identifier ) : dh_mgr = SoftLayer . DedicatedHostManager ( env . client ) host_id = helpers . resolve_id ( dh_mgr . resolve_ids , identifier , 'dedicated host' ) if not ( env . skip_confirmations or formatting . no_going_back ( host_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) table = formatting . Table ( [ 'id' , 'server name' , 'status' ] ) result = dh_mgr . cancel_guests ( host_id ) if result : for status in result : table . add_row ( [ status [ 'id' ] , status [ 'fqdn' ] , status [ 'status' ] ] ) env . fout ( table ) else : click . secho ( 'There is not any guest into the dedicated host %s' % host_id , fg = 'red' ) | Cancel all virtual guests of the dedicated host immediately . | 206 | 11 |
233,282 | def cli ( env , sortby , columns , datacenter , username , storage_type ) : file_manager = SoftLayer . FileStorageManager ( env . client ) file_volumes = file_manager . list_file_volumes ( datacenter = datacenter , username = username , storage_type = storage_type , mask = columns . mask ( ) ) table = formatting . Table ( columns . columns ) table . sortby = sortby for file_volume in file_volumes : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( file_volume ) ] ) env . fout ( table ) | List file storage . | 142 | 4 |
233,283 | def cli ( env , origin_volume_id , origin_snapshot_id , duplicate_size , duplicate_iops , duplicate_tier , duplicate_snapshot_size , billing ) : file_manager = SoftLayer . FileStorageManager ( env . client ) hourly_billing_flag = False if billing . lower ( ) == "hourly" : hourly_billing_flag = True if duplicate_tier is not None : duplicate_tier = float ( duplicate_tier ) try : order = file_manager . order_duplicate_volume ( origin_volume_id , origin_snapshot_id = origin_snapshot_id , duplicate_size = duplicate_size , duplicate_iops = duplicate_iops , duplicate_tier_level = duplicate_tier , duplicate_snapshot_size = duplicate_snapshot_size , hourly_billing_flag = hourly_billing_flag ) except ValueError as ex : raise exceptions . ArgumentError ( str ( ex ) ) if 'placedOrder' in order . keys ( ) : click . echo ( "Order #{0} placed successfully!" . format ( order [ 'placedOrder' ] [ 'id' ] ) ) for item in order [ 'placedOrder' ] [ 'items' ] : click . echo ( " > %s" % item [ 'description' ] ) else : click . echo ( "Order could not be placed! Please verify your options " + "and try again." ) | Order a duplicate file storage volume . | 312 | 7 |
233,284 | def cli ( env , context_id , subnet_id , subnet_type ) : manager = SoftLayer . IPSECManager ( env . client ) # ensure context can be retrieved by given id manager . get_tunnel_context ( context_id ) succeeded = False if subnet_type == 'internal' : succeeded = manager . remove_internal_subnet ( context_id , subnet_id ) elif subnet_type == 'remote' : succeeded = manager . remove_remote_subnet ( context_id , subnet_id ) elif subnet_type == 'service' : succeeded = manager . remove_service_subnet ( context_id , subnet_id ) if succeeded : env . out ( 'Removed {} subnet #{}' . format ( subnet_type , subnet_id ) ) else : raise CLIHalt ( 'Failed to remove {} subnet #{}' . format ( subnet_type , subnet_id ) ) | Remove a subnet from an IPSEC tunnel context . | 214 | 11 |
233,285 | def cli ( env , is_open ) : ticket_mgr = SoftLayer . TicketManager ( env . client ) table = formatting . Table ( [ 'id' , 'assigned_user' , 'title' , 'last_edited' , 'status' , 'updates' , 'priority' ] ) tickets = ticket_mgr . list_tickets ( open_status = is_open , closed_status = not is_open ) for ticket in tickets : user = formatting . blank ( ) if ticket . get ( 'assignedUser' ) : user = "%s %s" % ( ticket [ 'assignedUser' ] [ 'firstName' ] , ticket [ 'assignedUser' ] [ 'lastName' ] ) table . add_row ( [ ticket [ 'id' ] , user , click . wrap_text ( ticket [ 'title' ] ) , ticket [ 'lastEditDate' ] , ticket [ 'status' ] [ 'name' ] , ticket . get ( 'updateCount' , 0 ) , ticket . get ( 'priority' , 0 ) ] ) env . fout ( table ) | List tickets . | 242 | 3 |
233,286 | def cli ( env , identifier ) : mgr = SoftLayer . NetworkManager ( env . client ) secgroup = mgr . get_securitygroup ( identifier ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , secgroup [ 'id' ] ] ) table . add_row ( [ 'name' , secgroup . get ( 'name' ) or formatting . blank ( ) ] ) table . add_row ( [ 'description' , secgroup . get ( 'description' ) or formatting . blank ( ) ] ) rule_table = formatting . Table ( [ 'id' , 'remoteIp' , 'remoteGroupId' , 'direction' , 'ethertype' , 'portRangeMin' , 'portRangeMax' , 'protocol' ] ) for rule in secgroup . get ( 'rules' , [ ] ) : rg_id = rule . get ( 'remoteGroup' , { } ) . get ( 'id' ) or formatting . blank ( ) port_min = rule . get ( 'portRangeMin' ) port_max = rule . get ( 'portRangeMax' ) if port_min is None : port_min = formatting . blank ( ) if port_max is None : port_max = formatting . blank ( ) rule_table . add_row ( [ rule [ 'id' ] , rule . get ( 'remoteIp' ) or formatting . blank ( ) , rule . get ( 'remoteGroupId' , rg_id ) , rule [ 'direction' ] , rule . get ( 'ethertype' ) or formatting . blank ( ) , port_min , port_max , rule . get ( 'protocol' ) or formatting . blank ( ) ] ) table . add_row ( [ 'rules' , rule_table ] ) vsi_table = formatting . Table ( [ 'id' , 'hostname' , 'interface' , 'ipAddress' ] ) for binding in secgroup . get ( 'networkComponentBindings' , [ ] ) : try : vsi = binding [ 'networkComponent' ] [ 'guest' ] vsi_id = vsi [ 'id' ] hostname = vsi [ 'hostname' ] interface = ( 'PRIVATE' if binding [ 'networkComponent' ] [ 'port' ] == 0 else 'PUBLIC' ) ip_address = ( vsi [ 'primaryBackendIpAddress' ] if binding [ 'networkComponent' ] [ 'port' ] == 0 else vsi [ 'primaryIpAddress' ] ) except KeyError : vsi_id = "N/A" hostname = "Not enough permission to view" interface = "N/A" ip_address = "N/A" vsi_table . add_row ( [ vsi_id , hostname , interface , ip_address ] ) table . add_row ( [ 'servers' , vsi_table ] ) env . fout ( table ) | Get details about a security group . | 674 | 7 |
233,287 | def cli ( env , record , record_type , data , zone , ttl , priority , protocol , port , service , weight ) : manager = SoftLayer . DNSManager ( env . client ) record_type = record_type . upper ( ) if zone and record_type != 'PTR' : zone_id = helpers . resolve_id ( manager . resolve_ids , zone , name = 'zone' ) if record_type == 'MX' : manager . create_record_mx ( zone_id , record , data , ttl = ttl , priority = priority ) elif record_type == 'SRV' : manager . create_record_srv ( zone_id , record , data , protocol , port , service , ttl = ttl , priority = priority , weight = weight ) else : manager . create_record ( zone_id , record , record_type , data , ttl = ttl ) elif record_type == 'PTR' : manager . create_record_ptr ( record , data , ttl = ttl ) else : raise exceptions . CLIAbort ( "%s isn't a valid record type or zone is missing" % record_type ) click . secho ( "%s record added successfully" % record_type , fg = 'green' ) | Add resource record . | 278 | 4 |
233,288 | def cli ( env , identifier ) : mgr = SoftLayer . LoadBalancerManager ( env . client ) _ , loadbal_id = loadbal . parse_id ( identifier ) if not ( env . skip_confirmations or formatting . confirm ( "This action will cancel a load balancer. " "Continue?" ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) mgr . cancel_lb ( loadbal_id ) env . fout ( 'Load Balancer with id %s is being cancelled!' % identifier ) | Cancel an existing load balancer . | 117 | 8 |
233,289 | def cli ( env , package_keyname , keyword ) : table = formatting . Table ( COLUMNS ) manager = ordering . OrderingManager ( env . client ) _filter = { } if keyword : _filter = { 'activePresets' : { 'name' : { 'operation' : '*= %s' % keyword } } } presets = manager . list_presets ( package_keyname , filter = _filter ) for preset in presets : table . add_row ( [ preset [ 'name' ] , preset [ 'keyName' ] , preset [ 'description' ] ] ) env . fout ( table ) | List package presets . | 138 | 4 |
233,290 | def permission_table ( user_permissions , all_permissions ) : table = formatting . Table ( [ 'Description' , 'KeyName' , 'Assigned' ] ) table . align [ 'KeyName' ] = 'l' table . align [ 'Description' ] = 'l' table . align [ 'Assigned' ] = 'l' for perm in all_permissions : assigned = user_permissions . get ( perm [ 'keyName' ] , False ) table . add_row ( [ perm [ 'name' ] , perm [ 'keyName' ] , assigned ] ) return table | Creates a table of available permissions | 130 | 7 |
233,291 | def roles_table ( user ) : table = formatting . Table ( [ 'id' , 'Role Name' , 'Description' ] ) for role in user [ 'roles' ] : table . add_row ( [ role [ 'id' ] , role [ 'name' ] , role [ 'description' ] ] ) return table | Creates a table for a users roles | 71 | 8 |
233,292 | def _update_with_like_args ( ctx , _ , value ) : if value is None : return env = ctx . ensure_object ( environment . Environment ) vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , value , 'VS' ) like_details = vsi . get_instance ( vs_id ) like_args = { 'hostname' : like_details [ 'hostname' ] , 'domain' : like_details [ 'domain' ] , 'hourly' : like_details [ 'hourlyBillingFlag' ] , 'datacenter' : like_details [ 'datacenter' ] [ 'name' ] , 'network' : like_details [ 'networkComponents' ] [ 0 ] [ 'maxSpeed' ] , 'userdata' : like_details [ 'userData' ] or None , 'postinstall' : like_details . get ( 'postInstallScriptUri' ) , 'dedicated' : like_details [ 'dedicatedAccountHostOnlyFlag' ] , 'private' : like_details [ 'privateNetworkOnlyFlag' ] , 'placement_id' : like_details . get ( 'placementGroupId' , None ) , } like_args [ 'flavor' ] = utils . lookup ( like_details , 'billingItem' , 'orderItem' , 'preset' , 'keyName' ) if not like_args [ 'flavor' ] : like_args [ 'cpu' ] = like_details [ 'maxCpu' ] like_args [ 'memory' ] = '%smb' % like_details [ 'maxMemory' ] tag_refs = like_details . get ( 'tagReferences' , None ) if tag_refs is not None and len ( tag_refs ) > 0 : like_args [ 'tag' ] = [ t [ 'tag' ] [ 'name' ] for t in tag_refs ] # Handle mutually exclusive options like_image = utils . lookup ( like_details , 'blockDeviceTemplateGroup' , 'globalIdentifier' ) like_os = utils . lookup ( like_details , 'operatingSystem' , 'softwareLicense' , 'softwareDescription' , 'referenceCode' ) if like_image : like_args [ 'image' ] = like_image elif like_os : like_args [ 'os' ] = like_os if ctx . default_map is None : ctx . default_map = { } ctx . default_map . update ( like_args ) | Update arguments with options taken from a currently running VS . | 574 | 11 |
233,293 | def _build_receipt_table ( result , billing = "hourly" , test = False ) : title = "OrderId: %s" % ( result . get ( 'orderId' , 'No order placed' ) ) table = formatting . Table ( [ 'Cost' , 'Description' ] , title = title ) table . align [ 'Cost' ] = 'r' table . align [ 'Description' ] = 'l' total = 0.000 if test : prices = result [ 'prices' ] else : prices = result [ 'orderDetails' ] [ 'prices' ] for item in prices : rate = 0.000 if billing == "hourly" : rate += float ( item . get ( 'hourlyRecurringFee' , 0.000 ) ) else : rate += float ( item . get ( 'recurringFee' , 0.000 ) ) total += rate table . add_row ( [ rate , item [ 'item' ] [ 'description' ] ] ) table . add_row ( [ "%.3f" % total , "Total %s cost" % billing ] ) return table | Retrieve the total recurring fee of the items prices | 243 | 10 |
233,294 | def _validate_args ( env , args ) : if all ( [ args [ 'cpu' ] , args [ 'flavor' ] ] ) : raise exceptions . ArgumentError ( '[-c | --cpu] not allowed with [-f | --flavor]' ) if all ( [ args [ 'memory' ] , args [ 'flavor' ] ] ) : raise exceptions . ArgumentError ( '[-m | --memory] not allowed with [-f | --flavor]' ) if all ( [ args [ 'dedicated' ] , args [ 'flavor' ] ] ) : raise exceptions . ArgumentError ( '[-d | --dedicated] not allowed with [-f | --flavor]' ) if all ( [ args [ 'host_id' ] , args [ 'flavor' ] ] ) : raise exceptions . ArgumentError ( '[-h | --host-id] not allowed with [-f | --flavor]' ) if all ( [ args [ 'userdata' ] , args [ 'userfile' ] ] ) : raise exceptions . ArgumentError ( '[-u | --userdata] not allowed with [-F | --userfile]' ) image_args = [ args [ 'os' ] , args [ 'image' ] ] if all ( image_args ) : raise exceptions . ArgumentError ( '[-o | --os] not allowed with [--image]' ) while not any ( [ args [ 'os' ] , args [ 'image' ] ] ) : args [ 'os' ] = env . input ( "Operating System Code" , default = "" , show_default = False ) if not args [ 'os' ] : args [ 'image' ] = env . input ( "Image" , default = "" , show_default = False ) | Raises an ArgumentError if the given arguments are not valid . | 376 | 13 |
233,295 | def cli ( env , identifier , cpu , private , memory , network , flavor ) : vsi = SoftLayer . VSManager ( env . client ) if not any ( [ cpu , memory , network , flavor ] ) : raise exceptions . ArgumentError ( "Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade" ) if private and not cpu : raise exceptions . ArgumentError ( "Must specify [--cpu] when using [--private]" ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( "This action will incur charges on your account. Continue?" ) ) : raise exceptions . CLIAbort ( 'Aborted' ) if memory : memory = int ( memory / 1024 ) if not vsi . upgrade ( vs_id , cpus = cpu , memory = memory , nic_speed = network , public = not private , preset = flavor ) : raise exceptions . CLIAbort ( 'VS Upgrade Failed' ) | Upgrade a virtual server . | 231 | 5 |
233,296 | def reboot ( env , identifier , hard ) : hardware_server = env . client [ 'Hardware_Server' ] mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will power off the server with id %s. ' 'Continue?' % hw_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) if hard is True : hardware_server . rebootHard ( id = hw_id ) elif hard is False : hardware_server . rebootSoft ( id = hw_id ) else : hardware_server . rebootDefault ( id = hw_id ) | Reboot an active server . | 169 | 6 |
233,297 | def power_on ( env , identifier ) : mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) env . client [ 'Hardware_Server' ] . powerOn ( id = hw_id ) | Power on a server . | 69 | 5 |
233,298 | def power_cycle ( env , identifier ) : mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will power off the server with id %s. ' 'Continue?' % hw_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) env . client [ 'Hardware_Server' ] . powerCycle ( id = hw_id ) | Power cycle a server . | 122 | 5 |
233,299 | def cli ( env , group_id , name , description ) : mgr = SoftLayer . NetworkManager ( env . client ) data = { } if name : data [ 'name' ] = name if description : data [ 'description' ] = description if not mgr . edit_securitygroup ( group_id , * * data ) : raise exceptions . CLIAbort ( "Failed to edit security group" ) | Edit details of a security group . | 90 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.