query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Get age the game was won in .
def _won_in ( self ) : if not self . _summary [ 'finished' ] : return starting_age = self . _summary [ 'settings' ] [ 'starting_age' ] . lower ( ) if starting_age == 'post imperial' : starting_age = 'imperial' ages_reached = set ( [ starting_age ] ) for player in self . _summary [ 'players' ] : for age , reached in player [ 'ages' ] . items ( ) : if reached : ages_reached . add ( age ) ages = [ 'imperial' , 'castle' , 'feudal' , 'dark' ] for age in ages : if age in ages_reached : return age
3,100
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L398-L413
[ "def", "parseReaderConfig", "(", "self", ",", "confdict", ")", ":", "logger", ".", "debug", "(", "'parseReaderConfig input: %s'", ",", "confdict", ")", "conf", "=", "{", "}", "for", "k", ",", "v", "in", "confdict", ".", "items", "(", ")", ":", "if", "not", "k", ".", "startswith", "(", "'Parameter'", ")", ":", "continue", "ty", "=", "v", "[", "'Type'", "]", "data", "=", "v", "[", "'Data'", "]", "vendor", "=", "None", "subtype", "=", "None", "try", ":", "vendor", ",", "subtype", "=", "v", "[", "'Vendor'", "]", ",", "v", "[", "'Subtype'", "]", "except", "KeyError", ":", "pass", "if", "ty", "==", "1023", ":", "if", "vendor", "==", "25882", "and", "subtype", "==", "37", ":", "tempc", "=", "struct", ".", "unpack", "(", "'!H'", ",", "data", ")", "[", "0", "]", "conf", ".", "update", "(", "temperature", "=", "tempc", ")", "else", ":", "conf", "[", "ty", "]", "=", "data", "return", "conf" ]
Get rec owner number .
def _rec_owner_number ( self ) : player = self . _header . initial . players [ self . _header . replay . rec_player ] return player . attributes . player_color + 1
3,101
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L415-L418
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Get modification timestamp from rec file .
def _get_timestamp ( self ) : filename_date = _find_date ( os . path . basename ( self . _path ) ) if filename_date : return filename_date
3,102
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L427-L431
[ "def", "_put_bucket_policy", "(", "self", ")", ":", "if", "self", ".", "s3props", "[", "'bucket_policy'", "]", ":", "policy_str", "=", "json", ".", "dumps", "(", "self", ".", "s3props", "[", "'bucket_policy'", "]", ")", "_response", "=", "self", ".", "s3client", ".", "put_bucket_policy", "(", "Bucket", "=", "self", ".", "bucket", ",", "Policy", "=", "policy_str", ")", "else", ":", "_response", "=", "self", ".", "s3client", ".", "delete_bucket_policy", "(", "Bucket", "=", "self", ".", "bucket", ")", "LOG", ".", "debug", "(", "'Response adding bucket policy: %s'", ",", "_response", ")", "LOG", ".", "info", "(", "'S3 Bucket Policy Attached'", ")" ]
Mark the winning team .
def _set_winning_team ( self ) : if not self . _summary [ 'finished' ] : return for team in self . _summary [ 'diplomacy' ] [ 'teams' ] : team [ 'winner' ] = False for player_number in team [ 'player_numbers' ] : for player in self . _summary [ 'players' ] : if player_number == player [ 'number' ] : if player [ 'winner' ] : team [ 'winner' ] = True
3,103
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L444-L454
[ "def", "get_monitors", "(", "self", ",", "condition", "=", "None", ",", "page_size", "=", "1000", ")", ":", "req_kwargs", "=", "{", "}", "if", "condition", ":", "req_kwargs", "[", "'condition'", "]", "=", "condition", ".", "compile", "(", ")", "for", "monitor_data", "in", "self", ".", "_conn", ".", "iter_json_pages", "(", "\"/ws/Monitor\"", ",", "*", "*", "req_kwargs", ")", ":", "yield", "DeviceCloudMonitor", ".", "from_json", "(", "self", ".", "_conn", ",", "monitor_data", ",", "self", ".", "_tcp_client_manager", ")" ]
Compute a map hash based on a combination of map attributes .
def _map_hash ( self ) : elevation_bytes = bytes ( [ tile . elevation for tile in self . _header . map_info . tile ] ) map_name_bytes = self . _map . name ( ) . encode ( ) player_bytes = b'' for _ , attributes in self . _players ( ) : player_bytes += ( mgz . const . PLAYER_COLORS [ attributes . player_color ] . encode ( ) + attributes . player_name . encode ( ) + mgz . const . CIVILIZATION_NAMES [ attributes . civilization ] . encode ( ) ) return hashlib . sha1 ( elevation_bytes + map_name_bytes + player_bytes ) . hexdigest ( )
3,104
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L456-L470
[ "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" ]
Return device info dict .
def device_info ( self ) : return { 'family' : self . family , 'platform' : self . platform , 'os_type' : self . os_type , 'os_version' : self . os_version , 'udi' : self . udi , # TODO(klstanie): add property to make driver automatically 'driver_name' : self . driver . platform , 'mode' : self . mode , 'is_console' : self . is_console , 'is_target' : self . is_target , # 'prompt': self.driver.base_prompt(self.prompt), 'hostname' : self . hostname , }
3,105
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L65-L80
[ "def", "removefromreadergroup", "(", "self", ",", "groupname", ")", ":", "hresult", ",", "hcontext", "=", "SCardEstablishContext", "(", "SCARD_SCOPE_USER", ")", "if", "0", "!=", "hresult", ":", "raise", "EstablishContextException", "(", "hresult", ")", "try", ":", "hresult", "=", "SCardRemoveReaderFromGroup", "(", "hcontext", ",", "self", ".", "name", ",", "groupname", ")", "if", "0", "!=", "hresult", ":", "raise", "RemoveReaderFromGroupException", "(", "hresult", ",", "self", ".", "name", ",", "groupname", ")", "finally", ":", "hresult", "=", "SCardReleaseContext", "(", "hcontext", ")", "if", "0", "!=", "hresult", ":", "raise", "ReleaseContextException", "(", "hresult", ")" ]
Clear the device info .
def clear_info ( self ) : self . _version_text = None self . _inventory_text = None self . _users_text = None self . os_version = None self . os_type = None self . family = None self . platform = None self . udi = None # self.is_console = None self . prompt = None self . prompt_re = None
3,106
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L92-L104
[ "def", "delete_container_instance_group", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "container_group_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourcegroups/'", ",", "resource_group", ",", "'/providers/Microsoft.ContainerInstance/ContainerGroups/'", ",", "container_group_name", ",", "'?api-version='", ",", "CONTAINER_API", "]", ")", "return", "do_delete", "(", "endpoint", ",", "access_token", ")" ]
Disconnect the device .
def disconnect ( self ) : self . chain . connection . log ( "Disconnecting: {}" . format ( self ) ) if self . connected : if self . protocol : if self . is_console : while self . mode != 'global' : try : self . send ( 'exit' , timeout = 10 ) except CommandTimeoutError : break self . protocol . disconnect ( self . driver ) self . protocol = None self . connected = False self . ctrl = None
3,107
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L182-L198
[ "def", "clean_subject_location", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "ImageAdminForm", ",", "self", ")", ".", "clean", "(", ")", "subject_location", "=", "cleaned_data", "[", "'subject_location'", "]", "if", "not", "subject_location", ":", "# if supplied subject location is empty, do not check it", "return", "subject_location", "# use thumbnail's helper function to check the format", "coordinates", "=", "normalize_subject_location", "(", "subject_location", ")", "if", "not", "coordinates", ":", "err_msg", "=", "ugettext_lazy", "(", "'Invalid subject location format. '", ")", "err_code", "=", "'invalid_subject_format'", "elif", "(", "coordinates", "[", "0", "]", ">", "self", ".", "instance", ".", "width", "or", "coordinates", "[", "1", "]", ">", "self", ".", "instance", ".", "height", ")", ":", "err_msg", "=", "ugettext_lazy", "(", "'Subject location is outside of the image. '", ")", "err_code", "=", "'subject_out_of_bounds'", "else", ":", "return", "subject_location", "self", ".", "_set_previous_subject_location", "(", "cleaned_data", ")", "raise", "forms", ".", "ValidationError", "(", "string_concat", "(", "err_msg", ",", "ugettext_lazy", "(", "'Your input: \"{subject_location}\". '", ".", "format", "(", "subject_location", "=", "subject_location", ")", ")", ",", "'Previous value is restored.'", ")", ",", "code", "=", "err_code", ")" ]
Make driver factory function .
def make_driver ( self , driver_name = 'generic' ) : module_str = 'condoor.drivers.%s' % driver_name try : __import__ ( module_str ) module = sys . modules [ module_str ] driver_class = getattr ( module , 'Driver' ) except ImportError as e : # pylint: disable=invalid-name print ( "driver name: {}" . format ( driver_name ) ) self . chain . connection . log ( "Import error: {}: '{}'" . format ( driver_name , str ( e ) ) ) # no driver - call again with default 'generic' return self . make_driver ( ) self . chain . connection . log ( "Make Device: {} with Driver: {}" . format ( self , driver_class . platform ) ) return driver_class ( self )
3,108
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L310-L324
[ "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" ]
Return version text and collect if not collected .
def version_text ( self ) : if self . _version_text is None : self . chain . connection . log ( "Collecting version information" ) self . _version_text = self . driver . get_version_text ( ) if self . _version_text : self . chain . connection . log ( "Version info collected" ) else : self . chain . connection . log ( "Version info not collected" ) return self . _version_text
3,109
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L331-L341
[ "def", "apply_spm_config", "(", "overrides", ",", "defaults", ")", ":", "opts", "=", "defaults", ".", "copy", "(", ")", "_adjust_log_file_override", "(", "overrides", ",", "defaults", "[", "'log_file'", "]", ")", "if", "overrides", ":", "opts", ".", "update", "(", "overrides", ")", "# Prepend root_dir to other paths", "prepend_root_dirs", "=", "[", "'formula_path'", ",", "'pillar_path'", ",", "'reactor_path'", ",", "'spm_cache_dir'", ",", "'spm_build_dir'", "]", "# These can be set to syslog, so, not actual paths on the system", "for", "config_key", "in", "(", "'spm_logfile'", ",", ")", ":", "log_setting", "=", "opts", ".", "get", "(", "config_key", ",", "''", ")", "if", "log_setting", "is", "None", ":", "continue", "if", "urlparse", "(", "log_setting", ")", ".", "scheme", "==", "''", ":", "prepend_root_dirs", ".", "append", "(", "config_key", ")", "prepend_root_dir", "(", "opts", ",", "prepend_root_dirs", ")", "return", "opts" ]
Return hostname text and collect if not collected .
def hostname_text ( self ) : if self . _hostname_text is None : self . chain . connection . log ( "Collecting hostname information" ) self . _hostname_text = self . driver . get_hostname_text ( ) if self . _hostname_text : self . chain . connection . log ( "Hostname info collected" ) else : self . chain . connection . log ( "Hostname info not collected" ) return self . _hostname_text
3,110
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L344-L353
[ "def", "apply_spm_config", "(", "overrides", ",", "defaults", ")", ":", "opts", "=", "defaults", ".", "copy", "(", ")", "_adjust_log_file_override", "(", "overrides", ",", "defaults", "[", "'log_file'", "]", ")", "if", "overrides", ":", "opts", ".", "update", "(", "overrides", ")", "# Prepend root_dir to other paths", "prepend_root_dirs", "=", "[", "'formula_path'", ",", "'pillar_path'", ",", "'reactor_path'", ",", "'spm_cache_dir'", ",", "'spm_build_dir'", "]", "# These can be set to syslog, so, not actual paths on the system", "for", "config_key", "in", "(", "'spm_logfile'", ",", ")", ":", "log_setting", "=", "opts", ".", "get", "(", "config_key", ",", "''", ")", "if", "log_setting", "is", "None", ":", "continue", "if", "urlparse", "(", "log_setting", ")", ".", "scheme", "==", "''", ":", "prepend_root_dirs", ".", "append", "(", "config_key", ")", "prepend_root_dir", "(", "opts", ",", "prepend_root_dirs", ")", "return", "opts" ]
Return inventory information and collect if not available .
def inventory_text ( self ) : if self . _inventory_text is None : self . chain . connection . log ( "Collecting inventory information" ) self . _inventory_text = self . driver . get_inventory_text ( ) if self . _inventory_text : self . chain . connection . log ( "Inventory info collected" ) else : self . chain . connection . log ( "Inventory info not collected" ) return self . _inventory_text
3,111
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L356-L365
[ "def", "protein_only_and_noH", "(", "self", ",", "keep_ligands", "=", "None", ",", "force_rerun", "=", "False", ")", ":", "log", ".", "debug", "(", "'{}: running protein receptor isolation...'", ".", "format", "(", "self", ".", "id", ")", ")", "if", "not", "self", ".", "dockprep_path", ":", "return", "ValueError", "(", "'Please run dockprep'", ")", "receptor_mol2", "=", "op", ".", "join", "(", "self", ".", "dock_dir", ",", "'{}_receptor.mol2'", ".", "format", "(", "self", ".", "id", ")", ")", "receptor_noh", "=", "op", ".", "join", "(", "self", ".", "dock_dir", ",", "'{}_receptor_noH.pdb'", ".", "format", "(", "self", ".", "id", ")", ")", "prly_com", "=", "op", ".", "join", "(", "self", ".", "dock_dir", ",", "\"prly.com\"", ")", "if", "ssbio", ".", "utils", ".", "force_rerun", "(", "flag", "=", "force_rerun", ",", "outfile", "=", "receptor_noh", ")", ":", "with", "open", "(", "prly_com", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "'open {}\\n'", ".", "format", "(", "self", ".", "dockprep_path", ")", ")", "keep_str", "=", "'delete ~protein'", "if", "keep_ligands", ":", "keep_ligands", "=", "ssbio", ".", "utils", ".", "force_list", "(", "keep_ligands", ")", "for", "res", "in", "keep_ligands", ":", "keep_str", "+=", "' & ~:{} '", ".", "format", "(", "res", ")", "keep_str", "=", "keep_str", ".", "strip", "(", ")", "+", "'\\n'", "f", ".", "write", "(", "keep_str", ")", "f", ".", "write", "(", "'write format mol2 0 {}\\n'", ".", "format", "(", "receptor_mol2", ")", ")", "f", ".", "write", "(", "'delete element.H\\n'", ")", "f", ".", "write", "(", "'write format pdb 0 {}\\n'", ".", "format", "(", "receptor_noh", ")", ")", "cmd", "=", "'chimera --nogui {}'", ".", "format", "(", "prly_com", ")", "os", ".", "system", "(", "cmd", ")", "os", ".", "remove", "(", "prly_com", ")", "if", "ssbio", ".", "utils", ".", "is_non_zero_file", "(", "receptor_mol2", ")", "and", "ssbio", ".", "utils", ".", "is_non_zero_file", "(", "receptor_noh", ")", ":", "self", ".", "receptormol2_path", "=", "receptor_mol2", "self", ".", "receptorpdb_path", "=", "receptor_noh", "log", ".", "debug", "(", "'{}: successful receptor isolation (mol2)'", ".", "format", "(", "self", ".", "receptormol2_path", ")", ")", "log", ".", "debug", "(", "'{}: successful receptor isolation (pdb)'", ".", "format", "(", "self", ".", "receptorpdb_path", ")", ")", "else", ":", "log", ".", "critical", "(", "'{}: protein_only_and_noH failed to run on dockprep file'", ".", "format", "(", "self", ".", "dockprep_path", ")", ")" ]
Return connected users information and collect if not available .
def users_text ( self ) : if self . _users_text is None : self . chain . connection . log ( "Getting connected users text" ) self . _users_text = self . driver . get_users_text ( ) if self . _users_text : self . chain . connection . log ( "Users text collected" ) else : self . chain . connection . log ( "Users text not collected" ) return self . _users_text
3,112
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L368-L377
[ "def", "_enforce_max_region_size", "(", "in_file", ",", "data", ")", ":", "max_size", "=", "20000", "overlap_size", "=", "250", "def", "_has_larger_regions", "(", "f", ")", ":", "return", "any", "(", "r", ".", "stop", "-", "r", ".", "start", ">", "max_size", "for", "r", "in", "pybedtools", ".", "BedTool", "(", "f", ")", ")", "out_file", "=", "\"%s-regionlimit%s\"", "%", "utils", ".", "splitext_plus", "(", "in_file", ")", "if", "not", "utils", ".", "file_exists", "(", "out_file", ")", ":", "if", "_has_larger_regions", "(", "in_file", ")", ":", "with", "file_transaction", "(", "data", ",", "out_file", ")", "as", "tx_out_file", ":", "pybedtools", ".", "BedTool", "(", ")", ".", "window_maker", "(", "w", "=", "max_size", ",", "s", "=", "max_size", "-", "overlap_size", ",", "b", "=", "pybedtools", ".", "BedTool", "(", "in_file", ")", ")", ".", "saveas", "(", "tx_out_file", ")", "else", ":", "utils", ".", "symlink_plus", "(", "in_file", ",", "out_file", ")", "return", "out_file" ]
Provide protocol name based on node_info .
def get_protocol_name ( self ) : protocol_name = self . node_info . protocol if self . is_console : protocol_name += '_console' return protocol_name
3,113
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L379-L384
[ "def", "schemas_access_for_csv_upload", "(", "self", ")", ":", "if", "not", "request", ".", "args", ".", "get", "(", "'db_id'", ")", ":", "return", "json_error_response", "(", "'No database is allowed for your csv upload'", ")", "db_id", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'db_id'", ")", ")", "database", "=", "(", "db", ".", "session", ".", "query", "(", "models", ".", "Database", ")", ".", "filter_by", "(", "id", "=", "db_id", ")", ".", "one", "(", ")", ")", "try", ":", "schemas_allowed", "=", "database", ".", "get_schema_access_for_csv_upload", "(", ")", "if", "(", "security_manager", ".", "database_access", "(", "database", ")", "or", "security_manager", ".", "all_datasource_access", "(", ")", ")", ":", "return", "self", ".", "json_response", "(", "schemas_allowed", ")", "# the list schemas_allowed should not be empty here", "# and the list schemas_allowed_processed returned from security_manager", "# should not be empty either,", "# otherwise the database should have been filtered out", "# in CsvToDatabaseForm", "schemas_allowed_processed", "=", "security_manager", ".", "schemas_accessible_by_user", "(", "database", ",", "schemas_allowed", ",", "False", ")", "return", "self", ".", "json_response", "(", "schemas_allowed_processed", ")", "except", "Exception", ":", "return", "json_error_response", "(", "(", "'Failed to fetch schemas allowed for csv upload in this database! '", "'Please contact Superset Admin!\\n\\n'", "'The error message returned was:\\n{}'", ")", ".", "format", "(", "traceback", ".", "format_exc", "(", ")", ")", ")" ]
Update udi .
def update_udi ( self ) : self . chain . connection . log ( "Parsing inventory" ) # TODO: Maybe validate if udi is complete self . udi = parse_inventory ( self . inventory_text )
3,114
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L391-L395
[ "def", "user_deleted_from_site_event", "(", "event", ")", ":", "userid", "=", "event", ".", "principal", "catalog", "=", "api", ".", "portal", ".", "get_tool", "(", "'portal_catalog'", ")", "query", "=", "{", "'object_provides'", ":", "WORKSPACE_INTERFACE", "}", "query", "[", "'workspace_members'", "]", "=", "userid", "workspaces", "=", "[", "IWorkspace", "(", "b", ".", "_unrestrictedGetObject", "(", ")", ")", "for", "b", "in", "catalog", ".", "unrestrictedSearchResults", "(", "query", ")", "]", "for", "workspace", "in", "workspaces", ":", "workspace", ".", "remove_from_team", "(", "userid", ")" ]
Update config mode .
def update_config_mode ( self , prompt = None ) : # TODO: Fix the conflict with config mode attribute at connection if prompt : self . mode = self . driver . update_config_mode ( prompt ) else : self . mode = self . driver . update_config_mode ( self . prompt )
3,115
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L397-L403
[ "def", "remove_async_sns_topic", "(", "self", ",", "lambda_name", ")", ":", "topic_name", "=", "get_topic_name", "(", "lambda_name", ")", "removed_arns", "=", "[", "]", "for", "sub", "in", "self", ".", "sns_client", ".", "list_subscriptions", "(", ")", "[", "'Subscriptions'", "]", ":", "if", "topic_name", "in", "sub", "[", "'TopicArn'", "]", ":", "self", ".", "sns_client", ".", "delete_topic", "(", "TopicArn", "=", "sub", "[", "'TopicArn'", "]", ")", "removed_arns", ".", "append", "(", "sub", "[", "'TopicArn'", "]", ")", "return", "removed_arns" ]
Update driver based on new prompt .
def update_driver ( self , prompt ) : prompt = prompt . lstrip ( ) self . chain . connection . log ( "({}): Prompt: '{}'" . format ( self . driver . platform , prompt ) ) self . prompt = prompt driver_name = self . driver . update_driver ( prompt ) if driver_name is None : self . chain . connection . log ( "New driver not detected. Using existing {} driver." . format ( self . driver . platform ) ) return self . driver_name = driver_name
3,116
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L409-L418
[ "def", "tfidf_weight", "(", "X", ")", ":", "X", "=", "coo_matrix", "(", "X", ")", "# calculate IDF", "N", "=", "float", "(", "X", ".", "shape", "[", "0", "]", ")", "idf", "=", "log", "(", "N", ")", "-", "log1p", "(", "bincount", "(", "X", ".", "col", ")", ")", "# apply TF-IDF adjustment", "X", ".", "data", "=", "sqrt", "(", "X", ".", "data", ")", "*", "idf", "[", "X", ".", "col", "]", "return", "X" ]
Send commands to prepare terminal session configuration .
def prepare_terminal_session ( self ) : for cmd in self . driver . prepare_terminal_session : try : self . send ( cmd ) except CommandSyntaxError : self . chain . connection . log ( "Command not supported or not authorized: '{}'. Skipping" . format ( cmd ) ) pass
3,117
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L420-L427
[ "def", "filename", "(", "cls", ",", "tag", ",", "schemas", ",", "ext", "=", "'.rnc'", ")", ":", "if", "type", "(", "schemas", ")", "==", "str", ":", "schemas", "=", "re", ".", "split", "(", "\"\\s*,\\s*\"", ",", "schemas", ")", "for", "schema", "in", "schemas", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "schema", ",", "cls", ".", "dirname", "(", "tag", ")", ",", "cls", ".", "basename", "(", "tag", ",", "ext", "=", "ext", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "return", "fn" ]
Update os_type attribute .
def update_os_type ( self ) : self . chain . connection . log ( "Detecting os type" ) os_type = self . driver . get_os_type ( self . version_text ) if os_type : self . chain . connection . log ( "SW Type: {}" . format ( os_type ) ) self . os_type = os_type
3,118
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L429-L435
[ "def", "replace_postgres_db", "(", "self", ",", "file_url", ")", ":", "self", ".", "print_message", "(", "\"Replacing postgres database\"", ")", "if", "file_url", ":", "self", ".", "print_message", "(", "\"Sourcing data from online backup file '%s'\"", "%", "file_url", ")", "source_file", "=", "self", ".", "download_file_from_url", "(", "self", ".", "args", ".", "source_app", ",", "file_url", ")", "elif", "self", ".", "databases", "[", "'source'", "]", "[", "'name'", "]", ":", "self", ".", "print_message", "(", "\"Sourcing data from database '%s'\"", "%", "self", ".", "databases", "[", "'source'", "]", "[", "'name'", "]", ")", "source_file", "=", "self", ".", "dump_database", "(", ")", "else", ":", "self", ".", "print_message", "(", "\"Sourcing data from local backup file %s\"", "%", "self", ".", "args", ".", "file", ")", "source_file", "=", "self", ".", "args", ".", "file", "self", ".", "drop_database", "(", ")", "self", ".", "create_database", "(", ")", "source_file", "=", "self", ".", "unzip_file_if_necessary", "(", "source_file", ")", "self", ".", "print_message", "(", "\"Importing '%s' into database '%s'\"", "%", "(", "source_file", ",", "self", ".", "databases", "[", "'destination'", "]", "[", "'name'", "]", ")", ")", "args", "=", "[", "\"pg_restore\"", ",", "\"--no-acl\"", ",", "\"--no-owner\"", ",", "\"--dbname=%s\"", "%", "self", ".", "databases", "[", "'destination'", "]", "[", "'name'", "]", ",", "source_file", ",", "]", "args", ".", "extend", "(", "self", ".", "databases", "[", "'destination'", "]", "[", "'args'", "]", ")", "subprocess", ".", "check_call", "(", "args", ")" ]
Update os_version attribute .
def update_os_version ( self ) : self . chain . connection . log ( "Detecting os version" ) os_version = self . driver . get_os_version ( self . version_text ) if os_version : self . chain . connection . log ( "SW Version: {}" . format ( os_version ) ) self . os_version = os_version
3,119
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L437-L443
[ "def", "extract_entry", "(", "self", ",", "e", ",", "decompress", "=", "'auto'", ")", ":", "self", ".", "fileobj", ".", "seek", "(", "e", ".", "offset", ")", "stream", "=", "file_iter", "(", "self", ".", "fileobj", ")", "stream", "=", "takeexactly", "(", "stream", ",", "e", ".", "size", ")", "if", "decompress", "==", "'auto'", ":", "stream", "=", "auto_decompress_stream", "(", "stream", ")", "elif", "decompress", "==", "'bz2'", ":", "stream", "=", "bz2_decompress_stream", "(", "stream", ")", "elif", "decompress", "==", "'xz'", ":", "stream", "=", "xz_decompress_stream", "(", "stream", ")", "elif", "decompress", "is", "None", ":", "pass", "else", ":", "raise", "ValueError", "(", "\"Unsupported decompression type: {}\"", ".", "format", "(", "decompress", ")", ")", "for", "block", "in", "stream", ":", "yield", "block" ]
Update family attribute .
def update_family ( self ) : self . chain . connection . log ( "Detecting hw family" ) family = self . driver . get_hw_family ( self . version_text ) if family : self . chain . connection . log ( "HW Family: {}" . format ( family ) ) self . family = family
3,120
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L445-L451
[ "def", "get_segment_definer_comments", "(", "xml_file", ",", "include_version", "=", "True", ")", ":", "from", "glue", ".", "ligolw", ".", "ligolw", "import", "LIGOLWContentHandler", "as", "h", "lsctables", ".", "use_in", "(", "h", ")", "# read segment definer table", "xmldoc", ",", "_", "=", "ligolw_utils", ".", "load_fileobj", "(", "xml_file", ",", "gz", "=", "xml_file", ".", "name", ".", "endswith", "(", "\".gz\"", ")", ",", "contenthandler", "=", "h", ")", "seg_def_table", "=", "table", ".", "get_table", "(", "xmldoc", ",", "lsctables", ".", "SegmentDefTable", ".", "tableName", ")", "# put comment column into a dict", "comment_dict", "=", "{", "}", "for", "seg_def", "in", "seg_def_table", ":", "if", "include_version", ":", "full_channel_name", "=", "':'", ".", "join", "(", "[", "str", "(", "seg_def", ".", "ifos", ")", ",", "str", "(", "seg_def", ".", "name", ")", ",", "str", "(", "seg_def", ".", "version", ")", "]", ")", "else", ":", "full_channel_name", "=", "':'", ".", "join", "(", "[", "str", "(", "seg_def", ".", "ifos", ")", ",", "str", "(", "seg_def", ".", "name", ")", "]", ")", "comment_dict", "[", "full_channel_name", "]", "=", "seg_def", ".", "comment", "return", "comment_dict" ]
Update platform attribute .
def update_platform ( self ) : self . chain . connection . log ( "Detecting hw platform" ) platform = self . driver . get_hw_platform ( self . udi ) if platform : self . chain . connection . log ( "HW Platform: {}" . format ( platform ) ) self . platform = platform
3,121
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L453-L459
[ "def", "get_segment_definer_comments", "(", "xml_file", ",", "include_version", "=", "True", ")", ":", "from", "glue", ".", "ligolw", ".", "ligolw", "import", "LIGOLWContentHandler", "as", "h", "lsctables", ".", "use_in", "(", "h", ")", "# read segment definer table", "xmldoc", ",", "_", "=", "ligolw_utils", ".", "load_fileobj", "(", "xml_file", ",", "gz", "=", "xml_file", ".", "name", ".", "endswith", "(", "\".gz\"", ")", ",", "contenthandler", "=", "h", ")", "seg_def_table", "=", "table", ".", "get_table", "(", "xmldoc", ",", "lsctables", ".", "SegmentDefTable", ".", "tableName", ")", "# put comment column into a dict", "comment_dict", "=", "{", "}", "for", "seg_def", "in", "seg_def_table", ":", "if", "include_version", ":", "full_channel_name", "=", "':'", ".", "join", "(", "[", "str", "(", "seg_def", ".", "ifos", ")", ",", "str", "(", "seg_def", ".", "name", ")", ",", "str", "(", "seg_def", ".", "version", ")", "]", ")", "else", ":", "full_channel_name", "=", "':'", ".", "join", "(", "[", "str", "(", "seg_def", ".", "ifos", ")", ",", "str", "(", "seg_def", ".", "name", ")", "]", ")", "comment_dict", "[", "full_channel_name", "]", "=", "seg_def", ".", "comment", "return", "comment_dict" ]
Update is_console whether connected via console .
def update_console ( self ) : self . chain . connection . log ( "Detecting console connection" ) is_console = self . driver . is_console ( self . users_text ) if is_console is not None : self . is_console = is_console
3,122
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L461-L466
[ "def", "declareAsOntology", "(", "self", ",", "graph", ")", ":", "# <http://data.monarchinitiative.org/ttl/biogrid.ttl> a owl:Ontology ;", "# owl:versionInfo", "# <https://archive.monarchinitiative.org/YYYYMM/ttl/biogrid.ttl>", "model", "=", "Model", "(", "graph", ")", "# is self.outfile suffix set yet???", "ontology_file_id", "=", "'MonarchData:'", "+", "self", ".", "name", "+", "\".ttl\"", "model", ".", "addOntologyDeclaration", "(", "ontology_file_id", ")", "# add timestamp as version info", "cur_time", "=", "datetime", ".", "now", "(", ")", "t_string", "=", "cur_time", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "ontology_version", "=", "t_string", "# TEC this means the MonarchArchive IRI needs the release updated", "# maybe extract the version info from there", "# should not hardcode the suffix as it may change", "archive_url", "=", "'MonarchArchive:'", "+", "'ttl/'", "+", "self", ".", "name", "+", "'.ttl'", "model", ".", "addOWLVersionIRI", "(", "ontology_file_id", ",", "archive_url", ")", "model", ".", "addOWLVersionInfo", "(", "ontology_file_id", ",", "ontology_version", ")" ]
Reload device .
def reload ( self , reload_timeout , save_config , no_reload_cmd ) : if not no_reload_cmd : self . ctrl . send_command ( self . driver . reload_cmd ) return self . driver . reload ( reload_timeout , save_config )
3,123
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L476-L480
[ "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", "}", ")", ")" ]
Wrap the FSM code .
def run_fsm ( self , name , command , events , transitions , timeout , max_transitions = 20 ) : self . ctrl . send_command ( command ) return FSM ( name , self , events , transitions , timeout = timeout , max_transitions = max_transitions ) . run ( )
3,124
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L482-L485
[ "def", "cancelRealTimeBars", "(", "self", ",", "bars", ":", "RealTimeBarList", ")", ":", "self", ".", "client", ".", "cancelRealTimeBars", "(", "bars", ".", "reqId", ")", "self", ".", "wrapper", ".", "endSubscription", "(", "bars", ")" ]
Apply config to the device .
def config ( self , configlet , plane , * * attributes ) : try : config_text = configlet . format ( * * attributes ) except KeyError as exp : raise CommandSyntaxError ( "Configuration template error: {}" . format ( str ( exp ) ) ) return self . driver . config ( config_text , plane )
3,125
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L487-L494
[ "def", "add_copyright", "(", "self", ",", "material", "=", "None", ",", "holder", "=", "None", ",", "statement", "=", "None", ",", "url", "=", "None", ",", "year", "=", "None", ")", ":", "copyright", "=", "{", "}", "for", "key", "in", "(", "'holder'", ",", "'statement'", ",", "'url'", ")", ":", "if", "locals", "(", ")", "[", "key", "]", "is", "not", "None", ":", "copyright", "[", "key", "]", "=", "locals", "(", ")", "[", "key", "]", "if", "material", "is", "not", "None", ":", "copyright", "[", "'material'", "]", "=", "material", ".", "lower", "(", ")", "if", "year", "is", "not", "None", ":", "copyright", "[", "'year'", "]", "=", "int", "(", "year", ")", "self", ".", "_append_to", "(", "'copyright'", ",", "copyright", ")" ]
Device object generator .
def device_gen ( chain , urls ) : itr = iter ( urls ) last = next ( itr ) for url in itr : yield Device ( chain , make_hop_info_from_url ( last ) , driver_name = 'jumphost' , is_target = False ) last = url yield Device ( chain , make_hop_info_from_url ( last ) , driver_name = 'generic' , is_target = True )
3,126
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L12-L19
[ "def", "_apply_mask", "(", "self", ")", ":", "w", "=", "self", ".", "_w", "w_shape", "=", "w", ".", "get_shape", "(", ")", "mask_shape", "=", "self", ".", "_mask", ".", "get_shape", "(", ")", "if", "mask_shape", ".", "ndims", ">", "w_shape", ".", "ndims", ":", "raise", "base", ".", "IncompatibleShapeError", "(", "\"Invalid mask shape: {}. Max shape: {}\"", ".", "format", "(", "mask_shape", ".", "ndims", ",", "len", "(", "self", ".", "_data_format", ")", ")", ")", "if", "mask_shape", "!=", "w_shape", "[", ":", "mask_shape", ".", "ndims", "]", ":", "raise", "base", ".", "IncompatibleShapeError", "(", "\"Invalid mask shape: {}. Weight shape: {}\"", ".", "format", "(", "mask_shape", ",", "w_shape", ")", ")", "# TF broadcasting is a bit fragile.", "# Expand the shape of self._mask by one dim at a time to the right", "# until the rank matches `weight_shape`.", "while", "self", ".", "_mask", ".", "get_shape", "(", ")", ".", "ndims", "<", "w_shape", ".", "ndims", ":", "self", ".", "_mask", "=", "tf", ".", "expand_dims", "(", "self", ".", "_mask", ",", "-", "1", ")", "# tf.Variable & tf.ResourceVariable don't support *=.", "w", "=", "w", "*", "self", ".", "_mask", "# pylint: disable=g-no-augmented-assignment", "return", "w" ]
Connect to the target device using the intermediate jumphosts .
def connect ( self ) : device = None # logger.debug("Connecting to: {}".format(str(self))) for device in self . devices : if not device . connected : self . connection . emit_message ( "Connecting {}" . format ( str ( device ) ) , log_level = logging . INFO ) protocol_name = device . get_protocol_name ( ) device . protocol = make_protocol ( protocol_name , device ) command = device . protocol . get_command ( ) self . ctrl . spawn_session ( command = command ) try : result = device . connect ( self . ctrl ) except CommandSyntaxError as exc : # all commands during discovery provides itself in exception except # spawn session which is handled differently. If command syntax error is detected during spawning # a new session then the problem is either on jumphost or csm server. # The problem with spawning session is detected in connect FSM for telnet and ssh. if exc . command : cmd = exc . command host = device . hostname else : cmd = command host = "Jumphost/CSM" self . connection . log ( "Command not supported or not authorized on {}: '{}'" . format ( host , cmd ) ) raise CommandError ( message = "Command not supported or not authorized" , command = cmd , host = host ) if result : # logger.info("Connected to {}".format(device)) self . connection . emit_message ( "Connected {}" . format ( device ) , log_level = logging . INFO ) else : if device . last_error_msg : message = device . last_error_msg device . last_error_msg = None else : message = "Connection error" self . connection . log ( message ) raise ConnectionError ( message ) # , host=str(device)) if device is None : raise ConnectionError ( "No devices" ) return True
3,127
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L40-L87
[ "def", "color_group", "(", "self", ",", "checked", "=", "False", ",", "test_color", "=", "None", ")", ":", "group", "=", "self", ".", "tabs", ".", "currentWidget", "(", ")", "if", "test_color", "is", "None", ":", "newcolor", "=", "QColorDialog", ".", "getColor", "(", "group", ".", "idx_color", ")", "else", ":", "newcolor", "=", "test_color", "group", ".", "idx_color", "=", "newcolor", "self", ".", "apply", "(", ")" ]
Disconnect from the device .
def disconnect ( self ) : self . target_device . disconnect ( ) self . ctrl . disconnect ( ) self . tail_disconnect ( - 1 )
3,128
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L89-L93
[ "def", "clean_subject_location", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "ImageAdminForm", ",", "self", ")", ".", "clean", "(", ")", "subject_location", "=", "cleaned_data", "[", "'subject_location'", "]", "if", "not", "subject_location", ":", "# if supplied subject location is empty, do not check it", "return", "subject_location", "# use thumbnail's helper function to check the format", "coordinates", "=", "normalize_subject_location", "(", "subject_location", ")", "if", "not", "coordinates", ":", "err_msg", "=", "ugettext_lazy", "(", "'Invalid subject location format. '", ")", "err_code", "=", "'invalid_subject_format'", "elif", "(", "coordinates", "[", "0", "]", ">", "self", ".", "instance", ".", "width", "or", "coordinates", "[", "1", "]", ">", "self", ".", "instance", ".", "height", ")", ":", "err_msg", "=", "ugettext_lazy", "(", "'Subject location is outside of the image. '", ")", "err_code", "=", "'subject_out_of_bounds'", "else", ":", "return", "subject_location", "self", ".", "_set_previous_subject_location", "(", "cleaned_data", ")", "raise", "forms", ".", "ValidationError", "(", "string_concat", "(", "err_msg", ",", "ugettext_lazy", "(", "'Your input: \"{subject_location}\". '", ".", "format", "(", "subject_location", "=", "subject_location", ")", ")", ",", "'Previous value is restored.'", ")", ",", "code", "=", "err_code", ")" ]
Return if target device is discovered .
def is_discovered ( self ) : if self . target_device is None : return False if None in ( self . target_device . version_text , self . target_device . os_type , self . target_device . os_version , self . target_device . inventory_text , self . target_device . family , self . target_device . platform ) : return False return True
3,129
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L113-L121
[ "def", "placeOrder", "(", "self", ",", "contract", ":", "Contract", ",", "order", ":", "Order", ")", "->", "Trade", ":", "orderId", "=", "order", ".", "orderId", "or", "self", ".", "client", ".", "getReqId", "(", ")", "self", ".", "client", ".", "placeOrder", "(", "orderId", ",", "contract", ",", "order", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", "key", "=", "self", ".", "wrapper", ".", "orderKey", "(", "self", ".", "wrapper", ".", "clientId", ",", "orderId", ",", "order", ".", "permId", ")", "trade", "=", "self", ".", "wrapper", ".", "trades", ".", "get", "(", "key", ")", "if", "trade", ":", "# this is a modification of an existing order", "assert", "trade", ".", "orderStatus", ".", "status", "not", "in", "OrderStatus", ".", "DoneStates", "logEntry", "=", "TradeLogEntry", "(", "now", ",", "trade", ".", "orderStatus", ".", "status", ",", "'Modify'", ")", "trade", ".", "log", ".", "append", "(", "logEntry", ")", "self", ".", "_logger", ".", "info", "(", "f'placeOrder: Modify order {trade}'", ")", "trade", ".", "modifyEvent", ".", "emit", "(", "trade", ")", "self", ".", "orderModifyEvent", ".", "emit", "(", "trade", ")", "else", ":", "# this is a new order", "order", ".", "clientId", "=", "self", ".", "wrapper", ".", "clientId", "order", ".", "orderId", "=", "orderId", "orderStatus", "=", "OrderStatus", "(", "status", "=", "OrderStatus", ".", "PendingSubmit", ")", "logEntry", "=", "TradeLogEntry", "(", "now", ",", "orderStatus", ".", "status", ",", "''", ")", "trade", "=", "Trade", "(", "contract", ",", "order", ",", "orderStatus", ",", "[", "]", ",", "[", "logEntry", "]", ")", "self", ".", "wrapper", ".", "trades", "[", "key", "]", "=", "trade", "self", ".", "_logger", ".", "info", "(", "f'placeOrder: New order {trade}'", ")", "self", ".", "newOrderEvent", ".", "emit", "(", "trade", ")", "return", "trade" ]
Return the list of intermediate prompts . All except target .
def get_previous_prompts ( self , device ) : device_index = self . devices . index ( device ) prompts = [ re . compile ( "(?!x)x" ) ] + [ dev . prompt_re for dev in self . devices [ : device_index ] if dev . prompt_re is not None ] return prompts
3,130
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L131-L136
[ "def", "build_synchronize_decorator", "(", ")", ":", "lock", "=", "threading", ".", "Lock", "(", ")", "def", "lock_decorator", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "lock_decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "lock", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "lock_decorated", "return", "lock_decorator" ]
Return the device index in the chain based on prompt .
def get_device_index_based_on_prompt ( self , prompt ) : conn_info = "" for device in self . devices : conn_info += str ( device ) + "->" if device . prompt == prompt : self . connection . log ( "Connected: {}" . format ( conn_info ) ) return self . devices . index ( device ) else : return None
3,131
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L138-L147
[ "def", "update_custom_field_options", "(", "self", ",", "custom_field_key", ",", "new_options", ",", "keep_existing_options", ")", ":", "custom_field_key", "=", "quote", "(", "custom_field_key", ",", "''", ")", "body", "=", "{", "\"Options\"", ":", "new_options", ",", "\"KeepExistingOptions\"", ":", "keep_existing_options", "}", "response", "=", "self", ".", "_put", "(", "self", ".", "uri_for", "(", "\"customfields/%s/options\"", "%", "custom_field_key", ")", ",", "json", ".", "dumps", "(", "body", ")", ")" ]
Mark all devices disconnected except target in the chain .
def tail_disconnect ( self , index ) : try : for device in self . devices [ index + 1 : ] : device . connected = False except IndexError : pass
3,132
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L149-L155
[ "def", "create", "(", "cls", ",", "amount", ",", "counterparty_alias", ",", "description", ",", "monetary_account_id", "=", "None", ",", "attachment", "=", "None", ",", "merchant_reference", "=", "None", ",", "allow_bunqto", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "request_map", "=", "{", "cls", ".", "FIELD_AMOUNT", ":", "amount", ",", "cls", ".", "FIELD_COUNTERPARTY_ALIAS", ":", "counterparty_alias", ",", "cls", ".", "FIELD_DESCRIPTION", ":", "description", ",", "cls", ".", "FIELD_ATTACHMENT", ":", "attachment", ",", "cls", ".", "FIELD_MERCHANT_REFERENCE", ":", "merchant_reference", ",", "cls", ".", "FIELD_ALLOW_BUNQTO", ":", "allow_bunqto", "}", "request_map_string", "=", "converter", ".", "class_to_json", "(", "request_map", ")", "request_map_string", "=", "cls", ".", "_remove_field_for_request", "(", "request_map_string", ")", "api_client", "=", "client", ".", "ApiClient", "(", "cls", ".", "_get_api_context", "(", ")", ")", "request_bytes", "=", "request_map_string", ".", "encode", "(", ")", "endpoint_url", "=", "cls", ".", "_ENDPOINT_URL_CREATE", ".", "format", "(", "cls", ".", "_determine_user_id", "(", ")", ",", "cls", ".", "_determine_monetary_account_id", "(", "monetary_account_id", ")", ")", "response_raw", "=", "api_client", ".", "post", "(", "endpoint_url", ",", "request_bytes", ",", "custom_headers", ")", "return", "BunqResponseInt", ".", "cast_from_bunq_response", "(", "cls", ".", "_process_for_id", "(", "response_raw", ")", ")" ]
Send command to the target device .
def send ( self , cmd , timeout , wait_for_string , password ) : return self . target_device . send ( cmd , timeout = timeout , wait_for_string = wait_for_string , password = password )
3,133
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L157-L159
[ "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", ")" ]
Update the chain object with the predefined data .
def update ( self , data ) : if data is None : for device in self . devices : device . clear_info ( ) else : for device , device_info in zip ( self . devices , data ) : device . device_info = device_info self . connection . log ( "Device information updated -> [{}]" . format ( device ) )
3,134
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L161-L169
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
Wrap the FSM action function providing extended logging information based on doc string .
def action ( func ) : @ wraps ( func ) def call_action ( * args , * * kwargs ) : """Wrap the function with logger debug.""" try : ctx = kwargs [ 'ctx' ] except KeyError : ctx = None if ctx is None : try : ctx = args [ - 1 ] except IndexError : ctx = None if ctx : if func . __doc__ is None : ctx . device . chain . connection . log ( "A={}" . format ( func . __name__ ) ) else : ctx . device . chain . connection . log ( "A={}" . format ( func . __doc__ . split ( '\n' , 1 ) [ 0 ] ) ) return func ( * args , * * kwargs ) return call_action
3,135
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/fsm.py#L12-L33
[ "def", "_select_broker_pair", "(", "self", ",", "rg_destination", ",", "victim_partition", ")", ":", "broker_source", "=", "self", ".", "_elect_source_broker", "(", "victim_partition", ")", "broker_destination", "=", "rg_destination", ".", "_elect_dest_broker", "(", "victim_partition", ")", "return", "broker_source", ",", "broker_destination" ]
Start the FSM .
def run ( self ) : ctx = FSM . Context ( self . name , self . device ) transition_counter = 0 timeout = self . timeout self . log ( "{} Start" . format ( self . name ) ) while transition_counter < self . max_transitions : transition_counter += 1 try : start_time = time ( ) if self . init_pattern is None : ctx . event = self . ctrl . expect ( self . events , searchwindowsize = self . searchwindowsize , timeout = timeout ) else : self . log ( "INIT_PATTERN={}" . format ( pattern_to_str ( self . init_pattern ) ) ) try : ctx . event = self . events . index ( self . init_pattern ) except ValueError : self . log ( "INIT_PATTERN unknown." ) continue finally : self . init_pattern = None finish_time = time ( ) - start_time key = ( ctx . event , ctx . state ) ctx . pattern = self . events [ ctx . event ] if key in self . transition_table : transition = self . transition_table [ key ] next_state , action_instance , next_timeout = transition self . log ( "E={},S={},T={},RT={:.2f}" . format ( ctx . event , ctx . state , timeout , finish_time ) ) if callable ( action_instance ) and not isclass ( action_instance ) : if not action_instance ( ctx ) : self . log ( "Error: {}" . format ( ctx . msg ) ) return False elif isinstance ( action_instance , Exception ) : self . log ( "A=Exception {}" . format ( action_instance ) ) raise action_instance elif action_instance is None : self . log ( "A=None" ) else : self . log ( "FSM Action is not callable: {}" . format ( str ( action_instance ) ) ) raise RuntimeWarning ( "FSM Action is not callable" ) if next_timeout != 0 : # no change if set to 0 timeout = next_timeout ctx . state = next_state self . log ( "NS={},NT={}" . format ( next_state , timeout ) ) else : self . log ( "Unknown transition: EVENT={},STATE={}" . format ( ctx . event , ctx . state ) ) continue except EOF : raise ConnectionError ( "Session closed unexpectedly" , self . ctrl . hostname ) if ctx . finished or next_state == - 1 : self . log ( "{} Stop at E={},S={}" . format ( self . name , ctx . event , ctx . state ) ) return True # check while else if even exists self . log ( "FSM looped. Exiting" ) return False
3,136
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/fsm.py#L152-L218
[ "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" ]
Builds a server file .
def build ( port = 8000 , fixtures = None ) : extractor = Extractor ( ) parser = Parser ( extractor . url_details , fixtures ) parser . parse ( ) url_details = parser . results _store = get_store ( url_details ) store = json . dumps ( _store ) variables = str ( Variable ( 'let' , 'store' , store ) ) functions = DATA_FINDER + GET_HANDLER + MODIFY_HANDLER + POST_HANDLER endpoints = [ ] endpoint_uris = [ ] for u in parser . results : endpoint = Endpoint ( ) if u [ 'method' ] . lower ( ) in [ 'get' , 'post' ] : method = u [ 'method' ] . lower ( ) else : method = 'modify' response = str ( ResponseBody ( method ) ) # Check in store if the base url has individual instances u [ 'url' ] , list_url = clean_url ( u [ 'full_url' ] , _store , u [ 'method' ] . lower ( ) ) if list_url is not None and u [ 'method' ] . lower ( ) == 'get' : list_endpoint = Endpoint ( ) list_endpoint . construct ( 'get' , list_url , response ) if str ( list_endpoint ) not in endpoints : endpoints . append ( str ( list_endpoint ) ) if list_endpoint . uri not in endpoint_uris : endpoint_uris . append ( list_endpoint . uri ) if method == 'modify' : without_prefix = re . sub ( r'\/(\w+)\_\_' , '' , u [ 'url' ] ) for k , v in _store . items ( ) : if without_prefix in k : options = v . get ( 'options' , '{}' ) options = ast . literal_eval ( options ) modifiers = [ ] if options is not None : modifiers = options . get ( 'modifiers' , [ ] ) if modifiers : for mod in modifiers : if u [ 'method' ] . lower ( ) == mod : mod_endpoint = Endpoint ( ) uri = without_prefix if v . get ( 'position' ) is not None and v [ 'position' ] == 'url' : uri = re . sub ( r'\/?\_\_key' , '/:id' , u [ 'full_url' ] ) mod_endpoint . construct ( u [ 'method' ] . lower ( ) , uri , response ) if str ( mod_endpoint ) not in endpoints : endpoints . append ( str ( mod_endpoint ) ) if mod_endpoint . uri not in endpoint_uris : endpoint_uris . append ( mod_endpoint . uri ) else : endpoint . construct ( u [ 'method' ] , u [ 'url' ] , response ) if str ( endpoint ) not in endpoints : endpoints . append ( str ( endpoint ) ) if endpoint . uri not in endpoint_uris : endpoint_uris . append ( endpoint . uri ) endpoints = '' . join ( endpoints ) express = ExpressServer ( ) express . construct ( variables , functions , endpoints , port ) return express
3,137
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/builder.py#L177-L245
[ "def", "defBoundary", "(", "self", ")", ":", "self", ".", "BoroCnstNatAll", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "# Find the natural borrowing constraint conditional on next period's state", "for", "j", "in", "range", "(", "self", ".", "StateCount", ")", ":", "PermShkMinNext", "=", "np", ".", "min", "(", "self", ".", "IncomeDstn_list", "[", "j", "]", "[", "1", "]", ")", "TranShkMinNext", "=", "np", ".", "min", "(", "self", ".", "IncomeDstn_list", "[", "j", "]", "[", "2", "]", ")", "self", ".", "BoroCnstNatAll", "[", "j", "]", "=", "(", "self", ".", "solution_next", ".", "mNrmMin", "[", "j", "]", "-", "TranShkMinNext", ")", "*", "(", "self", ".", "PermGroFac_list", "[", "j", "]", "*", "PermShkMinNext", ")", "/", "self", ".", "Rfree_list", "[", "j", "]", "self", ".", "BoroCnstNat_list", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "self", ".", "mNrmMin_list", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "self", ".", "BoroCnstDependency", "=", "np", ".", "zeros", "(", "(", "self", ".", "StateCount", ",", "self", ".", "StateCount", ")", ")", "+", "np", ".", "nan", "# The natural borrowing constraint in each current state is the *highest*", "# among next-state-conditional natural borrowing constraints that could", "# occur from this current state.", "for", "i", "in", "range", "(", "self", ".", "StateCount", ")", ":", "possible_next_states", "=", "self", ".", "MrkvArray", "[", "i", ",", ":", "]", ">", "0", "self", ".", "BoroCnstNat_list", "[", "i", "]", "=", "np", ".", "max", "(", "self", ".", "BoroCnstNatAll", "[", "possible_next_states", "]", ")", "# Explicitly handle the \"None\" case: ", "if", "self", ".", "BoroCnstArt", "is", "None", ":", "self", ".", "mNrmMin_list", "[", "i", "]", "=", "self", ".", "BoroCnstNat_list", "[", "i", "]", "else", ":", "self", ".", "mNrmMin_list", "[", "i", "]", "=", "np", ".", "max", "(", "[", "self", ".", "BoroCnstNat_list", "[", "i", "]", ",", "self", ".", "BoroCnstArt", "]", ")", "self", ".", "BoroCnstDependency", "[", "i", ",", ":", "]", "=", "self", ".", "BoroCnstNat_list", "[", "i", "]", "==", "self", ".", "BoroCnstNatAll" ]
Get the preferred subtag .
def preferred ( self ) : if 'Preferred-Value' in self . data [ 'record' ] : preferred = self . data [ 'record' ] [ 'Preferred-Value' ] type = self . data [ 'type' ] if type == 'extlang' : type = 'language' return Subtag ( preferred , type ) return None
3,138
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Subtag.py#L86-L98
[ "def", "load_kernel_modules", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "W1ThermSensor", ".", "BASE_DIRECTORY", ")", ":", "os", ".", "system", "(", "\"modprobe w1-gpio >/dev/null 2>&1\"", ")", "os", ".", "system", "(", "\"modprobe w1-therm >/dev/null 2>&1\"", ")", "for", "_", "in", "range", "(", "W1ThermSensor", ".", "RETRY_ATTEMPTS", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "W1ThermSensor", ".", "BASE_DIRECTORY", ")", ":", "# w1 therm modules loaded correctly", "break", "time", ".", "sleep", "(", "W1ThermSensor", ".", "RETRY_DELAY_SECONDS", ")", "else", ":", "raise", "KernelModuleLoadError", "(", ")" ]
Get the subtag code conventional format according to RFC 5646 section 2 . 1 . 1 .
def format ( self ) : subtag = self . data [ 'subtag' ] if self . data [ 'type' ] == 'region' : return subtag . upper ( ) if self . data [ 'type' ] == 'script' : return subtag . capitalize ( ) return subtag
3,139
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Subtag.py#L101-L112
[ "def", "not_storable", "(", "_type", ")", ":", "return", "Storable", "(", "_type", ",", "handlers", "=", "StorableHandler", "(", "poke", "=", "fake_poke", ",", "peek", "=", "fail_peek", "(", "_type", ")", ")", ")" ]
Creates a Freshbooks client for a freshbooks domain using an auth object .
def AuthorizingClient ( domain , auth , request_encoder , response_decoder , user_agent = None ) : http_transport = transport . HttpTransport ( api_url ( domain ) , build_headers ( auth , user_agent ) ) return client . Client ( request_encoder , http_transport , response_decoder )
3,140
https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L72-L92
[ "def", "getComplexFileData", "(", "self", ",", "fileInfo", ",", "data", ")", ":", "result", "=", "fileInfo", "[", "fileInfo", ".", "find", "(", "data", "+", "\"</td>\"", ")", "+", "len", "(", "data", "+", "\"</td>\"", ")", ":", "]", "result", "=", "result", "[", ":", "result", ".", "find", "(", "\"</td>\"", ")", "]", "result", "=", "result", "[", "result", ".", "rfind", "(", "\">\"", ")", "+", "1", ":", "]", "return", "result" ]
Creates a Freshbooks client for a freshbooks domain using token - based auth . The optional request_encoder and response_decoder parameters can be passed the logging_request_encoder and logging_response_decoder objects from this module or custom encoders to aid debugging or change the behaviour of refreshbooks request - to - XML - to - response mapping . The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks . If unset a default user agent string is used .
def TokenClient ( domain , token , user_agent = None , request_encoder = default_request_encoder , response_decoder = default_response_decoder , ) : return AuthorizingClient ( domain , transport . TokenAuthorization ( token ) , request_encoder , response_decoder , user_agent = user_agent )
3,141
https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L94-L120
[ "def", "randomprune", "(", "self", ",", "n", ")", ":", "self", ".", "data", "=", "random", ".", "sample", "(", "self", ".", "data", ",", "n", ")" ]
Creates a Freshbooks client for a freshbooks domain using OAuth . Token management is assumed to have been handled out of band . The optional request_encoder and response_decoder parameters can be passed the logging_request_encoder and logging_response_decoder objects from this module or custom encoders to aid debugging or change the behaviour of refreshbooks request - to - XML - to - response mapping . The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks . If unset a default user agent string is used .
def OAuthClient ( domain , consumer_key , consumer_secret , token , token_secret , user_agent = None , request_encoder = default_request_encoder , response_decoder = default_response_decoder ) : return _create_oauth_client ( AuthorizingClient , domain , consumer_key , consumer_secret , token , token_secret , user_agent = user_agent , request_encoder = request_encoder , response_decoder = response_decoder )
3,142
https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L122-L154
[ "def", "randomprune", "(", "self", ",", "n", ")", ":", "self", ".", "data", "=", "random", ".", "sample", "(", "self", ".", "data", ",", "n", ")" ]
Decrypt GPG objects in configuration .
def gpg_decrypt ( cfg , gpg_config = None ) : def decrypt ( obj ) : """Decrypt the object. It is an inner function because we must first verify that gpg is ready. If we did them in the same function we would end up calling the gpg checks several times, potentially, since we are calling this recursively. """ if isinstance ( obj , list ) : res_v = [ ] for item in obj : res_v . append ( decrypt ( item ) ) return res_v elif isinstance ( obj , dict ) : if '_gpg' in obj : try : decrypted = gpg . decrypt ( obj [ '_gpg' ] ) if decrypted . ok : obj = n ( decrypted . data . decode ( 'utf-8' ) . encode ( ) ) else : log . error ( "gpg error unpacking secrets %s" , decrypted . stderr ) except Exception as err : log . error ( "error unpacking secrets %s" , err ) else : for k , v in obj . items ( ) : obj [ k ] = decrypt ( v ) else : try : if 'BEGIN PGP' in obj : try : decrypted = gpg . decrypt ( obj ) if decrypted . ok : obj = n ( decrypted . data . decode ( 'utf-8' ) . encode ( ) ) else : log . error ( "gpg error unpacking secrets %s" , decrypted . stderr ) except Exception as err : log . error ( "error unpacking secrets %s" , err ) except TypeError : log . debug ( 'Pass on decryption. Only decrypt strings' ) return obj if GPG_IMPORTED : if not gpg_config : gpg_config = { } defaults = { 'homedir' : '~/.gnupg/' } env_fields = { 'homedir' : 'FIGGYPY_GPG_HOMEDIR' , 'binary' : 'FIGGYPY_GPG_BINARY' , 'keyring' : 'FIGGYPY_GPG_KEYRING' } for k , v in env_fields . items ( ) : gpg_config [ k ] = env_or_default ( v , defaults [ k ] if k in defaults else None ) try : gpg = gnupg . GPG ( * * gpg_config ) except ( OSError , RuntimeError ) : log . exception ( 'Failed to configure gpg. Will be unable to decrypt secrets.' ) return decrypt ( cfg ) return cfg
3,143
https://github.com/theherk/figgypy/blob/324d1b281a8df20a26b92f42bf7fda0cca892116/figgypy/decrypt.py#L26-L119
[ "def", "remove_from_space_size", "(", "self", ",", "removal_bytes", ")", ":", "# type: (int) -> None", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'This Volume Descriptor is not yet initialized'", ")", "# The 'removal' parameter is expected to be in bytes, but the space", "# size we track is in extents. Round up to the next extent.", "self", ".", "space_size", "-=", "utils", ".", "ceiling_div", "(", "removal_bytes", ",", "self", ".", "log_block_size", ")" ]
Decrypt KMS objects in configuration .
def kms_decrypt ( cfg , aws_config = None ) : def decrypt ( obj ) : """Decrypt the object. It is an inner function because we must first configure our KMS client. Then we call this recursively on the object. """ if isinstance ( obj , list ) : res_v = [ ] for item in obj : res_v . append ( decrypt ( item ) ) return res_v elif isinstance ( obj , dict ) : if '_kms' in obj : try : res = client . decrypt ( CiphertextBlob = b64decode ( obj [ '_kms' ] ) ) obj = n ( res [ 'Plaintext' ] ) except ClientError as err : if 'AccessDeniedException' in err . args [ 0 ] : log . warning ( 'Unable to decrypt %s. Key does not exist or no access' , obj [ '_kms' ] ) else : raise else : for k , v in obj . items ( ) : obj [ k ] = decrypt ( v ) else : pass return obj try : aws = boto3 . session . Session ( * * aws_config ) client = aws . client ( 'kms' ) except NoRegionError : log . info ( 'Missing or invalid aws configuration. Will not be able to unpack KMS secrets.' ) return cfg return decrypt ( cfg )
3,144
https://github.com/theherk/figgypy/blob/324d1b281a8df20a26b92f42bf7fda0cca892116/figgypy/decrypt.py#L122-L191
[ "def", "wait_for_fresh_games", "(", "self", ",", "poll_interval", "=", "15.0", ")", ":", "wait_until_game", "=", "self", ".", "read_wait_cell", "(", ")", "if", "not", "wait_until_game", ":", "return", "latest_game", "=", "self", ".", "latest_game_number", "last_latest", "=", "latest_game", "while", "latest_game", "<", "wait_until_game", ":", "utils", ".", "dbg", "(", "'Latest game {} not yet at required game {} '", "'(+{}, {:0.3f} games/sec)'", ".", "format", "(", "latest_game", ",", "wait_until_game", ",", "latest_game", "-", "last_latest", ",", "(", "latest_game", "-", "last_latest", ")", "/", "poll_interval", ")", ")", "time", ".", "sleep", "(", "poll_interval", ")", "last_latest", "=", "latest_game", "latest_game", "=", "self", ".", "latest_game_number" ]
Return the version information from the device .
def get_version_text ( self ) : show_version_brief_not_supported = False version_text = None try : version_text = self . device . send ( "show version brief" , timeout = 120 ) except CommandError : show_version_brief_not_supported = True if show_version_brief_not_supported : try : # IOS Hack - need to check if show version brief is supported on IOS/IOS XE version_text = self . device . send ( "show version" , timeout = 120 ) except CommandError as exc : exc . command = 'show version' raise exc return version_text
3,145
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L63-L80
[ "def", "setOverlayTextureColorSpace", "(", "self", ",", "ulOverlayHandle", ",", "eTextureColorSpace", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTextureColorSpace", "result", "=", "fn", "(", "ulOverlayHandle", ",", "eTextureColorSpace", ")", "return", "result" ]
Return the inventory information from the device .
def get_inventory_text ( self ) : inventory_text = None if self . inventory_cmd : try : inventory_text = self . device . send ( self . inventory_cmd , timeout = 120 ) self . log ( 'Inventory collected' ) except CommandError : self . log ( 'Unable to collect inventory' ) else : self . log ( 'No inventory command for {}' . format ( self . platform ) ) return inventory_text
3,146
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L82-L93
[ "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", ")", ")" ]
Return the users logged in information from the device .
def get_users_text ( self ) : users_text = None if self . users_cmd : try : users_text = self . device . send ( self . users_cmd , timeout = 60 ) except CommandError : self . log ( 'Unable to collect connected users information' ) else : self . log ( 'No users command for {}' . format ( self . platform ) ) return users_text
3,147
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L99-L109
[ "def", "pack_turret", "(", "turret", ",", "temp_files", ",", "base_config_path", ",", "path", "=", "None", ")", ":", "file_name", "=", "turret", "[", "'name'", "]", "files", "=", "temp_files", "[", ":", "]", "for", "fname", "in", "turret", ".", "get", "(", "'extra_files'", ",", "[", "]", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "fname", ")", "or", "path", "is", "None", ":", "files", ".", "append", "(", "fname", ")", "else", ":", "files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "path", ",", "fname", ")", ")", "if", "path", "is", "not", "None", ":", "file_name", "=", "os", ".", "path", ".", "join", "(", "path", ",", "file_name", ")", "tar_file", "=", "tarfile", ".", "open", "(", "file_name", "+", "\".tar.gz\"", ",", "'w:gz'", ")", "for", "f", "in", "files", ":", "tar_file", ".", "add", "(", "os", ".", "path", ".", "abspath", "(", "f", ")", ",", "arcname", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "script_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "base_config_path", ")", ",", "turret", "[", "'script'", "]", ")", "tar_file", ".", "add", "(", "script_path", ",", "arcname", "=", "turret", "[", "'script'", "]", ")", "for", "f", "in", "tar_file", ".", "getnames", "(", ")", ":", "print", "(", "\"Added %s\"", "%", "f", ")", "tar_file", ".", "close", "(", ")", "print", "(", "\"Archive %s created\"", "%", "(", "tar_file", ".", "name", ")", ")", "print", "(", "\"=========================================\"", ")" ]
Return the OS type information from the device .
def get_os_type ( self , version_text ) : # pylint: disable=no-self-use os_type = None if version_text is None : return os_type match = re . search ( "(XR|XE|NX-OS)" , version_text ) if match : os_type = match . group ( 1 ) else : os_type = 'IOS' if os_type == "XR" : match = re . search ( "Build Information" , version_text ) if match : os_type = "eXR" match = re . search ( "XR Admin Software" , version_text ) if match : os_type = "Calvados" return os_type
3,148
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L111-L130
[ "def", "get", "(", "self", ")", ":", "chunk_size", "=", "self", ".", "_smallest_buffer", "(", ")", "all_full", "=", "self", ".", "_all_full", "(", ")", "if", "all_full", ":", "right_context", "=", "0", "num_frames", "=", "chunk_size", "-", "self", ".", "current_left_context", "else", ":", "right_context", "=", "self", ".", "right_context", "num_frames", "=", "self", ".", "min_frames", "chunk_size_needed", "=", "num_frames", "+", "self", ".", "current_left_context", "+", "right_context", "if", "chunk_size", ">=", "chunk_size_needed", ":", "data", "=", "[", "]", "keep_frames", "=", "self", ".", "left_context", "+", "self", ".", "right_context", "keep_from", "=", "max", "(", "0", ",", "chunk_size", "-", "keep_frames", ")", "for", "index", "in", "range", "(", "self", ".", "num_buffers", ")", ":", "data", ".", "append", "(", "self", ".", "buffers", "[", "index", "]", "[", ":", "chunk_size", "]", ")", "self", ".", "buffers", "[", "index", "]", "=", "self", ".", "buffers", "[", "index", "]", "[", "keep_from", ":", "]", "if", "self", ".", "num_buffers", "==", "1", ":", "data", "=", "data", "[", "0", "]", "chunk", "=", "Chunk", "(", "data", ",", "self", ".", "current_frame", ",", "all_full", ",", "self", ".", "current_left_context", ",", "right_context", ")", "self", ".", "current_left_context", "=", "min", "(", "self", ".", "left_context", ",", "chunk_size", ")", "self", ".", "current_frame", "=", "max", "(", "self", ".", "current_frame", "+", "chunk_size", "-", "keep_frames", ",", "0", ")", "return", "chunk" ]
Return the OS version information from the device .
def get_os_version ( self , version_text ) : os_version = None if version_text is None : return os_version match = re . search ( self . version_re , version_text , re . MULTILINE ) if match : os_version = match . group ( 1 ) return os_version
3,149
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L132-L141
[ "def", "set_alternative_view", "(", "self", ",", "request", ")", ":", "if", "not", "request", ".", "user", ".", "has_perm", "(", "'experiments.change_experiment'", ")", ":", "return", "HttpResponseForbidden", "(", ")", "experiment_name", "=", "request", ".", "POST", ".", "get", "(", "\"experiment\"", ")", "alternative_name", "=", "request", ".", "POST", ".", "get", "(", "\"alternative\"", ")", "if", "not", "(", "experiment_name", "and", "alternative_name", ")", ":", "return", "HttpResponseBadRequest", "(", ")", "participant", "(", "request", ")", ".", "set_alternative", "(", "experiment_name", ",", "alternative_name", ")", "return", "JsonResponse", "(", "{", "'success'", ":", "True", ",", "'alternative'", ":", "participant", "(", "request", ")", ".", "get_alternative", "(", "experiment_name", ")", "}", ")" ]
Return the HW family information from the device .
def get_hw_family ( self , version_text ) : family = None if version_text is None : return family match = re . search ( self . platform_re , version_text , re . MULTILINE ) if match : self . platform_string = match . group ( ) self . log ( "Platform string: {}" . format ( match . group ( ) ) ) self . raw_family = match . group ( 1 ) # sort keys on len reversed (longest first) for key in sorted ( self . families , key = len , reverse = True ) : if self . raw_family . startswith ( key ) : family = self . families [ key ] break else : self . log ( "Platform {} not supported" . format ( family ) ) else : self . log ( "Platform string not present. Refer to CSCux08958" ) return family
3,150
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L143-L163
[ "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", ")", ")" ]
Return th HW platform information from the device .
def get_hw_platform ( self , udi ) : platform = None try : pid = udi [ 'pid' ] if pid == '' : self . log ( "Empty PID. Use the hw family from the platform string." ) return self . raw_family match = re . search ( self . pid2platform_re , pid ) if match : platform = match . group ( 1 ) except KeyError : pass return platform
3,151
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L165-L178
[ "def", "_MultiNotifyQueue", "(", "self", ",", "queue", ",", "notifications", ",", "mutation_pool", "=", "None", ")", ":", "notification_list", "=", "[", "]", "now", "=", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "notification", "in", "notifications", ":", "if", "not", "notification", ".", "first_queued", ":", "notification", ".", "first_queued", "=", "(", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", ")", "else", ":", "diff", "=", "now", "-", "notification", ".", "first_queued", "if", "diff", ".", "seconds", ">=", "self", ".", "notification_expiry_time", ":", "# This notification has been around for too long, we drop it.", "logging", ".", "debug", "(", "\"Dropping notification: %s\"", ",", "str", "(", "notification", ")", ")", "continue", "notification_list", ".", "append", "(", "notification", ")", "mutation_pool", ".", "CreateNotifications", "(", "self", ".", "GetNotificationShard", "(", "queue", ")", ",", "notification_list", ")" ]
Return if device is connected over console .
def is_console ( self , users_text ) : if users_text is None : self . log ( "Console information not collected" ) return None for line in users_text . split ( '\n' ) : if '*' in line : match = re . search ( self . vty_re , line ) if match : self . log ( "Detected connection to vty" ) return False else : match = re . search ( self . console_re , line ) if match : self . log ( "Detected connection to console" ) return True self . log ( "Connection port unknown" ) return None
3,152
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L180-L199
[ "def", "_get_manifest_list", "(", "self", ",", "image", ")", ":", "if", "image", "in", "self", ".", "manifest_list_cache", ":", "return", "self", ".", "manifest_list_cache", "[", "image", "]", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "image", ".", "registry", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "if", "'@sha256:'", "in", "str", "(", "image", ")", "and", "not", "manifest_list", ":", "# we want to adjust the tag only for manifest list fetching", "image", "=", "image", ".", "copy", "(", ")", "try", ":", "config_blob", "=", "get_config_from_registry", "(", "image", ",", "image", ".", "registry", ",", "image", ".", "tag", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "except", "(", "HTTPError", ",", "RetryError", ",", "Timeout", ")", "as", "ex", ":", "self", ".", "log", ".", "warning", "(", "'Unable to fetch config for %s, got error %s'", ",", "image", ",", "ex", ".", "response", ".", "status_code", ")", "raise", "RuntimeError", "(", "'Unable to fetch config for base image'", ")", "release", "=", "config_blob", "[", "'config'", "]", "[", "'Labels'", "]", "[", "'release'", "]", "version", "=", "config_blob", "[", "'config'", "]", "[", "'Labels'", "]", "[", "'version'", "]", "docker_tag", "=", "\"%s-%s\"", "%", "(", "version", ",", "release", ")", "image", ".", "tag", "=", "docker_tag", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "image", ".", "registry", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "self", ".", "manifest_list_cache", "[", "image", "]", "=", "manifest_list", "return", "self", ".", "manifest_list_cache", "[", "image", "]" ]
Wait for string FSM .
def wait_for_string ( self , expected_string , timeout = 60 ) : # 0 1 2 3 events = [ self . syntax_error_re , self . connection_closed_re , expected_string , self . press_return_re , # 4 5 6 7 self . more_re , pexpect . TIMEOUT , pexpect . EOF , self . buffer_overflow_re ] # add detected prompts chain events += self . device . get_previous_prompts ( ) # without target prompt self . log ( "Expecting: {}" . format ( pattern_to_str ( expected_string ) ) ) transitions = [ ( self . syntax_error_re , [ 0 ] , - 1 , CommandSyntaxError ( "Command unknown" , self . device . hostname ) , 0 ) , ( self . connection_closed_re , [ 0 ] , 1 , a_connection_closed , 10 ) , ( pexpect . TIMEOUT , [ 0 ] , - 1 , CommandTimeoutError ( "Timeout waiting for prompt" , self . device . hostname ) , 0 ) , ( pexpect . EOF , [ 0 , 1 ] , - 1 , ConnectionError ( "Unexpected device disconnect" , self . device . hostname ) , 0 ) , ( self . more_re , [ 0 ] , 0 , partial ( a_send , " " ) , 10 ) , ( expected_string , [ 0 , 1 ] , - 1 , a_expected_prompt , 0 ) , ( self . press_return_re , [ 0 ] , - 1 , a_stays_connected , 0 ) , # TODO: Customize in XR driver ( self . buffer_overflow_re , [ 0 ] , - 1 , CommandSyntaxError ( "Command too long" , self . device . hostname ) , 0 ) ] for prompt in self . device . get_previous_prompts ( ) : transitions . append ( ( prompt , [ 0 , 1 ] , 0 , a_unexpected_prompt , 0 ) ) fsm = FSM ( "WAIT-4-STRING" , self . device , events , transitions , timeout = timeout ) return fsm . run ( )
3,153
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L206-L234
[ "def", "busday_count_mask_NaT", "(", "begindates", ",", "enddates", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "empty", "(", "broadcast", "(", "begindates", ",", "enddates", ")", ".", "shape", ",", "dtype", "=", "float", ")", "beginmask", "=", "isnat", "(", "begindates", ")", "endmask", "=", "isnat", "(", "enddates", ")", "out", "=", "busday_count", "(", "# Temporarily fill in non-NaT values.", "where", "(", "beginmask", ",", "_notNaT", ",", "begindates", ")", ",", "where", "(", "endmask", ",", "_notNaT", ",", "enddates", ")", ",", "out", "=", "out", ",", ")", "# Fill in entries where either comparison was NaT with nan in the output.", "out", "[", "beginmask", "|", "endmask", "]", "=", "nan", "return", "out" ]
Reload the device and waits for device to boot up .
def reload ( self , reload_timeout = 300 , save_config = True ) : self . log ( "Reload not implemented on {} platform" . format ( self . platform ) )
3,154
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L282-L287
[ "def", "is_local_url", "(", "target", ")", ":", "ref_url", "=", "urlparse", "(", "cfg", ".", "get", "(", "'CFG_SITE_SECURE_URL'", ")", ")", "test_url", "=", "urlparse", "(", "urljoin", "(", "cfg", ".", "get", "(", "'CFG_SITE_SECURE_URL'", ")", ",", "target", ")", ")", "return", "test_url", ".", "scheme", "in", "(", "'http'", ",", "'https'", ")", "and", "ref_url", ".", "netloc", "==", "test_url", ".", "netloc" ]
Extract the base prompt pattern .
def base_prompt ( self , prompt ) : if prompt is None : return None if not self . device . is_target : return prompt pattern = pattern_manager . pattern ( self . platform , "prompt_dynamic" , compiled = False ) pattern = pattern . format ( prompt = "(?P<prompt>.*?)" ) result = re . search ( pattern , prompt ) if result : base = result . group ( "prompt" ) + "#" self . log ( "base prompt: {}" . format ( base ) ) return base else : self . log ( "Unable to extract the base prompt" ) return prompt
3,155
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L293-L308
[ "def", "set_owner_process", "(", "uid", ",", "gid", ")", ":", "if", "gid", ":", "try", ":", "os", ".", "setgid", "(", "gid", ")", "except", "OverflowError", ":", "# versions of python < 2.6.2 don't manage unsigned int for", "# groups like on osx or fedora", "os", ".", "setgid", "(", "-", "ctypes", ".", "c_int", "(", "-", "gid", ")", ".", "value", ")", "if", "uid", ":", "os", ".", "setuid", "(", "uid", ")" ]
Update config mode based on the prompt analysis .
def update_config_mode ( self , prompt ) : # pylint: disable=no-self-use mode = 'global' if prompt : if 'config' in prompt : mode = 'config' elif 'admin' in prompt : mode = 'admin' self . log ( "Mode: {}" . format ( mode ) ) return mode
3,156
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L327-L337
[ "def", "list_blobs", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "# pylint: disable=unused-argument", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "'container'", "not", "in", "kwargs", ":", "raise", "SaltCloudSystemExit", "(", "'A container must be specified'", ")", "storageservice", "=", "_get_block_blob_service", "(", "kwargs", ")", "ret", "=", "{", "}", "try", ":", "for", "blob", "in", "storageservice", ".", "list_blobs", "(", "kwargs", "[", "'container'", "]", ")", ".", "items", ":", "ret", "[", "blob", ".", "name", "]", "=", "{", "'blob_type'", ":", "blob", ".", "properties", ".", "blob_type", ",", "'last_modified'", ":", "blob", ".", "properties", ".", "last_modified", ".", "isoformat", "(", ")", ",", "'server_encrypted'", ":", "blob", ".", "properties", ".", "server_encrypted", ",", "}", "except", "Exception", "as", "exc", ":", "log", ".", "warning", "(", "six", ".", "text_type", "(", "exc", ")", ")", "return", "ret" ]
Update the hostname based on the prompt analysis .
def update_hostname ( self , prompt ) : result = re . search ( self . prompt_re , prompt ) if result : hostname = result . group ( 'hostname' ) self . log ( "Hostname detected: {}" . format ( hostname ) ) else : hostname = self . device . hostname self . log ( "Hostname not set: {}" . format ( prompt ) ) return hostname
3,157
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L339-L348
[ "def", "create_or_update", "(", "cls", ",", "bucket", ",", "key", ",", "value", ")", ":", "obj", "=", "cls", ".", "get", "(", "bucket", ",", "key", ")", "if", "obj", ":", "obj", ".", "value", "=", "value", "db", ".", "session", ".", "merge", "(", "obj", ")", "else", ":", "obj", "=", "cls", ".", "create", "(", "bucket", ",", "key", ",", "value", ")", "return", "obj" ]
Enter the device plane .
def enter_plane ( self , plane ) : try : cmd = CONF [ 'driver' ] [ self . platform ] [ 'planes' ] [ plane ] self . plane = plane except KeyError : cmd = None if cmd : self . log ( "Entering the {} plane" . format ( plane ) ) self . device . send ( cmd )
3,158
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L360-L373
[ "def", "_get_manifest_list", "(", "self", ",", "image", ")", ":", "if", "image", "in", "self", ".", "manifest_list_cache", ":", "return", "self", ".", "manifest_list_cache", "[", "image", "]", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "image", ".", "registry", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "if", "'@sha256:'", "in", "str", "(", "image", ")", "and", "not", "manifest_list", ":", "# we want to adjust the tag only for manifest list fetching", "image", "=", "image", ".", "copy", "(", ")", "try", ":", "config_blob", "=", "get_config_from_registry", "(", "image", ",", "image", ".", "registry", ",", "image", ".", "tag", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "except", "(", "HTTPError", ",", "RetryError", ",", "Timeout", ")", "as", "ex", ":", "self", ".", "log", ".", "warning", "(", "'Unable to fetch config for %s, got error %s'", ",", "image", ",", "ex", ".", "response", ".", "status_code", ")", "raise", "RuntimeError", "(", "'Unable to fetch config for base image'", ")", "release", "=", "config_blob", "[", "'config'", "]", "[", "'Labels'", "]", "[", "'release'", "]", "version", "=", "config_blob", "[", "'config'", "]", "[", "'Labels'", "]", "[", "'version'", "]", "docker_tag", "=", "\"%s-%s\"", "%", "(", "version", ",", "release", ")", "image", ".", "tag", "=", "docker_tag", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "image", ".", "registry", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "self", ".", "manifest_list_cache", "[", "image", "]", "=", "manifest_list", "return", "self", ".", "manifest_list_cache", "[", "image", "]" ]
This is a temporary static method when there are more factory methods we can move this to another class or find a way to maintain it in a scalable manner
def handle_other_factory_method ( attr , minimum , maximum ) : if attr == 'percentage' : if minimum : minimum = ast . literal_eval ( minimum ) else : minimum = 0 if maximum : maximum = ast . literal_eval ( maximum ) else : maximum = 100 val = random . uniform ( minimum , maximum ) return val # If `attr` isn't specified above, we need to raise an error raise ValueError ( '`%s` isn\'t a valid factory method.' % attr )
3,159
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/factory.py#L82-L101
[ "def", "wait", "(", "self", ")", ":", "self", ".", "_done_event", ".", "wait", "(", "MAXINT", ")", "return", "self", ".", "_status", ",", "self", ".", "_exception" ]
Retrieves the syntax from the response and goes through each one to generate and replace it with mock values
def _parse_syntax ( self , raw ) : raw = str ( raw ) # treat the value as a string regardless of its actual data type has_syntax = re . findall ( r'<(\^)?(fk__)?(\w+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>' , raw , flags = re . DOTALL ) if has_syntax : fake_val = re . sub ( r'\'?\"?<(\^)?(fk__)?(\w+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>\'?\"?' , self . _replace_faker_attr , raw , flags = re . DOTALL ) fake_val = fake_val . replace ( "'" , '"' ) try : fake_val = json . loads ( fake_val ) except : pass return fake_val else : return raw
3,160
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/factory.py#L234-L256
[ "def", "console_save_asc", "(", "con", ":", "tcod", ".", "console", ".", "Console", ",", "filename", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "lib", ".", "TCOD_console_save_asc", "(", "_console", "(", "con", ")", ",", "filename", ".", "encode", "(", "\"utf-8\"", ")", ")", ")" ]
The count relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute .
def count ( self , source , target ) : try : source_value = self . _response_holder [ source ] except KeyError : # Source value hasn't been determined yet, we need # to generate the source value first raw = self . fake_response [ source ] source_value = self . _parse_syntax ( raw ) if isinstance ( source_value , str ) : source_value = int ( source_value ) target = self . fake_response [ target ] values = [ ] for _ in range ( source_value ) : self . _is_empty = False # Remote state for re.sub to switch in case it hits a None value mock_value = self . _parse_syntax ( target ) mock_value = str ( mock_value ) # Treat the value as a string regardless of its actual data type _target = mock_value [ 1 : - 1 ] # Remove extra quotation _target = _target . replace ( "'" , '"' ) try : mock_value = json . loads ( _target ) except : mock_value = _target # If uniqueness is specified and this mock value isn't # in the store yet, then we can append it to the results if not self . _is_empty : values . append ( mock_value ) return values
3,161
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/factory.py#L262-L294
[ "def", "_remove_invalid_char", "(", "s", ")", ":", "s", "=", "''", ".", "join", "(", "[", "i", "if", "ord", "(", "i", ")", ">=", "32", "and", "ord", "(", "i", ")", "<", "127", "else", "''", "for", "i", "in", "s", "]", ")", "s", "=", "s", ".", "translate", "(", "dict", ".", "fromkeys", "(", "map", "(", "ord", ",", "\"_%~#\\\\{}\\\":\"", ")", ")", ")", "return", "s" ]
Return the SSH protocol specific command to connect .
def get_command ( self , version = 2 ) : try : options = _C [ 'options' ] options_str = " -o " . join ( options ) if options_str : options_str = "-o " + options_str + " " except KeyError : options_str = "" if self . username : # Not supported on SunOS # "-o ConnectTimeout={} command = "ssh {}" "-{} " "-p {} {}@{}" . format ( options_str , version , self . port , self . username , self . hostname ) else : command = "ssh {} " "-{} " "-p {} {}" . format ( options_str , version , self . port , self . hostname ) return command
3,162
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L32-L52
[ "def", "remove_unused_resources", "(", "issues", ",", "app_dir", ",", "ignore_layouts", ")", ":", "for", "issue", "in", "issues", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "app_dir", ",", "issue", ".", "filepath", ")", "if", "issue", ".", "remove_file", ":", "remove_resource_file", "(", "issue", ",", "filepath", ",", "ignore_layouts", ")", "else", ":", "remove_resource_value", "(", "issue", ",", "filepath", ")" ]
Connect using the SSH protocol specific FSM .
def connect ( self , driver ) : # 0 1 2 events = [ driver . password_re , self . device . prompt_re , driver . unable_to_connect_re , # 3 4 5 6 7 NEWSSHKEY , KNOWN_HOSTS , HOST_KEY_FAILED , MODULUS_TOO_SMALL , PROTOCOL_DIFFER , # 8 9 10 driver . timeout_re , pexpect . TIMEOUT , driver . syntax_error_re ] transitions = [ ( driver . password_re , [ 0 , 1 , 4 , 5 ] , - 1 , partial ( a_save_last_pattern , self ) , 0 ) , ( driver . syntax_error_re , [ 0 ] , - 1 , CommandSyntaxError ( "Command syntax error" ) , 0 ) , ( self . device . prompt_re , [ 0 ] , - 1 , partial ( a_save_last_pattern , self ) , 0 ) , # cover all messages indicating that connection was not set up ( driver . unable_to_connect_re , [ 0 ] , - 1 , a_unable_to_connect , 0 ) , ( NEWSSHKEY , [ 0 ] , 1 , partial ( a_send_line , "yes" ) , 10 ) , ( KNOWN_HOSTS , [ 0 , 1 ] , 0 , None , 0 ) , ( HOST_KEY_FAILED , [ 0 ] , - 1 , ConnectionError ( "Host key failed" , self . hostname ) , 0 ) , ( MODULUS_TOO_SMALL , [ 0 ] , 0 , self . fallback_to_sshv1 , 0 ) , ( PROTOCOL_DIFFER , [ 0 ] , 4 , self . fallback_to_sshv1 , 0 ) , ( PROTOCOL_DIFFER , [ 4 ] , - 1 , ConnectionError ( "Protocol version differs" , self . hostname ) , 0 ) , ( pexpect . TIMEOUT , [ 0 ] , 5 , partial ( a_send , "\r\n" ) , 10 ) , ( pexpect . TIMEOUT , [ 5 ] , - 1 , ConnectionTimeoutError ( "Connection timeout" , self . hostname ) , 0 ) , ( driver . timeout_re , [ 0 ] , - 1 , ConnectionTimeoutError ( "Connection timeout" , self . hostname ) , 0 ) , ] self . log ( "EXPECTED_PROMPT={}" . format ( pattern_to_str ( self . device . prompt_re ) ) ) fsm = FSM ( "SSH-CONNECT" , self . device , events , transitions , timeout = _C [ 'connect_timeout' ] , searchwindowsize = 160 ) return fsm . run ( )
3,163
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L54-L83
[ "def", "cancelRealTimeBars", "(", "self", ",", "bars", ":", "RealTimeBarList", ")", ":", "self", ".", "client", ".", "cancelRealTimeBars", "(", "bars", ".", "reqId", ")", "self", ".", "wrapper", ".", "endSubscription", "(", "bars", ")" ]
Authenticate using the SSH protocol specific FSM .
def authenticate ( self , driver ) : # 0 1 2 3 events = [ driver . press_return_re , driver . password_re , self . device . prompt_re , pexpect . TIMEOUT ] transitions = [ ( driver . press_return_re , [ 0 , 1 ] , 1 , partial ( a_send , "\r\n" ) , 10 ) , ( driver . password_re , [ 0 ] , 1 , partial ( a_send_password , self . _acquire_password ( ) ) , _C [ 'first_prompt_timeout' ] ) , ( driver . password_re , [ 1 ] , - 1 , a_authentication_error , 0 ) , ( self . device . prompt_re , [ 0 , 1 ] , - 1 , None , 0 ) , ( pexpect . TIMEOUT , [ 1 ] , - 1 , ConnectionError ( "Error getting device prompt" ) if self . device . is_target else partial ( a_send , "\r\n" ) , 0 ) ] self . log ( "EXPECTED_PROMPT={}" . format ( pattern_to_str ( self . device . prompt_re ) ) ) fsm = FSM ( "SSH-AUTH" , self . device , events , transitions , init_pattern = self . last_pattern , timeout = 30 ) return fsm . run ( )
3,164
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L85-L102
[ "def", "cancelRealTimeBars", "(", "self", ",", "bars", ":", "RealTimeBarList", ")", ":", "self", ".", "client", ".", "cancelRealTimeBars", "(", "bars", ".", "reqId", ")", "self", ".", "wrapper", ".", "endSubscription", "(", "bars", ")" ]
Disconnect using the protocol specific method .
def disconnect ( self , driver ) : self . log ( "SSH disconnect" ) try : self . device . ctrl . sendline ( '\x03' ) self . device . ctrl . sendline ( '\x04' ) except OSError : self . log ( "Protocol already disconnected" )
3,165
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L104-L111
[ "def", "compose", "(", "list_of_files", ",", "destination_file", ",", "files_metadata", "=", "None", ",", "content_type", "=", "None", ",", "retry_params", "=", "None", ",", "_account_id", "=", "None", ")", ":", "api", "=", "storage_api", ".", "_get_storage_api", "(", "retry_params", "=", "retry_params", ",", "account_id", "=", "_account_id", ")", "if", "os", ".", "getenv", "(", "'SERVER_SOFTWARE'", ")", ".", "startswith", "(", "'Dev'", ")", ":", "def", "_temp_func", "(", "file_list", ",", "destination_file", ",", "content_type", ")", ":", "bucket", "=", "'/'", "+", "destination_file", ".", "split", "(", "'/'", ")", "[", "1", "]", "+", "'/'", "with", "open", "(", "destination_file", ",", "'w'", ",", "content_type", "=", "content_type", ")", "as", "gcs_merge", ":", "for", "source_file", "in", "file_list", ":", "with", "open", "(", "bucket", "+", "source_file", "[", "'Name'", "]", ",", "'r'", ")", "as", "gcs_source", ":", "gcs_merge", ".", "write", "(", "gcs_source", ".", "read", "(", ")", ")", "compose_object", "=", "_temp_func", "else", ":", "compose_object", "=", "api", ".", "compose_object", "file_list", ",", "_", "=", "_validate_compose_list", "(", "destination_file", ",", "list_of_files", ",", "files_metadata", ",", "32", ")", "compose_object", "(", "file_list", ",", "destination_file", ",", "content_type", ")" ]
Fallback to SSHv1 .
def fallback_to_sshv1 ( self , ctx ) : command = self . get_command ( version = 1 ) ctx . spawn_session ( command ) return True
3,166
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L115-L119
[ "def", "create_atomic_wrapper", "(", "cls", ",", "wrapped_func", ")", ":", "def", "_create_atomic_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Actual wrapper.\"\"\"", "# When a view call fails due to a permissions error, it raises an exception.", "# An uncaught exception breaks the DB transaction for any following DB operations", "# unless it's wrapped in a atomic() decorator or context manager.", "with", "transaction", ".", "atomic", "(", ")", ":", "return", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_create_atomic_wrapper" ]
Checks whether the html_doc contains a meta matching the prefix & code
def search_meta_tag ( html_doc , prefix , code ) : regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>' . format ( prefix , code ) meta = re . compile ( regex , flags = re . MULTILINE | re . IGNORECASE ) m = meta . search ( html_doc ) if m : head = re . search ( r'</head>' , html_doc , flags = re . IGNORECASE ) if head and m . start ( ) < head . start ( ) : return True return False
3,167
https://github.com/rs/domcheck/blob/43e10c345320564a1236778e8577e2b8ef825925/domcheck/strategies.py#L51-L62
[ "def", "exerciseOptions", "(", "self", ",", "contract", ":", "Contract", ",", "exerciseAction", ":", "int", ",", "exerciseQuantity", ":", "int", ",", "account", ":", "str", ",", "override", ":", "int", ")", ":", "reqId", "=", "self", ".", "client", ".", "getReqId", "(", ")", "self", ".", "client", ".", "exerciseOptions", "(", "reqId", ",", "contract", ",", "exerciseAction", ",", "exerciseQuantity", ",", "account", ",", "override", ")" ]
Find postgame struct .
def find_postgame ( data , size ) : pos = None for i in range ( size - SEARCH_MAX_BYTES , size - LOOKAHEAD ) : op_type , length , action_type = struct . unpack ( '<IIB' , data [ i : i + LOOKAHEAD ] ) if op_type == 0x01 and length == POSTGAME_LENGTH and action_type == 0xFF : LOGGER . debug ( "found postgame candidate @ %d with length %d" , i + LOOKAHEAD , length ) return i + LOOKAHEAD , length
3,168
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L54-L73
[ "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", "(", ")" ]
Parse postgame structure .
def parse_postgame ( handle , size ) : data = handle . read ( ) postgame = find_postgame ( data , size ) if postgame : pos , length = postgame try : return mgz . body . actions . postgame . parse ( data [ pos : pos + length ] ) except construct . core . ConstructError : raise IOError ( "failed to parse postgame" ) raise IOError ( "could not find postgame" )
3,169
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L76-L86
[ "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" ]
Get field from achievements structure .
def ach ( structure , fields ) : field = fields . pop ( 0 ) if structure : if hasattr ( structure , field ) : structure = getattr ( structure , field ) if not fields : return structure return ach ( structure , fields ) return None
3,170
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L89-L98
[ "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" ]
Get postgame structure .
def get_postgame ( self ) : if self . _cache [ 'postgame' ] is not None : return self . _cache [ 'postgame' ] self . _handle . seek ( 0 ) try : self . _cache [ 'postgame' ] = parse_postgame ( self . _handle , self . size ) return self . _cache [ 'postgame' ] except IOError : self . _cache [ 'postgame' ] = False return None finally : self . _handle . seek ( self . body_position )
3,171
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L138-L150
[ "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" ]
Get game duration .
def get_duration ( self ) : postgame = self . get_postgame ( ) if postgame : return postgame . duration_int * 1000 duration = self . _header . initial . restore_time try : while self . _handle . tell ( ) < self . size : operation = mgz . body . operation . parse_stream ( self . _handle ) if operation . type == 'sync' : duration += operation . time_increment elif operation . type == 'action' : if operation . action . type == 'resign' : self . _cache [ 'resigned' ] . add ( operation . action . player_id ) self . _handle . seek ( self . body_position ) except ( construct . core . ConstructError , zlib . error , ValueError ) : raise RuntimeError ( "invalid mgz file" ) return duration
3,172
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L152-L169
[ "def", "delete_snl", "(", "self", ",", "snl_ids", ")", ":", "try", ":", "payload", "=", "{", "\"ids\"", ":", "json", ".", "dumps", "(", "snl_ids", ")", "}", "response", "=", "self", ".", "session", ".", "post", "(", "\"{}/snl/delete\"", ".", "format", "(", "self", ".", "preamble", ")", ",", "data", "=", "payload", ")", "if", "response", ".", "status_code", "in", "[", "200", ",", "400", "]", ":", "resp", "=", "json", ".", "loads", "(", "response", ".", "text", ",", "cls", "=", "MontyDecoder", ")", "if", "resp", "[", "\"valid_response\"", "]", ":", "if", "resp", ".", "get", "(", "\"warning\"", ")", ":", "warnings", ".", "warn", "(", "resp", "[", "\"warning\"", "]", ")", "return", "resp", "else", ":", "raise", "MPRestError", "(", "resp", "[", "\"error\"", "]", ")", "raise", "MPRestError", "(", "\"REST error with status code {} and error {}\"", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")", "except", "Exception", "as", "ex", ":", "raise", "MPRestError", "(", "str", "(", "ex", ")", ")" ]
Check for restored game .
def get_restored ( self ) : return self . _header . initial . restore_time > 0 , self . _header . initial . restore_time
3,173
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L171-L173
[ "def", "_proc_member", "(", "self", ",", "tarfile", ")", ":", "if", "self", ".", "type", "in", "(", "GNUTYPE_LONGNAME", ",", "GNUTYPE_LONGLINK", ")", ":", "return", "self", ".", "_proc_gnulong", "(", "tarfile", ")", "elif", "self", ".", "type", "==", "GNUTYPE_SPARSE", ":", "return", "self", ".", "_proc_sparse", "(", "tarfile", ")", "elif", "self", ".", "type", "in", "(", "XHDTYPE", ",", "XGLTYPE", ",", "SOLARIS_XHDTYPE", ")", ":", "return", "self", ".", "_proc_pax", "(", "tarfile", ")", "else", ":", "return", "self", ".", "_proc_builtin", "(", "tarfile", ")" ]
Get game version .
def get_version ( self ) : return mgz . const . VERSIONS [ self . _header . version ] , str ( self . _header . sub_version ) [ : 5 ]
3,174
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L175-L177
[ "def", "get_user_permissions", "(", "user", ")", ":", "permissions", "=", "SeedPermission", ".", "objects", ".", "all", "(", ")", "# User must be on a team that grants the permission", "permissions", "=", "permissions", ".", "filter", "(", "seedteam__users", "=", "user", ")", "# The team must be active", "permissions", "=", "permissions", ".", "filter", "(", "seedteam__archived", "=", "False", ")", "# The organization of that team must be active", "permissions", "=", "permissions", ".", "filter", "(", "seedteam__organization__archived", "=", "False", ")", "return", "permissions" ]
Get dataset .
def get_dataset ( self ) : sample = self . _header . initial . players [ 0 ] . attributes . player_stats if 'mod' in sample and sample . mod [ 'id' ] > 0 : return sample . mod elif 'trickle_food' in sample and sample . trickle_food : return { 'id' : 1 , 'name' : mgz . const . MODS . get ( 1 ) , 'version' : '<5.7.2' } return { 'id' : 0 , 'name' : 'Age of Kings: The Conquerors' , 'version' : '1.0c' }
3,175
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L179-L194
[ "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 teams .
def get_teams ( self ) : if self . _cache [ 'teams' ] : return self . _cache [ 'teams' ] teams = [ ] for j , player in enumerate ( self . _header . initial . players ) : added = False for i in range ( 0 , len ( self . _header . initial . players ) ) : if player . attributes . my_diplomacy [ i ] == 'ally' : inner_team = False outer_team = False new_team = True for t , tl in enumerate ( teams ) : if j in tl or i in tl : new_team = False if j in tl and i not in tl : inner_team = t break if j not in tl and i in tl : outer_team = t break if new_team : teams . append ( [ i , j ] ) if inner_team is not False : teams [ inner_team ] . append ( i ) if outer_team is not False : teams [ outer_team ] . append ( j ) added = True if not added and j != 0 : teams . append ( [ j ] ) self . _cache [ 'teams' ] = teams return teams
3,176
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L200-L231
[ "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 achievements for a player .
def get_achievements ( self , name ) : postgame = self . get_postgame ( ) if not postgame : return None for achievements in postgame . achievements : # achievements player name can be shorter if name . startswith ( achievements . player_name . replace ( b'\x00' , b'' ) ) : return achievements return None
3,177
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L265-L277
[ "def", "delete_table", "(", "self", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "connection", "(", "*", "*", "kwargs", ")", "as", "connection", ":", "kwargs", "[", "'connection'", "]", "=", "connection", "if", "not", "self", ".", "has_table", "(", "str", "(", "schema", ")", ",", "*", "*", "kwargs", ")", ":", "return", "True", "with", "self", ".", "transaction", "(", "*", "*", "kwargs", ")", ":", "self", ".", "_delete_table", "(", "schema", ",", "*", "*", "kwargs", ")", "return", "True" ]
Get Voobly ladder .
def _process_body ( self ) : start_time = time . time ( ) ratings = { } encoding = self . get_encoding ( ) checksums = [ ] ladder = None voobly = False rated = False i = 0 while self . _handle . tell ( ) < self . size : try : op = mgz . body . operation . parse_stream ( self . _handle ) if op . type == 'sync' : i += 1 if op . type == 'sync' and op . checksum is not None and len ( checksums ) < CHECKSUMS : checksums . append ( op . checksum . sync . to_bytes ( 8 , 'big' , signed = True ) ) elif op . type == 'message' and op . subtype == 'chat' : text = op . data . text . decode ( encoding ) if text . find ( 'Voobly: Ratings provided' ) > 0 : start = text . find ( "'" ) + 1 end = text . find ( "'" , start ) ladder = text [ start : end ] voobly = True elif text . find ( '<Rating>' ) > 0 : player_start = text . find ( '>' ) + 2 player_end = text . find ( ':' , player_start ) player = text [ player_start : player_end ] ratings [ player ] = int ( text [ player_end + 2 : len ( text ) ] ) elif text . find ( 'No ratings are available' ) > 0 : voobly = True elif text . find ( 'This match was played at Voobly.com' ) > 0 : voobly = True if i > MAX_SYNCS : break except ( construct . core . ConstructError , ValueError ) : break self . _handle . seek ( self . body_position ) rated = len ( ratings ) > 0 and set ( ratings . values ( ) ) != { 1600 } self . _cache [ 'hash' ] = hashlib . sha1 ( b'' . join ( checksums ) ) if len ( checksums ) == CHECKSUMS else None self . _cache [ 'from_voobly' ] = voobly self . _cache [ 'ladder' ] = ladder self . _cache [ 'rated' ] = rated self . _cache [ 'ratings' ] = ratings if rated else { } LOGGER . info ( "parsed limited rec body in %.2f seconds" , time . time ( ) - start_time ) return voobly , ladder , rated , ratings
3,178
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L353-L403
[ "def", "_intersection", "(", "self", ",", "keys", ",", "rows", ")", ":", "# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.", "if", "not", "keys", ":", "return", "rows", "ret", "=", "list", "(", ")", "for", "row", "in", "rows", ":", "start_date", "=", "row", "[", "self", ".", "_key_start_date", "]", "end_date", "=", "row", "[", "self", ".", "_key_end_date", "]", "for", "key_start_date", ",", "key_end_date", "in", "keys", ":", "start_date", ",", "end_date", "=", "Type2JoinHelper", ".", "_intersect", "(", "start_date", ",", "end_date", ",", "row", "[", "key_start_date", "]", ",", "row", "[", "key_end_date", "]", ")", "if", "not", "start_date", ":", "break", "if", "key_start_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_start_date", "]", "if", "key_end_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_end_date", "]", "if", "start_date", ":", "row", "[", "self", ".", "_key_start_date", "]", "=", "start_date", "row", "[", "self", ".", "_key_end_date", "]", "=", "end_date", "ret", ".", "append", "(", "row", ")", "return", "ret" ]
Get settings .
def get_settings ( self ) : postgame = self . get_postgame ( ) return { 'type' : ( self . _header . lobby . game_type_id , self . _header . lobby . game_type ) , 'difficulty' : ( self . _header . scenario . game_settings . difficulty_id , self . _header . scenario . game_settings . difficulty ) , 'population_limit' : self . _header . lobby . population_limit * 25 , 'map_reveal_choice' : ( self . _header . lobby . reveal_map_id , self . _header . lobby . reveal_map ) , 'speed' : ( self . _header . replay . game_speed_id , mgz . const . SPEEDS . get ( self . _header . replay . game_speed_id ) ) , 'cheats' : self . _header . replay . cheats_enabled , 'lock_teams' : self . _header . lobby . lock_teams , 'starting_resources' : ( postgame . resource_level_id if postgame else None , postgame . resource_level if postgame else None , ) , 'starting_age' : ( postgame . starting_age_id if postgame else None , postgame . starting_age if postgame else None ) , 'victory_condition' : ( postgame . victory_type_id if postgame else None , postgame . victory_type if postgame else None ) , 'team_together' : not postgame . team_together if postgame else None , 'all_technologies' : postgame . all_techs if postgame else None , 'lock_speed' : postgame . lock_speed if postgame else None , 'multiqueue' : None }
3,179
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L405-L444
[ "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 the map metadata .
def get_map ( self ) : if self . _cache [ 'map' ] : return self . _cache [ 'map' ] map_id = self . _header . scenario . game_settings . map_id instructions = self . _header . scenario . messages . instructions size = mgz . const . MAP_SIZES . get ( self . _header . map_info . size_x ) dimension = self . _header . map_info . size_x custom = True name = 'Unknown' language = None encoding = 'unknown' # detect encoding and language for pair in ENCODING_MARKERS : marker = pair [ 0 ] test_encoding = pair [ 1 ] e_m = marker . encode ( test_encoding ) for line in instructions . split ( b'\n' ) : pos = line . find ( e_m ) if pos > - 1 : encoding = test_encoding name = line [ pos + len ( e_m ) : ] . decode ( encoding ) language = pair [ 2 ] break # disambiguate certain languages if not language : language = 'unknown' for pair in LANGUAGE_MARKERS : if instructions . find ( pair [ 0 ] . encode ( pair [ 1 ] ) ) > - 1 : language = pair [ 2 ] break self . _cache [ 'encoding' ] = encoding self . _cache [ 'language' ] = language # lookup base game map if applicable if map_id != 44 : if map_id not in mgz . const . MAP_NAMES : raise ValueError ( 'unspecified builtin map' ) name = mgz . const . MAP_NAMES [ map_id ] custom = False # extract map seed match = re . search ( b'\x00.*? (\-?[0-9]+)\x00.*?\.rms' , instructions ) seed = None if match : seed = int ( match . group ( 1 ) ) # extract userpatch modes has_modes = name . find ( ': !' ) mode_string = '' if has_modes > - 1 : mode_string = name [ has_modes + 3 : ] name = name [ : has_modes ] modes = { 'direct_placement' : 'P' in mode_string , 'effect_quantity' : 'C' in mode_string , 'guard_state' : 'G' in mode_string , 'fixed_positions' : 'F' in mode_string } self . _cache [ 'map' ] = { 'id' : map_id if not custom else None , 'name' : name . strip ( ) , 'size' : size , 'dimension' : dimension , 'seed' : seed , 'modes' : modes , 'custom' : custom , 'zr' : name . startswith ( 'ZR@' ) } return self . _cache [ 'map' ]
3,180
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L461-L533
[ "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" ]
Determine if the game was completed .
def get_completed ( self ) : postgame = self . get_postgame ( ) if postgame : return postgame . complete else : return True if self . _cache [ 'resigned' ] else False
3,181
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L535-L545
[ "def", "wrap", "(", "vtkdataset", ")", ":", "wrappers", "=", "{", "'vtkUnstructuredGrid'", ":", "vtki", ".", "UnstructuredGrid", ",", "'vtkRectilinearGrid'", ":", "vtki", ".", "RectilinearGrid", ",", "'vtkStructuredGrid'", ":", "vtki", ".", "StructuredGrid", ",", "'vtkPolyData'", ":", "vtki", ".", "PolyData", ",", "'vtkImageData'", ":", "vtki", ".", "UniformGrid", ",", "'vtkStructuredPoints'", ":", "vtki", ".", "UniformGrid", ",", "'vtkMultiBlockDataSet'", ":", "vtki", ".", "MultiBlock", ",", "}", "key", "=", "vtkdataset", ".", "GetClassName", "(", ")", "try", ":", "wrapped", "=", "wrappers", "[", "key", "]", "(", "vtkdataset", ")", "except", ":", "logging", ".", "warning", "(", "'VTK data type ({}) is not currently supported by vtki.'", ".", "format", "(", "key", ")", ")", "return", "vtkdataset", "# if not supported just passes the VTK data object", "return", "wrapped" ]
Determine mirror match .
def get_mirror ( self ) : mirror = False if self . get_diplomacy ( ) [ '1v1' ] : civs = set ( ) for data in self . get_players ( ) : civs . add ( data [ 'civilization' ] ) mirror = ( len ( civs ) == 1 ) return mirror
3,182
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L547-L555
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", ".", "_project", ")", "self", ".", "_aux", "=", "None", "if", "aux", "is", "not", "None", ":", "self", ".", "_aux", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "aux", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: aux port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "aux", ")", ")" ]
Guess if a player won .
def guess_winner ( self , i ) : for team in self . get_teams ( ) : if i not in team : continue for p in team : if p in self . _cache [ 'resigned' ] : return False return True
3,183
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L557-L569
[ "def", "_ParseStorageMediaOptions", "(", "self", ",", "options", ")", ":", "self", ".", "_ParseStorageMediaImageOptions", "(", "options", ")", "self", ".", "_ParseVSSProcessingOptions", "(", "options", ")", "self", ".", "_ParseCredentialOptions", "(", "options", ")", "self", ".", "_ParseSourcePathOption", "(", "options", ")" ]
Execute the handlers with a message if any .
def trigger ( self , * args , * * kwargs ) : for h in self . handlers : h ( * args , * * kwargs )
3,184
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L43-L46
[ "def", "predict", "(", "self", ",", "Xstar", ")", ":", "KV", "=", "self", ".", "_update_cache", "(", ")", "self", ".", "covar", ".", "setXstar", "(", "Xstar", ")", "Kstar", "=", "self", ".", "covar", ".", "Kcross", "(", ")", "Ystar", "=", "SP", ".", "dot", "(", "Kstar", ",", "KV", "[", "'alpha'", "]", ")", "return", "Ystar" ]
Create add or update an event with a handler or more attached .
def on ( self , event , handler = None ) : if isinstance ( event , str ) and ' ' in event : # event is list str-based self . on ( event . split ( ' ' ) , handler ) elif isinstance ( event , list ) : # many events contains same handler for each in event : self . on ( each , handler ) elif isinstance ( event , dict ) : # event is a dict of <event, handler> for key , value in event . items ( ) : self . on ( key , value ) elif isinstance ( handler , list ) : # handler is a list of handlers for each in handler : self . on ( event , each ) elif isinstance ( handler , Event ) : # handler is Event object self . events [ event ] = handler # add or update an event setattr ( self , event , self . events [ event ] ) # self.event.trigger() elif event in self . events : # add a handler to an existing event self . events [ event ] . on ( handler ) else : # create new event with a handler attached self . on ( event , Event ( handler ) )
3,185
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L59-L78
[ "def", "validate_cookies", "(", "session", ",", "class_name", ")", ":", "if", "not", "do_we_have_enough_cookies", "(", "session", ".", "cookies", ",", "class_name", ")", ":", "return", "False", "url", "=", "CLASS_URL", ".", "format", "(", "class_name", "=", "class_name", ")", "+", "'/class'", "r", "=", "session", ".", "head", "(", "url", ",", "allow_redirects", "=", "False", ")", "if", "r", ".", "status_code", "==", "200", ":", "return", "True", "else", ":", "logging", ".", "debug", "(", "'Stale session.'", ")", "try", ":", "session", ".", "cookies", ".", "clear", "(", "'.coursera.org'", ")", "except", "KeyError", ":", "pass", "return", "False" ]
Remove an event or a handler from it .
def off ( self , event , handler = None ) : if handler : self . events [ event ] . off ( handler ) else : del self . events [ event ] delattr ( self , event )
3,186
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L80-L86
[ "def", "seek", "(", "self", ",", "value", ")", ":", "# Pause the stream", "self", ".", "pause", "(", ")", "# Make sure the movie starts at 1s as 0s gives trouble.", "self", ".", "clock", ".", "time", "=", "max", "(", "0.5", ",", "value", ")", "logger", ".", "debug", "(", "\"Seeking to {} seconds; frame {}\"", ".", "format", "(", "self", ".", "clock", ".", "time", ",", "self", ".", "clock", ".", "current_frame", ")", ")", "if", "self", ".", "audioformat", ":", "self", ".", "__calculate_audio_frames", "(", ")", "# Resume the stream", "self", ".", "pause", "(", ")" ]
Execute all event handlers with optional arguments for the observable .
def trigger ( self , * args , * * kargs ) : event = args [ 0 ] if isinstance ( event , str ) and ' ' in event : event = event . split ( ' ' ) # split event names ... if isinstance ( event , list ) : # event is a list of events for each in event : self . events [ each ] . trigger ( * args [ 1 : ] , * * kargs ) else : self . events [ event ] . trigger ( * args [ 1 : ] , * * kargs )
3,187
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L88-L101
[ "def", "_validate_columns", "(", "self", ")", ":", "geom_cols", "=", "{", "'the_geom'", ",", "'the_geom_webmercator'", ",", "}", "col_overlap", "=", "set", "(", "self", ".", "style_cols", ")", "&", "geom_cols", "if", "col_overlap", ":", "raise", "ValueError", "(", "'Style columns cannot be geometry '", "'columns. `{col}` was chosen.'", ".", "format", "(", "col", "=", "','", ".", "join", "(", "col_overlap", ")", ")", ")" ]
Ignore SIGINT . During typical keyboard interrupts the parent does the killing .
def _initializer_wrapper ( initializer , * args ) : signal . signal ( signal . SIGINT , signal . SIG_IGN ) if initializer is not None : initializer ( * args )
3,188
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/kombine/interruptible_pool.py#L20-L27
[ "def", "get_failed_requests", "(", "self", ",", "results", ")", ":", "data", "=", "{", "member", "[", "'guid'", "]", ":", "member", "for", "member", "in", "results", "}", "for", "request", "in", "self", ".", "requests", ":", "if", "request", "[", "'guid'", "]", "not", "in", "data", ":", "yield", "request" ]
Determines the set of types present in a DataFrame column .
def _col_type_set ( self , col , df ) : type_set = set ( ) if df [ col ] . dtype == np . dtype ( object ) : unindexed_col = list ( df [ col ] ) for i in range ( 0 , len ( df [ col ] ) ) : if unindexed_col [ i ] == np . nan : continue else : type_set . add ( type ( unindexed_col [ i ] ) ) return type_set else : type_set . add ( df [ col ] . dtype ) return type_set
3,189
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/base_extractor.py#L84-L103
[ "async", "def", "async_get_bridgeid", "(", "session", ",", "host", ",", "port", ",", "api_key", ",", "*", "*", "kwargs", ")", ":", "url", "=", "'http://{}:{}/api/{}/config'", ".", "format", "(", "host", ",", "str", "(", "port", ")", ",", "api_key", ")", "response", "=", "await", "async_request", "(", "session", ".", "get", ",", "url", ")", "bridgeid", "=", "response", "[", "'bridgeid'", "]", "_LOGGER", ".", "info", "(", "\"Bridge id: %s\"", ",", "bridgeid", ")", "return", "bridgeid" ]
Produces the extractor object s data as it is stored internally .
def raw ( self , drop_collections = False ) : base_df = self . _data if drop_collections is True : out_df = self . _drop_collections ( base_df ) else : out_df = base_df return out_df
3,190
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/base_extractor.py#L121-L134
[ "def", "present", "(", "name", ",", "parent", "=", "None", ",", "vlan", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "# Comment and change messages", "comment_bridge_created", "=", "'Bridge {0} created.'", ".", "format", "(", "name", ")", "comment_bridge_notcreated", "=", "'Unable to create bridge: {0}.'", ".", "format", "(", "name", ")", "comment_bridge_exists", "=", "'Bridge {0} already exists.'", ".", "format", "(", "name", ")", "comment_bridge_mismatch", "=", "(", "'Bridge {0} already exists, but has a different'", "' parent or VLAN ID.'", ")", ".", "format", "(", "name", ")", "changes_bridge_created", "=", "{", "name", ":", "{", "'old'", ":", "'Bridge {0} does not exist.'", ".", "format", "(", "name", ")", ",", "'new'", ":", "'Bridge {0} created'", ".", "format", "(", "name", ")", ",", "}", "}", "bridge_exists", "=", "__salt__", "[", "'openvswitch.bridge_exists'", "]", "(", "name", ")", "if", "bridge_exists", ":", "current_parent", "=", "__salt__", "[", "'openvswitch.bridge_to_parent'", "]", "(", "name", ")", "if", "current_parent", "==", "name", ":", "current_parent", "=", "None", "current_vlan", "=", "__salt__", "[", "'openvswitch.bridge_to_vlan'", "]", "(", "name", ")", "if", "current_vlan", "==", "0", ":", "current_vlan", "=", "None", "# Dry run, test=true mode", "if", "__opts__", "[", "'test'", "]", ":", "if", "bridge_exists", ":", "if", "current_parent", "==", "parent", "and", "current_vlan", "==", "vlan", ":", "ret", "[", "'result'", "]", "=", "True", "ret", "[", "'comment'", "]", "=", "comment_bridge_exists", "else", ":", "ret", "[", "'result'", "]", "=", "False", "ret", "[", "'comment'", "]", "=", "comment_bridge_mismatch", "else", ":", "ret", "[", "'result'", "]", "=", "None", "ret", "[", "'comment'", "]", "=", "comment_bridge_created", "return", "ret", "if", "bridge_exists", ":", "if", "current_parent", "==", "parent", "and", "current_vlan", "==", "vlan", ":", "ret", "[", "'result'", "]", "=", "True", "ret", "[", "'comment'", "]", "=", "comment_bridge_exists", "else", ":", "ret", "[", "'result'", "]", "=", "False", "ret", "[", "'comment'", "]", "=", "comment_bridge_mismatch", "else", ":", "bridge_create", "=", "__salt__", "[", "'openvswitch.bridge_create'", "]", "(", "name", ",", "parent", "=", "parent", ",", "vlan", "=", "vlan", ")", "if", "bridge_create", ":", "ret", "[", "'result'", "]", "=", "True", "ret", "[", "'comment'", "]", "=", "comment_bridge_created", "ret", "[", "'changes'", "]", "=", "changes_bridge_created", "else", ":", "ret", "[", "'result'", "]", "=", "False", "ret", "[", "'comment'", "]", "=", "comment_bridge_notcreated", "return", "ret" ]
A modified os . walk with support for maximum traversal depth .
def _walk ( path , follow_links = False , maximum_depth = None ) : root_level = path . rstrip ( os . path . sep ) . count ( os . path . sep ) for root , dirs , files in os . walk ( path , followlinks = follow_links ) : yield root , dirs , files if maximum_depth is None : continue if root_level + maximum_depth <= root . count ( os . path . sep ) : del dirs [ : ]
3,191
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L14-L23
[ "def", "get_sync_sql", "(", "self", ",", "field_name", ",", "missing_langs", ",", "model", ")", ":", "qn", "=", "connection", ".", "ops", ".", "quote_name", "style", "=", "no_style", "(", ")", "sql_output", "=", "[", "]", "db_table", "=", "model", ".", "_meta", ".", "db_table", "for", "lang", "in", "missing_langs", ":", "new_field", "=", "build_localized_fieldname", "(", "field_name", ",", "lang", ")", "f", "=", "model", ".", "_meta", ".", "get_field", "(", "new_field", ")", "col_type", "=", "f", ".", "db_type", "(", "connection", "=", "connection", ")", "field_sql", "=", "[", "style", ".", "SQL_FIELD", "(", "qn", "(", "f", ".", "column", ")", ")", ",", "style", ".", "SQL_COLTYPE", "(", "col_type", ")", "]", "# column creation", "stmt", "=", "\"ALTER TABLE %s ADD COLUMN %s\"", "%", "(", "qn", "(", "db_table", ")", ",", "' '", ".", "join", "(", "field_sql", ")", ")", "if", "not", "f", ".", "null", ":", "stmt", "+=", "\" \"", "+", "style", ".", "SQL_KEYWORD", "(", "'NOT NULL'", ")", "sql_output", ".", "append", "(", "stmt", "+", "\";\"", ")", "return", "sql_output" ]
Add one or more ClassFile sources to the class loader .
def update ( self , * sources , follow_symlinks : bool = False , maximum_depth : int = 20 ) : for source in sources : if isinstance ( source , self . klass ) : self . path_map [ source . this . name . value ] = source self . class_cache [ source . this . name . value ] = source continue # Explicit cast to str to support Path objects. source = str ( source ) if source . lower ( ) . endswith ( ( '.zip' , '.jar' ) ) : zf = ZipFile ( source , 'r' ) self . path_map . update ( zip ( zf . namelist ( ) , repeat ( zf ) ) ) elif os . path . isdir ( source ) : walker = _walk ( source , follow_links = follow_symlinks , maximum_depth = maximum_depth ) for root , dirs , files in walker : for file_ in files : path_full = os . path . join ( root , file_ ) path_suffix = os . path . relpath ( path_full , source ) self . path_map [ path_suffix ] = path_full
3,192
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L62-L105
[ "def", "_get_unique_variable_name", "(", "vname", ",", "variables", ")", ":", "count", "=", "2", "vname_base", "=", "vname", "while", "vname", "in", "variables", ":", "vname", "=", "'{}_{}'", ".", "format", "(", "vname_base", ",", "count", ")", "count", "+=", "1", "return", "vname" ]
Open an IO - like object for path .
def open ( self , path : str , mode : str = 'r' ) -> IO : entry = self . path_map . get ( path ) if entry is None : raise FileNotFoundError ( ) if isinstance ( entry , str ) : with open ( entry , 'rb' if mode == 'r' else mode ) as source : yield source elif isinstance ( entry , ZipFile ) : yield io . BytesIO ( entry . read ( path ) ) else : raise NotImplementedError ( )
3,193
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L108-L129
[ "def", "store_result", "(", "self", ",", "message", ",", "result", ":", "Result", ",", "ttl", ":", "int", ")", "->", "None", ":", "message_key", "=", "self", ".", "build_message_key", "(", "message", ")", "return", "self", ".", "_store", "(", "message_key", ",", "result", ",", "ttl", ")" ]
Load the class at path and return it .
def load ( self , path : str ) -> ClassFile : # Try to refresh the class from the cache, loading it from disk # if not found. try : r = self . class_cache . pop ( path ) except KeyError : with self . open ( f'{path}.class' ) as source : r = self . klass ( source ) r . classloader = self # Even if it was found re-set the key to update the OrderedDict # ordering. self . class_cache [ path ] = r # If the cache is enabled remove every item over N started from # the least-used. if self . max_cache > 0 : to_pop = max ( len ( self . class_cache ) - self . max_cache , 0 ) for _ in repeat ( None , to_pop ) : self . class_cache . popitem ( last = False ) return r
3,194
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L131-L159
[ "def", "_CreateZMQSocket", "(", "self", ")", ":", "super", "(", "ZeroMQBufferedQueue", ",", "self", ")", ".", "_CreateZMQSocket", "(", ")", "if", "not", "self", ".", "_zmq_thread", ":", "thread_name", "=", "'{0:s}_zmq_responder'", ".", "format", "(", "self", ".", "name", ")", "self", ".", "_zmq_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_ZeroMQResponder", ",", "args", "=", "[", "self", ".", "_queue", "]", ",", "name", "=", "thread_name", ")", "self", ".", "_zmq_thread", ".", "start", "(", ")" ]
Returns a set of all classes referenced by the ClassFile at path without reading the entire ClassFile .
def dependencies ( self , path : str ) -> Set [ str ] : return set ( c . name . value for c in self . search_constant_pool ( path = path , type_ = ConstantClass ) )
3,195
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L166-L178
[ "def", "on_session_start", "(", "self", ",", "data", ")", ":", "# pylint: disable=W0613", "# Send initial presence", "self", ".", "send_presence", "(", "ppriority", "=", "self", ".", "_initial_priority", ")", "# Request roster", "self", ".", "get_roster", "(", ")" ]
Partially load the class at path yield all matching constants from the ConstantPool .
def search_constant_pool ( self , * , path : str , * * options ) : with self . open ( f'{path}.class' ) as source : # Skip over the magic, minor, and major version. source . read ( 8 ) pool = ConstantPool ( ) pool . unpack ( source ) yield from pool . find ( * * options )
3,196
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L180-L195
[ "def", "to_bam", "(", "in_file", ",", "out_file", ",", "data", ")", ":", "if", "not", "utils", ".", "file_uptodate", "(", "out_file", ",", "in_file", ")", ":", "with", "file_transaction", "(", "data", ",", "out_file", ")", "as", "tx_out_file", ":", "cmd", "=", "[", "\"samtools\"", ",", "\"view\"", ",", "\"-O\"", ",", "\"BAM\"", ",", "\"-o\"", ",", "tx_out_file", ",", "in_file", "]", "do", ".", "run", "(", "cmd", ",", "\"Convert CRAM to BAM\"", ")", "bam", ".", "index", "(", "out_file", ",", "data", "[", "\"config\"", "]", ")", "return", "out_file" ]
Yield the name of all classes discovered in the path map .
def classes ( self ) -> Iterator [ str ] : yield from ( c [ : - 6 ] for c in self . path_map . keys ( ) if c . endswith ( '.class' ) )
3,197
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L198-L203
[ "def", "encode", "(", "self", ",", "frame", ":", "Frame", ")", "->", "Frame", ":", "# Skip control frames.", "if", "frame", ".", "opcode", "in", "CTRL_OPCODES", ":", "return", "frame", "# Since we always encode and never fragment messages, there's no logic", "# similar to decode() here at this time.", "if", "frame", ".", "opcode", "!=", "OP_CONT", ":", "# Re-initialize per-message decoder.", "if", "self", ".", "local_no_context_takeover", ":", "self", ".", "encoder", "=", "zlib", ".", "compressobj", "(", "wbits", "=", "-", "self", ".", "local_max_window_bits", ",", "*", "*", "self", ".", "compress_settings", ")", "# Compress data frames.", "data", "=", "self", ".", "encoder", ".", "compress", "(", "frame", ".", "data", ")", "+", "self", ".", "encoder", ".", "flush", "(", "zlib", ".", "Z_SYNC_FLUSH", ")", "if", "frame", ".", "fin", "and", "data", ".", "endswith", "(", "_EMPTY_UNCOMPRESSED_BLOCK", ")", ":", "data", "=", "data", "[", ":", "-", "4", "]", "# Allow garbage collection of the encoder if it won't be reused.", "if", "frame", ".", "fin", "and", "self", ".", "local_no_context_takeover", ":", "del", "self", ".", "encoder", "return", "frame", ".", "_replace", "(", "data", "=", "data", ",", "rsv1", "=", "True", ")" ]
Processes an object exporting its data as a nested dictionary .
def _make_object_dict ( self , obj ) : data = { } for attr in dir ( obj ) : if attr [ 0 ] is not '_' and attr is not 'status' : datum = getattr ( obj , attr ) if not isinstance ( datum , types . MethodType ) : data . update ( self . _handle_object ( attr , datum ) ) return data
3,198
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidytwitter/twitter_extractor.py#L165-L178
[ "def", "add_license", "(", "self", ",", "contents", ")", ":", "buf_size", "=", "len", "(", "contents", ")", "buf", "=", "(", "ctypes", ".", "c_char", "*", "(", "buf_size", "+", "1", ")", ")", "(", "*", "contents", ".", "encode", "(", ")", ")", "res", "=", "self", ".", "_dll", ".", "JLINK_EMU_AddLicense", "(", "buf", ")", "if", "res", "==", "-", "1", ":", "raise", "errors", ".", "JLinkException", "(", "'Unspecified error.'", ")", "elif", "res", "==", "-", "2", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to read/write license area.'", ")", "elif", "res", "==", "-", "3", ":", "raise", "errors", ".", "JLinkException", "(", "'J-Link out of space.'", ")", "return", "(", "res", "==", "0", ")" ]
Read the Field from the file - like object fio .
def unpack ( self , source : IO ) : self . access_flags . unpack ( source . read ( 2 ) ) self . _name_index , self . _descriptor_index = unpack ( '>HH' , source . read ( 4 ) ) self . attributes . unpack ( source )
3,199
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L59-L72
[ "def", "_is_path_match", "(", "req_path", ":", "str", ",", "cookie_path", ":", "str", ")", "->", "bool", ":", "if", "not", "req_path", ".", "startswith", "(", "\"/\"", ")", ":", "req_path", "=", "\"/\"", "if", "req_path", "==", "cookie_path", ":", "return", "True", "if", "not", "req_path", ".", "startswith", "(", "cookie_path", ")", ":", "return", "False", "if", "cookie_path", ".", "endswith", "(", "\"/\"", ")", ":", "return", "True", "non_matching", "=", "req_path", "[", "len", "(", "cookie_path", ")", ":", "]", "return", "non_matching", ".", "startswith", "(", "\"/\"", ")" ]