query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Gets the details for a Network and its IP Addresses .
def GetNetworkDetails ( network , alias = None , location = None ) : if alias is None : alias = clc . v1 . Account . GetAlias ( ) if location is None : location = clc . v1 . Account . GetLocation ( ) r = clc . v1 . API . Call ( 'post' , 'Network/GetNetworkDetails' , { 'AccountAlias' : alias , 'Location' : location , 'Name' : network } ) if int ( r [ 'StatusCode' ] ) == 0 : return ( r [ 'NetworkDetails' ] [ 'IPAddresses' ] )
6,500
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/network.py#L30-L42
[ "def", "increment_lessons", "(", "self", ",", "measure_vals", ",", "reward_buff_sizes", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "reward_buff_sizes", ":", "for", "brain_name", ",", "buff_size", "in", "reward_buff_sizes", ".", "items", "(", ")", ":", "if", "self", ".", "_lesson_ready_to_increment", "(", "brain_name", ",", "buff_size", ")", ":", "measure_val", "=", "measure_vals", "[", "brain_name", "]", "ret", "[", "brain_name", "]", "=", "(", "self", ".", "brains_to_curriculums", "[", "brain_name", "]", ".", "increment_lesson", "(", "measure_val", ")", ")", "else", ":", "for", "brain_name", ",", "measure_val", "in", "measure_vals", ".", "items", "(", ")", ":", "ret", "[", "brain_name", "]", "=", "(", "self", ".", "brains_to_curriculums", "[", "brain_name", "]", ".", "increment_lesson", "(", "measure_val", ")", ")", "return", "ret" ]
Grab the variable from closest frame in the stack
def get_variable_from_exception ( exception , variable_name ) : for frame in reversed ( trace ( ) ) : try : # From http://stackoverflow.com/a/9059407/6461688 frame_variable = frame [ 0 ] . f_locals [ variable_name ] except KeyError : pass else : return frame_variable else : raise KeyError ( "Variable '%s' not in any stack frames" , variable_name )
6,501
https://github.com/blag/django-secure-mail/blob/52987b6ce829e6de2dc8ab38ed3190bc2752b341/secure_mail/handlers.py#L14-L27
[ "def", "create_bundle", "(", "self", ",", "bundleId", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "url", "=", "self", ".", "__get_base_bundle_url", "(", ")", "+", "\"/\"", "+", "bundleId", "if", "data", "is", "None", ":", "data", "=", "{", "}", "data", "[", "'sourceLanguage'", "]", "=", "'en'", "data", "[", "'targetLanguages'", "]", "=", "[", "]", "data", "[", "'notes'", "]", "=", "[", "]", "data", "[", "'metadata'", "]", "=", "{", "}", "data", "[", "'partner'", "]", "=", "''", "data", "[", "'segmentSeparatorPattern'", "]", "=", "''", "data", "[", "'noTranslationPattern'", "]", "=", "''", "json_data", "=", "json", ".", "dumps", "(", "data", ")", "response", "=", "self", ".", "__perform_rest_call", "(", "requestURL", "=", "url", ",", "restType", "=", "'PUT'", ",", "body", "=", "json_data", ",", "headers", "=", "headers", ")", "return", "response" ]
Delete the key from the keyring and the Key and Address objects from the database
def force_delete_key ( address ) : address_object = Address . objects . get ( address = address ) address_object . key . delete ( ) address_object . delete ( )
6,502
https://github.com/blag/django-secure-mail/blob/52987b6ce829e6de2dc8ab38ed3190bc2752b341/secure_mail/handlers.py#L72-L79
[ "def", "upload", "(", "self", ",", "params", "=", "{", "}", ")", ":", "if", "self", ".", "upload_token", "is", "not", "None", ":", "# resume upload", "status", "=", "self", ".", "check", "(", ")", "if", "status", "[", "'status'", "]", "!=", "4", ":", "return", "self", ".", "commit", "(", ")", "else", ":", "self", ".", "new_slice", "(", ")", "while", "self", ".", "slice_task_id", "!=", "0", ":", "self", ".", "upload_slice", "(", ")", "return", "self", ".", "commit", "(", ")", "else", ":", "# new upload", "self", ".", "create", "(", "self", ".", "prepare_video_params", "(", "*", "*", "params", ")", ")", "self", ".", "create_file", "(", ")", "self", ".", "new_slice", "(", ")", "while", "self", ".", "slice_task_id", "!=", "0", ":", "self", ".", "upload_slice", "(", ")", "return", "self", ".", "commit", "(", ")" ]
Wrap accepted value in the list if yet not wrapped .
def __wrap_accepted_val ( self , value ) : if isinstance ( value , tuple ) : value = list ( value ) elif not isinstance ( value , list ) : value = [ value ] return value
6,503
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L44-L51
[ "def", "load_draco", "(", "file_obj", ",", "*", "*", "kwargs", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.drc'", ")", "as", "temp_drc", ":", "temp_drc", ".", "write", "(", "file_obj", ".", "read", "(", ")", ")", "temp_drc", ".", "flush", "(", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.ply'", ")", "as", "temp_ply", ":", "subprocess", ".", "check_output", "(", "[", "draco_decoder", ",", "'-i'", ",", "temp_drc", ".", "name", ",", "'-o'", ",", "temp_ply", ".", "name", "]", ")", "temp_ply", ".", "seek", "(", "0", ")", "kwargs", "=", "load_ply", "(", "temp_ply", ")", "return", "kwargs" ]
Compare value of each required argument with list of accepted values .
def __validate_args ( self , func_name , args , kwargs ) : from pyvalid . validators import Validator for i , ( arg_name , accepted_values ) in enumerate ( self . accepted_args ) : if i < len ( args ) : value = args [ i ] else : if arg_name in kwargs : value = kwargs [ arg_name ] elif i in self . optional_args : continue else : raise InvalidArgumentNumberError ( func_name ) is_valid = False for accepted_val in accepted_values : is_validator = ( isinstance ( accepted_val , Validator ) or ( isinstance ( accepted_val , MethodType ) and hasattr ( accepted_val , '__func__' ) and isinstance ( accepted_val . __func__ , Validator ) ) ) if is_validator : is_valid = accepted_val ( value ) elif isinstance ( accepted_val , type ) : is_valid = isinstance ( value , accepted_val ) else : is_valid = value == accepted_val if is_valid : break if not is_valid : ord_num = self . __ordinal ( i + 1 ) raise ArgumentValidationError ( ord_num , func_name , value , accepted_values )
6,504
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L94-L145
[ "def", "parse_game_result", "(", "result", ")", ":", "if", "re", ".", "match", "(", "r'[bB]\\+'", ",", "result", ")", ":", "return", "1", "if", "re", ".", "match", "(", "r'[wW]\\+'", ",", "result", ")", ":", "return", "-", "1", "return", "0" ]
Returns the ordinal number of a given integer as a string . eg . 1 - > 1st 2 - > 2nd 3 - > 3rd etc .
def __ordinal ( self , num ) : if 10 <= num % 100 < 20 : return str ( num ) + 'th' else : ord_info = { 1 : 'st' , 2 : 'nd' , 3 : 'rd' } . get ( num % 10 , 'th' ) return '{}{}' . format ( num , ord_info )
6,505
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L147-L155
[ "def", "detach_all_classes", "(", "self", ")", ":", "classes", "=", "list", "(", "self", ".", "_observers", ".", "keys", "(", ")", ")", "for", "cls", "in", "classes", ":", "self", ".", "detach_class", "(", "cls", ")" ]
Retrieves file identified by name .
def get_file ( self , name , save_to , add_to_cache = True , force_refresh = False , _lock_exclusive = False ) : uname , version = split_name ( name ) lock = None if self . local_store : lock = self . lock_manager . lock_for ( uname ) if _lock_exclusive : lock . lock_exclusive ( ) else : lock . lock_shared ( ) else : add_to_cache = False t = time . time ( ) logger . debug ( ' downloading %s' , name ) try : if not self . remote_store or ( version is not None and not force_refresh ) : try : if self . local_store and self . local_store . exists ( name ) : return self . local_store . get_file ( name , save_to ) except Exception : if self . remote_store : logger . warning ( "Error getting '%s' from local store" , name , exc_info = True ) else : raise if self . remote_store : if not _lock_exclusive and add_to_cache : if lock : lock . unlock ( ) return self . get_file ( name , save_to , add_to_cache , _lock_exclusive = True ) vname = self . remote_store . get_file ( name , save_to ) if add_to_cache : self . _add_to_cache ( vname , save_to ) return vname raise FiletrackerError ( "File not available: %s" % name ) finally : if lock : lock . close ( ) logger . debug ( ' processed %s in %.2fs' , name , time . time ( ) - t )
6,506
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L91-L152
[ "def", "start_publishing", "(", "mysql_settings", ",", "*", "*", "kwargs", ")", ":", "_logger", ".", "info", "(", "'Start publishing from %s with:\\n%s'", "%", "(", "mysql_settings", ",", "kwargs", ")", ")", "kwargs", ".", "setdefault", "(", "'server_id'", ",", "random", ".", "randint", "(", "1000000000", ",", "4294967295", ")", ")", "kwargs", ".", "setdefault", "(", "'freeze_schema'", ",", "True", ")", "# connect to binlog stream", "stream", "=", "pymysqlreplication", ".", "BinLogStreamReader", "(", "mysql_settings", ",", "only_events", "=", "[", "row_event", ".", "DeleteRowsEvent", ",", "row_event", ".", "UpdateRowsEvent", ",", "row_event", ".", "WriteRowsEvent", "]", ",", "*", "*", "kwargs", ")", "\"\"\":type list[RowsEvent]\"\"\"", "for", "event", "in", "stream", ":", "# ignore non row events", "if", "not", "isinstance", "(", "event", ",", "row_event", ".", "RowsEvent", ")", ":", "continue", "_logger", ".", "debug", "(", "'Send binlog signal \"%s@%s.%s\"'", "%", "(", "event", ".", "__class__", ".", "__name__", ",", "event", ".", "schema", ",", "event", ".", "table", ")", ")", "signals", ".", "binlog_signal", ".", "send", "(", "event", ",", "stream", "=", "stream", ")", "signals", ".", "binlog_position_signal", ".", "send", "(", "(", "stream", ".", "log_file", ",", "stream", ".", "log_pos", ")", ")" ]
Retrieves file identified by name in streaming mode .
def get_stream ( self , name , force_refresh = False , serve_from_cache = False ) : uname , version = split_name ( name ) lock = None if self . local_store : lock = self . lock_manager . lock_for ( uname ) lock . lock_shared ( ) try : if not self . remote_store or ( version is not None and not force_refresh ) : try : if self . local_store and self . local_store . exists ( name ) : return self . local_store . get_stream ( name ) except Exception : if self . remote_store : logger . warning ( "Error getting '%s' from local store" , name , exc_info = True ) else : raise if self . remote_store : if self . local_store and serve_from_cache : if version is None : version = self . remote_store . file_version ( name ) if version : name = versioned_name ( uname , version ) if force_refresh or not self . local_store . exists ( name ) : ( stream , vname ) = self . remote_store . get_stream ( name ) name = self . local_store . add_stream ( vname , stream ) return self . local_store . get_stream ( name ) return self . remote_store . get_stream ( name ) raise FiletrackerError ( "File not available: %s" % name ) finally : if lock : lock . close ( )
6,507
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L154-L199
[ "def", "dump", "(", "self", ")", ":", "assert", "self", ".", "database", "is", "not", "None", "cmd", "=", "\"SELECT count from {} WHERE rowid={}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_INFO_TABLE", ",", "self", ".", "STATE_INFO_ROW", ")", ")", "ret", "=", "self", ".", "_fetchall", "(", ")", "assert", "len", "(", "ret", ")", "==", "1", "assert", "len", "(", "ret", "[", "0", "]", ")", "==", "1", "count", "=", "self", ".", "_from_sqlite", "(", "ret", "[", "0", "]", "[", "0", "]", ")", "+", "self", ".", "inserts", "if", "count", ">", "self", ".", "row_limit", ":", "msg", "=", "\"cleaning up state, this might take a while.\"", "logger", ".", "warning", "(", "msg", ")", "delete", "=", "count", "-", "self", ".", "row_limit", "delete", "+=", "int", "(", "self", ".", "row_limit", "*", "(", "self", ".", "row_cleanup_quota", "/", "100.0", ")", ")", "cmd", "=", "(", "\"DELETE FROM {} WHERE timestamp IN (\"", "\"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});\"", ")", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_TABLE", ",", "self", ".", "STATE_TABLE", ",", "delete", ")", ")", "self", ".", "_vacuum", "(", ")", "cmd", "=", "\"SELECT COUNT(*) FROM {}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_TABLE", ")", ")", "ret", "=", "self", ".", "_fetchall", "(", ")", "assert", "len", "(", "ret", ")", "==", "1", "assert", "len", "(", "ret", "[", "0", "]", ")", "==", "1", "count", "=", "ret", "[", "0", "]", "[", "0", "]", "cmd", "=", "\"UPDATE {} SET count = {} WHERE rowid = {}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_INFO_TABLE", ",", "self", ".", "_to_sqlite", "(", "count", ")", ",", "self", ".", "STATE_INFO_ROW", ",", ")", ")", "self", ".", "_update_cache_directory_state", "(", ")", "self", ".", "database", ".", "commit", "(", ")", "self", ".", "cursor", ".", "close", "(", ")", "self", ".", "database", ".", "close", "(", ")", "self", ".", "database", "=", "None", "self", ".", "cursor", "=", "None", "self", ".", "inserts", "=", "0" ]
Returns the newest available version number of the file .
def file_version ( self , name ) : if self . remote_store : return self . remote_store . file_version ( name ) else : return self . local_store . file_version ( name )
6,508
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L201-L214
[ "def", "is_string_type", "(", "type_", ")", ":", "string_types", "=", "_get_types", "(", "Types", ".", "STRING", ")", "if", "is_typing_type", "(", "type_", ")", ":", "return", "type_", "in", "string_types", "or", "is_regex_type", "(", "type_", ")", "return", "type_", "in", "string_types" ]
Returns the size of the file .
def file_size ( self , name , force_refresh = False ) : uname , version = split_name ( name ) t = time . time ( ) logger . debug ( ' querying size of %s' , name ) try : if not self . remote_store or ( version is not None and not force_refresh ) : try : if self . local_store and self . local_store . exists ( name ) : return self . local_store . file_size ( name ) except Exception : if self . remote_store : logger . warning ( "Error getting '%s' from local store" , name , exc_info = True ) else : raise if self . remote_store : return self . remote_store . file_size ( name ) raise FiletrackerError ( "File not available: %s" % name ) finally : logger . debug ( ' processed %s in %.2fs' , name , time . time ( ) - t )
6,509
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L216-L243
[ "def", "deletecols", "(", "X", ",", "cols", ")", ":", "if", "isinstance", "(", "cols", ",", "str", ")", ":", "cols", "=", "cols", ".", "split", "(", "','", ")", "retain", "=", "[", "n", "for", "n", "in", "X", ".", "dtype", ".", "names", "if", "n", "not", "in", "cols", "]", "if", "len", "(", "retain", ")", ">", "0", ":", "return", "X", "[", "retain", "]", "else", ":", "return", "None" ]
Adds file filename to the filetracker under the name name .
def put_file ( self , name , filename , to_local_store = True , to_remote_store = True , compress_hint = True ) : if not to_local_store and not to_remote_store : raise ValueError ( "Neither to_local_store nor to_remote_store set " "in a call to filetracker.Client.put_file" ) check_name ( name ) lock = None if self . local_store : lock = self . lock_manager . lock_for ( name ) lock . lock_exclusive ( ) try : if ( to_local_store or not self . remote_store ) and self . local_store : versioned_name = self . local_store . add_file ( name , filename ) if ( to_remote_store or not self . local_store ) and self . remote_store : versioned_name = self . remote_store . add_file ( name , filename , compress_hint = compress_hint ) finally : if lock : lock . close ( ) return versioned_name
6,510
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L245-L292
[ "def", "start", "(", "self", ",", "device_uuid", ")", ":", "status_code", ",", "_", ",", "session", "=", "self", ".", "http_client", ".", "post", "(", "'/sync/start'", ",", "body", "=", "None", ",", "headers", "=", "self", ".", "build_headers", "(", "device_uuid", ")", ")", "return", "None", "if", "status_code", "==", "204", "else", "session" ]
Deletes the file identified by name along with its metadata .
def delete_file ( self , name ) : if self . local_store : lock = self . lock_manager . lock_for ( name ) lock . lock_exclusive ( ) try : self . local_store . delete_file ( name ) finally : lock . close ( ) if self . remote_store : self . remote_store . delete_file ( name )
6,511
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L294-L307
[ "def", "win32_refresh_window", "(", "cls", ")", ":", "# Get console handle", "handle", "=", "windll", ".", "kernel32", ".", "GetConsoleWindow", "(", ")", "RDW_INVALIDATE", "=", "0x0001", "windll", ".", "user32", ".", "RedrawWindow", "(", "handle", ",", "None", ",", "None", ",", "c_uint", "(", "RDW_INVALIDATE", ")", ")" ]
Returns list of all stored local files .
def list_local_files ( self ) : result = [ ] if self . local_store : result . extend ( self . local_store . list_files ( ) ) return result
6,512
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L309-L318
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Load the checkers
def load_checkers ( ) : for loader , name , _ in pkgutil . iter_modules ( [ os . path . join ( __path__ [ 0 ] , 'checkers' ) ] ) : loader . find_module ( name ) . load_module ( name )
6,513
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/__init__.py#L17-L20
[ "def", "_timestamp_regulator", "(", "self", ")", ":", "unified_timestamps", "=", "_PrettyDefaultDict", "(", "list", ")", "staged_files", "=", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", "for", "timestamp_basename", "in", "self", ".", "__timestamps_unregulated", ":", "if", "len", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ">", "1", ":", "# File has been splitted", "timestamp_name", "=", "''", ".", "join", "(", "timestamp_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "staged_splitted_files_of_timestamp", "=", "list", "(", "filter", "(", "lambda", "staged_file", ":", "(", "timestamp_name", "==", "staged_file", "[", ":", "-", "3", "]", "and", "all", "(", "[", "(", "x", "in", "set", "(", "map", "(", "str", ",", "range", "(", "10", ")", ")", ")", ")", "for", "x", "in", "staged_file", "[", "-", "3", ":", "]", "]", ")", ")", ",", "staged_files", ")", ")", "if", "len", "(", "staged_splitted_files_of_timestamp", ")", "==", "0", ":", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "timestamp_basename", ")", "]", "=", "{", "\"reason\"", ":", "\"Missing staged file\"", ",", "\"current_staged_files\"", ":", "staged_files", "}", "continue", "staged_splitted_files_of_timestamp", ".", "sort", "(", ")", "unified_timestamp", "=", "list", "(", ")", "for", "staging_digits", ",", "splitted_file", "in", "enumerate", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ":", "prev_splits_sec", "=", "0", "if", "int", "(", "staging_digits", ")", "!=", "0", ":", "prev_splits_sec", "=", "self", ".", "_get_audio_duration_seconds", "(", "\"{}/staging/{}{:03d}\"", ".", "format", "(", "self", ".", "src_dir", ",", "timestamp_name", ",", "staging_digits", "-", "1", ")", ")", "for", "word_block", "in", "splitted_file", ":", "unified_timestamp", ".", "append", "(", "_WordBlock", "(", "word", "=", "word_block", ".", "word", ",", "start", "=", "round", "(", "word_block", ".", "start", "+", "prev_splits_sec", ",", "2", ")", ",", "end", "=", "round", "(", "word_block", ".", "end", "+", "prev_splits_sec", ",", "2", ")", ")", ")", "unified_timestamps", "[", "str", "(", "timestamp_basename", ")", "]", "+=", "unified_timestamp", "else", ":", "unified_timestamps", "[", "timestamp_basename", "]", "+=", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", "[", "0", "]", "self", ".", "__timestamps", ".", "update", "(", "unified_timestamps", ")", "self", ".", "__timestamps_unregulated", "=", "_PrettyDefaultDict", "(", "list", ")" ]
Check all the things
def check ( operations , loud = False ) : if not CHECKERS : load_checkers ( ) roll_call = [ ] everything_ok = True if loud and operations : title = "Preflyt Checklist" sys . stderr . write ( "{}\n{}\n" . format ( title , "=" * len ( title ) ) ) for operation in operations : if operation . get ( 'checker' ) not in CHECKERS : raise CheckerNotFoundError ( operation ) checker_cls = CHECKERS [ operation [ 'checker' ] ] args = { k : v for k , v in operation . items ( ) if k != 'checker' } checker = checker_cls ( * * args ) success , message = checker . check ( ) if not success : everything_ok = False roll_call . append ( { "check" : operation , "success" : success , "message" : message } ) if loud : sys . stderr . write ( " {}\n" . format ( pformat_check ( success , operation , message ) ) ) return everything_ok , roll_call
6,514
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/__init__.py#L22-L49
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
Check all the things and be assertive about it
def verify ( operations , loud = False ) : everything_ok , roll_call = check ( operations , loud = loud ) if not everything_ok : raise CheckFailedException ( roll_call ) return roll_call
6,515
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/__init__.py#L51-L62
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
Returns the sexagesimal representation of a decimal number .
def deci2sexa ( deci , pre = 3 , trunc = False , lower = None , upper = None , b = False , upper_trim = False ) : if lower is not None and upper is not None : deci = normalize ( deci , lower = lower , upper = upper , b = b ) sign = 1 if deci < 0 : deci = abs ( deci ) sign = - 1 hd , f1 = divmod ( deci , 1 ) mm , f2 = divmod ( f1 * 60.0 , 1 ) sf = f2 * 60.0 # Find the seconds part to required precision. fp = 10 ** pre if trunc : ss , _ = divmod ( sf * fp , 1 ) else : ss = round ( sf * fp , 0 ) ss = int ( ss ) # If ss is 60 to given precision then update mm, and if necessary # hd. if ss == 60 * fp : mm += 1 ss = 0 if mm == 60 : hd += 1 mm = 0 hd = int ( hd ) mm = int ( mm ) if lower is not None and upper is not None and upper_trim : # For example 24h0m0s => 0h0m0s. if hd == upper : hd = int ( lower ) if hd == 0 and mm == 0 and ss == 0 : sign = 1 ss /= float ( fp ) # hd and mm parts are integer values but of type float return ( sign , hd , mm , ss )
6,516
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L269-L403
[ "def", "listMetaContentTypes", "(", "self", ")", ":", "all_md_content_types", "=", "(", "CT_CORE_PROPS", ",", "CT_EXT_PROPS", ",", "CT_CUSTOM_PROPS", ")", "return", "[", "k", "for", "k", "in", "self", ".", "overrides", ".", "keys", "(", ")", "if", "k", "in", "all_md_content_types", "]" ]
Combine sexagesimal components into a decimal number .
def sexa2deci ( sign , hd , mm , ss , todeg = False ) : divisors = [ 1.0 , 60.0 , 3600.0 ] d = 0.0 # sexages[0] is sign. if sign not in ( - 1 , 1 ) : raise ValueError ( "Sign has to be -1 or 1." ) sexages = [ sign , hd , mm , ss ] for i , divis in zip ( sexages [ 1 : ] , divisors ) : d += i / divis # Add proper sign. d *= sexages [ 0 ] if todeg : d = h2d ( d ) return d
6,517
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L406-L477
[ "def", "register_on_session_state_changed", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_session_state_changed", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_type", ")" ]
Return sexagesimal string of given angle in degrees or hours .
def fmt_angle ( val , s1 = " " , s2 = " " , s3 = "" , pre = 3 , trunc = False , lower = None , upper = None , b = False , upper_trim = False ) : x = deci2sexa ( val , pre = pre , trunc = trunc , lower = lower , upper = upper , upper_trim = upper_trim , b = b ) left_digits_plus_deci_point = 3 if pre > 0 else 2 p = "{3:0" + "{0}.{1}" . format ( pre + left_digits_plus_deci_point , pre ) + "f}" + s3 p = "{0}{1:02d}" + s1 + "{2:02d}" + s2 + p return p . format ( "-" if x [ 0 ] < 0 else "+" , * x [ 1 : ] )
6,518
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L480-L551
[ "def", "BlockDevice", "(", "self", ",", "adapter_device_name", ",", "device_address", ")", ":", "device_name", "=", "'dev_'", "+", "device_address", ".", "replace", "(", "':'", ",", "'_'", ")", ".", "upper", "(", ")", "adapter_path", "=", "'/org/bluez/'", "+", "adapter_device_name", "device_path", "=", "adapter_path", "+", "'/'", "+", "device_name", "if", "adapter_path", "not", "in", "mockobject", ".", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'Adapter %s does not exist.'", "%", "adapter_device_name", ",", "name", "=", "BLUEZ_MOCK_IFACE", "+", "'.NoSuchAdapter'", ")", "if", "device_path", "not", "in", "mockobject", ".", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'Device %s does not exist.'", "%", "device_name", ",", "name", "=", "BLUEZ_MOCK_IFACE", "+", "'.NoSuchDevice'", ")", "device", "=", "mockobject", ".", "objects", "[", "device_path", "]", "device", ".", "props", "[", "DEVICE_IFACE", "]", "[", "'Blocked'", "]", "=", "dbus", ".", "Boolean", "(", "True", ",", "variant_level", "=", "1", ")", "device", ".", "props", "[", "DEVICE_IFACE", "]", "[", "'Connected'", "]", "=", "dbus", ".", "Boolean", "(", "False", ",", "variant_level", "=", "1", ")", "device", ".", "EmitSignal", "(", "dbus", ".", "PROPERTIES_IFACE", ",", "'PropertiesChanged'", ",", "'sa{sv}as'", ",", "[", "DEVICE_IFACE", ",", "{", "'Blocked'", ":", "dbus", ".", "Boolean", "(", "True", ",", "variant_level", "=", "1", ")", ",", "'Connected'", ":", "dbus", ".", "Boolean", "(", "False", ",", "variant_level", "=", "1", ")", ",", "}", ",", "[", "]", ",", "]", ")" ]
Parse a string containing a sexagesimal number .
def phmsdms ( hmsdms ) : units = None sign = None # Floating point regex: # http://www.regular-expressions.info/floatingpoint.html # # pattern1: find a decimal number (int or float) and any # characters following it upto the next decimal number. [^0-9\-+]* # => keep gathering elements until we get to a digit, a - or a # +. These three indicates the possible start of the next number. pattern1 = re . compile ( r"([-+]?[0-9]*\.?[0-9]+[^0-9\-+]*)" ) # pattern2: find decimal number (int or float) in string. pattern2 = re . compile ( r"([-+]?[0-9]*\.?[0-9]+)" ) hmsdms = hmsdms . lower ( ) hdlist = pattern1 . findall ( hmsdms ) parts = [ None , None , None ] def _fill_right_not_none ( ) : # Find the pos. where parts is not None. Next value must # be inserted to the right of this. If this is 2 then we have # already filled seconds part, raise exception. If this is 1 # then fill 2. If this is 0 fill 1. If none of these then fill # 0. rp = reversed ( parts ) for i , j in enumerate ( rp ) : if j is not None : break if i == 0 : # Seconds part already filled. raise ValueError ( "Invalid string." ) elif i == 1 : parts [ 2 ] = v elif i == 2 : # Either parts[0] is None so fill it, or it is filled # and hence fill parts[1]. if parts [ 0 ] is None : parts [ 0 ] = v else : parts [ 1 ] = v for valun in hdlist : try : # See if this is pure number. v = float ( valun ) # Sexagesimal part cannot be determined. So guess it by # seeing which all parts have already been identified. _fill_right_not_none ( ) except ValueError : # Not a pure number. Infer sexagesimal part from the # suffix. if "hh" in valun or "h" in valun : m = pattern2 . search ( valun ) parts [ 0 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) units = "hours" if "dd" in valun or "d" in valun : m = pattern2 . search ( valun ) parts [ 0 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) units = "degrees" if "mm" in valun or "m" in valun : m = pattern2 . search ( valun ) parts [ 1 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if "ss" in valun or "s" in valun : m = pattern2 . search ( valun ) parts [ 2 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if "'" in valun : m = pattern2 . search ( valun ) parts [ 1 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if '"' in valun : m = pattern2 . search ( valun ) parts [ 2 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if ":" in valun : # Sexagesimal part cannot be determined. So guess it by # seeing which all parts have already been identified. v = valun . replace ( ":" , "" ) v = float ( v ) _fill_right_not_none ( ) if not units : units = "degrees" # Find sign. Only the first identified part can have a -ve sign. for i in parts : if i and i < 0.0 : if sign is None : sign = - 1 else : raise ValueError ( "Only one number can be negative." ) if sign is None : # None of these are negative. sign = 1 vals = [ abs ( i ) if i is not None else 0.0 for i in parts ] return dict ( sign = sign , units = units , vals = vals , parts = parts )
6,519
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L554-L746
[ "def", "createDashboardOverlay", "(", "self", ",", "pchOverlayKey", ",", "pchOverlayFriendlyName", ")", ":", "fn", "=", "self", ".", "function_table", ".", "createDashboardOverlay", "pMainHandle", "=", "VROverlayHandle_t", "(", ")", "pThumbnailHandle", "=", "VROverlayHandle_t", "(", ")", "result", "=", "fn", "(", "pchOverlayKey", ",", "pchOverlayFriendlyName", ",", "byref", "(", "pMainHandle", ")", ",", "byref", "(", "pThumbnailHandle", ")", ")", "return", "result", ",", "pMainHandle", ",", "pThumbnailHandle" ]
Parse string into angular position .
def pposition ( hd , details = False ) : # :TODO: split two angles based on user entered separator and process each part separately. # Split at any character other than a digit, ".", "-", and "+". p = re . split ( r"[^\d\-+.]*" , hd ) if len ( p ) not in [ 2 , 6 ] : raise ValueError ( "Input must contain either 2 or 6 numbers." ) # Two floating point numbers if string has 2 numbers. if len ( p ) == 2 : x , y = float ( p [ 0 ] ) , float ( p [ 1 ] ) if details : numvals = 2 raw_x = p [ 0 ] raw_y = p [ 1 ] # Two sexagesimal numbers if string has 6 numbers. elif len ( p ) == 6 : x_p = phmsdms ( " " . join ( p [ : 3 ] ) ) x = sexa2deci ( x_p [ 'sign' ] , * x_p [ 'vals' ] ) y_p = phmsdms ( " " . join ( p [ 3 : ] ) ) y = sexa2deci ( y_p [ 'sign' ] , * y_p [ 'vals' ] ) if details : raw_x = x_p raw_y = y_p numvals = 6 if details : result = dict ( x = x , y = y , numvals = numvals , raw_x = raw_x , raw_y = raw_y ) else : result = x , y return result
6,520
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L749-L845
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Angular spearation between two points on a unit sphere .
def sep ( a1 , b1 , a2 , b2 ) : # Tolerance to decide if the calculated separation is zero. tol = 1e-15 v = CartesianVector . from_spherical ( 1.0 , a1 , b1 ) v2 = CartesianVector . from_spherical ( 1.0 , a2 , b2 ) d = v . dot ( v2 ) c = v . cross ( v2 ) . mod res = math . atan2 ( c , d ) if abs ( res ) < tol : return 0.0 else : return res
6,521
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L848-L908
[ "def", "__getBio", "(", "self", ",", "web", ")", ":", "bio", "=", "web", ".", "find_all", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"user-profile-bio\"", "}", ")", "if", "bio", ":", "try", ":", "bio", "=", "bio", "[", "0", "]", ".", "text", "if", "bio", "and", "GitHubUser", ".", "isASCII", "(", "bio", ")", ":", "bioText", "=", "bio", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "bioText", "=", "bioText", ".", "replace", "(", "\"\\t\"", ",", "\" \"", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"\"", ")", "bioText", "=", "bioText", ".", "replace", "(", "\"\\'\"", ",", "\"\"", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"\"", ")", "self", ".", "bio", "=", "bioText", "else", ":", "self", ".", "bio", "=", "\"\"", "except", "IndexError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")", "except", "AttributeError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")" ]
Normalize angles of a point on a sphere .
def normalize_sphere ( alpha , delta ) : v = CartesianVector . from_spherical ( r = 1.0 , alpha = d2r ( alpha ) , delta = d2r ( delta ) ) angles = v . normalized_angles return r2d ( angles [ 0 ] ) , r2d ( angles [ 1 ] )
6,522
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1969-L2003
[ "def", "save_to_file", "(", "self", ",", "filename", ",", "remap_dim0", "=", "None", ",", "remap_dim1", "=", "None", ")", ":", "# rows - first index", "# columns - second index", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fobj", ":", "columns", "=", "list", "(", "sorted", "(", "self", ".", "_dim1", ")", ")", "for", "col", "in", "columns", ":", "fobj", ".", "write", "(", "','", ")", "fobj", ".", "write", "(", "str", "(", "remap_dim1", "[", "col", "]", "if", "remap_dim1", "else", "col", ")", ")", "fobj", ".", "write", "(", "'\\n'", ")", "for", "row", "in", "sorted", "(", "self", ".", "_dim0", ")", ":", "fobj", ".", "write", "(", "str", "(", "remap_dim0", "[", "row", "]", "if", "remap_dim0", "else", "row", ")", ")", "for", "col", "in", "columns", ":", "fobj", ".", "write", "(", "','", ")", "fobj", ".", "write", "(", "str", "(", "self", "[", "row", ",", "col", "]", ")", ")", "fobj", ".", "write", "(", "'\\n'", ")" ]
Construct Cartesian vector from spherical coordinates .
def from_spherical ( cls , r = 1.0 , alpha = 0.0 , delta = 0.0 ) : x = r * math . cos ( delta ) * math . cos ( alpha ) y = r * math . cos ( delta ) * math . sin ( alpha ) z = r * math . sin ( delta ) return cls ( x = x , y = y , z = z )
6,523
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1908-L1916
[ "def", "data", "(", "self", ")", ":", "d", "=", "super", "(", "CommunityForm", ",", "self", ")", ".", "data", "d", ".", "pop", "(", "'csrf_token'", ",", "None", ")", "return", "d" ]
Cross product of two vectors .
def cross ( self , v ) : n = self . __class__ ( ) n . x = self . y * v . z - self . z * v . y n . y = - ( self . x * v . z - self . z * v . x ) n . z = self . x * v . y - self . y * v . x return n
6,524
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1921-L1940
[ "def", "list_tables", "(", ")", ":", "tables", "=", "[", "]", "try", ":", "table_list", "=", "DYNAMODB_CONNECTION", ".", "list_tables", "(", ")", "while", "True", ":", "for", "table_name", "in", "table_list", "[", "u'TableNames'", "]", ":", "tables", ".", "append", "(", "get_table", "(", "table_name", ")", ")", "if", "u'LastEvaluatedTableName'", "in", "table_list", ":", "table_list", "=", "DYNAMODB_CONNECTION", ".", "list_tables", "(", "table_list", "[", "u'LastEvaluatedTableName'", "]", ")", "else", ":", "break", "except", "DynamoDBResponseError", "as", "error", ":", "dynamodb_error", "=", "error", ".", "body", "[", "'__type'", "]", ".", "rsplit", "(", "'#'", ",", "1", ")", "[", "1", "]", "if", "dynamodb_error", "==", "'ResourceNotFoundException'", ":", "logger", ".", "error", "(", "'No tables found'", ")", "elif", "dynamodb_error", "==", "'AccessDeniedException'", ":", "logger", ".", "debug", "(", "'Your AWS API keys lack access to listing tables. '", "'That is an issue if you are trying to use regular '", "'expressions in your table configuration.'", ")", "elif", "dynamodb_error", "==", "'UnrecognizedClientException'", ":", "logger", ".", "error", "(", "'Invalid security token. Are your AWS API keys correct?'", ")", "else", ":", "logger", ".", "error", "(", "(", "'Unhandled exception: {0}: {1}. '", "'Please file a bug report at '", "'https://github.com/sebdah/dynamic-dynamodb/issues'", ")", ".", "format", "(", "dynamodb_error", ",", "error", ".", "body", "[", "'message'", "]", ")", ")", "except", "JSONResponseError", "as", "error", ":", "logger", ".", "error", "(", "'Communication error: {0}'", ".", "format", "(", "error", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "tables" ]
Modulus of vector .
def mod ( self ) : return math . sqrt ( self . x ** 2 + self . y ** 2 + self . z ** 2 )
6,525
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1943-L1945
[ "def", "_boto_conn_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'region_name'", ":", "self", ".", "region", "}", "if", "self", ".", "account_id", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Connecting for account %s role '%s' with STS \"", "\"(region: %s)\"", ",", "self", ".", "account_id", ",", "self", ".", "account_role", ",", "self", ".", "region", ")", "credentials", "=", "self", ".", "_get_sts_token", "(", ")", "kwargs", "[", "'aws_access_key_id'", "]", "=", "credentials", ".", "access_key", "kwargs", "[", "'aws_secret_access_key'", "]", "=", "credentials", ".", "secret_key", "kwargs", "[", "'aws_session_token'", "]", "=", "credentials", ".", "session_token", "elif", "self", ".", "profile_name", "is", "not", "None", ":", "# use boto3.Session to get credentials from the named profile", "logger", ".", "debug", "(", "\"Using credentials profile: %s\"", ",", "self", ".", "profile_name", ")", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "self", ".", "profile_name", ")", "credentials", "=", "session", ".", "_session", ".", "get_credentials", "(", ")", "kwargs", "[", "'aws_access_key_id'", "]", "=", "credentials", ".", "access_key", "kwargs", "[", "'aws_secret_access_key'", "]", "=", "credentials", ".", "secret_key", "kwargs", "[", "'aws_session_token'", "]", "=", "credentials", ".", "token", "else", ":", "logger", ".", "debug", "(", "\"Connecting to region %s\"", ",", "self", ".", "region", ")", "return", "kwargs" ]
Angular spearation between objects in radians .
def sep ( self , p ) : return sep ( self . alpha . r , self . delta . r , p . alpha . r , p . delta . r )
6,526
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L2194-L2213
[ "def", "create_snapshot", "(", "self", ",", "volume_id", ",", "description", "=", "None", ")", ":", "params", "=", "{", "'VolumeId'", ":", "volume_id", "}", "if", "description", ":", "params", "[", "'Description'", "]", "=", "description", "[", "0", ":", "255", "]", "snapshot", "=", "self", ".", "get_object", "(", "'CreateSnapshot'", ",", "params", ",", "Snapshot", ",", "verb", "=", "'POST'", ")", "volume", "=", "self", ".", "get_all_volumes", "(", "[", "volume_id", "]", ")", "[", "0", "]", "volume_name", "=", "volume", ".", "tags", ".", "get", "(", "'Name'", ")", "if", "volume_name", ":", "snapshot", ".", "add_tag", "(", "'Name'", ",", "volume_name", ")", "return", "snapshot" ]
Find position angle between objects in radians .
def bear ( self , p ) : return bear ( self . alpha . r , self . delta . r , p . alpha . r , p . delta . r )
6,527
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L2215-L2233
[ "def", "delete", "(", "self", ",", "message_id", ",", "reservation_id", "=", "None", ",", "subscriber_name", "=", "None", ")", ":", "url", "=", "\"queues/%s/messages/%s\"", "%", "(", "self", ".", "name", ",", "message_id", ")", "qitems", "=", "{", "}", "if", "reservation_id", "is", "not", "None", ":", "qitems", "[", "'reservation_id'", "]", "=", "reservation_id", "if", "subscriber_name", "is", "not", "None", ":", "qitems", "[", "'subscriber_name'", "]", "=", "subscriber_name", "body", "=", "json", ".", "dumps", "(", "qitems", ")", "result", "=", "self", ".", "client", ".", "delete", "(", "url", "=", "url", ",", "body", "=", "body", ",", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", ")", "return", "result", "[", "'body'", "]" ]
Returns the chunk object for the supplied identifier
def get_chunk ( self , chunk_id ) : if chunk_id in self . idx : return Cchunk ( self . idx [ chunk_id ] , self . type ) else : return None
6,528
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/chunk_data.py#L191-L200
[ "def", "_timeout_exceeded", "(", "self", ",", "start", ",", "msg", "=", "\"Timeout exceeded!\"", ")", ":", "if", "not", "start", ":", "# Must provide a comparison time", "return", "False", "if", "time", ".", "time", "(", ")", "-", "start", ">", "self", ".", "session_timeout", ":", "# session_timeout exceeded", "raise", "NetMikoTimeoutException", "(", "msg", ")", "return", "False" ]
Adds a chunk object to the layer
def add_chunk ( self , chunk_obj ) : if chunk_obj . get_id ( ) in self . idx : raise ValueError ( "Chunk with id {} already exists!" . format ( chunk_obj . get_id ( ) ) ) self . node . append ( chunk_obj . get_node ( ) ) self . idx [ chunk_obj . get_id ( ) ] = chunk_obj
6,529
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/chunk_data.py#L202-L212
[ "def", "parse_config", "(", "args", ")", ":", "# Try user config or return default location early", "config_path", "=", "path", ".", "expanduser", "(", "args", ".", "config_file", ")", "if", "not", "path", ".", "exists", "(", "config_path", ")", ":", "# Complain if they provided non-existant config", "if", "args", ".", "config_file", "!=", "DEFAULT_JOURNAL_RC", ":", "print", "(", "\"journal: error: config file '\"", "+", "args", ".", "config_file", "+", "\"' not found\"", ")", "sys", ".", "exit", "(", ")", "else", ":", "# If no config file, use default journal location", "return", "DEFAULT_JOURNAL", "# If we get here, assume valid config file", "config", "=", "ConfigParser", ".", "SafeConfigParser", "(", "{", "'journal'", ":", "{", "'default'", ":", "'__journal'", "}", ",", "'__journal'", ":", "{", "'location'", ":", "DEFAULT_JOURNAL", "}", "}", ")", "config", ".", "read", "(", "config_path", ")", "journal_location", "=", "config", ".", "get", "(", "config", ".", "get", "(", "'journal'", ",", "'default'", ")", ",", "'location'", ")", "if", "args", ".", "journal", ":", "journal_location", "=", "config", ".", "get", "(", "args", ".", "journal", ",", "'location'", ")", "return", "journal_location" ]
show a value assocciated with an attribute for each DataProperty instance in the dp_list
def display_col_dp ( dp_list , attr_name ) : print ( ) print ( "---------- {:s} ----------" . format ( attr_name ) ) print ( [ getattr ( dp , attr_name ) for dp in dp_list ] )
6,530
https://github.com/thombashi/DataProperty/blob/1d1a4c6abee87264c2f870a932c0194895d80a18/examples/py/to_column_dp_list.py#L16-L24
[ "def", "remove_backslash_r", "(", "filename", ",", "encoding", ")", ":", "with", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "encoding", ",", "newline", "=", "r'\\n'", ")", "as", "filereader", ":", "contents", "=", "filereader", ".", "read", "(", ")", "contents", "=", "re", ".", "sub", "(", "r'\\r'", ",", "''", ",", "contents", ")", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "filewriter", ":", "filewriter", ".", "truncate", "(", ")", "filewriter", ".", "write", "(", "contents", ")" ]
Delay for dl seconds .
def delay ( self , dl = 0 ) : if dl is None : time . sleep ( self . dl ) elif dl < 0 : sys . stderr . write ( "delay cannot less than zero, this takes no effects.\n" ) else : time . sleep ( dl )
6,531
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L134-L143
[ "def", "correspondence", "(", "soup", ")", ":", "correspondence", "=", "[", "]", "author_notes_nodes", "=", "raw_parser", ".", "author_notes", "(", "soup", ")", "if", "author_notes_nodes", ":", "corresp_nodes", "=", "raw_parser", ".", "corresp", "(", "author_notes_nodes", ")", "for", "tag", "in", "corresp_nodes", ":", "correspondence", ".", "append", "(", "tag", ".", "text", ")", "return", "correspondence" ]
Scroll up n times .
def scroll_up ( self , n , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . m . scroll ( vertical = n ) self . delay ( post_dl )
6,532
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L203-L212
[ "def", "detach_storage", "(", "self", ",", "server", ",", "address", ")", ":", "body", "=", "{", "'storage_device'", ":", "{", "'address'", ":", "address", "}", "}", "url", "=", "'/server/{0}/storage/detach'", ".", "format", "(", "server", ")", "res", "=", "self", ".", "post_request", "(", "url", ",", "body", ")", "return", "Storage", ".", "_create_storage_objs", "(", "res", "[", "'server'", "]", "[", "'storage_devices'", "]", ",", "cloud_manager", "=", "self", ")" ]
Scroll right n times .
def scroll_right ( self , n , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . m . scroll ( horizontal = n ) self . delay ( post_dl )
6,533
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L225-L234
[ "def", "detach_storage", "(", "self", ",", "server", ",", "address", ")", ":", "body", "=", "{", "'storage_device'", ":", "{", "'address'", ":", "address", "}", "}", "url", "=", "'/server/{0}/storage/detach'", ".", "format", "(", "server", ")", "res", "=", "self", ".", "post_request", "(", "url", ",", "body", ")", "return", "Storage", ".", "_create_storage_objs", "(", "res", "[", "'server'", "]", "[", "'storage_devices'", "]", ",", "cloud_manager", "=", "self", ")" ]
Tap a key on keyboard for n times with interval seconds of interval . Key is declared by it s name
def tap_key ( self , key_name , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : key = self . _parse_key ( key_name ) self . delay ( pre_dl ) self . k . tap_key ( key , n , interval ) self . delay ( post_dl )
6,534
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L273-L293
[ "def", "store", "(", "self", ",", "mutagen_file", ",", "pictures", ")", ":", "mutagen_file", ".", "clear_pictures", "(", ")", "for", "pic", "in", "pictures", ":", "mutagen_file", ".", "add_picture", "(", "pic", ")" ]
Press enter key n times .
def enter ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . enter_key , n , interval ) self . delay ( post_dl )
6,535
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L295-L304
[ "def", "libvlc_video_set_crop_geometry", "(", "p_mi", ",", "psz_geometry", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_crop_geometry'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_crop_geometry'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_geometry", ")" ]
Press backspace key n times .
def backspace ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . backspace_key , n , interval ) self . delay ( post_dl )
6,536
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L306-L315
[ "def", "resize_image", "(", "image", ",", "canvas_size", ",", "filter", "=", "Filter", ".", "NearestNeighbor", ",", "does_crop", "=", "False", ",", "crop_aligment", "=", "CropAlignment", ".", "center", ",", "crop_form", "=", "CropForm", ".", "rectangle", ",", "match_orientation", "=", "False", ")", ":", "(", "source_width", ",", "source_height", ")", "=", "image", ".", "size", "source_aspect", "=", "source_width", "/", "float", "(", "source_height", ")", "(", "canvas_width", ",", "canvas_height", ")", "=", "canvas_size", "canvas_aspect", "=", "canvas_width", "/", "float", "(", "canvas_height", ")", "if", "match_orientation", ":", "if", "(", "source_aspect", ">", "1.0", ">", "canvas_aspect", ")", "or", "(", "source_aspect", "<", "1.0", "<", "canvas_aspect", ")", ":", "(", "canvas_width", ",", "canvas_height", ")", "=", "(", "canvas_height", ",", "canvas_width", ")", "canvas_aspect", "=", "canvas_width", "/", "float", "(", "canvas_height", ")", "if", "does_crop", ":", "if", "source_aspect", ">", "canvas_aspect", ":", "destination_width", "=", "int", "(", "source_height", "*", "canvas_aspect", ")", "offset", "=", "0", "if", "crop_aligment", "==", "CropAlignment", ".", "left_or_top", "else", "source_width", "-", "destination_width", "if", "crop_aligment", "==", "CropAlignment", ".", "right_or_bottom", "else", "(", "source_width", "-", "destination_width", ")", "/", "2", "box", "=", "(", "offset", ",", "0", ",", "offset", "+", "destination_width", ",", "source_height", ")", "else", ":", "destination_height", "=", "int", "(", "source_width", "/", "canvas_aspect", ")", "offset", "=", "0", "if", "crop_aligment", "==", "CropAlignment", ".", "left_or_top", "else", "source_height", "-", "destination_height", "if", "crop_aligment", "==", "CropAlignment", ".", "right_or_bottom", "else", "(", "source_height", "-", "destination_height", ")", "/", "2", "box", "=", "(", "0", ",", "offset", ",", "source_width", ",", "destination_height", "+", "offset", ")", "else", ":", "if", "canvas_aspect", ">", "source_aspect", ":", "# The canvas aspect is greater than the image aspect when the canvas's", "# width is greater than the image's width, in which case we need to", "# crop the left and right edges of the image.", "destination_width", "=", "int", "(", "canvas_aspect", "*", "source_height", ")", "offset", "=", "(", "source_width", "-", "destination_width", ")", "/", "2", "box", "=", "(", "offset", ",", "0", ",", "source_width", "-", "offset", ",", "source_height", ")", "else", ":", "# The image aspect is greater than the canvas aspect when the image's", "# width is greater than the canvas's width, in which case we need to", "# crop the top and bottom edges of the image.", "destination_height", "=", "int", "(", "source_width", "/", "canvas_aspect", ")", "offset", "=", "(", "source_height", "-", "destination_height", ")", "/", "2", "box", "=", "(", "0", ",", "offset", ",", "source_width", ",", "source_height", "-", "offset", ")", "return", "image", ".", "crop", "(", "box", ")", ".", "resize", "(", "(", "canvas_width", ",", "canvas_height", ")", ",", "PIL_FILTER_MAP", "[", "filter", "]", ")" ]
Press white space key n times .
def space ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . space_key , n ) self . delay ( post_dl )
6,537
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L317-L326
[ "def", "ensemble", "(", "subresults", ":", "List", "[", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ")", "->", "torch", ".", "Tensor", ":", "# Choose the highest average confidence span.", "span_start_probs", "=", "sum", "(", "subresult", "[", "'span_start_probs'", "]", "for", "subresult", "in", "subresults", ")", "/", "len", "(", "subresults", ")", "span_end_probs", "=", "sum", "(", "subresult", "[", "'span_end_probs'", "]", "for", "subresult", "in", "subresults", ")", "/", "len", "(", "subresults", ")", "return", "get_best_span", "(", "span_start_probs", ".", "log", "(", ")", ",", "span_end_probs", ".", "log", "(", ")", ")" ]
Press Fn key n times .
def fn ( self , i , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . function_keys [ i ] , n , interval ) self . delay ( post_dl )
6,538
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L328-L337
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", "(", "state_m", ")", ")", "return", "margin", "=", "cal_margin", "(", "state_m", ".", "parent", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", ")", "pos", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "size", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "# otherwise measure from reference state itself", "if", "from_logical_port", "in", "[", "\"outcome\"", ",", "\"income\"", "]", ":", "size", "=", "(", "margin", ",", "margin", ")", "if", "from_logical_port", "==", "\"outcome\"", ":", "outcomes_m", "=", "[", "outcome_m", "for", "outcome_m", "in", "state_m", ".", "outcomes", "if", "outcome_m", ".", "outcome", ".", "outcome_id", ">=", "0", "]", "free_outcomes_m", "=", "[", "oc_m", "for", "oc_m", "in", "outcomes_m", "if", "not", "state_m", ".", "state", ".", "parent", ".", "get_transition_for_outcome", "(", "state_m", ".", "state", ",", "oc_m", ".", "outcome", ")", "]", "if", "free_outcomes_m", ":", "outcome_m", "=", "free_outcomes_m", "[", "0", "]", "else", ":", "outcome_m", "=", "outcomes_m", "[", "0", "]", "pos", "=", "add_pos", "(", "pos", ",", "outcome_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "elif", "from_logical_port", "==", "\"income\"", ":", "pos", "=", "add_pos", "(", "pos", ",", "state_m", ".", "income", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "min_distance", "=", "None", "for", "sibling_state_m", "in", "state_m", ".", "parent", ".", "states", ".", "values", "(", ")", ":", "if", "sibling_state_m", "is", "state_m", ":", "continue", "sibling_pos", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "sibling_size", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "distance", "=", "geometry", ".", "cal_dist_between_2_coord_frame_aligned_boxes", "(", "pos", ",", "size", ",", "sibling_pos", ",", "sibling_size", ")", "if", "not", "min_distance", "or", "min_distance", "[", "0", "]", ">", "distance", ":", "min_distance", "=", "(", "distance", ",", "sibling_state_m", ")", "return", "min_distance" ]
Tap tab key for n times with interval seconds of interval .
def tab ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . tab_key , n , interval ) self . delay ( post_dl )
6,539
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L339-L348
[ "def", "handle_error", "(", "self", ",", "error", ",", "download_request", ")", ":", "if", "hasattr", "(", "error", ",", "\"errno\"", ")", "and", "error", ".", "errno", "==", "errno", ".", "EACCES", ":", "self", ".", "handle_certificate_problem", "(", "str", "(", "error", ")", ")", "else", ":", "self", ".", "handle_general_download_error", "(", "str", "(", "error", ")", ",", "download_request", ")" ]
Press up key n times .
def up ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . up_key , n , interval ) self . delay ( post_dl )
6,540
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L350-L359
[ "def", "libvlc_video_set_crop_geometry", "(", "p_mi", ",", "psz_geometry", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_crop_geometry'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_crop_geometry'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_geometry", ")" ]
Press down key n times .
def down ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . down_key , n , interval ) self . delay ( post_dl )
6,541
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L361-L370
[ "def", "libvlc_video_set_crop_geometry", "(", "p_mi", ",", "psz_geometry", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_crop_geometry'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_crop_geometry'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_geometry", ")" ]
Press left key n times
def left ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . left_key , n , interval ) self . delay ( post_dl )
6,542
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L372-L381
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", "(", "state_m", ")", ")", "return", "margin", "=", "cal_margin", "(", "state_m", ".", "parent", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", ")", "pos", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "size", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "# otherwise measure from reference state itself", "if", "from_logical_port", "in", "[", "\"outcome\"", ",", "\"income\"", "]", ":", "size", "=", "(", "margin", ",", "margin", ")", "if", "from_logical_port", "==", "\"outcome\"", ":", "outcomes_m", "=", "[", "outcome_m", "for", "outcome_m", "in", "state_m", ".", "outcomes", "if", "outcome_m", ".", "outcome", ".", "outcome_id", ">=", "0", "]", "free_outcomes_m", "=", "[", "oc_m", "for", "oc_m", "in", "outcomes_m", "if", "not", "state_m", ".", "state", ".", "parent", ".", "get_transition_for_outcome", "(", "state_m", ".", "state", ",", "oc_m", ".", "outcome", ")", "]", "if", "free_outcomes_m", ":", "outcome_m", "=", "free_outcomes_m", "[", "0", "]", "else", ":", "outcome_m", "=", "outcomes_m", "[", "0", "]", "pos", "=", "add_pos", "(", "pos", ",", "outcome_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "elif", "from_logical_port", "==", "\"income\"", ":", "pos", "=", "add_pos", "(", "pos", ",", "state_m", ".", "income", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "min_distance", "=", "None", "for", "sibling_state_m", "in", "state_m", ".", "parent", ".", "states", ".", "values", "(", ")", ":", "if", "sibling_state_m", "is", "state_m", ":", "continue", "sibling_pos", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "sibling_size", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "distance", "=", "geometry", ".", "cal_dist_between_2_coord_frame_aligned_boxes", "(", "pos", ",", "size", ",", "sibling_pos", ",", "sibling_size", ")", "if", "not", "min_distance", "or", "min_distance", "[", "0", "]", ">", "distance", ":", "min_distance", "=", "(", "distance", ",", "sibling_state_m", ")", "return", "min_distance" ]
Press right key n times .
def right ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . right_key , n , interval ) self . delay ( post_dl )
6,543
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L383-L392
[ "def", "libvlc_video_set_crop_geometry", "(", "p_mi", ",", "psz_geometry", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_crop_geometry'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_crop_geometry'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_geometry", ")" ]
Pres delete key n times .
def delete ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . delete_key , n , interval ) self . delay ( post_dl )
6,544
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L394-L403
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", "(", "state_m", ")", ")", "return", "margin", "=", "cal_margin", "(", "state_m", ".", "parent", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", ")", "pos", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "size", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "# otherwise measure from reference state itself", "if", "from_logical_port", "in", "[", "\"outcome\"", ",", "\"income\"", "]", ":", "size", "=", "(", "margin", ",", "margin", ")", "if", "from_logical_port", "==", "\"outcome\"", ":", "outcomes_m", "=", "[", "outcome_m", "for", "outcome_m", "in", "state_m", ".", "outcomes", "if", "outcome_m", ".", "outcome", ".", "outcome_id", ">=", "0", "]", "free_outcomes_m", "=", "[", "oc_m", "for", "oc_m", "in", "outcomes_m", "if", "not", "state_m", ".", "state", ".", "parent", ".", "get_transition_for_outcome", "(", "state_m", ".", "state", ",", "oc_m", ".", "outcome", ")", "]", "if", "free_outcomes_m", ":", "outcome_m", "=", "free_outcomes_m", "[", "0", "]", "else", ":", "outcome_m", "=", "outcomes_m", "[", "0", "]", "pos", "=", "add_pos", "(", "pos", ",", "outcome_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "elif", "from_logical_port", "==", "\"income\"", ":", "pos", "=", "add_pos", "(", "pos", ",", "state_m", ".", "income", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "min_distance", "=", "None", "for", "sibling_state_m", "in", "state_m", ".", "parent", ".", "states", ".", "values", "(", ")", ":", "if", "sibling_state_m", "is", "state_m", ":", "continue", "sibling_pos", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "sibling_size", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "distance", "=", "geometry", ".", "cal_dist_between_2_coord_frame_aligned_boxes", "(", "pos", ",", "size", ",", "sibling_pos", ",", "sibling_size", ")", "if", "not", "min_distance", "or", "min_distance", "[", "0", "]", ">", "distance", ":", "min_distance", "=", "(", "distance", ",", "sibling_state_m", ")", "return", "min_distance" ]
Pres insert key n times .
def insert ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . insert_key , n , interval ) self . delay ( post_dl )
6,545
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L405-L414
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", "(", "state_m", ")", ")", "return", "margin", "=", "cal_margin", "(", "state_m", ".", "parent", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", ")", "pos", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "size", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "# otherwise measure from reference state itself", "if", "from_logical_port", "in", "[", "\"outcome\"", ",", "\"income\"", "]", ":", "size", "=", "(", "margin", ",", "margin", ")", "if", "from_logical_port", "==", "\"outcome\"", ":", "outcomes_m", "=", "[", "outcome_m", "for", "outcome_m", "in", "state_m", ".", "outcomes", "if", "outcome_m", ".", "outcome", ".", "outcome_id", ">=", "0", "]", "free_outcomes_m", "=", "[", "oc_m", "for", "oc_m", "in", "outcomes_m", "if", "not", "state_m", ".", "state", ".", "parent", ".", "get_transition_for_outcome", "(", "state_m", ".", "state", ",", "oc_m", ".", "outcome", ")", "]", "if", "free_outcomes_m", ":", "outcome_m", "=", "free_outcomes_m", "[", "0", "]", "else", ":", "outcome_m", "=", "outcomes_m", "[", "0", "]", "pos", "=", "add_pos", "(", "pos", ",", "outcome_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "elif", "from_logical_port", "==", "\"income\"", ":", "pos", "=", "add_pos", "(", "pos", ",", "state_m", ".", "income", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "min_distance", "=", "None", "for", "sibling_state_m", "in", "state_m", ".", "parent", ".", "states", ".", "values", "(", ")", ":", "if", "sibling_state_m", "is", "state_m", ":", "continue", "sibling_pos", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "sibling_size", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "distance", "=", "geometry", ".", "cal_dist_between_2_coord_frame_aligned_boxes", "(", "pos", ",", "size", ",", "sibling_pos", ",", "sibling_size", ")", "if", "not", "min_distance", "or", "min_distance", "[", "0", "]", ">", "distance", ":", "min_distance", "=", "(", "distance", ",", "sibling_state_m", ")", "return", "min_distance" ]
Pres home key n times .
def home ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . home_key , n , interval ) self . delay ( post_dl )
6,546
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L416-L425
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", "(", "state_m", ")", ")", "return", "margin", "=", "cal_margin", "(", "state_m", ".", "parent", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", ")", "pos", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "size", "=", "state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "# otherwise measure from reference state itself", "if", "from_logical_port", "in", "[", "\"outcome\"", ",", "\"income\"", "]", ":", "size", "=", "(", "margin", ",", "margin", ")", "if", "from_logical_port", "==", "\"outcome\"", ":", "outcomes_m", "=", "[", "outcome_m", "for", "outcome_m", "in", "state_m", ".", "outcomes", "if", "outcome_m", ".", "outcome", ".", "outcome_id", ">=", "0", "]", "free_outcomes_m", "=", "[", "oc_m", "for", "oc_m", "in", "outcomes_m", "if", "not", "state_m", ".", "state", ".", "parent", ".", "get_transition_for_outcome", "(", "state_m", ".", "state", ",", "oc_m", ".", "outcome", ")", "]", "if", "free_outcomes_m", ":", "outcome_m", "=", "free_outcomes_m", "[", "0", "]", "else", ":", "outcome_m", "=", "outcomes_m", "[", "0", "]", "pos", "=", "add_pos", "(", "pos", ",", "outcome_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "elif", "from_logical_port", "==", "\"income\"", ":", "pos", "=", "add_pos", "(", "pos", ",", "state_m", ".", "income", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", ")", "min_distance", "=", "None", "for", "sibling_state_m", "in", "state_m", ".", "parent", ".", "states", ".", "values", "(", ")", ":", "if", "sibling_state_m", "is", "state_m", ":", "continue", "sibling_pos", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "sibling_size", "=", "sibling_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size'", "]", "distance", "=", "geometry", ".", "cal_dist_between_2_coord_frame_aligned_boxes", "(", "pos", ",", "size", ",", "sibling_pos", ",", "sibling_size", ")", "if", "not", "min_distance", "or", "min_distance", "[", "0", "]", ">", "distance", ":", "min_distance", "=", "(", "distance", ",", "sibling_state_m", ")", "return", "min_distance" ]
Press end key n times .
def end ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . end_key , n , interval ) self . delay ( post_dl )
6,547
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L427-L436
[ "def", "libvlc_video_set_crop_geometry", "(", "p_mi", ",", "psz_geometry", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_crop_geometry'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_crop_geometry'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_geometry", ")" ]
Pres page_up key n times .
def page_up ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . page_up_key , n , interval ) self . delay ( post_dl )
6,548
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L438-L447
[ "def", "from_wms", "(", "cls", ",", "filename", ",", "vector", ",", "resolution", ",", "destination_file", "=", "None", ")", ":", "doc", "=", "wms_vrt", "(", "filename", ",", "bounds", "=", "vector", ",", "resolution", "=", "resolution", ")", ".", "tostring", "(", ")", "filename", "=", "cls", ".", "_save_to_destination_file", "(", "doc", ",", "destination_file", ")", "return", "GeoRaster2", ".", "open", "(", "filename", ")" ]
Pres page_down key n times .
def page_down ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . page_down , n , interval ) self . delay ( post_dl )
6,549
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L449-L458
[ "def", "queries", "(", "self", ",", "request", ")", ":", "queries", "=", "self", ".", "get_queries", "(", "request", ")", "worlds", "=", "[", "]", "with", "self", ".", "mapper", ".", "begin", "(", ")", "as", "session", ":", "for", "_", "in", "range", "(", "queries", ")", ":", "world", "=", "session", ".", "query", "(", "World", ")", ".", "get", "(", "randint", "(", "1", ",", "MAXINT", ")", ")", "worlds", ".", "append", "(", "self", ".", "get_json", "(", "world", ")", ")", "return", "Json", "(", "worlds", ")", ".", "http_response", "(", "request", ")" ]
Press combination of two keys like Ctrl + C Alt + F4 . The second key could be tapped for multiple time .
def press_and_tap ( self , press_key , tap_key , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : press_key = self . _parse_key ( press_key ) tap_key = self . _parse_key ( tap_key ) self . delay ( pre_dl ) self . k . press_key ( press_key ) self . k . tap_key ( tap_key , n , interval ) self . k . release_key ( press_key ) self . delay ( post_dl )
6,550
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L461-L481
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "course_id", "=", "data", "course_video", "=", "image", "=", "''", "if", "data", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "(", "course_id", ",", "image", ")", ",", "=", "list", "(", "data", ".", "items", "(", ")", ")", "course_video", "=", "CourseVideo", "(", "course_id", "=", "course_id", ")", "course_video", ".", "full_clean", "(", "exclude", "=", "[", "'video'", "]", ")", "return", "course_video", ",", "image" ]
Press combination of three keys like Ctrl + Shift + C The tap key could be tapped for multiple time .
def press_two_and_tap ( self , press_key1 , press_key2 , tap_key , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : press_key1 = self . _parse_key ( press_key1 ) press_key2 = self . _parse_key ( press_key2 ) tap_key = self . _parse_key ( tap_key ) self . delay ( pre_dl ) self . k . press_key ( press_key1 ) self . k . press_key ( press_key2 ) self . k . tap_key ( tap_key , n , interval ) self . k . release_key ( press_key1 ) self . k . release_key ( press_key2 ) self . delay ( post_dl )
6,551
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L483-L506
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "course_id", "=", "data", "course_video", "=", "image", "=", "''", "if", "data", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "(", "course_id", ",", "image", ")", ",", "=", "list", "(", "data", ".", "items", "(", ")", ")", "course_video", "=", "CourseVideo", "(", "course_id", "=", "course_id", ")", "course_video", ".", "full_clean", "(", "exclude", "=", "[", "'video'", "]", ")", "return", "course_video", ",", "image" ]
Press Ctrl + C usually for copy .
def ctrl_c ( self , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . control_key ) self . k . tap_key ( "c" ) self . k . release_key ( self . k . control_key ) self . delay ( post_dl )
6,552
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L508-L519
[ "def", "_fetch_secrets", "(", "vault_url", ",", "path", ",", "token", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1'", ",", "path", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "VaultLoader", ".", "_get_headers", "(", "token", ")", ")", "resp", ".", "raise_for_status", "(", ")", "data", "=", "resp", ".", "json", "(", ")", "if", "data", ".", "get", "(", "'errors'", ")", ":", "raise", "VaultException", "(", "u'Error fetching Vault secrets from path {}: {}'", ".", "format", "(", "path", ",", "data", "[", "'errors'", "]", ")", ")", "return", "data", "[", "'data'", "]" ]
Press Ctrl + Fn1 ~ 12 once .
def ctrl_fn ( self , i , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . control_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . control_key ) self . delay ( post_dl )
6,553
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L599-L610
[ "def", "make_or_augment_meta", "(", "self", ",", "role", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "paths", "[", "\"meta\"", "]", ")", ":", "utils", ".", "create_meta_main", "(", "self", ".", "paths", "[", "\"meta\"", "]", ",", "self", ".", "config", ",", "role", ",", "\"\"", ")", "self", ".", "report", "[", "\"state\"", "]", "[", "\"ok_role\"", "]", "+=", "1", "self", ".", "report", "[", "\"roles\"", "]", "[", "role", "]", "[", "\"state\"", "]", "=", "\"ok\"", "# swap values in place to use the config values", "swaps", "=", "[", "(", "\"author\"", ",", "self", ".", "config", "[", "\"author_name\"", "]", ")", ",", "(", "\"company\"", ",", "self", ".", "config", "[", "\"author_company\"", "]", ")", ",", "(", "\"license\"", ",", "self", ".", "config", "[", "\"license_type\"", "]", ")", ",", "]", "(", "new_meta", ",", "_", ")", "=", "utils", ".", "swap_yaml_string", "(", "self", ".", "paths", "[", "\"meta\"", "]", ",", "swaps", ")", "# normalize the --- at the top of the file by removing it first", "new_meta", "=", "new_meta", ".", "replace", "(", "\"---\"", ",", "\"\"", ")", "new_meta", "=", "new_meta", ".", "lstrip", "(", ")", "# augment missing main keys", "augments", "=", "[", "(", "\"ansigenome_info\"", ",", "\"{}\"", ")", ",", "(", "\"galaxy_info\"", ",", "\"{}\"", ")", ",", "(", "\"dependencies\"", ",", "\"[]\"", ")", ",", "]", "new_meta", "=", "self", ".", "augment_main_keys", "(", "augments", ",", "new_meta", ")", "# re-attach the ---", "new_meta", "=", "\"---\\n\\n\"", "+", "new_meta", "travis_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "paths", "[", "\"role\"", "]", ",", "\".travis.yml\"", ")", "if", "os", ".", "path", ".", "exists", "(", "travis_path", ")", ":", "new_meta", "=", "new_meta", ".", "replace", "(", "\"travis: False\"", ",", "\"travis: True\"", ")", "utils", ".", "string_to_file", "(", "self", ".", "paths", "[", "\"meta\"", "]", ",", "new_meta", ")" ]
Press Alt + Fn1 ~ 12 once .
def alt_fn ( self , i , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . alt_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . alt_key ) self . delay ( post_dl )
6,554
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L612-L623
[ "def", "make_or_augment_meta", "(", "self", ",", "role", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "paths", "[", "\"meta\"", "]", ")", ":", "utils", ".", "create_meta_main", "(", "self", ".", "paths", "[", "\"meta\"", "]", ",", "self", ".", "config", ",", "role", ",", "\"\"", ")", "self", ".", "report", "[", "\"state\"", "]", "[", "\"ok_role\"", "]", "+=", "1", "self", ".", "report", "[", "\"roles\"", "]", "[", "role", "]", "[", "\"state\"", "]", "=", "\"ok\"", "# swap values in place to use the config values", "swaps", "=", "[", "(", "\"author\"", ",", "self", ".", "config", "[", "\"author_name\"", "]", ")", ",", "(", "\"company\"", ",", "self", ".", "config", "[", "\"author_company\"", "]", ")", ",", "(", "\"license\"", ",", "self", ".", "config", "[", "\"license_type\"", "]", ")", ",", "]", "(", "new_meta", ",", "_", ")", "=", "utils", ".", "swap_yaml_string", "(", "self", ".", "paths", "[", "\"meta\"", "]", ",", "swaps", ")", "# normalize the --- at the top of the file by removing it first", "new_meta", "=", "new_meta", ".", "replace", "(", "\"---\"", ",", "\"\"", ")", "new_meta", "=", "new_meta", ".", "lstrip", "(", ")", "# augment missing main keys", "augments", "=", "[", "(", "\"ansigenome_info\"", ",", "\"{}\"", ")", ",", "(", "\"galaxy_info\"", ",", "\"{}\"", ")", ",", "(", "\"dependencies\"", ",", "\"[]\"", ")", ",", "]", "new_meta", "=", "self", ".", "augment_main_keys", "(", "augments", ",", "new_meta", ")", "# re-attach the ---", "new_meta", "=", "\"---\\n\\n\"", "+", "new_meta", "travis_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "paths", "[", "\"role\"", "]", ",", "\".travis.yml\"", ")", "if", "os", ".", "path", ".", "exists", "(", "travis_path", ")", ":", "new_meta", "=", "new_meta", ".", "replace", "(", "\"travis: False\"", ",", "\"travis: True\"", ")", "utils", ".", "string_to_file", "(", "self", ".", "paths", "[", "\"meta\"", "]", ",", "new_meta", ")" ]
Press Shift + Fn1 ~ 12 once .
def shift_fn ( self , i , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . shift_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . shift_key ) self . delay ( post_dl )
6,555
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L625-L636
[ "def", "decode_from_bytes", "(", "cls", ",", "data", ")", ":", "decoded_message", "=", "c_uamqp", ".", "decode_message", "(", "len", "(", "data", ")", ",", "data", ")", "return", "cls", "(", "message", "=", "decoded_message", ")" ]
Press Alt + Tab once usually for switching between windows . Tab can be tapped for n times default once .
def alt_tab ( self , n = 1 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . alt_key ) self . k . tap_key ( self . k . tab_key , n = n , interval = 0.1 ) self . k . release_key ( self . k . alt_key ) self . delay ( post_dl )
6,556
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L638-L650
[ "def", "new_result", "(", "self", ",", "job", ",", "update_model", "=", "True", ")", ":", "if", "not", "job", ".", "exception", "is", "None", ":", "self", ".", "logger", ".", "warning", "(", "\"job {} failed with exception\\n{}\"", ".", "format", "(", "job", ".", "id", ",", "job", ".", "exception", ")", ")" ]
Enter strings .
def type_string ( self , text , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . type_string ( text , interval ) self . delay ( post_dl )
6,557
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L653-L662
[ "def", "on_response", "(", "self", ",", "ch", ",", "method_frame", ",", "props", ",", "body", ")", ":", "LOGGER", ".", "debug", "(", "\"rabbitmq.Requester.on_response\"", ")", "if", "self", ".", "corr_id", "==", "props", ".", "correlation_id", ":", "self", ".", "response", "=", "{", "'props'", ":", "props", ",", "'body'", ":", "body", "}", "else", ":", "LOGGER", ".", "warn", "(", "\"rabbitmq.Requester.on_response - discarded response : \"", "+", "str", "(", "props", ".", "correlation_id", ")", ")", "LOGGER", ".", "debug", "(", "\"natsd.Requester.on_response - discarded response : \"", "+", "str", "(", "{", "'properties'", ":", "props", ",", "'body'", ":", "body", "}", ")", ")" ]
Returns list of server objects populates if necessary .
def Servers ( self , cached = True ) : if not hasattr ( self , '_servers' ) or not cached : self . _servers = [ ] for server in self . servers_lst : self . _servers . append ( Server ( id = server , alias = self . alias , session = self . session ) ) return ( self . _servers )
6,558
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L90-L105
[ "def", "authors_titles_validator", "(", "record", ",", "result", ")", ":", "record_authors", "=", "get_value", "(", "record", ",", "'authors'", ",", "[", "]", ")", "result_authors", "=", "get_value", "(", "result", ",", "'_source.authors'", ",", "[", "]", ")", "author_score", "=", "compute_author_match_score", "(", "record_authors", ",", "result_authors", ")", "title_max_score", "=", "0.0", "record_titles", "=", "get_value", "(", "record", ",", "'titles.title'", ",", "[", "]", ")", "result_titles", "=", "get_value", "(", "result", ",", "'_source.titles.title'", ",", "[", "]", ")", "for", "cartesian_pair", "in", "product", "(", "record_titles", ",", "result_titles", ")", ":", "record_title_tokens", "=", "get_tokenized_title", "(", "cartesian_pair", "[", "0", "]", ")", "result_title_tokens", "=", "get_tokenized_title", "(", "cartesian_pair", "[", "1", "]", ")", "current_title_jaccard", "=", "compute_jaccard_index", "(", "record_title_tokens", ",", "result_title_tokens", ")", "if", "current_title_jaccard", ">", "title_max_score", "and", "current_title_jaccard", ">=", "0.5", ":", "title_max_score", "=", "current_title_jaccard", "return", "(", "author_score", "+", "title_max_score", ")", "/", "2", ">", "0.5" ]
Return account object for account containing this server .
def Account ( self ) : return ( clc . v2 . Account ( alias = self . alias , session = self . session ) )
6,559
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L232-L242
[ "def", "set_rainbow", "(", "self", ",", "duration", ")", ":", "for", "i", "in", "range", "(", "0", ",", "359", ")", ":", "self", ".", "set_color_hsv", "(", "i", ",", "100", ",", "100", ")", "time", ".", "sleep", "(", "duration", "/", "359", ")" ]
Return group object for group containing this server .
def Group ( self ) : return ( clc . v2 . Group ( id = self . groupId , alias = self . alias , session = self . session ) )
6,560
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L245-L255
[ "def", "pad_for_tpu", "(", "shapes_dict", ",", "hparams", ",", "max_length", ")", ":", "padded_shapes", "=", "{", "}", "def", "get_filler", "(", "specified_max_length", ")", ":", "if", "not", "specified_max_length", ":", "return", "max_length", "return", "min", "(", "specified_max_length", ",", "max_length", ")", "inputs_none_filler", "=", "get_filler", "(", "hparams", ".", "max_input_seq_length", ")", "targets_none_filler", "=", "get_filler", "(", "hparams", ".", "max_target_seq_length", ")", "def", "pad_one_shape", "(", "shape", ",", "none_filler", ")", ":", "return", "[", "(", "dim", "if", "dim", "is", "not", "None", "else", "none_filler", ")", "for", "dim", "in", "shape", ".", "as_list", "(", ")", "]", "for", "key", ",", "shape", "in", "six", ".", "iteritems", "(", "shapes_dict", ")", ":", "if", "key", "==", "\"inputs\"", ":", "padded_shapes", "[", "key", "]", "=", "pad_one_shape", "(", "shape", ",", "inputs_none_filler", ")", "elif", "key", "==", "\"targets\"", ":", "padded_shapes", "[", "key", "]", "=", "pad_one_shape", "(", "shape", ",", "targets_none_filler", ")", "else", ":", "padded_shapes", "[", "key", "]", "=", "pad_one_shape", "(", "shape", ",", "max_length", ")", "return", "padded_shapes" ]
Return disks object associated with server .
def Disks ( self ) : if not self . disks : self . disks = clc . v2 . Disks ( server = self , disks_lst = self . data [ 'details' ] [ 'disks' ] , session = self . session ) return ( self . disks )
6,561
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L258-L268
[ "def", "derivativeZ", "(", "self", ",", "mLvl", ",", "pLvl", ",", "MedShk", ")", ":", "xLvl", "=", "self", ".", "xFunc", "(", "mLvl", ",", "pLvl", ",", "MedShk", ")", "dxdShk", "=", "self", ".", "xFunc", ".", "derivativeZ", "(", "mLvl", ",", "pLvl", ",", "MedShk", ")", "dcdx", "=", "self", ".", "cFunc", ".", "derivativeX", "(", "xLvl", ",", "MedShk", ")", "dcdShk", "=", "dxdShk", "*", "dcdx", "+", "self", ".", "cFunc", ".", "derivativeY", "(", "xLvl", ",", "MedShk", ")", "dMeddShk", "=", "(", "dxdShk", "-", "dcdShk", ")", "/", "self", ".", "MedPrice", "return", "dcdShk", ",", "dMeddShk" ]
Returns PublicIPs object associated with the server .
def PublicIPs ( self ) : if not self . public_ips : self . public_ips = clc . v2 . PublicIPs ( server = self , public_ips_lst = self . ip_addresses , session = self . session ) return ( self . public_ips )
6,562
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L271-L277
[ "def", "_build_web_client", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "cookie_jar", "=", "cls", ".", "_build_cookie_jar", "(", "session", ")", "http_client", "=", "cls", ".", "_build_http_client", "(", "session", ")", "redirect_factory", "=", "functools", ".", "partial", "(", "session", ".", "factory", ".", "class_map", "[", "'RedirectTracker'", "]", ",", "max_redirects", "=", "session", ".", "args", ".", "max_redirect", ")", "return", "session", ".", "factory", ".", "new", "(", "'WebClient'", ",", "http_client", ",", "redirect_tracker_factory", "=", "redirect_factory", ",", "cookie_jar", "=", "cookie_jar", ",", "request_factory", "=", "cls", ".", "_build_request_factory", "(", "session", ")", ",", ")" ]
Returns the hourly unit component prices for this server .
def PriceUnits ( self ) : try : units = clc . v2 . API . Call ( 'GET' , 'billing/%s/serverPricing/%s' % ( self . alias , self . name ) , session = self . session ) except clc . APIFailedResponse : raise ( clc . ServerDeletedException ) return ( { 'cpu' : units [ 'cpu' ] , 'memory' : units [ 'memoryGB' ] , 'storage' : units [ 'storageGB' ] , 'managed_os' : units [ 'managedOS' ] , } )
6,563
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L290-L311
[ "def", "__flags", "(", "self", ")", ":", "flags", "=", "[", "]", "if", "self", ".", "_capture", ":", "flags", ".", "append", "(", "\"-capture\"", ")", "if", "self", ".", "_spy", ":", "flags", ".", "append", "(", "\"-spy\"", ")", "if", "self", ".", "_dbpath", ":", "flags", "+=", "[", "\"-db-path\"", ",", "self", ".", "_dbpath", "]", "flags", "+=", "[", "\"-db\"", ",", "\"boltdb\"", "]", "else", ":", "flags", "+=", "[", "\"-db\"", ",", "\"memory\"", "]", "if", "self", ".", "_synthesize", ":", "assert", "(", "self", ".", "_middleware", ")", "flags", "+=", "[", "\"-synthesize\"", "]", "if", "self", ".", "_simulation", ":", "flags", "+=", "[", "\"-import\"", ",", "self", ".", "_simulation", "]", "if", "self", ".", "_proxyPort", ":", "flags", "+=", "[", "\"-pp\"", ",", "str", "(", "self", ".", "_proxyPort", ")", "]", "if", "self", ".", "_adminPort", ":", "flags", "+=", "[", "\"-ap\"", ",", "str", "(", "self", ".", "_adminPort", ")", "]", "if", "self", ".", "_modify", ":", "flags", "+=", "[", "\"-modify\"", "]", "if", "self", ".", "_verbose", ":", "flags", "+=", "[", "\"-v\"", "]", "if", "self", ".", "_dev", ":", "flags", "+=", "[", "\"-dev\"", "]", "if", "self", ".", "_metrics", ":", "flags", "+=", "[", "\"-metrics\"", "]", "if", "self", ".", "_auth", ":", "flags", "+=", "[", "\"-auth\"", "]", "if", "self", ".", "_middleware", ":", "flags", "+=", "[", "\"-middleware\"", ",", "self", ".", "_middleware", "]", "if", "self", ".", "_cert", ":", "flags", "+=", "[", "\"-cert\"", ",", "self", ".", "_cert", "]", "if", "self", ".", "_certName", ":", "flags", "+=", "[", "\"-cert-name\"", ",", "self", ".", "_certName", "]", "if", "self", ".", "_certOrg", ":", "flags", "+=", "[", "\"-cert-org\"", ",", "self", ".", "_certOrg", "]", "if", "self", ".", "_destination", ":", "flags", "+=", "[", "\"-destination\"", ",", "self", ".", "_destination", "]", "if", "self", ".", "_key", ":", "flags", "+=", "[", "\"-key\"", ",", "self", ".", "_key", "]", "if", "self", ".", "_dest", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_dest", ")", ")", ":", "flags", "+=", "[", "\"-dest\"", ",", "self", ".", "_dest", "[", "i", "]", "]", "if", "self", ".", "_generateCACert", ":", "flags", "+=", "[", "\"-generate-ca-cert\"", "]", "if", "not", "self", ".", "_tlsVerification", ":", "flags", "+=", "[", "\"-tls-verification\"", ",", "\"false\"", "]", "logging", ".", "debug", "(", "\"flags:\"", "+", "str", "(", "flags", ")", ")", "return", "flags" ]
Returns the total hourly price for the server .
def PriceHourly ( self ) : units = self . PriceUnits ( ) return ( units [ 'cpu' ] * self . cpu + units [ 'memory' ] * self . memory + units [ 'storage' ] * self . storage + units [ 'managed_os' ] )
6,564
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L314-L326
[ "def", "__flags", "(", "self", ")", ":", "flags", "=", "[", "]", "if", "self", ".", "_capture", ":", "flags", ".", "append", "(", "\"-capture\"", ")", "if", "self", ".", "_spy", ":", "flags", ".", "append", "(", "\"-spy\"", ")", "if", "self", ".", "_dbpath", ":", "flags", "+=", "[", "\"-db-path\"", ",", "self", ".", "_dbpath", "]", "flags", "+=", "[", "\"-db\"", ",", "\"boltdb\"", "]", "else", ":", "flags", "+=", "[", "\"-db\"", ",", "\"memory\"", "]", "if", "self", ".", "_synthesize", ":", "assert", "(", "self", ".", "_middleware", ")", "flags", "+=", "[", "\"-synthesize\"", "]", "if", "self", ".", "_simulation", ":", "flags", "+=", "[", "\"-import\"", ",", "self", ".", "_simulation", "]", "if", "self", ".", "_proxyPort", ":", "flags", "+=", "[", "\"-pp\"", ",", "str", "(", "self", ".", "_proxyPort", ")", "]", "if", "self", ".", "_adminPort", ":", "flags", "+=", "[", "\"-ap\"", ",", "str", "(", "self", ".", "_adminPort", ")", "]", "if", "self", ".", "_modify", ":", "flags", "+=", "[", "\"-modify\"", "]", "if", "self", ".", "_verbose", ":", "flags", "+=", "[", "\"-v\"", "]", "if", "self", ".", "_dev", ":", "flags", "+=", "[", "\"-dev\"", "]", "if", "self", ".", "_metrics", ":", "flags", "+=", "[", "\"-metrics\"", "]", "if", "self", ".", "_auth", ":", "flags", "+=", "[", "\"-auth\"", "]", "if", "self", ".", "_middleware", ":", "flags", "+=", "[", "\"-middleware\"", ",", "self", ".", "_middleware", "]", "if", "self", ".", "_cert", ":", "flags", "+=", "[", "\"-cert\"", ",", "self", ".", "_cert", "]", "if", "self", ".", "_certName", ":", "flags", "+=", "[", "\"-cert-name\"", ",", "self", ".", "_certName", "]", "if", "self", ".", "_certOrg", ":", "flags", "+=", "[", "\"-cert-org\"", ",", "self", ".", "_certOrg", "]", "if", "self", ".", "_destination", ":", "flags", "+=", "[", "\"-destination\"", ",", "self", ".", "_destination", "]", "if", "self", ".", "_key", ":", "flags", "+=", "[", "\"-key\"", ",", "self", ".", "_key", "]", "if", "self", ".", "_dest", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_dest", ")", ")", ":", "flags", "+=", "[", "\"-dest\"", ",", "self", ".", "_dest", "[", "i", "]", "]", "if", "self", ".", "_generateCACert", ":", "flags", "+=", "[", "\"-generate-ca-cert\"", "]", "if", "not", "self", ".", "_tlsVerification", ":", "flags", "+=", "[", "\"-tls-verification\"", ",", "\"false\"", "]", "logging", ".", "debug", "(", "\"flags:\"", "+", "str", "(", "flags", ")", ")", "return", "flags" ]
Returns the administrative credentials for this server .
def Credentials ( self ) : return ( clc . v2 . API . Call ( 'GET' , 'servers/%s/%s/credentials' % ( self . alias , self . name ) , session = self . session ) )
6,565
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L329-L337
[ "def", "get_part", "(", "self", ",", "vertex_in", ",", "vertices_border", ")", ":", "vertices_new", "=", "set", "(", "self", ".", "neighbors", "[", "vertex_in", "]", ")", "vertices_part", "=", "set", "(", "[", "vertex_in", "]", ")", "while", "len", "(", "vertices_new", ")", ">", "0", ":", "pivot", "=", "vertices_new", ".", "pop", "(", ")", "if", "pivot", "in", "vertices_border", ":", "continue", "vertices_part", ".", "add", "(", "pivot", ")", "pivot_neighbors", "=", "set", "(", "self", ".", "neighbors", "[", "pivot", "]", ")", "pivot_neighbors", "-=", "vertices_part", "vertices_new", "|=", "pivot_neighbors", "return", "vertices_part" ]
Execute an existing Bluerprint package on the server .
def ExecutePackage ( self , package_id , parameters = { } ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'operations/%s/servers/executePackage' % ( self . alias ) , json . dumps ( { 'servers' : [ self . id ] , 'package' : { 'packageId' : package_id , 'parameters' : parameters } } ) , session = self . session ) , alias = self . alias , session = self . session ) )
6,566
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L387-L406
[ "def", "ismount", "(", "self", ",", "path", ")", ":", "path", "=", "make_string_path", "(", "path", ")", "if", "not", "path", ":", "return", "False", "normed_path", "=", "self", ".", "filesystem", ".", "absnormpath", "(", "path", ")", "sep", "=", "self", ".", "filesystem", ".", "_path_separator", "(", "path", ")", "if", "self", ".", "filesystem", ".", "is_windows_fs", ":", "if", "self", ".", "filesystem", ".", "alternative_path_separator", "is", "not", "None", ":", "path_seps", "=", "(", "sep", ",", "self", ".", "filesystem", ".", "_alternative_path_separator", "(", "path", ")", ")", "else", ":", "path_seps", "=", "(", "sep", ",", ")", "drive", ",", "rest", "=", "self", ".", "filesystem", ".", "splitdrive", "(", "normed_path", ")", "if", "drive", "and", "drive", "[", ":", "1", "]", "in", "path_seps", ":", "return", "(", "not", "rest", ")", "or", "(", "rest", "in", "path_seps", ")", "if", "rest", "in", "path_seps", ":", "return", "True", "for", "mount_point", "in", "self", ".", "filesystem", ".", "mount_points", ":", "if", "normed_path", ".", "rstrip", "(", "sep", ")", "==", "mount_point", ".", "rstrip", "(", "sep", ")", ":", "return", "True", "return", "False" ]
Add a NIC from the provided network to server and if provided assign a provided IP address
def AddNIC ( self , network_id , ip = '' ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/networks' % ( self . alias , self . id ) , json . dumps ( { 'networkId' : network_id , 'ipAddress' : ip } ) , session = self . session ) , alias = self . alias , session = self . session ) )
6,567
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L409-L435
[ "def", "_unscramble_regressor_columns", "(", "parent_data", ",", "data", ")", ":", "matches", "=", "[", "'_power[0-9]+'", ",", "'_derivative[0-9]+'", "]", "var", "=", "OrderedDict", "(", "(", "c", ",", "deque", "(", ")", ")", "for", "c", "in", "parent_data", ".", "columns", ")", "for", "c", "in", "data", ".", "columns", ":", "col", "=", "c", "for", "m", "in", "matches", ":", "col", "=", "re", ".", "sub", "(", "m", ",", "''", ",", "col", ")", "if", "col", "==", "c", ":", "var", "[", "col", "]", ".", "appendleft", "(", "c", ")", "else", ":", "var", "[", "col", "]", ".", "append", "(", "c", ")", "unscrambled", "=", "reduce", "(", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ")", ",", "var", ".", "values", "(", ")", ")", "return", "data", "[", "[", "*", "unscrambled", "]", "]" ]
Remove the NIC associated with the provided network from the server .
def RemoveNIC ( self , network_id ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , 'servers/%s/%s/networks/%s' % ( self . alias , self . id , network_id ) , session = self . session ) , alias = self . alias , session = self . session ) )
6,568
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L437-L459
[ "def", "rename_sectors", "(", "self", ",", "sectors", ")", ":", "if", "type", "(", "sectors", ")", "is", "list", ":", "sectors", "=", "{", "old", ":", "new", "for", "old", ",", "new", "in", "zip", "(", "self", ".", "get_sectors", "(", ")", ",", "sectors", ")", "}", "for", "df", "in", "self", ".", "get_DataFrame", "(", "data", "=", "True", ")", ":", "df", ".", "rename", "(", "index", "=", "sectors", ",", "columns", "=", "sectors", ",", "inplace", "=", "True", ")", "try", ":", "for", "ext", "in", "self", ".", "get_extensions", "(", "data", "=", "True", ")", ":", "for", "df", "in", "ext", ".", "get_DataFrame", "(", "data", "=", "True", ")", ":", "df", ".", "rename", "(", "index", "=", "sectors", ",", "columns", "=", "sectors", ",", "inplace", "=", "True", ")", "except", ":", "pass", "self", ".", "meta", ".", "_add_modify", "(", "\"Changed sector names\"", ")", "return", "self" ]
Removes an existing Hypervisor level snapshot .
def DeleteSnapshot ( self , names = None ) : if names is None : names = self . GetSnapshots ( ) requests_lst = [ ] for name in names : name_links = [ obj [ 'links' ] for obj in self . data [ 'details' ] [ 'snapshots' ] if obj [ 'name' ] == name ] [ 0 ] requests_lst . append ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , [ obj [ 'href' ] for obj in name_links if obj [ 'rel' ] == 'delete' ] [ 0 ] , session = self . session ) , alias = self . alias , session = self . session ) ) return ( sum ( requests_lst ) )
6,569
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L495-L519
[ "def", "get_topic_keyword_dictionary", "(", ")", ":", "topic_keyword_dictionary", "=", "dict", "(", ")", "file_row_gen", "=", "get_file_row_generator", "(", "get_package_path", "(", ")", "+", "\"/twitter/res/topics/topic_keyword_mapping\"", "+", "\".txt\"", ",", "\",\"", ",", "\"utf-8\"", ")", "for", "file_row", "in", "file_row_gen", ":", "topic_keyword_dictionary", "[", "file_row", "[", "0", "]", "]", "=", "set", "(", "[", "keyword", "for", "keyword", "in", "file_row", "[", "1", ":", "]", "]", ")", "return", "topic_keyword_dictionary" ]
Restores an existing Hypervisor level snapshot .
def RestoreSnapshot ( self , name = None ) : if not len ( self . data [ 'details' ] [ 'snapshots' ] ) : raise ( clc . CLCException ( "No snapshots exist" ) ) if name is None : name = self . GetSnapshots ( ) [ 0 ] name_links = [ obj [ 'links' ] for obj in self . data [ 'details' ] [ 'snapshots' ] if obj [ 'name' ] == name ] [ 0 ] return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , [ obj [ 'href' ] for obj in name_links if obj [ 'rel' ] == 'restore' ] [ 0 ] , session = self . session ) , alias = self . alias , session = self . session ) )
6,570
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L522-L541
[ "def", "get_topic_keyword_dictionary", "(", ")", ":", "topic_keyword_dictionary", "=", "dict", "(", ")", "file_row_gen", "=", "get_file_row_generator", "(", "get_package_path", "(", ")", "+", "\"/twitter/res/topics/topic_keyword_mapping\"", "+", "\".txt\"", ",", "\",\"", ",", "\"utf-8\"", ")", "for", "file_row", "in", "file_row_gen", ":", "topic_keyword_dictionary", "[", "file_row", "[", "0", "]", "]", "=", "set", "(", "[", "keyword", "for", "keyword", "in", "file_row", "[", "1", ":", "]", "]", ")", "return", "topic_keyword_dictionary" ]
Creates a new server .
def Create ( name , template , group_id , network_id , cpu = None , memory = None , alias = None , password = None , ip_address = None , storage_type = "standard" , type = "standard" , primary_dns = None , secondary_dns = None , additional_disks = [ ] , custom_fields = [ ] , ttl = None , managed_os = False , description = None , source_server_password = None , cpu_autoscale_policy_id = None , anti_affinity_policy_id = None , packages = [ ] , configuration_id = None , session = None ) : if not alias : alias = clc . v2 . Account . GetAlias ( session = session ) if not description : description = name if type . lower ( ) != "baremetal" : if not cpu or not memory : group = clc . v2 . Group ( id = group_id , alias = alias , session = session ) if not cpu and group . Defaults ( "cpu" ) : cpu = group . Defaults ( "cpu" ) elif not cpu : raise ( clc . CLCException ( "No default CPU defined" ) ) if not memory and group . Defaults ( "memory" ) : memory = group . Defaults ( "memory" ) elif not memory : raise ( clc . CLCException ( "No default Memory defined" ) ) if type . lower ( ) == "standard" and storage_type . lower ( ) not in ( "standard" , "premium" ) : raise ( clc . CLCException ( "Invalid type/storage_type combo" ) ) if type . lower ( ) == "hyperscale" and storage_type . lower ( ) != "hyperscale" : raise ( clc . CLCException ( "Invalid type/storage_type combo" ) ) if type . lower ( ) == "baremetal" : type = "bareMetal" if ttl and ttl <= 3600 : raise ( clc . CLCException ( "ttl must be greater than 3600 seconds" ) ) if ttl : ttl = clc . v2 . time_utils . SecondsToZuluTS ( int ( time . time ( ) ) + ttl ) # TODO - validate custom_fields as a list of dicts with an id and a value key # TODO - validate template exists # TODO - validate additional_disks as a list of dicts with a path, sizeGB, and type (partitioned,raw) keys # TODO - validate addition_disks path not in template reserved paths # TODO - validate antiaffinity policy id set only with type=hyperscale payload = { 'name' : name , 'description' : description , 'groupId' : group_id , 'primaryDNS' : primary_dns , 'secondaryDNS' : secondary_dns , 'networkId' : network_id , 'password' : password , 'type' : type , 'customFields' : custom_fields } if type == 'bareMetal' : payload . update ( { 'configurationId' : configuration_id , 'osType' : template } ) else : payload . update ( { 'sourceServerId' : template , 'isManagedOS' : managed_os , 'ipAddress' : ip_address , 'sourceServerPassword' : source_server_password , 'cpu' : cpu , 'cpuAutoscalePolicyId' : cpu_autoscale_policy_id , 'memoryGB' : memory , 'storageType' : storage_type , 'antiAffinityPolicyId' : anti_affinity_policy_id , 'additionalDisks' : additional_disks , 'ttl' : ttl , 'packages' : packages } ) return clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s' % ( alias ) , json . dumps ( payload ) , session = session ) , alias = alias , session = session )
6,571
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L545-L617
[ "def", "setOverlayTextureBounds", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTextureBounds", "pOverlayTextureBounds", "=", "VRTextureBounds_t", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "byref", "(", "pOverlayTextureBounds", ")", ")", "return", "result", ",", "pOverlayTextureBounds" ]
Creates one or more clones of existing server .
def Clone ( self , network_id , name = None , cpu = None , memory = None , group_id = None , alias = None , password = None , ip_address = None , storage_type = None , type = None , primary_dns = None , secondary_dns = None , custom_fields = None , ttl = None , managed_os = False , description = None , source_server_password = None , cpu_autoscale_policy_id = None , anti_affinity_policy_id = None , packages = [ ] , count = 1 ) : if not name : name = re . search ( "%s(.+)\d{2}$" % self . alias , self . name ) . group ( 1 ) #if not description and self.description: description = self.description if not cpu : cpu = self . cpu if not memory : memory = self . memory if not group_id : group_id = self . group_id if not alias : alias = self . alias if not source_server_password : source_server_password = self . Credentials ( ) [ 'password' ] if not password : password = source_server_password # is this the expected behavior? if not storage_type : storage_type = self . storage_type if not type : type = self . type if not storage_type : storage_type = self . storage_type if not custom_fields and len ( self . custom_fields ) : custom_fields = self . custom_fields if not description : description = self . description # TODO - #if not cpu_autoscale_policy_id: cpu_autoscale_policy_id = # TODO - #if not anti_affinity_policy_id: anti_affinity_policy_id = # TODO - need to get network_id of self, not currently exposed via API :( requests_lst = [ ] for i in range ( 0 , count ) : requests_lst . append ( Server . Create ( name = name , cpu = cpu , memory = memory , group_id = group_id , network_id = network_id , alias = self . alias , password = password , ip_address = ip_address , storage_type = storage_type , type = type , primary_dns = primary_dns , secondary_dns = secondary_dns , custom_fields = custom_fields , ttl = ttl , managed_os = managed_os , description = description , source_server_password = source_server_password , cpu_autoscale_policy_id = cpu_autoscale_policy_id , anti_affinity_policy_id = anti_affinity_policy_id , packages = packages , template = self . id , session = self . session ) ) return ( sum ( requests_lst ) )
6,572
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L620-L674
[ "def", "get_topic_keyword_dictionary", "(", ")", ":", "topic_keyword_dictionary", "=", "dict", "(", ")", "file_row_gen", "=", "get_file_row_generator", "(", "get_package_path", "(", ")", "+", "\"/twitter/res/topics/topic_keyword_mapping\"", "+", "\".txt\"", ",", "\",\"", ",", "\"utf-8\"", ")", "for", "file_row", "in", "file_row_gen", ":", "topic_keyword_dictionary", "[", "file_row", "[", "0", "]", "]", "=", "set", "(", "[", "keyword", "for", "keyword", "in", "file_row", "[", "1", ":", "]", "]", ")", "return", "topic_keyword_dictionary" ]
Converts existing server to a template .
def ConvertToTemplate ( self , visibility , description = None , password = None ) : if visibility not in ( 'private' , 'shared' ) : raise ( clc . CLCException ( "Invalid visibility - must be private or shared" ) ) if not password : password = self . Credentials ( ) [ 'password' ] if not description : description = self . description return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/convertToTemplate' % ( self . alias , self . id ) , json . dumps ( { "description" : description , "visibility" : visibility , "password" : password } ) , session = self . session ) , alias = self . alias , session = self . session ) )
6,573
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L678-L697
[ "def", "remove_armor", "(", "armored_data", ")", ":", "stream", "=", "io", ".", "BytesIO", "(", "armored_data", ")", "lines", "=", "stream", ".", "readlines", "(", ")", "[", "3", ":", "-", "1", "]", "data", "=", "base64", ".", "b64decode", "(", "b''", ".", "join", "(", "lines", ")", ")", "payload", ",", "checksum", "=", "data", "[", ":", "-", "3", "]", ",", "data", "[", "-", "3", ":", "]", "assert", "util", ".", "crc24", "(", "payload", ")", "==", "checksum", "return", "payload" ]
Change existing server object .
def Change ( self , cpu = None , memory = None , description = None , group_id = None ) : if group_id : groupId = group_id else : groupId = None payloads = [ ] requests = [ ] for key in ( "cpu" , "memory" , "description" , "groupId" ) : if locals ( ) [ key ] : requests . append ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . alias , self . id ) , json . dumps ( [ { "op" : "set" , "member" : key , "value" : locals ( ) [ key ] } ] ) , session = self . session ) , alias = self . alias , session = self . session ) ) if len ( requests ) : self . dirty = True return ( sum ( requests ) )
6,574
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L701-L727
[ "def", "load_tag", "(", "corpus", ",", "path", ")", ":", "tag_idx", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "data_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'by_book'", ")", "tag_utt_ids", "=", "[", "]", "for", "gender_path", "in", "MailabsReader", ".", "get_folders", "(", "data_path", ")", ":", "# IN MIX FOLDERS THERE ARE NO SPEAKERS", "# HANDLE EVERY UTT AS DIFFERENT ISSUER", "if", "os", ".", "path", ".", "basename", "(", "gender_path", ")", "==", "'mix'", ":", "utt_ids", "=", "MailabsReader", ".", "load_books_of_speaker", "(", "corpus", ",", "gender_path", ",", "None", ")", "tag_utt_ids", ".", "extend", "(", "utt_ids", ")", "else", ":", "for", "speaker_path", "in", "MailabsReader", ".", "get_folders", "(", "gender_path", ")", ":", "speaker", "=", "MailabsReader", ".", "load_speaker", "(", "corpus", ",", "speaker_path", ")", "utt_ids", "=", "MailabsReader", ".", "load_books_of_speaker", "(", "corpus", ",", "speaker_path", ",", "speaker", ")", "tag_utt_ids", ".", "extend", "(", "utt_ids", ")", "filter", "=", "subset", ".", "MatchingUtteranceIdxFilter", "(", "utterance_idxs", "=", "set", "(", "tag_utt_ids", ")", ")", "subview", "=", "subset", ".", "Subview", "(", "corpus", ",", "filter_criteria", "=", "[", "filter", "]", ")", "corpus", ".", "import_subview", "(", "tag_idx", ",", "subview", ")" ]
Request change of password .
def SetPassword ( self , password ) : # 0: {op: "set", member: "password", value: {current: " r`5Mun/vT:qZ]2?z", password: "Savvis123!"}} if self . data [ 'status' ] != "active" : raise ( clc . CLCException ( "Server must be powered on to change password" ) ) return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . alias , self . id ) , json . dumps ( [ { "op" : "set" , "member" : "password" , "value" : { "current" : self . Credentials ( ) [ 'password' ] , "password" : password } } ] ) , session = self . session ) , alias = self . alias , session = self . session ) )
6,575
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L736-L754
[ "def", "sample", "(", "self", ",", "n", "=", "100", ",", "seed", "=", "None", ")", ":", "if", "n", "<", "1", ":", "raise", "ValueError", "(", "\"Number of samples must be larger than 0, got '%g'\"", "%", "n", ")", "if", "seed", "is", "None", ":", "seed", "=", "random", ".", "randint", "(", "0", ",", "2", "**", "32", ")", "if", "self", ".", "mode", "==", "'spark'", ":", "result", "=", "asarray", "(", "self", ".", "values", ".", "tordd", "(", ")", ".", "values", "(", ")", ".", "takeSample", "(", "False", ",", "n", ",", "seed", ")", ")", "else", ":", "basedims", "=", "[", "self", ".", "shape", "[", "d", "]", "for", "d", "in", "self", ".", "baseaxes", "]", "inds", "=", "[", "unravel_index", "(", "int", "(", "k", ")", ",", "basedims", ")", "for", "k", "in", "random", ".", "rand", "(", "n", ")", "*", "prod", "(", "basedims", ")", "]", "result", "=", "asarray", "(", "[", "self", ".", "values", "[", "tupleize", "(", "i", ")", "+", "(", "slice", "(", "None", ",", "None", ")", ",", ")", "]", "for", "i", "in", "inds", "]", ")", "return", "self", ".", "_constructor", "(", "result", ",", "index", "=", "self", ".", "index", ")" ]
Delete server .
def Delete ( self ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , 'servers/%s/%s' % ( self . alias , self . id ) , session = self . session ) , alias = self . alias , session = self . session ) )
6,576
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L757-L766
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Get public_ip by providing either the public or the internal IP address .
def Get ( self , key ) : for public_ip in self . public_ips : if public_ip . id == key : return ( public_ip ) elif key == public_ip . internal : return ( public_ip )
6,577
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L54-L59
[ "def", "units", "(", "self", ",", "value", ")", ":", "for", "m", "in", "self", ".", "geometry", ".", "values", "(", ")", ":", "m", ".", "units", "=", "value" ]
Add new public_ip .
def Add ( self , ports , source_restrictions = None , private_ip = None ) : payload = { 'ports' : [ ] } for port in ports : if 'port_to' in port : payload [ 'ports' ] . append ( { 'protocol' : port [ 'protocol' ] , 'port' : port [ 'port' ] , 'portTo' : port [ 'port_to' ] } ) else : payload [ 'ports' ] . append ( { 'protocol' : port [ 'protocol' ] , 'port' : port [ 'port' ] } ) if source_restrictions : payload [ 'sourceRestrictions' ] = source_restrictions if private_ip : payload [ 'internalIPAddress' ] = private_ip return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/publicIPAddresses' % ( self . server . alias , self . server . id ) , json . dumps ( payload ) , session = self . session ) , alias = self . server . alias , session = self . session ) )
6,578
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L62-L109
[ "def", "subst_dict", "(", "target", ",", "source", ")", ":", "dict", "=", "{", "}", "if", "target", ":", "def", "get_tgt_subst_proxy", "(", "thing", ")", ":", "try", ":", "subst_proxy", "=", "thing", ".", "get_subst_proxy", "(", ")", "except", "AttributeError", ":", "subst_proxy", "=", "thing", "# probably a string, just return it", "return", "subst_proxy", "tnl", "=", "NLWrapper", "(", "target", ",", "get_tgt_subst_proxy", ")", "dict", "[", "'TARGETS'", "]", "=", "Targets_or_Sources", "(", "tnl", ")", "dict", "[", "'TARGET'", "]", "=", "Target_or_Source", "(", "tnl", ")", "# This is a total cheat, but hopefully this dictionary goes", "# away soon anyway. We just let these expand to $TARGETS", "# because that's \"good enough\" for the use of ToolSurrogates", "# (see test/ToolSurrogate.py) to generate documentation.", "dict", "[", "'CHANGED_TARGETS'", "]", "=", "'$TARGETS'", "dict", "[", "'UNCHANGED_TARGETS'", "]", "=", "'$TARGETS'", "else", ":", "dict", "[", "'TARGETS'", "]", "=", "NullNodesList", "dict", "[", "'TARGET'", "]", "=", "NullNodesList", "if", "source", ":", "def", "get_src_subst_proxy", "(", "node", ")", ":", "try", ":", "rfile", "=", "node", ".", "rfile", "except", "AttributeError", ":", "pass", "else", ":", "node", "=", "rfile", "(", ")", "try", ":", "return", "node", ".", "get_subst_proxy", "(", ")", "except", "AttributeError", ":", "return", "node", "# probably a String, just return it", "snl", "=", "NLWrapper", "(", "source", ",", "get_src_subst_proxy", ")", "dict", "[", "'SOURCES'", "]", "=", "Targets_or_Sources", "(", "snl", ")", "dict", "[", "'SOURCE'", "]", "=", "Target_or_Source", "(", "snl", ")", "# This is a total cheat, but hopefully this dictionary goes", "# away soon anyway. We just let these expand to $TARGETS", "# because that's \"good enough\" for the use of ToolSurrogates", "# (see test/ToolSurrogate.py) to generate documentation.", "dict", "[", "'CHANGED_SOURCES'", "]", "=", "'$SOURCES'", "dict", "[", "'UNCHANGED_SOURCES'", "]", "=", "'$SOURCES'", "else", ":", "dict", "[", "'SOURCES'", "]", "=", "NullNodesList", "dict", "[", "'SOURCE'", "]", "=", "NullNodesList", "return", "dict" ]
Performs a full load of all PublicIP metadata .
def _Load ( self , cached = True ) : if not self . data or not cached : self . data = clc . v2 . API . Call ( 'GET' , 'servers/%s/%s/publicIPAddresses/%s' % ( self . parent . server . alias , self . parent . server . id , self . id ) , session = self . session ) # build ports self . data [ '_ports' ] = self . data [ 'ports' ] self . data [ 'ports' ] = [ ] for port in self . data [ '_ports' ] : if 'portTo' in port : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] , port [ 'portTo' ] ) ) else : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] ) ) # build source restriction self . data [ '_source_restrictions' ] = self . data [ 'sourceRestrictions' ] self . data [ 'source_restrictions' ] = [ ] for source_restriction in self . data [ '_source_restrictions' ] : self . source_restrictions . append ( SourceRestriction ( self , source_restriction [ 'cidr' ] ) ) return ( self . data )
6,579
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L125-L145
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "ResponseParameters", ",", "self", ")", ".", "to_array", "(", ")", "if", "self", ".", "migrate_to_chat_id", "is", "not", "None", ":", "array", "[", "'migrate_to_chat_id'", "]", "=", "int", "(", "self", ".", "migrate_to_chat_id", ")", "# type int", "if", "self", ".", "retry_after", "is", "not", "None", ":", "array", "[", "'retry_after'", "]", "=", "int", "(", "self", ".", "retry_after", ")", "# type int", "return", "array" ]
Delete public IP .
def Delete ( self ) : public_ip_set = [ { 'public_ipId' : o . id } for o in self . parent . public_ips if o != self ] self . parent . public_ips = [ o for o in self . parent . public_ips if o != self ] return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , 'servers/%s/%s/publicIPAddresses/%s' % ( self . parent . server . alias , self . parent . server . id , self . id ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
6,580
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L148-L161
[ "def", "removeMigrationRequest", "(", "self", ",", "migration_rqst", ")", ":", "conn", "=", "self", ".", "dbi", ".", "connection", "(", ")", "try", ":", "tran", "=", "conn", ".", "begin", "(", ")", "self", ".", "mgrremove", ".", "execute", "(", "conn", ",", "migration_rqst", ")", "tran", ".", "commit", "(", ")", "except", "dbsException", "as", "he", ":", "if", "conn", ":", "conn", ".", "close", "(", ")", "raise", "except", "Exception", "as", "ex", ":", "if", "conn", ":", "conn", ".", "close", "(", ")", "raise", "if", "conn", ":", "conn", ".", "close", "(", ")" ]
Commit current PublicIP definition to cloud .
def Update ( self ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PUT' , 'servers/%s/%s/publicIPAddresses/%s' % ( self . parent . server . alias , self . parent . server . id , self . id ) , json . dumps ( { 'ports' : [ o . ToDict ( ) for o in self . ports ] , 'sourceRestrictions' : [ o . ToDict ( ) for o in self . source_restrictions ] } ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
6,581
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L164-L179
[ "def", "retino_colors", "(", "vcolorfn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "def", "_retino_color_pass", "(", "*", "args", ",", "*", "*", "new_kwargs", ")", ":", "return", "retino_colors", "(", "vcolorfn", ",", "*", "args", ",", "*", "*", "{", "k", ":", "(", "new_kwargs", "[", "k", "]", "if", "k", "in", "new_kwargs", "else", "kwargs", "[", "k", "]", ")", "for", "k", "in", "set", "(", "kwargs", ".", "keys", "(", ")", "+", "new_kwargs", ".", "keys", "(", ")", ")", "}", ")", "return", "_retino_color_pass", "elif", "len", "(", "args", ")", ">", "1", ":", "raise", "ValueError", "(", "'retinotopy color functions accepts at most one argument'", ")", "m", "=", "args", "[", "0", "]", "# we need to handle the arguments", "if", "isinstance", "(", "m", ",", "(", "geo", ".", "VertexSet", ",", "pimms", ".", "ITable", ")", ")", ":", "tbl", "=", "m", ".", "properties", "if", "isinstance", "(", "m", ",", "geo", ".", "VertexSet", ")", "else", "m", "n", "=", "tbl", ".", "row_count", "# if the weight or property arguments are lists, we need to thread these along", "if", "'property'", "in", "kwargs", ":", "props", "=", "kwargs", "[", "'property'", "]", "del", "kwargs", "[", "'property'", "]", "if", "not", "(", "pimms", ".", "is_vector", "(", "props", ")", "or", "pimms", ".", "is_matrix", "(", "props", ")", ")", ":", "props", "=", "[", "props", "for", "_", "in", "range", "(", "n", ")", "]", "else", ":", "props", "=", "None", "if", "'weight'", "in", "kwargs", ":", "ws", "=", "kwargs", "[", "'weight'", "]", "del", "kwargs", "[", "'weight'", "]", "if", "not", "pimms", ".", "is_vector", "(", "ws", ")", "and", "not", "pimms", ".", "is_matrix", "(", "ws", ")", ":", "ws", "=", "[", "ws", "for", "_", "in", "range", "(", "n", ")", "]", "else", ":", "ws", "=", "None", "vcolorfn0", "=", "vcolorfn", "(", "Ellipsis", ",", "*", "*", "kwargs", ")", "if", "len", "(", "kwargs", ")", ">", "0", "else", "vcolorfn", "if", "props", "is", "None", "and", "ws", "is", "None", ":", "vcfn", "=", "lambda", "m", ",", "k", ":", "vcolorfn0", "(", "m", ")", "elif", "props", "is", "None", ":", "vcfn", "=", "lambda", "m", ",", "k", ":", "vcolorfn0", "(", "m", ",", "weight", "=", "ws", "[", "k", "]", ")", "elif", "ws", "is", "None", ":", "vcfn", "=", "lambda", "m", ",", "k", ":", "vcolorfn0", "(", "m", ",", "property", "=", "props", "[", "k", "]", ")", "else", ":", "vcfn", "=", "lambda", "m", ",", "k", ":", "vcolorfn0", "(", "m", ",", "property", "=", "props", "[", "k", "]", ",", "weight", "=", "ws", "[", "k", "]", ")", "return", "np", ".", "asarray", "(", "[", "vcfn", "(", "r", ",", "kk", ")", "for", "(", "kk", ",", "r", ")", "in", "enumerate", "(", "tbl", ".", "rows", ")", "]", ")", "else", ":", "return", "vcolorfn", "(", "m", ",", "*", "*", "kwargs", ")" ]
Add and commit a single port .
def AddPort ( self , protocol , port , port_to = None ) : self . ports . append ( Port ( self , protocol , port , port_to ) ) return ( self . Update ( ) )
6,582
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L182-L197
[ "def", "create_badge_blueprint", "(", "allowed_types", ")", ":", "from", "invenio_formatter", ".", "context_processors", ".", "badges", "import", "generate_badge_png", ",", "generate_badge_svg", "blueprint", "=", "Blueprint", "(", "'invenio_formatter_badges'", ",", "__name__", ",", "template_folder", "=", "'templates'", ",", ")", "@", "blueprint", ".", "route", "(", "'/badge/<any({0}):title>/<path:value>.<any(svg, png):ext>'", ".", "format", "(", "', '", ".", "join", "(", "allowed_types", ")", ")", ")", "def", "badge", "(", "title", ",", "value", ",", "ext", "=", "'svg'", ")", ":", "\"\"\"Generate a badge response.\"\"\"", "if", "ext", "==", "'svg'", ":", "generator", "=", "generate_badge_svg", "mimetype", "=", "'image/svg+xml'", "elif", "ext", "==", "'png'", ":", "generator", "=", "generate_badge_png", "mimetype", "=", "'image/png'", "badge_title_mapping", "=", "current_app", ".", "config", "[", "'FORMATTER_BADGES_TITLE_MAPPING'", "]", ".", "get", "(", "title", ",", "title", ")", "response", "=", "Response", "(", "generator", "(", "badge_title_mapping", ",", "value", ")", ",", "mimetype", "=", "mimetype", ")", "# Generate Etag from badge title and value.", "hashable_badge", "=", "\"{0}.{1}\"", ".", "format", "(", "badge_title_mapping", ",", "value", ")", ".", "encode", "(", "'utf-8'", ")", "response", ".", "set_etag", "(", "hashlib", ".", "sha1", "(", "hashable_badge", ")", ".", "hexdigest", "(", ")", ")", "# Add headers to prevent caching.", "response", ".", "headers", "[", "\"Pragma\"", "]", "=", "\"no-cache\"", "response", ".", "cache_control", ".", "no_cache", "=", "True", "response", ".", "cache_control", ".", "max_age", "=", "current_app", ".", "config", "[", "'FORMATTER_BADGES_MAX_CACHE_AGE'", "]", "response", ".", "last_modified", "=", "dt", ".", "utcnow", "(", ")", "extra", "=", "timedelta", "(", "seconds", "=", "current_app", ".", "config", "[", "'FORMATTER_BADGES_MAX_CACHE_AGE'", "]", ")", "response", ".", "expires", "=", "response", ".", "last_modified", "+", "extra", "return", "response", ".", "make_conditional", "(", "request", ")", "return", "blueprint" ]
Create one or more port access policies .
def AddPorts ( self , ports ) : for port in ports : if 'port_to' in port : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] , port [ 'port_to' ] ) ) else : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] ) ) return ( self . Update ( ) )
6,583
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L200-L216
[ "def", "delete_metadata_for_uri", "(", "self", ",", "uri", ")", ":", "hash_value", "=", "self", ".", "hash_for_datasource", "(", "uri", ")", "try", ":", "cursor", "=", "self", ".", "get_cursor", "(", ")", "# now see if we have any data for our hash", "sql", "=", "'delete from metadata where hash = \\''", "+", "hash_value", "+", "'\\';'", "cursor", ".", "execute", "(", "sql", ")", "self", ".", "connection", ".", "commit", "(", ")", "except", "sqlite", ".", "Error", "as", "e", ":", "LOGGER", ".", "debug", "(", "\"SQLITE Error %s:\"", "%", "e", ".", "args", "[", "0", "]", ")", "self", ".", "connection", ".", "rollback", "(", ")", "except", "Exception", "as", "e", ":", "LOGGER", ".", "debug", "(", "\"Error %s:\"", "%", "e", ".", "args", "[", "0", "]", ")", "self", ".", "connection", ".", "rollback", "(", ")", "raise", "finally", ":", "self", ".", "close_connection", "(", ")" ]
Add and commit a single source IP restriction policy .
def AddSourceRestriction ( self , cidr ) : self . source_restrictions . append ( SourceRestriction ( self , cidr ) ) return ( self . Update ( ) )
6,584
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L219-L230
[ "def", "public_timeline", "(", "self", ",", "delegate", ",", "params", "=", "{", "}", ",", "extra_args", "=", "None", ")", ":", "return", "self", ".", "__get", "(", "'/statuses/public_timeline.atom'", ",", "delegate", ",", "params", ",", "extra_args", "=", "extra_args", ")" ]
Create one or more CIDR source restriction policies .
def AddSourceRestrictions ( self , cidrs ) : for cidr in cidrs : self . source_restrictions . append ( SourceRestriction ( self , cidr ) ) return ( self . Update ( ) )
6,585
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L233-L246
[ "def", "release", "(", "cls", ",", "entity", ",", "unit_of_work", ")", ":", "if", "not", "hasattr", "(", "entity", ",", "'__everest__'", ")", ":", "raise", "ValueError", "(", "'Trying to unregister an entity that has not '", "'been registered yet!'", ")", "elif", "not", "unit_of_work", "is", "entity", ".", "__everest__", ".", "unit_of_work", ":", "raise", "ValueError", "(", "'Trying to unregister an entity that has been '", "'registered with another session!'", ")", "delattr", "(", "entity", ",", "'__everest__'", ")" ]
Delete this port and commit change to cloud .
def Delete ( self ) : self . public_ip . ports = [ o for o in self . public_ip . ports if o != self ] return ( self . public_ip . Update ( ) )
6,586
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L274-L284
[ "def", "get_items_shuffled_metadata", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'items_shuffled'", "]", ")", "metadata", ".", "update", "(", "{", "'existing_boolean_values'", ":", "self", ".", "_my_map", "[", "'itemsShuffled'", "]", "}", ")", "return", "Metadata", "(", "*", "*", "metadata", ")" ]
Delete this source restriction and commit change to cloud .
def Delete ( self ) : self . public_ip . source_restrictions = [ o for o in self . public_ip . source_restrictions if o != self ] return ( self . public_ip . Update ( ) )
6,587
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L308-L318
[ "def", "getMonitorByName", "(", "self", ",", "monitorFriendlyName", ")", ":", "url", "=", "self", ".", "baseUrl", "url", "+=", "\"getMonitors?apiKey=%s\"", "%", "self", ".", "apiKey", "url", "+=", "\"&noJsonCallback=1&format=json\"", "success", ",", "response", "=", "self", ".", "requestApi", "(", "url", ")", "if", "success", ":", "monitors", "=", "response", ".", "get", "(", "'monitors'", ")", ".", "get", "(", "'monitor'", ")", "for", "i", "in", "range", "(", "len", "(", "monitors", ")", ")", ":", "monitor", "=", "monitors", "[", "i", "]", "if", "monitor", ".", "get", "(", "'friendlyname'", ")", "==", "monitorFriendlyName", ":", "status", "=", "monitor", ".", "get", "(", "'status'", ")", "alltimeuptimeratio", "=", "monitor", ".", "get", "(", "'alltimeuptimeratio'", ")", "return", "status", ",", "alltimeuptimeratio", "return", "None", ",", "None" ]
Returns the WGS84 bbox of the specified tile
def tile_bbox ( self , tile_indices ) : ( z , x , y ) = tile_indices topleft = ( x * self . tilesize , ( y + 1 ) * self . tilesize ) bottomright = ( ( x + 1 ) * self . tilesize , y * self . tilesize ) nw = self . unproject_pixels ( topleft , z ) se = self . unproject_pixels ( bottomright , z ) return nw + se
6,588
https://github.com/kamicut/tilepie/blob/103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96/tilepie/proj.py#L73-L82
[ "def", "simple_parse_file", "(", "filename", ":", "str", ")", "->", "Feed", ":", "pairs", "=", "(", "(", "rss", ".", "parse_rss_file", ",", "_adapt_rss_channel", ")", ",", "(", "atom", ".", "parse_atom_file", ",", "_adapt_atom_feed", ")", ",", "(", "json_feed", ".", "parse_json_feed_file", ",", "_adapt_json_feed", ")", ")", "return", "_simple_parse", "(", "pairs", ",", "filename", ")" ]
Returns the coordinates from position in meters
def unproject ( self , xy ) : ( x , y ) = xy lng = x / EARTH_RADIUS * RAD_TO_DEG lat = 2 * atan ( exp ( y / EARTH_RADIUS ) ) - pi / 2 * RAD_TO_DEG return ( lng , lat )
6,589
https://github.com/kamicut/tilepie/blob/103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96/tilepie/proj.py#L95-L102
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Given a handler output s type generates a response towards the processor
def from_entrypoint_output ( json_encoder , handler_output ) : response = { 'body' : '' , 'content_type' : 'text/plain' , 'headers' : { } , 'status_code' : 200 , 'body_encoding' : 'text' , } # if the type of the output is a string, just return that and 200 if isinstance ( handler_output , str ) : response [ 'body' ] = handler_output # if it's a tuple of 2 elements, first is status second is body elif isinstance ( handler_output , tuple ) and len ( handler_output ) == 2 : response [ 'status_code' ] = handler_output [ 0 ] if isinstance ( handler_output [ 1 ] , str ) : response [ 'body' ] = handler_output [ 1 ] else : response [ 'body' ] = json_encoder ( handler_output [ 1 ] ) response [ 'content_type' ] = 'application/json' # if it's a dict, populate the response and set content type to json elif isinstance ( handler_output , dict ) or isinstance ( handler_output , list ) : response [ 'content_type' ] = 'application/json' response [ 'body' ] = json_encoder ( handler_output ) # if it's a response object, populate the response elif isinstance ( handler_output , Response ) : if isinstance ( handler_output . body , dict ) : response [ 'body' ] = json . dumps ( handler_output . body ) response [ 'content_type' ] = 'application/json' else : response [ 'body' ] = handler_output . body response [ 'content_type' ] = handler_output . content_type response [ 'headers' ] = handler_output . headers response [ 'status_code' ] = handler_output . status_code else : response [ 'body' ] = handler_output if isinstance ( response [ 'body' ] , bytes ) : response [ 'body' ] = base64 . b64encode ( response [ 'body' ] ) . decode ( 'ascii' ) response [ 'body_encoding' ] = 'base64' return response
6,590
https://github.com/nuclio/nuclio-sdk-py/blob/5af9ffc19a0d96255ff430bc358be9cd7a57f424/nuclio_sdk/response.py#L34-L83
[ "def", "plot_bcr", "(", "fignum", ",", "Bcr1", ",", "Bcr2", ")", ":", "plt", ".", "figure", "(", "num", "=", "fignum", ")", "plt", ".", "plot", "(", "Bcr1", ",", "Bcr2", ",", "'ro'", ")", "plt", ".", "xlabel", "(", "'Bcr1'", ")", "plt", ".", "ylabel", "(", "'Bcr2'", ")", "plt", ".", "title", "(", "'Compare coercivity of remanence'", ")" ]
functions check architecture of target python
def check_python_architecture ( pythondir , target_arch_str ) : pyth_str = subprocess . check_output ( [ pythondir + 'python' , '-c' , 'import platform; print platform.architecture()[0]' ] ) if pyth_str [ : 2 ] != target_arch_str : raise Exception ( "Wrong architecture of target python. Expected arch is" + target_arch_str )
6,591
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/sample_data.py#L42-L52
[ "def", "get_last_components_by_type", "(", "component_types", ",", "topic_id", ",", "db_conn", "=", "None", ")", ":", "db_conn", "=", "db_conn", "or", "flask", ".", "g", ".", "db_conn", "schedule_components_ids", "=", "[", "]", "for", "ct", "in", "component_types", ":", "where_clause", "=", "sql", ".", "and_", "(", "models", ".", "COMPONENTS", ".", "c", ".", "type", "==", "ct", ",", "models", ".", "COMPONENTS", ".", "c", ".", "topic_id", "==", "topic_id", ",", "models", ".", "COMPONENTS", ".", "c", ".", "export_control", "==", "True", ",", "models", ".", "COMPONENTS", ".", "c", ".", "state", "==", "'active'", ")", "# noqa", "query", "=", "(", "sql", ".", "select", "(", "[", "models", ".", "COMPONENTS", ".", "c", ".", "id", "]", ")", ".", "where", "(", "where_clause", ")", ".", "order_by", "(", "sql", ".", "desc", "(", "models", ".", "COMPONENTS", ".", "c", ".", "created_at", ")", ")", ")", "cmpt_id", "=", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchone", "(", ")", "if", "cmpt_id", "is", "None", ":", "msg", "=", "'Component of type \"%s\" not found or not exported.'", "%", "ct", "raise", "dci_exc", ".", "DCIException", "(", "msg", ",", "status_code", "=", "412", ")", "cmpt_id", "=", "cmpt_id", "[", "0", "]", "if", "cmpt_id", "in", "schedule_components_ids", ":", "msg", "=", "(", "'Component types %s malformed: type %s duplicated.'", "%", "(", "component_types", ",", "ct", ")", ")", "raise", "dci_exc", ".", "DCIException", "(", "msg", ",", "status_code", "=", "412", ")", "schedule_components_ids", ".", "append", "(", "cmpt_id", ")", "return", "schedule_components_ids" ]
Download unzip and delete .
def downzip ( url , destination = './sample_data/' ) : # url = "http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip" logmsg = "downloading from '" + url + "'" print ( logmsg ) logger . debug ( logmsg ) local_file_name = os . path . join ( destination , 'tmp.zip' ) urllibr . urlretrieve ( url , local_file_name ) datafile = zipfile . ZipFile ( local_file_name ) datafile . extractall ( destination ) remove ( local_file_name )
6,592
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/sample_data.py#L64-L77
[ "def", "setOverlayTransformTrackedDeviceRelative", "(", "self", ",", "ulOverlayHandle", ",", "unTrackedDevice", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTransformTrackedDeviceRelative", "pmatTrackedDeviceToOverlayTransform", "=", "HmdMatrix34_t", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "unTrackedDevice", ",", "byref", "(", "pmatTrackedDeviceToOverlayTransform", ")", ")", "return", "result", ",", "pmatTrackedDeviceToOverlayTransform" ]
Return checksum given by path . Wildcards can be used in check sum . Function is strongly dependent on checksumdir package by cakepietoast .
def checksum ( path , hashfunc = 'md5' ) : import checksumdir hash_func = checksumdir . HASH_FUNCS . get ( hashfunc ) if not hash_func : raise NotImplementedError ( '{} not implemented.' . format ( hashfunc ) ) if os . path . isdir ( path ) : return checksumdir . dirhash ( path , hashfunc = hashfunc ) hashvalues = [ ] path_list = glob . glob ( path ) logger . debug ( "path_list " + str ( path_list ) ) for path in path_list : if os . path . isfile ( path ) : hashvalues . append ( checksumdir . _filehash ( path , hashfunc = hash_func ) ) logger . debug ( str ( hashvalues ) ) hash = checksumdir . _reduce_hash ( hashvalues , hashfunc = hash_func ) return hash
6,593
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/sample_data.py#L166-L191
[ "def", "reload", "(", "self", ")", ":", "self", ".", "buf", "=", "self", ".", "fetch", "(", "buf", "=", "self", ".", "buf", ")", "return", "self" ]
Get disk by providing mount point or ID
def Get ( self , key ) : for disk in self . disks : if disk . id == key : return ( disk ) elif key in disk . partition_paths : return ( disk )
6,594
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L31-L40
[ "def", "write_wavefile", "(", "f", ",", "samples", ",", "nframes", "=", "None", ",", "nchannels", "=", "2", ",", "sampwidth", "=", "2", ",", "framerate", "=", "44100", ",", "bufsize", "=", "2048", ")", ":", "if", "nframes", "is", "None", ":", "nframes", "=", "0", "w", "=", "wave", ".", "open", "(", "f", ",", "'wb'", ")", "w", ".", "setparams", "(", "(", "nchannels", ",", "sampwidth", ",", "framerate", ",", "nframes", ",", "'NONE'", ",", "'not compressed'", ")", ")", "max_amplitude", "=", "float", "(", "int", "(", "(", "2", "**", "(", "sampwidth", "*", "8", ")", ")", "/", "2", ")", "-", "1", ")", "# split the samples into chunks (to reduce memory consumption and improve performance)", "for", "chunk", "in", "grouper", "(", "bufsize", ",", "samples", ")", ":", "frames", "=", "b''", ".", "join", "(", "b''", ".", "join", "(", "struct", ".", "pack", "(", "'h'", ",", "int", "(", "max_amplitude", "*", "sample", ")", ")", "for", "sample", "in", "channels", ")", "for", "channels", "in", "chunk", "if", "channels", "is", "not", "None", ")", "w", ".", "writeframesraw", "(", "frames", ")", "w", ".", "close", "(", ")" ]
Search disk list by partial mount point or ID
def Search ( self , key ) : results = [ ] for disk in self . disks : if disk . id . lower ( ) . find ( key . lower ( ) ) != - 1 : results . append ( disk ) # TODO - search in list to match partial mount points elif key . lower ( ) in disk . partition_paths : results . append ( disk ) return ( results )
6,595
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L43-L54
[ "def", "start", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_running", "(", ")", ":", "self", ".", "websock_url", "=", "self", ".", "chrome", ".", "start", "(", "*", "*", "kwargs", ")", "self", ".", "websock", "=", "websocket", ".", "WebSocketApp", "(", "self", ".", "websock_url", ")", "self", ".", "websock_thread", "=", "WebsockReceiverThread", "(", "self", ".", "websock", ",", "name", "=", "'WebsockThread:%s'", "%", "self", ".", "chrome", ".", "port", ")", "self", ".", "websock_thread", ".", "start", "(", ")", "self", ".", "_wait_for", "(", "lambda", ":", "self", ".", "websock_thread", ".", "is_open", ",", "timeout", "=", "30", ")", "# tell browser to send us messages we're interested in", "self", ".", "send_to_chrome", "(", "method", "=", "'Network.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'Page.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'Console.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'Runtime.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'ServiceWorker.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'ServiceWorker.setForceUpdateOnPageLoad'", ")", "# disable google analytics", "self", ".", "send_to_chrome", "(", "method", "=", "'Network.setBlockedURLs'", ",", "params", "=", "{", "'urls'", ":", "[", "'*google-analytics.com/analytics.js'", ",", "'*google-analytics.com/ga.js'", "]", "}", ")" ]
Add new disk .
def Add ( self , size , path = None , type = "partitioned" ) : if type == "partitioned" and not path : raise ( clc . CLCException ( "Must specify path to mount new disk" ) ) # TODO - Raise exception if too many disks # TODO - Raise exception if too much total size (4TB standard, 1TB HS) disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . disks ] disk_set . append ( { 'sizeGB' : size , 'type' : type , 'path' : path } ) self . disks . append ( Disk ( id = int ( time . time ( ) ) , parent = self , disk_obj = { 'sizeGB' : size , 'partitionPaths' : [ path ] } , session = self . session ) ) self . size = size self . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . server . alias , self . server . id ) , json . dumps ( [ { "op" : "set" , "member" : "disks" , "value" : disk_set } ] ) , session = self . session ) , alias = self . server . alias , session = self . session ) )
6,596
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L57-L86
[ "def", "announceManagementEvent", "(", "self", ",", "action", ",", "varBind", ",", "*", "*", "context", ")", ":", "name", ",", "val", "=", "varBind", "cbFun", "=", "context", "[", "'cbFun'", "]", "if", "not", "self", ".", "_augmentingRows", ":", "cbFun", "(", "varBind", ",", "*", "*", "context", ")", "return", "# Convert OID suffix into index values", "instId", "=", "name", "[", "len", "(", "self", ".", "name", ")", "+", "1", ":", "]", "baseIndices", "=", "[", "]", "indices", "=", "[", "]", "for", "impliedFlag", ",", "modName", ",", "symName", "in", "self", ".", "_indexNames", ":", "mibObj", ",", "=", "mibBuilder", ".", "importSymbols", "(", "modName", ",", "symName", ")", "syntax", ",", "instId", "=", "self", ".", "oidToValue", "(", "mibObj", ".", "syntax", ",", "instId", ",", "impliedFlag", ",", "indices", ")", "if", "self", ".", "name", "==", "mibObj", ".", "name", "[", ":", "-", "1", "]", ":", "baseIndices", ".", "append", "(", "(", "mibObj", ".", "name", ",", "syntax", ")", ")", "indices", ".", "append", "(", "syntax", ")", "if", "instId", ":", "exc", "=", "error", ".", "SmiError", "(", "'Excessive instance identifier sub-OIDs left at %s: %s'", "%", "(", "self", ",", "instId", ")", ")", "cbFun", "(", "varBind", ",", "*", "*", "dict", "(", "context", ",", "error", "=", "exc", ")", ")", "return", "if", "not", "baseIndices", ":", "cbFun", "(", "varBind", ",", "*", "*", "context", ")", "return", "count", "=", "[", "len", "(", "self", ".", "_augmentingRows", ")", "]", "def", "_cbFun", "(", "varBind", ",", "*", "*", "context", ")", ":", "count", "[", "0", "]", "-=", "1", "if", "not", "count", "[", "0", "]", ":", "cbFun", "(", "varBind", ",", "*", "*", "context", ")", "for", "modName", ",", "mibSym", "in", "self", ".", "_augmentingRows", ":", "mibObj", ",", "=", "mibBuilder", ".", "importSymbols", "(", "modName", ",", "mibSym", ")", "mibObj", ".", "receiveManagementEvent", "(", "action", ",", "(", "baseIndices", ",", "val", ")", ",", "*", "*", "dict", "(", "context", ",", "cbFun", "=", "_cbFun", ")", ")", "debug", ".", "logger", "&", "debug", ".", "FLAG_INS", "and", "debug", ".", "logger", "(", "'announceManagementEvent %s to %s'", "%", "(", "action", ",", "mibObj", ")", ")" ]
Grow disk to the newly specified size .
def Grow ( self , size ) : if size > 1024 : raise ( clc . CLCException ( "Cannot grow disk beyond 1024GB" ) ) if size <= self . size : raise ( clc . CLCException ( "New size must exceed current disk size" ) ) # TODO - Raise exception if too much total size (4TB standard, 1TB HS) disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . parent . disks if o != self ] self . size = size disk_set . append ( { 'diskId' : self . id , 'sizeGB' : self . size } ) self . parent . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . parent . server . alias , self . parent . server . id ) , json . dumps ( [ { "op" : "set" , "member" : "disks" , "value" : disk_set } ] ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
6,597
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L102-L125
[ "def", "to_arff", "(", "dataset", ",", "*", "*", "kwargs", ")", ":", "pods_data", "=", "dataset", "(", "*", "*", "kwargs", ")", "vals", "=", "list", "(", "kwargs", ".", "values", "(", ")", ")", "for", "i", ",", "v", "in", "enumerate", "(", "vals", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "vals", "[", "i", "]", "=", "'|'", ".", "join", "(", "v", ")", "else", ":", "vals", "[", "i", "]", "=", "str", "(", "v", ")", "args", "=", "'_'", ".", "join", "(", "vals", ")", "n", "=", "dataset", ".", "__name__", "if", "len", "(", "args", ")", ">", "0", ":", "n", "+=", "'_'", "+", "args", "n", "=", "n", ".", "replace", "(", "' '", ",", "'-'", ")", "ks", "=", "pods_data", ".", "keys", "(", ")", "d", "=", "None", "if", "'Y'", "in", "ks", "and", "'X'", "in", "ks", ":", "d", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'X'", "]", ")", "if", "'Xtest'", "in", "ks", ":", "d", "=", "d", ".", "append", "(", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Xtest'", "]", ")", ",", "ignore_index", "=", "True", ")", "if", "'covariates'", "in", "ks", ":", "d", ".", "columns", "=", "pods_data", "[", "'covariates'", "]", "dy", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Y'", "]", ")", "if", "'Ytest'", "in", "ks", ":", "dy", "=", "dy", ".", "append", "(", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Ytest'", "]", ")", ",", "ignore_index", "=", "True", ")", "if", "'response'", "in", "ks", ":", "dy", ".", "columns", "=", "pods_data", "[", "'response'", "]", "for", "c", "in", "dy", ".", "columns", ":", "if", "c", "not", "in", "d", ".", "columns", ":", "d", "[", "c", "]", "=", "dy", "[", "c", "]", "else", ":", "d", "[", "'y'", "+", "str", "(", "c", ")", "]", "=", "dy", "[", "c", "]", "elif", "'Y'", "in", "ks", ":", "d", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Y'", "]", ")", "if", "'Ytest'", "in", "ks", ":", "d", "=", "d", ".", "append", "(", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Ytest'", "]", ")", ",", "ignore_index", "=", "True", ")", "elif", "'data'", "in", "ks", ":", "d", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'data'", "]", ")", "if", "d", "is", "not", "None", ":", "df2arff", "(", "d", ",", "n", ",", "pods_data", ")" ]
Delete disk .
def Delete ( self ) : disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . parent . disks if o != self ] self . parent . disks = [ o for o in self . parent . disks if o != self ] self . parent . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . parent . server . alias , self . parent . server . id ) , json . dumps ( [ { "op" : "set" , "member" : "disks" , "value" : disk_set } ] ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
6,598
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L128-L145
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Calculates SHA256 digest of a file .
def file_digest ( source ) : hash_sha256 = hashlib . sha256 ( ) should_close = False if isinstance ( source , six . string_types ) : should_close = True source = open ( source , 'rb' ) for chunk in iter ( lambda : source . read ( _BUFFER_SIZE ) , b'' ) : hash_sha256 . update ( chunk ) if should_close : source . close ( ) return hash_sha256 . hexdigest ( )
6,599
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/utils.py#L68-L88
[ "def", "handle_invocation", "(", "self", ",", "message", ")", ":", "req_id", "=", "message", ".", "request_id", "reg_id", "=", "message", ".", "registration_id", "if", "reg_id", "in", "self", ".", "_registered_calls", ":", "handler", "=", "self", ".", "_registered_calls", "[", "reg_id", "]", "[", "REGISTERED_CALL_CALLBACK", "]", "invoke", "=", "WampInvokeWrapper", "(", "self", ",", "handler", ",", "message", ")", "invoke", ".", "start", "(", ")", "else", ":", "error_uri", "=", "self", ".", "get_full_uri", "(", "'error.unknown.uri'", ")", "self", ".", "send_message", "(", "ERROR", "(", "request_code", "=", "WAMP_INVOCATION", ",", "request_id", "=", "req_id", ",", "details", "=", "{", "}", ",", "error", "=", "error_uri", ")", ")" ]