query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Set the conditions for the trigger .
def set_conditions ( self , trigger_id , conditions , trigger_mode = None ) : data = self . _serialize_object ( conditions ) if trigger_mode is not None : url = self . _service_url ( [ 'triggers' , trigger_id , 'conditions' , trigger_mode ] ) else : url = self . _service_url ( [ 'triggers' , trigger_id , 'conditions' ] ) response = self . _put ( url , data ) return Condition . list_to_object_list ( response )
7,200
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L279-L299
[ "def", "log1p", "(", "data", ":", "Union", "[", "AnnData", ",", "np", ".", "ndarray", ",", "spmatrix", "]", ",", "copy", ":", "bool", "=", "False", ",", "chunked", ":", "bool", "=", "False", ",", "chunk_size", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "Optional", "[", "AnnData", "]", ":", "if", "copy", ":", "if", "not", "isinstance", "(", "data", ",", "AnnData", ")", ":", "data", "=", "data", ".", "astype", "(", "np", ".", "floating", ")", "else", ":", "data", "=", "data", ".", "copy", "(", ")", "elif", "not", "isinstance", "(", "data", ",", "AnnData", ")", "and", "np", ".", "issubdtype", "(", "data", ".", "dtype", ",", "np", ".", "integer", ")", ":", "raise", "TypeError", "(", "\"Cannot perform inplace log1p on integer array\"", ")", "def", "_log1p", "(", "X", ")", ":", "if", "issparse", "(", "X", ")", ":", "np", ".", "log1p", "(", "X", ".", "data", ",", "out", "=", "X", ".", "data", ")", "else", ":", "np", ".", "log1p", "(", "X", ",", "out", "=", "X", ")", "return", "X", "if", "isinstance", "(", "data", ",", "AnnData", ")", ":", "if", "not", "np", ".", "issubdtype", "(", "data", ".", "X", ".", "dtype", ",", "np", ".", "floating", ")", ":", "data", ".", "X", "=", "data", ".", "X", ".", "astype", "(", "np", ".", "float32", ")", "if", "chunked", ":", "for", "chunk", ",", "start", ",", "end", "in", "data", ".", "chunked_X", "(", "chunk_size", ")", ":", "data", ".", "X", "[", "start", ":", "end", "]", "=", "_log1p", "(", "chunk", ")", "else", ":", "_log1p", "(", "data", ".", "X", ")", "else", ":", "_log1p", "(", "data", ")", "return", "data", "if", "copy", "else", "None" ]
Get all conditions for a specific trigger .
def conditions ( self , trigger_id ) : response = self . _get ( self . _service_url ( [ 'triggers' , trigger_id , 'conditions' ] ) ) return Condition . list_to_object_list ( response )
7,201
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L301-L309
[ "def", "log1p", "(", "data", ":", "Union", "[", "AnnData", ",", "np", ".", "ndarray", ",", "spmatrix", "]", ",", "copy", ":", "bool", "=", "False", ",", "chunked", ":", "bool", "=", "False", ",", "chunk_size", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "Optional", "[", "AnnData", "]", ":", "if", "copy", ":", "if", "not", "isinstance", "(", "data", ",", "AnnData", ")", ":", "data", "=", "data", ".", "astype", "(", "np", ".", "floating", ")", "else", ":", "data", "=", "data", ".", "copy", "(", ")", "elif", "not", "isinstance", "(", "data", ",", "AnnData", ")", "and", "np", ".", "issubdtype", "(", "data", ".", "dtype", ",", "np", ".", "integer", ")", ":", "raise", "TypeError", "(", "\"Cannot perform inplace log1p on integer array\"", ")", "def", "_log1p", "(", "X", ")", ":", "if", "issparse", "(", "X", ")", ":", "np", ".", "log1p", "(", "X", ".", "data", ",", "out", "=", "X", ".", "data", ")", "else", ":", "np", ".", "log1p", "(", "X", ",", "out", "=", "X", ")", "return", "X", "if", "isinstance", "(", "data", ",", "AnnData", ")", ":", "if", "not", "np", ".", "issubdtype", "(", "data", ".", "X", ".", "dtype", ",", "np", ".", "floating", ")", ":", "data", ".", "X", "=", "data", ".", "X", ".", "astype", "(", "np", ".", "float32", ")", "if", "chunked", ":", "for", "chunk", ",", "start", ",", "end", "in", "data", ".", "chunked_X", "(", "chunk_size", ")", ":", "data", ".", "X", "[", "start", ":", "end", "]", "=", "_log1p", "(", "chunk", ")", "else", ":", "_log1p", "(", "data", ".", "X", ")", "else", ":", "_log1p", "(", "data", ")", "return", "data", "if", "copy", "else", "None" ]
Create a new dampening .
def create_dampening ( self , trigger_id , dampening ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , trigger_id , 'dampenings' ] ) return Dampening ( self . _post ( url , data ) )
7,202
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L328-L339
[ "def", "_purge_index", "(", "self", ",", "database_name", ",", "collection_name", "=", "None", ",", "index_name", "=", "None", ")", ":", "with", "self", ".", "__index_cache_lock", ":", "if", "not", "database_name", "in", "self", ".", "__index_cache", ":", "return", "if", "collection_name", "is", "None", ":", "del", "self", ".", "__index_cache", "[", "database_name", "]", "return", "if", "not", "collection_name", "in", "self", ".", "__index_cache", "[", "database_name", "]", ":", "return", "if", "index_name", "is", "None", ":", "del", "self", ".", "__index_cache", "[", "database_name", "]", "[", "collection_name", "]", "return", "if", "index_name", "in", "self", ".", "__index_cache", "[", "database_name", "]", "[", "collection_name", "]", ":", "del", "self", ".", "__index_cache", "[", "database_name", "]", "[", "collection_name", "]", "[", "index_name", "]" ]
Delete an existing dampening definition .
def delete_dampening ( self , trigger_id , dampening_id ) : self . _delete ( self . _service_url ( [ 'triggers' , trigger_id , 'dampenings' , dampening_id ] ) )
7,203
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L341-L348
[ "def", "serialize", "(", "pagination", ",", "*", "*", "kwargs", ")", ":", "if", "not", "pagination", ".", "has_next", ":", "return", "token_builder", "=", "URLSafeTimedSerializer", "(", "current_app", ".", "config", "[", "'SECRET_KEY'", "]", ",", "salt", "=", "kwargs", "[", "'verb'", "]", ",", ")", "schema", "=", "_schema_from_verb", "(", "kwargs", "[", "'verb'", "]", ",", "partial", "=", "False", ")", "data", "=", "dict", "(", "seed", "=", "random", ".", "random", "(", ")", ",", "page", "=", "pagination", ".", "next_num", ",", "kwargs", "=", "schema", ".", "dump", "(", "kwargs", ")", ".", "data", ")", "scroll_id", "=", "getattr", "(", "pagination", ",", "'_scroll_id'", ",", "None", ")", "if", "scroll_id", ":", "data", "[", "'scroll_id'", "]", "=", "scroll_id", "return", "token_builder", ".", "dumps", "(", "data", ")" ]
Update an existing dampening definition .
def update_dampening ( self , trigger_id , dampening_id ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , trigger_id , 'dampenings' , dampening_id ] ) return Dampening ( self . _put ( url , data ) )
7,204
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L350-L361
[ "def", "serialize", "(", "pagination", ",", "*", "*", "kwargs", ")", ":", "if", "not", "pagination", ".", "has_next", ":", "return", "token_builder", "=", "URLSafeTimedSerializer", "(", "current_app", ".", "config", "[", "'SECRET_KEY'", "]", ",", "salt", "=", "kwargs", "[", "'verb'", "]", ",", ")", "schema", "=", "_schema_from_verb", "(", "kwargs", "[", "'verb'", "]", ",", "partial", "=", "False", ")", "data", "=", "dict", "(", "seed", "=", "random", ".", "random", "(", ")", ",", "page", "=", "pagination", ".", "next_num", ",", "kwargs", "=", "schema", ".", "dump", "(", "kwargs", ")", ".", "data", ")", "scroll_id", "=", "getattr", "(", "pagination", ",", "'_scroll_id'", ",", "None", ")", "if", "scroll_id", ":", "data", "[", "'scroll_id'", "]", "=", "scroll_id", "return", "token_builder", ".", "dumps", "(", "data", ")" ]
Create a new group dampening
def create_group_dampening ( self , group_id , dampening ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' ] ) return Dampening ( self . _post ( url , data ) )
7,205
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L363-L374
[ "def", "enable_pretty_logging", "(", "options", ":", "Any", "=", "None", ",", "logger", ":", "logging", ".", "Logger", "=", "None", ")", "->", "None", ":", "if", "options", "is", "None", ":", "import", "tornado", ".", "options", "options", "=", "tornado", ".", "options", ".", "options", "if", "options", ".", "logging", "is", "None", "or", "options", ".", "logging", ".", "lower", "(", ")", "==", "\"none\"", ":", "return", "if", "logger", "is", "None", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "setLevel", "(", "getattr", "(", "logging", ",", "options", ".", "logging", ".", "upper", "(", ")", ")", ")", "if", "options", ".", "log_file_prefix", ":", "rotate_mode", "=", "options", ".", "log_rotate_mode", "if", "rotate_mode", "==", "\"size\"", ":", "channel", "=", "logging", ".", "handlers", ".", "RotatingFileHandler", "(", "filename", "=", "options", ".", "log_file_prefix", ",", "maxBytes", "=", "options", ".", "log_file_max_size", ",", "backupCount", "=", "options", ".", "log_file_num_backups", ",", "encoding", "=", "\"utf-8\"", ",", ")", "# type: logging.Handler", "elif", "rotate_mode", "==", "\"time\"", ":", "channel", "=", "logging", ".", "handlers", ".", "TimedRotatingFileHandler", "(", "filename", "=", "options", ".", "log_file_prefix", ",", "when", "=", "options", ".", "log_rotate_when", ",", "interval", "=", "options", ".", "log_rotate_interval", ",", "backupCount", "=", "options", ".", "log_file_num_backups", ",", "encoding", "=", "\"utf-8\"", ",", ")", "else", ":", "error_message", "=", "(", "\"The value of log_rotate_mode option should be \"", "+", "'\"size\" or \"time\", not \"%s\".'", "%", "rotate_mode", ")", "raise", "ValueError", "(", "error_message", ")", "channel", ".", "setFormatter", "(", "LogFormatter", "(", "color", "=", "False", ")", ")", "logger", ".", "addHandler", "(", "channel", ")", "if", "options", ".", "log_to_stderr", "or", "(", "options", ".", "log_to_stderr", "is", "None", "and", "not", "logger", ".", "handlers", ")", ":", "# Set up color if we are in a tty and curses is installed", "channel", "=", "logging", ".", "StreamHandler", "(", ")", "channel", ".", "setFormatter", "(", "LogFormatter", "(", ")", ")", "logger", ".", "addHandler", "(", "channel", ")" ]
Update an existing group dampening
def update_group_dampening ( self , group_id , dampening_id , dampening ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' , dampening_id ] ) return Dampening ( self . _put ( url , data ) )
7,206
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L376-L386
[ "def", "logs", "(", "environment", ",", "opts", ")", ":", "container", "=", "'web'", "if", "opts", "[", "'--solr'", "]", ":", "container", "=", "'solr'", "if", "opts", "[", "'--postgres'", "]", ":", "container", "=", "'postgres'", "if", "opts", "[", "'--datapusher'", "]", ":", "container", "=", "'datapusher'", "tail", "=", "opts", "[", "'--tail'", "]", "if", "tail", "!=", "'all'", ":", "tail", "=", "int", "(", "tail", ")", "l", "=", "environment", ".", "logs", "(", "container", ",", "tail", ",", "opts", "[", "'--follow'", "]", ",", "opts", "[", "'--timestamps'", "]", ")", "if", "not", "opts", "[", "'--follow'", "]", ":", "print", "l", "return", "try", ":", "for", "message", "in", "l", ":", "write", "(", "message", ")", "except", "KeyboardInterrupt", ":", "print" ]
Delete an existing group dampening
def delete_group_dampening ( self , group_id , dampening_id ) : self . _delete ( self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' , dampening_id ] ) )
7,207
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L388-L395
[ "def", "logs", "(", "environment", ",", "opts", ")", ":", "container", "=", "'web'", "if", "opts", "[", "'--solr'", "]", ":", "container", "=", "'solr'", "if", "opts", "[", "'--postgres'", "]", ":", "container", "=", "'postgres'", "if", "opts", "[", "'--datapusher'", "]", ":", "container", "=", "'datapusher'", "tail", "=", "opts", "[", "'--tail'", "]", "if", "tail", "!=", "'all'", ":", "tail", "=", "int", "(", "tail", ")", "l", "=", "environment", ".", "logs", "(", "container", ",", "tail", ",", "opts", "[", "'--follow'", "]", ",", "opts", "[", "'--timestamps'", "]", ")", "if", "not", "opts", "[", "'--follow'", "]", ":", "print", "l", "return", "try", ":", "for", "message", "in", "l", ":", "write", "(", "message", ")", "except", "KeyboardInterrupt", ":", "print" ]
Make a non - orphan member trigger into an orphan .
def set_group_member_orphan ( self , member_id ) : self . _put ( self . _service_url ( [ 'triggers' , 'groups' , 'members' , member_id , 'orphan' ] ) , data = None , parse_json = False )
7,208
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L397-L403
[ "def", "get_dbs", "(", ")", ":", "url", "=", "posixpath", ".", "join", "(", "config", ".", "db_index_url", ",", "'DBS'", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "dbs", "=", "response", ".", "content", ".", "decode", "(", "'ascii'", ")", ".", "splitlines", "(", ")", "dbs", "=", "[", "re", ".", "sub", "(", "'\\t{2,}'", ",", "'\\t'", ",", "line", ")", ".", "split", "(", "'\\t'", ")", "for", "line", "in", "dbs", "]", "return", "dbs" ]
Make an orphan member trigger into an group trigger .
def set_group_member_unorphan ( self , member_id , unorphan_info ) : data = self . _serialize_object ( unorphan_info ) data = self . _service_url ( [ 'triggers' , 'groups' , 'members' , member_id , 'unorphan' ] ) return Trigger ( self . _put ( url , data ) )
7,209
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L405-L416
[ "def", "list_domains", "(", ")", ":", "vms", "=", "[", "]", "cmd", "=", "'vagrant global-status'", "reply", "=", "__salt__", "[", "'cmd.shell'", "]", "(", "cmd", ")", "log", ".", "info", "(", "'--->\\n%s'", ",", "reply", ")", "for", "line", "in", "reply", ".", "split", "(", "'\\n'", ")", ":", "# build a list of the text reply", "tokens", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "try", ":", "_", "=", "int", "(", "tokens", "[", "0", "]", ",", "16", ")", "# valid id numbers are hexadecimal", "except", "(", "ValueError", ",", "IndexError", ")", ":", "continue", "# skip lines without valid id numbers", "machine", "=", "tokens", "[", "1", "]", "cwd", "=", "tokens", "[", "-", "1", "]", "name", "=", "get_machine_id", "(", "machine", ",", "cwd", ")", "if", "name", ":", "vms", ".", "append", "(", "name", ")", "return", "vms" ]
Enable triggers .
def enable ( self , trigger_ids = [ ] ) : trigger_ids = ',' . join ( trigger_ids ) url = self . _service_url ( [ 'triggers' , 'enabled' ] , params = { 'triggerIds' : trigger_ids , 'enabled' : 'true' } ) self . _put ( url , data = None , parse_json = False )
7,210
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L418-L426
[ "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" ]
Location may be specified with a string name or latitude longitude radius
def get_twitter ( app_key = None , app_secret = None , search = 'python' , location = '' , * * kwargs ) : if not app_key : from settings_secret import TWITTER_API_KEY as app_key if not app_secret : from settings_secret import TWITTER_API_SECRET as app_secret twitter = Twython ( app_key , app_secret , oauth_version = 2 ) return Twython ( app_key , access_token = twitter . obtain_access_token ( ) )
7,211
https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/tweets.py#L69-L76
[ "def", "_DeserializeResponse", "(", "self", ",", "payload", ")", ":", "# Strip off the status line.", "status_line", ",", "payload", "=", "payload", ".", "split", "(", "'\\n'", ",", "1", ")", "_", ",", "status", ",", "_", "=", "status_line", ".", "split", "(", "' '", ",", "2", ")", "# Parse the rest of the response.", "parser", "=", "email_parser", ".", "Parser", "(", ")", "msg", "=", "parser", ".", "parsestr", "(", "payload", ")", "# Get the headers.", "info", "=", "dict", "(", "msg", ")", "info", "[", "'status'", "]", "=", "status", "# Create Response from the parsed headers.", "content", "=", "msg", ".", "get_payload", "(", ")", "return", "http_wrapper", ".", "Response", "(", "info", ",", "content", ",", "self", ".", "__batch_url", ")" ]
Dump a limitted number of json . dump - able objects to the indicated file
def limitted_dump ( cursor = None , twitter = None , path = 'tweets.json' , limit = 450 , rate = TWITTER_SEARCH_RATE_LIMIT , indent = - 1 ) : if not twitter : twitter = get_twitter ( ) cursor = cursor or 'python' if isinstance ( cursor , basestring ) : cursor = get_cursor ( twitter , search = cursor ) newline = '\n' if indent is not None else '' if indent < 0 : indent = None # TODO: keep track of T0 for the optimal "reset" sleep duration with ( open ( path , 'w' ) if not isinstance ( path , file ) else path ) as f : f . write ( '[\n' ) for i , obj in enumerate ( cursor ) : f . write ( json . dumps ( obj , indent = indent ) ) if i < limit - 1 : f . write ( ',' + newline ) else : break remaining = int ( twitter . get_lastfunction_header ( 'x-rate-limit-remaining' ) ) if remaining > 0 : sleep ( 1. / rate ) else : sleep ( 15 * 60 ) f . write ( '\n]\n' )
7,212
https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/tweets.py#L87-L114
[ "def", "_compute_ogg_page_crc", "(", "page", ")", ":", "page_zero_crc", "=", "page", "[", ":", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "]", "+", "b\"\\00\"", "*", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", "+", "page", "[", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "+", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", ":", "]", "return", "ogg_page_crc", "(", "page_zero_crc", ")" ]
calculate Gruneisen parameter for Altshuler equation
def altshuler_grun ( v , v0 , gamma0 , gamma_inf , beta ) : x = v / v0 return gamma_inf + ( gamma0 - gamma_inf ) * np . power ( x , beta )
7,213
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L9-L21
[ "def", "_get_image_paths", "(", "im1", ",", "im2", ")", ":", "paths", "=", "[", "]", "for", "im", "in", "[", "im1", ",", "im2", "]", ":", "if", "im", "is", "None", ":", "# Groupwise registration: only one image (ndim+1 dimensions)", "paths", ".", "append", "(", "paths", "[", "0", "]", ")", "continue", "if", "isinstance", "(", "im", ",", "str", ")", ":", "# Given a location", "if", "os", ".", "path", ".", "isfile", "(", "im1", ")", ":", "paths", ".", "append", "(", "im", ")", "else", ":", "raise", "ValueError", "(", "'Image location does not exist.'", ")", "elif", "isinstance", "(", "im", ",", "np", ".", "ndarray", ")", ":", "# Given a numpy array", "id", "=", "len", "(", "paths", ")", "+", "1", "p", "=", "_write_image_data", "(", "im", ",", "id", ")", "paths", ".", "append", "(", "p", ")", "else", ":", "# Given something else ...", "raise", "ValueError", "(", "'Invalid input image.'", ")", "# Done", "return", "tuple", "(", "paths", ")" ]
calculate Debye temperature for Altshuler equation
def altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta0 ) : x = v / v0 if isuncertainties ( [ v , v0 , gamma0 , gamma_inf , beta , theta0 ] ) : theta = theta0 * np . power ( x , - 1. * gamma_inf ) * unp . exp ( ( gamma0 - gamma_inf ) / beta * ( 1. - np . power ( x , beta ) ) ) else : theta = theta0 * np . power ( x , - 1. * gamma_inf ) * np . exp ( ( gamma0 - gamma_inf ) / beta * ( 1. - np . power ( x , beta ) ) ) return theta
7,214
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L24-L43
[ "def", "wrap_conn", "(", "conn_func", ")", ":", "def", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "conn", "=", "conn_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "cursor_func", "=", "getattr", "(", "conn", ",", "CURSOR_WRAP_METHOD", ")", "wrapped", "=", "wrap_cursor", "(", "cursor_func", ")", "setattr", "(", "conn", ",", "cursor_func", ".", "__name__", ",", "wrapped", ")", "return", "conn", "except", "Exception", ":", "# pragma: NO COVER", "logging", ".", "warning", "(", "'Fail to wrap conn, mysql not traced.'", ")", "return", "conn_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "call" ]
calculate thermal pressure for Dorogokupets 2007 EOS
def dorogokupets2007_pth ( v , temp , v0 , gamma0 , gamma_inf , beta , theta0 , n , z , three_r = 3. * constants . R , t_ref = 300. ) : v_mol = vol_uc2mol ( v , z ) # x = v_mol / v0_mol gamma = altshuler_grun ( v , v0 , gamma0 , gamma_inf , beta ) theta = altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta0 ) def f ( t ) : xx = theta / t debye = debye_E ( xx ) Eth = three_r * n * t * debye return ( gamma / v_mol * Eth ) * 1.e-9 return f ( temp ) - f ( t_ref )
7,215
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L46-L75
[ "def", "round", "(", "self", ",", "decimals", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "core", ".", "reshape", ".", "concat", "import", "concat", "def", "_dict_round", "(", "df", ",", "decimals", ")", ":", "for", "col", ",", "vals", "in", "df", ".", "iteritems", "(", ")", ":", "try", ":", "yield", "_series_round", "(", "vals", ",", "decimals", "[", "col", "]", ")", "except", "KeyError", ":", "yield", "vals", "def", "_series_round", "(", "s", ",", "decimals", ")", ":", "if", "is_integer_dtype", "(", "s", ")", "or", "is_float_dtype", "(", "s", ")", ":", "return", "s", ".", "round", "(", "decimals", ")", "return", "s", "nv", ".", "validate_round", "(", "args", ",", "kwargs", ")", "if", "isinstance", "(", "decimals", ",", "(", "dict", ",", "Series", ")", ")", ":", "if", "isinstance", "(", "decimals", ",", "Series", ")", ":", "if", "not", "decimals", ".", "index", ".", "is_unique", ":", "raise", "ValueError", "(", "\"Index of decimals must be unique\"", ")", "new_cols", "=", "[", "col", "for", "col", "in", "_dict_round", "(", "self", ",", "decimals", ")", "]", "elif", "is_integer", "(", "decimals", ")", ":", "# Dispatch to Series.round", "new_cols", "=", "[", "_series_round", "(", "v", ",", "decimals", ")", "for", "_", ",", "v", "in", "self", ".", "iteritems", "(", ")", "]", "else", ":", "raise", "TypeError", "(", "\"decimals must be an integer, a dict-like or a \"", "\"Series\"", ")", "if", "len", "(", "new_cols", ")", ">", "0", ":", "return", "self", ".", "_constructor", "(", "concat", "(", "new_cols", ",", "axis", "=", "1", ")", ",", "index", "=", "self", ".", "index", ",", "columns", "=", "self", ".", "columns", ")", "else", ":", "return", "self" ]
Connect to admin interface and application .
def bind ( cls , app , * paths , methods = None , name = None , view = None ) : # Register self in admin if view is None : app . ps . admin . register ( cls ) if not paths : paths = ( '%s/%s' % ( app . ps . admin . cfg . prefix , name or cls . name ) , ) cls . url = paths [ 0 ] return super ( AdminHandler , cls ) . bind ( app , * paths , methods = methods , name = name , view = view )
7,216
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L70-L78
[ "def", "_record_offset", "(", "self", ")", ":", "offset", "=", "self", ".", "blob_file", ".", "tell", "(", ")", "self", ".", "event_offsets", ".", "append", "(", "offset", ")" ]
Register admin view action .
def action ( cls , view ) : name = "%s:%s" % ( cls . name , view . __name__ ) path = "%s/%s" % ( cls . url , view . __name__ ) cls . actions . append ( ( view . __doc__ , path ) ) return cls . register ( path , name = name ) ( view )
7,217
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L81-L86
[ "def", "create_alarm_subscription", "(", "self", ",", "on_data", "=", "None", ",", "timeout", "=", "60", ")", ":", "manager", "=", "WebSocketSubscriptionManager", "(", "self", ".", "_client", ",", "resource", "=", "'alarms'", ")", "# Represent subscription as a future", "subscription", "=", "AlarmSubscription", "(", "manager", ")", "wrapped_callback", "=", "functools", ".", "partial", "(", "_wrap_callback_parse_alarm_data", ",", "subscription", ",", "on_data", ")", "manager", ".", "open", "(", "wrapped_callback", ",", "instance", "=", "self", ".", "_instance", ",", "processor", "=", "self", ".", "_processor", ")", "# Wait until a reply or exception is received", "subscription", ".", "reply", "(", "timeout", "=", "timeout", ")", "return", "subscription" ]
Dispatch a request .
async def dispatch ( self , request , * * kwargs ) : # Authorize request self . auth = await self . authorize ( request ) # Load collection self . collection = await self . load_many ( request ) # Load resource self . resource = await self . load_one ( request ) if request . method == 'GET' and self . resource is None : # Filter collection self . collection = await self . filter ( request ) # Sort collection self . columns_sort = request . query . get ( 'ap-sort' , self . columns_sort ) if self . columns_sort : reverse = self . columns_sort . startswith ( '-' ) self . columns_sort = self . columns_sort . lstrip ( '+-' ) self . collection = await self . sort ( request , reverse = reverse ) # Paginate collection try : self . offset = int ( request . query . get ( 'ap-offset' , 0 ) ) if self . limit : self . count = await self . count ( request ) self . collection = await self . paginate ( request ) except ValueError : pass return await super ( AdminHandler , self ) . dispatch ( request , * * kwargs )
7,218
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L88-L120
[ "def", "get_urls", "(", "self", ")", ":", "not_clone_url", "=", "[", "url", "(", "r'^(.+)/will_not_clone/$'", ",", "admin", ".", "site", ".", "admin_view", "(", "self", ".", "will_not_clone", ")", ")", "]", "restore_url", "=", "[", "url", "(", "r'^(.+)/restore/$'", ",", "admin", ".", "site", ".", "admin_view", "(", "self", ".", "restore", ")", ")", "]", "return", "not_clone_url", "+", "restore_url", "+", "super", "(", "VersionedAdmin", ",", "self", ")", ".", "get_urls", "(", ")" ]
Sort collection .
async def sort ( self , request , reverse = False ) : return sorted ( self . collection , key = lambda o : getattr ( o , self . columns_sort , 0 ) , reverse = reverse )
7,219
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L152-L155
[ "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" ]
Base point load resource .
async def get_form ( self , request ) : if not self . form : return None formdata = await request . post ( ) return self . form ( formdata , obj = self . resource )
7,220
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L161-L166
[ "def", "setMaxDaysBack", "(", "self", ",", "maxDaysBack", ")", ":", "assert", "isinstance", "(", "maxDaysBack", ",", "int", ")", ",", "\"maxDaysBack value has to be a positive integer\"", "assert", "maxDaysBack", ">=", "1", "self", ".", "topicPage", "[", "\"maxDaysBack\"", "]", "=", "maxDaysBack" ]
Get collection of resources .
async def get ( self , request ) : form = await self . get_form ( request ) ctx = dict ( active = self , form = form , request = request ) if self . resource : return self . app . ps . jinja2 . render ( self . template_item , * * ctx ) return self . app . ps . jinja2 . render ( self . template_list , * * ctx )
7,221
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L184-L190
[ "def", "configure", "(", "self", ",", "organization", ",", "base_url", "=", "''", ",", "ttl", "=", "''", ",", "max_ttl", "=", "''", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'organization'", ":", "organization", ",", "'base_url'", ":", "base_url", ",", "'ttl'", ":", "ttl", ",", "'max_ttl'", ":", "max_ttl", ",", "}", "api_path", "=", "'/v1/auth/{mount_point}/config'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Decorator to mark a function as columns formatter .
def columns_formatter ( cls , colname ) : def wrapper ( func ) : cls . columns_formatters [ colname ] = func return func return wrapper
7,222
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L202-L207
[ "def", "secret_file", "(", "filename", ")", ":", "filestat", "=", "os", ".", "stat", "(", "abspath", "(", "filename", ")", ")", "if", "stat", ".", "S_ISREG", "(", "filestat", ".", "st_mode", ")", "==", "0", "and", "stat", ".", "S_ISLNK", "(", "filestat", ".", "st_mode", ")", "==", "0", ":", "e_msg", "=", "\"Secret file %s must be a real file or symlink\"", "%", "filename", "raise", "aomi", ".", "exceptions", ".", "AomiFile", "(", "e_msg", ")", "if", "platform", ".", "system", "(", ")", "!=", "\"Windows\"", ":", "if", "filestat", ".", "st_mode", "&", "stat", ".", "S_IROTH", "or", "filestat", ".", "st_mode", "&", "stat", ".", "S_IWOTH", "or", "filestat", ".", "st_mode", "&", "stat", ".", "S_IWGRP", ":", "e_msg", "=", "\"Secret file %s has too loose permissions\"", "%", "filename", "raise", "aomi", ".", "exceptions", ".", "AomiFile", "(", "e_msg", ")" ]
Render value .
def render_value ( self , data , column ) : renderer = self . columns_formatters . get ( column , format_value ) return renderer ( self , data , column )
7,223
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L209-L212
[ "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" ]
Dict of all environment variables that will be run with this command .
def env ( self ) : env_vars = os . environ . copy ( ) env_vars . update ( self . _env ) new_path = ":" . join ( self . _paths + [ env_vars [ "PATH" ] ] if "PATH" in env_vars else [ ] + self . _paths ) env_vars [ "PATH" ] = new_path for env_var in self . _env_drop : if env_var in env_vars : del env_vars [ env_var ] return env_vars
7,224
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L72-L85
[ "def", "add_reference", "(", "self", ",", "source", ",", "target", ",", "*", "*", "kwargs", ")", ":", "# Tweak keyword arguments for addReference", "addRef_kw", "=", "kwargs", ".", "copy", "(", ")", "addRef_kw", ".", "setdefault", "(", "\"referenceClass\"", ",", "self", ".", "referenceClass", ")", "if", "\"schema\"", "in", "addRef_kw", ":", "del", "addRef_kw", "[", "\"schema\"", "]", "uid", "=", "api", ".", "get_uid", "(", "target", ")", "rc", "=", "api", ".", "get_tool", "(", "\"reference_catalog\"", ")", "# throws IndexError if uid is invalid", "rc", ".", "addReference", "(", "source", ",", "uid", ",", "self", ".", "relationship", ",", "*", "*", "addRef_kw", ")", "# link the version of the reference", "self", ".", "link_version", "(", "source", ",", "target", ")" ]
Return new command object that will not raise an exception when return code > 0 .
def ignore_errors ( self ) : new_command = copy . deepcopy ( self ) new_command . _ignore_errors = True return new_command
7,225
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L87-L94
[ "async", "def", "write_request", "(", "self", ",", "method", ":", "constants", ".", "HttpRequestMethod", ",", "*", ",", "uri", ":", "str", "=", "\"/\"", ",", "authority", ":", "Optional", "[", "str", "]", "=", "None", ",", "scheme", ":", "Optional", "[", "str", "]", "=", "None", ",", "headers", ":", "Optional", "[", "_HeaderType", "]", "=", "None", ")", "->", "\"writers.HttpRequestWriter\"", ":", "return", "await", "self", ".", "_delegate", ".", "write_request", "(", "method", ",", "uri", "=", "uri", ",", "authority", "=", "authority", ",", "scheme", "=", "scheme", ",", "headers", "=", "headers", ")" ]
Return new Command object that will be run with additional environment variables .
def with_env ( self , * * environment_variables ) : new_env_vars = { str ( var ) : str ( val ) for var , val in environment_variables . items ( ) } new_command = copy . deepcopy ( self ) new_command . _env . update ( new_env_vars ) return new_command
7,226
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L115-L129
[ "def", "partition", "(", "self", ")", ":", "if", "self", ".", "urltype", "!=", "'partition'", ":", "return", "None", "return", "self", ".", "_bundle", ".", "library", ".", "partition", "(", "self", ".", "url", ")" ]
Return new Command object that will drop a specified environment variable if it is set .
def without_env ( self , environment_variable ) : new_command = copy . deepcopy ( self ) new_command . _env_drop . append ( str ( environment_variable ) ) return new_command
7,227
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L131-L140
[ "def", "write_adj_list", "(", "self", ",", "path", ":", "str", ")", "->", "None", ":", "adj_list", "=", "self", ".", "get_adjlist", "(", ")", "with", "open", "(", "path", ",", "mode", "=", "\"w\"", ")", "as", "file", ":", "for", "i", ",", "line", "in", "enumerate", "(", "adj_list", ")", ":", "print", "(", "i", ",", "*", "line", ",", "file", "=", "file", ")" ]
Return new Command object that will be run in specified directory .
def in_dir ( self , directory ) : new_command = copy . deepcopy ( self ) new_command . _directory = str ( directory ) return new_command
7,228
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L142-L151
[ "def", "replace_nan", "(", "trainingset", ",", "replace_with", "=", "None", ")", ":", "# if replace_with = None, replaces with mean value", "training_data", "=", "np", ".", "array", "(", "[", "instance", ".", "features", "for", "instance", "in", "trainingset", "]", ")", ".", "astype", "(", "np", ".", "float64", ")", "def", "encoder", "(", "dataset", ")", ":", "for", "instance", "in", "dataset", ":", "instance", ".", "features", "=", "instance", ".", "features", ".", "astype", "(", "np", ".", "float64", ")", "if", "np", ".", "sum", "(", "np", ".", "isnan", "(", "instance", ".", "features", ")", ")", ":", "if", "replace_with", "==", "None", ":", "instance", ".", "features", "[", "np", ".", "isnan", "(", "instance", ".", "features", ")", "]", "=", "means", "[", "np", ".", "isnan", "(", "instance", ".", "features", ")", "]", "else", ":", "instance", ".", "features", "[", "np", ".", "isnan", "(", "instance", ".", "features", ")", "]", "=", "replace_with", "return", "dataset", "#end", "if", "replace_nan_with", "==", "None", ":", "means", "=", "np", ".", "mean", "(", "np", ".", "nan_to_num", "(", "training_data", ")", ",", "axis", "=", "0", ")", "return", "encoder" ]
Return new Command object that will be run using shell .
def with_shell ( self ) : new_command = copy . deepcopy ( self ) new_command . _shell = True return new_command
7,229
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L153-L159
[ "def", "_str_to_ord", "(", "content", ",", "weights", ")", ":", "ordinal", "=", "0", "for", "i", ",", "c", "in", "enumerate", "(", "content", ")", ":", "ordinal", "+=", "weights", "[", "i", "]", "*", "_ALPHABET", ".", "index", "(", "c", ")", "+", "1", "return", "ordinal" ]
Return new Command object that will be run with specified trailing arguments .
def with_trailing_args ( self , * arguments ) : new_command = copy . deepcopy ( self ) new_command . _trailing_args = [ str ( arg ) for arg in arguments ] return new_command
7,230
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L161-L168
[ "def", "add_bonus", "(", "worker_dict", ")", ":", "try", ":", "unique_id", "=", "'{}:{}'", ".", "format", "(", "worker_dict", "[", "'workerId'", "]", ",", "worker_dict", "[", "'assignmentId'", "]", ")", "worker", "=", "Participant", ".", "query", ".", "filter", "(", "Participant", ".", "uniqueid", "==", "unique_id", ")", ".", "one", "(", ")", "worker_dict", "[", "'bonus'", "]", "=", "worker", ".", "bonus", "except", "sa", ".", "exc", ".", "InvalidRequestError", ":", "# assignment is found on mturk but not in local database.", "worker_dict", "[", "'bonus'", "]", "=", "'N/A'", "return", "worker_dict" ]
Return new Command object that will be run with a new addition to the PATH environment variable that will be fed to the command .
def with_path ( self , path ) : new_command = copy . deepcopy ( self ) new_command . _paths . append ( str ( path ) ) return new_command
7,231
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L170-L177
[ "def", "_sendMessage", "(", "self", ",", "msg", ")", ":", "if", "not", "msg", ":", "return", "msg", "=", "self", ".", "_collapseMsg", "(", "msg", ")", "self", ".", "sendStatus", "(", "msg", ")" ]
Run command and return pexpect process object .
def pexpect ( self ) : import pexpect assert not self . _ignore_errors _check_directory ( self . directory ) arguments = self . arguments return pexpect . spawn ( arguments [ 0 ] , args = arguments [ 1 : ] , env = self . env , cwd = self . directory )
7,232
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L203-L219
[ "def", "ensure_indexes", "(", "self", ")", ":", "for", "collection_name", "in", "INDEXES", ":", "existing_indexes", "=", "self", ".", "indexes", "(", "collection_name", ")", "indexes", "=", "INDEXES", "[", "collection_name", "]", "for", "index", "in", "indexes", ":", "index_name", "=", "index", ".", "document", ".", "get", "(", "'name'", ")", "if", "index_name", "in", "existing_indexes", ":", "logger", ".", "debug", "(", "\"Index exists: %s\"", "%", "index_name", ")", "self", ".", "db", "[", "collection_name", "]", ".", "drop_index", "(", "index_name", ")", "logger", ".", "info", "(", "\"creating indexes for collection {0}: {1}\"", ".", "format", "(", "collection_name", ",", "', '", ".", "join", "(", "[", "index", ".", "document", ".", "get", "(", "'name'", ")", "for", "index", "in", "indexes", "]", ")", ",", ")", ")", "self", ".", "db", "[", "collection_name", "]", ".", "create_indexes", "(", "indexes", ")" ]
Run command and wait until it finishes .
def run ( self ) : _check_directory ( self . directory ) with DirectoryContextManager ( self . directory ) : process = subprocess . Popen ( self . arguments , shell = self . _shell , env = self . env ) _ , _ = process . communicate ( ) returncode = process . returncode if returncode != 0 and not self . _ignore_errors : raise CommandError ( '"{0}" failed (err code {1})' . format ( self . __repr__ ( ) , returncode ) )
7,233
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L221-L235
[ "def", "merge_config", "(", "self", ",", "user_config", ")", ":", "# provisioanlly update the default configurations with the user preferences", "temp_data_config", "=", "copy", ".", "deepcopy", "(", "self", ".", "data_config", ")", ".", "update", "(", "user_config", ")", "temp_model_config", "=", "copy", ".", "deepcopy", "(", "self", ".", "model_config", ")", ".", "update", "(", "user_config", ")", "temp_conversation_config", "=", "copy", ".", "deepcopy", "(", "self", ".", "conversation_config", ")", ".", "update", "(", "user_config", ")", "# if the new configurations validate, apply them", "if", "validate_data_config", "(", "temp_data_config", ")", ":", "self", ".", "data_config", "=", "temp_data_config", "if", "validate_model_config", "(", "temp_model_config", ")", ":", "self", ".", "model_config", "=", "temp_model_config", "if", "validate_conversation_config", "(", "temp_conversation_config", ")", ":", "self", ".", "conversation_config", "=", "temp_conversation_config" ]
This calcfunction will take a CifData node attempt to create a StructureData object from it using the parse_engine and pass it through SeeKpath to try and get the primitive cell . Finally it will store several keys from the SeeKpath output parameters dictionary directly on the structure data as attributes which are otherwise difficult if not impossible to query for .
def primitive_structure_from_cif ( cif , parse_engine , symprec , site_tolerance ) : CifCleanWorkChain = WorkflowFactory ( 'codtools.cif_clean' ) # pylint: disable=invalid-name try : structure = cif . get_structure ( converter = parse_engine . value , site_tolerance = site_tolerance , store = False ) except exceptions . UnsupportedSpeciesError : return CifCleanWorkChain . exit_codes . ERROR_CIF_HAS_UNKNOWN_SPECIES except InvalidOccupationsError : return CifCleanWorkChain . exit_codes . ERROR_CIF_HAS_INVALID_OCCUPANCIES except Exception : # pylint: disable=broad-except return CifCleanWorkChain . exit_codes . ERROR_CIF_STRUCTURE_PARSING_FAILED try : seekpath_results = get_kpoints_path ( structure , symprec = symprec ) except ValueError : return CifCleanWorkChain . exit_codes . ERROR_SEEKPATH_INCONSISTENT_SYMMETRY except SymmetryDetectionError : return CifCleanWorkChain . exit_codes . ERROR_SEEKPATH_SYMMETRY_DETECTION_FAILED # Store important information that should be easily queryable as attributes in the StructureData parameters = seekpath_results [ 'parameters' ] . get_dict ( ) structure = seekpath_results [ 'primitive_structure' ] for key in [ 'spacegroup_international' , 'spacegroup_number' , 'bravais_lattice' , 'bravais_lattice_extended' ] : try : value = parameters [ key ] structure . set_extra ( key , value ) except KeyError : pass # Store the formula as a string, in both hill as well as hill-compact notation, so it can be easily queried for structure . set_extra ( 'formula_hill' , structure . get_formula ( mode = 'hill' ) ) structure . set_extra ( 'formula_hill_compact' , structure . get_formula ( mode = 'hill_compact' ) ) structure . set_extra ( 'chemical_system' , '-{}-' . format ( '-' . join ( sorted ( structure . get_symbols_set ( ) ) ) ) ) return structure
7,234
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/functions/primitive_structure_from_cif.py#L14-L62
[ "def", "merge_ownership_periods", "(", "mappings", ")", ":", "return", "valmap", "(", "lambda", "v", ":", "tuple", "(", "OwnershipPeriod", "(", "a", ".", "start", ",", "b", ".", "start", ",", "a", ".", "sid", ",", "a", ".", "value", ",", ")", "for", "a", ",", "b", "in", "sliding_window", "(", "2", ",", "concatv", "(", "sorted", "(", "v", ")", ",", "# concat with a fake ownership object to make the last", "# end date be max timestamp", "[", "OwnershipPeriod", "(", "pd", ".", "Timestamp", ".", "max", ".", "tz_localize", "(", "'utc'", ")", ",", "None", ",", "None", ",", "None", ",", ")", "]", ",", ")", ",", ")", ")", ",", "mappings", ",", ")" ]
List Mimetypes that current object can export to
def export_capacities ( self ) : return [ export for cls in getmro ( type ( self ) ) if hasattr ( cls , "EXPORT_TO" ) for export in cls . EXPORT_TO ]
7,235
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/base.py#L21-L24
[ "def", "sendCommand", "(", "self", ",", "command", ")", ":", "data", "=", "{", "'rapi'", ":", "command", "}", "full_url", "=", "self", ".", "url", "+", "urllib", ".", "parse", ".", "urlencode", "(", "data", ")", "data", "=", "urllib", ".", "request", ".", "urlopen", "(", "full_url", ")", "response", "=", "re", ".", "search", "(", "'\\<p>&gt;\\$(.+)\\<script'", ",", "data", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "if", "response", "==", "None", ":", "#If we are using version 1 - https://github.com/OpenEVSE/ESP8266_WiFi_v1.x/blob/master/OpenEVSE_RAPI_WiFi_ESP8266.ino#L357", "response", "=", "re", ".", "search", "(", "'\\>\\>\\$(.+)\\<p>'", ",", "data", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "return", "response", ".", "group", "(", "1", ")", ".", "split", "(", ")" ]
Converts a set of boolean - valued options into the relevant HTTP values .
def _filter_options ( self , aliases = True , comments = True , historical = True ) : options = [ ] if not aliases : options . append ( 'noaliases' ) if not comments : options . append ( 'nocomments' ) if not historical : options . append ( 'nohistorical' ) return options
7,236
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L109-L118
[ "def", "synchronize", "(", "lock", ",", "func", ",", "log_duration_secs", "=", "0", ")", ":", "def", "newfunc", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Execute function synchronized.\"\"\"", "t", "=", "time", ".", "time", "(", ")", "with", "lock", ":", "duration", "=", "time", ".", "time", "(", ")", "-", "t", "if", "duration", ">", "log_duration_secs", ">", "0", ":", "print", "(", "\"WARN:\"", ",", "func", ".", "__name__", ",", "\"locking took %0.2f seconds\"", "%", "duration", ",", "file", "=", "sys", ".", "stderr", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "update_func_meta", "(", "newfunc", ",", "func", ")" ]
Generically shared HTTP request method .
def _request ( self , path , key , data , method , key_is_cik , extra_headers = { } ) : if method == 'GET' : if len ( data ) > 0 : url = path + '?' + data else : url = path body = None else : url = path body = data headers = { } if key_is_cik : headers [ 'X-Exosite-CIK' ] = key else : headers [ 'X-Exosite-Token' ] = key if method == 'POST' : headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded; charset=utf-8' headers [ 'Accept' ] = 'text/plain, text/csv, application/x-www-form-urlencoded' headers . update ( extra_headers ) body , response = self . _onephttp . request ( method , url , body , headers ) pr = ProvisionResponse ( body , response ) if self . _raise_api_exceptions and not pr . isok : raise ProvisionException ( pr ) return pr
7,237
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L120-L162
[ "def", "GetEntries", "(", "self", ",", "parser_mediator", ",", "match", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "stores", "=", "match", ".", "get", "(", "'Stores'", ",", "{", "}", ")", "for", "volume_name", ",", "volume", "in", "iter", "(", "stores", ".", "items", "(", ")", ")", ":", "datetime_value", "=", "volume", ".", "get", "(", "'CreationDate'", ",", "None", ")", "if", "not", "datetime_value", ":", "continue", "partial_path", "=", "volume", "[", "'PartialPath'", "]", "event_data", "=", "plist_event", ".", "PlistTimeEventData", "(", ")", "event_data", ".", "desc", "=", "'Spotlight Volume {0:s} ({1:s}) activated.'", ".", "format", "(", "volume_name", ",", "partial_path", ")", "event_data", ".", "key", "=", "''", "event_data", ".", "root", "=", "'/Stores'", "event", "=", "time_events", ".", "PythonDatetimeEvent", "(", "datetime_value", ",", "definitions", ".", "TIME_DESCRIPTION_WRITTEN", ")", "parser_mediator", ".", "ProduceEventWithEventData", "(", "event", ",", "event_data", ")" ]
Creates a content entity bucket with the given contentid .
def content_create ( self , key , model , contentid , meta , protected = False ) : params = { 'id' : contentid , 'meta' : meta } if protected is not False : params [ 'protected' ] = 'true' data = urlencode ( params ) path = PROVISION_MANAGE_CONTENT + model + '/' return self . _request ( path , key , data , 'POST' , self . _manage_by_cik )
7,238
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L172-L191
[ "def", "disable_paging", "(", "self", ",", "command", "=", "\"pager off\"", ",", "delay_factor", "=", "1", ")", ":", "return", "super", "(", "PluribusSSH", ",", "self", ")", ".", "disable_paging", "(", "command", "=", "command", ",", "delay_factor", "=", "delay_factor", ")" ]
Returns the list of content IDs for a given model .
def content_list ( self , key , model ) : path = PROVISION_MANAGE_CONTENT + model + '/' return self . _request ( path , key , '' , 'GET' , self . _manage_by_cik )
7,239
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L237-L248
[ "def", "trace_integration", "(", "tracer", "=", "None", ")", ":", "log", ".", "info", "(", "'Integrated module: {}'", ".", "format", "(", "MODULE_NAME", ")", ")", "# Wrap the httplib request function", "request_func", "=", "getattr", "(", "httplib", ".", "HTTPConnection", ",", "HTTPLIB_REQUEST_FUNC", ")", "wrapped_request", "=", "wrap_httplib_request", "(", "request_func", ")", "setattr", "(", "httplib", ".", "HTTPConnection", ",", "request_func", ".", "__name__", ",", "wrapped_request", ")", "# Wrap the httplib response function", "response_func", "=", "getattr", "(", "httplib", ".", "HTTPConnection", ",", "HTTPLIB_RESPONSE_FUNC", ")", "wrapped_response", "=", "wrap_httplib_response", "(", "response_func", ")", "setattr", "(", "httplib", ".", "HTTPConnection", ",", "response_func", ".", "__name__", ",", "wrapped_response", ")" ]
Deletes the information for the given contentid under the given model .
def content_remove ( self , key , model , contentid ) : path = PROVISION_MANAGE_CONTENT + model + '/' + contentid return self . _request ( path , key , '' , 'DELETE' , self . _manage_by_cik )
7,240
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L250-L261
[ "def", "sync_auth", "(", "self", ",", "vault_client", ",", "resources", ")", ":", "for", "auth", "in", "self", ".", "auths", "(", ")", ":", "auth", ".", "sync", "(", "vault_client", ")", "auth_resources", "=", "[", "x", "for", "x", "in", "resources", "if", "isinstance", "(", "x", ",", "(", "LDAP", ",", "UserPass", ")", ")", "]", "for", "resource", "in", "auth_resources", ":", "resource", ".", "sync", "(", "vault_client", ")", "return", "[", "x", "for", "x", "in", "resources", "if", "not", "isinstance", "(", "x", ",", "(", "LDAP", ",", "UserPass", ",", "AuditLog", ")", ")", "]" ]
Store the given data as a result of a query for content id given the model .
def content_upload ( self , key , model , contentid , data , mimetype ) : headers = { "Content-Type" : mimetype } path = PROVISION_MANAGE_CONTENT + model + '/' + contentid return self . _request ( path , key , data , 'POST' , self . _manage_by_cik , headers )
7,241
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/provision.py#L263-L278
[ "def", "_check_rest_version", "(", "self", ",", "version", ")", ":", "version", "=", "str", "(", "version", ")", "if", "version", "not", "in", "self", ".", "supported_rest_versions", ":", "msg", "=", "\"Library is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "array_rest_versions", "=", "self", ".", "_list_available_rest_versions", "(", ")", "if", "version", "not", "in", "array_rest_versions", ":", "msg", "=", "\"Array is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "return", "LooseVersion", "(", "version", ")" ]
Assert the absolute URL of the browser is as provided .
def url_should_be ( self , url ) : if world . browser . current_url != url : raise AssertionError ( "Browser URL expected to be {!r}, got {!r}." . format ( url , world . browser . current_url ) )
7,242
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L75-L81
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
Assert the absolute URL of the browser contains the provided .
def url_should_contain ( self , url ) : if url not in world . browser . current_url : raise AssertionError ( "Browser URL expected to contain {!r}, got {!r}." . format ( url , world . browser . current_url ) )
7,243
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L86-L92
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
Assert the absolute URL of the browser does not contain the provided .
def url_should_not_contain ( self , url ) : if url in world . browser . current_url : raise AssertionError ( "Browser URL expected not to contain {!r}, got {!r}." . format ( url , world . browser . current_url ) )
7,244
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L97-L103
[ "def", "_read_footer", "(", "file_obj", ")", ":", "footer_size", "=", "_get_footer_size", "(", "file_obj", ")", "if", "logger", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "logger", ".", "debug", "(", "\"Footer size in bytes: %s\"", ",", "footer_size", ")", "file_obj", ".", "seek", "(", "-", "(", "8", "+", "footer_size", ")", ",", "2", ")", "# seek to beginning of footer", "tin", "=", "TFileTransport", "(", "file_obj", ")", "pin", "=", "TCompactProtocolFactory", "(", ")", ".", "get_protocol", "(", "tin", ")", "fmd", "=", "parquet_thrift", ".", "FileMetaData", "(", ")", "fmd", ".", "read", "(", "pin", ")", "return", "fmd" ]
Assert the page title matches the given text .
def page_title ( self , title ) : if world . browser . title != title : raise AssertionError ( "Page title expected to be {!r}, got {!r}." . format ( title , world . browser . title ) )
7,245
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L109-L117
[ "def", "_check_rest_version", "(", "self", ",", "version", ")", ":", "version", "=", "str", "(", "version", ")", "if", "version", "not", "in", "self", ".", "supported_rest_versions", ":", "msg", "=", "\"Library is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "array_rest_versions", "=", "self", ".", "_list_available_rest_versions", "(", ")", "if", "version", "not", "in", "array_rest_versions", ":", "msg", "=", "\"Array is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "return", "LooseVersion", "(", "version", ")" ]
Click the link with the provided link text .
def click ( self , name ) : try : elem = world . browser . find_element_by_link_text ( name ) except NoSuchElementException : raise AssertionError ( "Cannot find the link with text '{}'." . format ( name ) ) elem . click ( )
7,246
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L125-L132
[ "def", "_unpack_headers", "(", "self", ",", "headers", ")", ":", "return", "dict", "(", "(", "k", ",", "v", "[", "0", "]", ")", "for", "(", "k", ",", "v", ")", "in", "headers", ".", "getAllRawHeaders", "(", ")", ")" ]
Assert a link with the provided URL is visible on the page .
def should_see_link ( self , link_url ) : elements = ElementSelector ( world . browser , str ( '//a[@href="%s"]' % link_url ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected link not found." )
7,247
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L137-L146
[ "def", "picard_reorder", "(", "picard", ",", "in_bam", ",", "ref_file", ",", "out_file", ")", ":", "if", "not", "file_exists", "(", "out_file", ")", ":", "with", "tx_tmpdir", "(", "picard", ".", "_config", ")", "as", "tmp_dir", ":", "with", "file_transaction", "(", "picard", ".", "_config", ",", "out_file", ")", "as", "tx_out_file", ":", "opts", "=", "[", "(", "\"INPUT\"", ",", "in_bam", ")", ",", "(", "\"OUTPUT\"", ",", "tx_out_file", ")", ",", "(", "\"REFERENCE\"", ",", "ref_file", ")", ",", "(", "\"ALLOW_INCOMPLETE_DICT_CONCORDANCE\"", ",", "\"true\"", ")", ",", "(", "\"TMP_DIR\"", ",", "tmp_dir", ")", "]", "picard", ".", "run", "(", "\"ReorderSam\"", ",", "opts", ")", "return", "out_file" ]
Assert a link with the provided text points to the provided URL .
def should_see_link_text ( self , link_text , link_url ) : elements = ElementSelector ( world . browser , str ( '//a[@href="%s"][./text()="%s"]' % ( link_url , link_text ) ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected link not found." )
7,248
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L152-L161
[ "def", "_unpack_headers", "(", "self", ",", "headers", ")", ":", "return", "dict", "(", "(", "k", ",", "v", "[", "0", "]", ")", "for", "(", "k", ",", "v", ")", "in", "headers", ".", "getAllRawHeaders", "(", ")", ")" ]
Assert a link containing the provided text points to the provided URL .
def should_include_link_text ( self , link_text , link_url ) : elements = ElementSelector ( world . browser , str ( '//a[@href="%s"][contains(., %s)]' % ( link_url , string_literal ( link_text ) ) ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected link not found." )
7,249
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L169-L181
[ "def", "_unpack_headers", "(", "self", ",", "headers", ")", ":", "return", "dict", "(", "(", "k", ",", "v", "[", "0", "]", ")", "for", "(", "k", ",", "v", ")", "in", "headers", ".", "getAllRawHeaders", "(", ")", ")" ]
Assert provided content is contained within an element found by id .
def element_contains ( self , element_id , value ) : elements = ElementSelector ( world . browser , str ( 'id("{id}")[contains(., "{value}")]' . format ( id = element_id , value = value ) ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected element not found." )
7,250
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L190-L202
[ "def", "import_file", "(", "filename", ")", ":", "#file_path = os.path.relpath(filename)", "file_path", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "log", "(", "DEBUG", ",", "\"Loading prices from %s\"", ",", "file_path", ")", "prices", "=", "__read_prices_from_file", "(", "file_path", ")", "with", "BookAggregate", "(", "for_writing", "=", "True", ")", "as", "svc", ":", "svc", ".", "prices", ".", "import_prices", "(", "prices", ")", "print", "(", "\"Saving book...\"", ")", "svc", ".", "book", ".", "save", "(", ")" ]
Assert provided content is not contained within an element found by id .
def element_not_contains ( self , element_id , value ) : elem = world . browser . find_elements_by_xpath ( str ( 'id("{id}")[contains(., "{value}")]' . format ( id = element_id , value = value ) ) ) assert not elem , "Expected element not to contain the given text."
7,251
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L208-L216
[ "def", "_set_config_keystone", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "_keystone_auth", "=", "KeystoneAuth", "(", "settings", ".", "KEYSTONE_AUTH_URL", ",", "settings", ".", "KEYSTONE_PROJECT_NAME", ",", "username", ",", "password", ",", "settings", ".", "KEYSTONE_USER_DOMAIN_NAME", ",", "settings", ".", "KEYSTONE_PROJECT_DOMAIN_NAME", ",", "settings", ".", "KEYSTONE_TIMEOUT", ")" ]
Assert an element with the given id is visible within n seconds .
def should_see_id_in_seconds ( self , element_id , timeout ) : def check_element ( ) : """Check for the element with the given id.""" assert ElementSelector ( world . browser , 'id("%s")' % element_id , filter_displayed = True , ) , "Expected element with given id." wait_for ( check_element ) ( timeout = int ( timeout ) )
7,252
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L220-L234
[ "def", "create_meta_main", "(", "create_path", ",", "config", ",", "role", ",", "categories", ")", ":", "meta_file", "=", "c", ".", "DEFAULT_META_FILE", ".", "replace", "(", "\"%author_name\"", ",", "config", "[", "\"author_name\"", "]", ")", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%author_company\"", ",", "config", "[", "\"author_company\"", "]", ")", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%license_type\"", ",", "config", "[", "\"license_type\"", "]", ")", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%role_name\"", ",", "role", ")", "# Normalize the category so %categories always gets replaced.", "if", "not", "categories", ":", "categories", "=", "\"\"", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%categories\"", ",", "categories", ")", "string_to_file", "(", "create_path", ",", "meta_file", ")" ]
Assert an element with the given id is visible .
def should_see_id ( self , element_id ) : elements = ElementSelector ( world . browser , 'id("%s")' % element_id , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected element with given id." )
7,253
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L239-L250
[ "def", "_updateVariantAnnotationSets", "(", "self", ",", "variantFile", ",", "dataUrl", ")", ":", "# TODO check the consistency of this between VCF files.", "if", "not", "self", ".", "isAnnotated", "(", ")", ":", "annotationType", "=", "None", "for", "record", "in", "variantFile", ".", "header", ".", "records", ":", "if", "record", ".", "type", "==", "\"GENERIC\"", ":", "if", "record", ".", "key", "==", "\"SnpEffVersion\"", ":", "annotationType", "=", "ANNOTATIONS_SNPEFF", "elif", "record", ".", "key", "==", "\"VEP\"", ":", "version", "=", "record", ".", "value", ".", "split", "(", ")", "[", "0", "]", "# TODO we need _much_ more sophisticated processing", "# of VEP versions here. When do they become", "# incompatible?", "if", "version", "==", "\"v82\"", ":", "annotationType", "=", "ANNOTATIONS_VEP_V82", "elif", "version", "==", "\"v77\"", ":", "annotationType", "=", "ANNOTATIONS_VEP_V77", "else", ":", "# TODO raise a proper typed exception there with", "# the file name as an argument.", "raise", "ValueError", "(", "\"Unsupported VEP version {} in '{}'\"", ".", "format", "(", "version", ",", "dataUrl", ")", ")", "if", "annotationType", "is", "None", ":", "infoKeys", "=", "variantFile", ".", "header", ".", "info", ".", "keys", "(", ")", "if", "'CSQ'", "in", "infoKeys", "or", "'ANN'", "in", "infoKeys", ":", "# TODO likewise, we want a properly typed exception that", "# we can throw back to the repo manager UI and display", "# as an import error.", "raise", "ValueError", "(", "\"Unsupported annotations in '{}'\"", ".", "format", "(", "dataUrl", ")", ")", "if", "annotationType", "is", "not", "None", ":", "vas", "=", "HtslibVariantAnnotationSet", "(", "self", ",", "self", ".", "getLocalId", "(", ")", ")", "vas", ".", "populateFromFile", "(", "variantFile", ",", "annotationType", ")", "self", ".", "addVariantAnnotationSet", "(", "vas", ")" ]
Assert the element is focused .
def element_focused ( self , id_ ) : try : elem = world . browser . find_element_by_id ( id_ ) except NoSuchElementException : raise AssertionError ( "Element with ID '{}' not found." . format ( id_ ) ) focused = world . browser . switch_to . active_element # Elements don't have __ne__ defined, cannot test for inequality if not elem == focused : raise AssertionError ( "Expected element to be focused." )
7,254
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L271-L285
[ "def", "load_from_package", "(", ")", ":", "try", ":", "import", "pkg_resources", "f", "=", "pkg_resources", ".", "resource_stream", "(", "meta", ".", "__app__", ",", "'cache/unicategories.cache'", ")", "dversion", ",", "mversion", ",", "data", "=", "pickle", ".", "load", "(", "f", ")", "if", "dversion", "==", "data_version", "and", "mversion", "==", "module_version", ":", "return", "data", "warnings", ".", "warn", "(", "'Unicode unicategories database is outdated. '", "'Please reinstall unicategories module to regenerate it.'", "if", "dversion", "<", "data_version", "else", "'Incompatible unicategories database. '", "'Please reinstall unicategories module to regenerate it.'", ")", "except", "(", "ValueError", ",", "EOFError", ")", ":", "warnings", ".", "warn", "(", "'Incompatible unicategories database. '", "'Please reinstall unicategories module to regenerate it.'", ")", "except", "(", "ImportError", ",", "FileNotFoundError", ")", ":", "pass" ]
Assert provided text is visible within n seconds .
def should_see_in_seconds ( self , text , timeout ) : def check_element ( ) : """Check for an element with the given content.""" assert contains_content ( world . browser , text ) , "Expected element with the given text." wait_for ( check_element ) ( timeout = int ( timeout ) )
7,255
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L312-L327
[ "def", "_handle_request_error", "(", "self", ",", "orig_request", ",", "error", ",", "start_response", ")", ":", "headers", "=", "[", "(", "'Content-Type'", ",", "'application/json'", ")", "]", "status_code", "=", "error", ".", "status_code", "(", ")", "body", "=", "error", ".", "rest_error", "(", ")", "response_status", "=", "'%d %s'", "%", "(", "status_code", ",", "httplib", ".", "responses", ".", "get", "(", "status_code", ",", "'Unknown Error'", ")", ")", "cors_handler", "=", "self", ".", "_create_cors_handler", "(", "orig_request", ")", "return", "util", ".", "send_wsgi_response", "(", "response_status", ",", "headers", ",", "body", ",", "start_response", ",", "cors_handler", "=", "cors_handler", ")" ]
Assert the existence of a HTML form that submits to the given URL .
def see_form ( self , url ) : elements = ElementSelector ( world . browser , str ( '//form[@action="%s"]' % url ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected form not found." )
7,256
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L366-L377
[ "def", "sample", "(", "self", ",", "wavelength", ")", ":", "wave", "=", "self", ".", "waveunits", ".", "Convert", "(", "wavelength", ",", "'angstrom'", ")", "return", "self", "(", "wave", ")" ]
Click the button with the given label .
def press_button ( self , value ) : button = find_button ( world . browser , value ) if not button : raise AssertionError ( "Cannot find a button named '{}'." . format ( value ) ) button . click ( )
7,257
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L440-L448
[ "def", "addNoiseToVector", "(", "inputVector", ",", "noiseLevel", ",", "vectorType", ")", ":", "if", "vectorType", "==", "'sparse'", ":", "corruptSparseVector", "(", "inputVector", ",", "noiseLevel", ")", "elif", "vectorType", "==", "'dense'", ":", "corruptDenseVector", "(", "inputVector", ",", "noiseLevel", ")", "else", ":", "raise", "ValueError", "(", "\"vectorType must be 'sparse' or 'dense' \"", ")" ]
Click on the given label .
def click_on_label ( self , label ) : elem = ElementSelector ( world . browser , str ( '//label[normalize-space(text())=%s]' % string_literal ( label ) ) , filter_displayed = True , ) if not elem : raise AssertionError ( "Cannot find a label with text '{}'." . format ( label ) ) elem . click ( )
7,258
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L454-L469
[ "def", "_mmUpdateDutyCycles", "(", "self", ")", ":", "period", "=", "self", ".", "getDutyCyclePeriod", "(", ")", "unionSDRArray", "=", "numpy", ".", "zeros", "(", "self", ".", "getNumColumns", "(", ")", ")", "unionSDRArray", "[", "list", "(", "self", ".", "_mmTraces", "[", "\"unionSDR\"", "]", ".", "data", "[", "-", "1", "]", ")", "]", "=", "1", "self", ".", "_mmData", "[", "\"unionSDRDutyCycle\"", "]", "=", "UnionTemporalPoolerMonitorMixin", ".", "_mmUpdateDutyCyclesHelper", "(", "self", ".", "_mmData", "[", "\"unionSDRDutyCycle\"", "]", ",", "unionSDRArray", ",", "period", ")", "self", ".", "_mmData", "[", "\"persistenceDutyCycle\"", "]", "=", "UnionTemporalPoolerMonitorMixin", ".", "_mmUpdateDutyCyclesHelper", "(", "self", ".", "_mmData", "[", "\"persistenceDutyCycle\"", "]", ",", "self", ".", "_poolingActivation", ",", "period", ")" ]
Look for a form on the page and submit it .
def submit_the_only_form ( self ) : form = ElementSelector ( world . browser , str ( '//form' ) ) assert form , "Cannot find a form on the page." form . submit ( )
7,259
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L495-L503
[ "def", "get_correlation_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Correlations\"", ",", "label", "=", "\"tab:parameter_correlations\"", ")", ":", "parameters", ",", "cor", "=", "self", ".", "get_correlations", "(", "chain", "=", "chain", ",", "parameters", "=", "parameters", ")", "return", "self", ".", "_get_2d_latex_table", "(", "parameters", ",", "cor", ",", "caption", ",", "label", ")" ]
Assert an alert is showing with the given text .
def check_alert ( self , text ) : try : alert = Alert ( world . browser ) if alert . text != text : raise AssertionError ( "Alert text expected to be {!r}, got {!r}." . format ( text , alert . text ) ) except WebDriverException : # PhantomJS is kinda poor pass
7,260
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L762-L775
[ "def", "delete_client", "(", "self", ",", "identifier", ")", ":", "params", "=", "{", "'id'", ":", "identifier", "}", "response", "=", "yield", "from", "self", ".", "_transact", "(", "SERVER_DELETECLIENT", ",", "params", ")", "self", ".", "synchronize", "(", "response", ")" ]
Assert there is no alert .
def check_no_alert ( self ) : try : alert = Alert ( world . browser ) raise AssertionError ( "Should not see an alert. Alert '%s' shown." % alert . text ) except NoAlertPresentException : pass
7,261
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L779-L789
[ "def", "in_64", "(", "library", ",", "session", ",", "space", ",", "offset", ",", "extended", "=", "False", ")", ":", "value_64", "=", "ViUInt64", "(", ")", "if", "extended", ":", "ret", "=", "library", ".", "viIn64Ex", "(", "session", ",", "space", ",", "offset", ",", "byref", "(", "value_64", ")", ")", "else", ":", "ret", "=", "library", ".", "viIn64", "(", "session", ",", "space", ",", "offset", ",", "byref", "(", "value_64", ")", ")", "return", "value_64", ".", "value", ",", "ret" ]
Find elements with the given tooltip .
def find_by_tooltip ( browser , tooltip ) : return ElementSelector ( world . browser , str ( '//*[@title=%(tooltip)s or @data-original-title=%(tooltip)s]' % dict ( tooltip = string_literal ( tooltip ) ) ) , filter_displayed = True , )
7,262
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L794-L809
[ "def", "_ubridge_apply_filters", "(", "self", ",", "adapter_number", ",", "port_number", ",", "filters", ")", ":", "bridge_name", "=", "\"IOL-BRIDGE-{}\"", ".", "format", "(", "self", ".", "application_id", "+", "512", ")", "location", "=", "'{bridge_name} {bay} {unit}'", ".", "format", "(", "bridge_name", "=", "bridge_name", ",", "bay", "=", "adapter_number", ",", "unit", "=", "port_number", ")", "yield", "from", "self", ".", "_ubridge_send", "(", "'iol_bridge reset_packet_filters '", "+", "location", ")", "for", "filter", "in", "self", ".", "_build_filter_list", "(", "filters", ")", ":", "cmd", "=", "'iol_bridge add_packet_filter {} {}'", ".", "format", "(", "location", ",", "filter", ")", "yield", "from", "self", ".", "_ubridge_send", "(", "cmd", ")" ]
Click on a HTML element with a given tooltip .
def press_by_tooltip ( self , tooltip ) : for button in find_by_tooltip ( world . browser , tooltip ) : try : button . click ( ) break except : # pylint:disable=bare-except pass else : raise AssertionError ( "No button with tooltip '{0}' found" . format ( tooltip ) )
7,263
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L840-L854
[ "def", "_readXput", "(", "self", ",", "fileCards", ",", "directory", ",", "session", ",", "spatial", "=", "False", ",", "spatialReferenceID", "=", "4236", ",", "replaceParamFile", "=", "None", ")", ":", "## NOTE: This function is dependent on the project file being read first", "# Read Input/Output Files", "for", "card", "in", "self", ".", "projectCards", ":", "if", "(", "card", ".", "name", "in", "fileCards", ")", "and", "self", ".", "_noneOrNumValue", "(", "card", ".", "value", ")", "and", "fileCards", "[", "card", ".", "name", "]", ":", "fileIO", "=", "fileCards", "[", "card", ".", "name", "]", "filename", "=", "card", ".", "value", ".", "strip", "(", "'\"'", ")", "# Invoke read method on each file", "self", ".", "_invokeRead", "(", "fileIO", "=", "fileIO", ",", "directory", "=", "directory", ",", "filename", "=", "filename", ",", "session", "=", "session", ",", "spatial", "=", "spatial", ",", "spatialReferenceID", "=", "spatialReferenceID", ",", "replaceParamFile", "=", "replaceParamFile", ")" ]
show equations used for the EOS
def print_equations ( self ) : print ( "P_static: " , self . eqn_st ) print ( "P_thermal: " , self . eqn_th ) print ( "P_anharmonic: " , self . eqn_anh ) print ( "P_electronic: " , self . eqn_el )
7,264
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L84-L91
[ "def", "tab_join", "(", "ToMerge", ",", "keycols", "=", "None", ",", "nullvals", "=", "None", ",", "renamer", "=", "None", ",", "returnrenaming", "=", "False", ",", "Names", "=", "None", ")", ":", "[", "Result", ",", "Renaming", "]", "=", "spreadsheet", ".", "join", "(", "ToMerge", ",", "keycols", "=", "keycols", ",", "nullvals", "=", "nullvals", ",", "renamer", "=", "renamer", ",", "returnrenaming", "=", "True", ",", "Names", "=", "Names", ")", "if", "isinstance", "(", "ToMerge", ",", "dict", ")", ":", "Names", "=", "ToMerge", ".", "keys", "(", ")", "else", ":", "Names", "=", "range", "(", "len", "(", "ToMerge", ")", ")", "Colorings", "=", "dict", "(", "[", "(", "k", ",", "ToMerge", "[", "k", "]", ".", "coloring", ")", "if", "'coloring'", "in", "dir", "(", "ToMerge", "[", "k", "]", ")", "else", "{", "}", "for", "k", "in", "Names", "]", ")", "for", "k", "in", "Names", ":", "if", "k", "in", "Renaming", ".", "keys", "(", ")", ":", "l", "=", "ToMerge", "[", "k", "]", "Colorings", "[", "k", "]", "=", "dict", "(", "[", "(", "g", ",", "[", "n", "if", "not", "n", "in", "Renaming", "[", "k", "]", ".", "keys", "(", ")", "else", "Renaming", "[", "k", "]", "[", "n", "]", "for", "n", "in", "l", ".", "coloring", "[", "g", "]", "]", ")", "for", "g", "in", "Colorings", "[", "k", "]", ".", "keys", "(", ")", "]", ")", "Coloring", "=", "{", "}", "for", "k", "in", "Colorings", ".", "keys", "(", ")", ":", "for", "j", "in", "Colorings", "[", "k", "]", ".", "keys", "(", ")", ":", "if", "j", "in", "Coloring", ".", "keys", "(", ")", ":", "Coloring", "[", "j", "]", "=", "utils", ".", "uniqify", "(", "Coloring", "[", "j", "]", "+", "Colorings", "[", "k", "]", "[", "j", "]", ")", "else", ":", "Coloring", "[", "j", "]", "=", "utils", ".", "uniqify", "(", "Colorings", "[", "k", "]", "[", "j", "]", ")", "Result", "=", "Result", ".", "view", "(", "tabarray", ")", "Result", ".", "coloring", "=", "Coloring", "if", "returnrenaming", ":", "return", "[", "Result", ",", "Renaming", "]", "else", ":", "return", "Result" ]
change parameters in OrderedDict to list with or without uncertainties
def _set_params ( self , p ) : if self . force_norm : params = [ value . n for key , value in p . items ( ) ] else : params = [ value for key , value in p . items ( ) ] return params
7,265
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L102-L114
[ "def", "fetcher", "(", "date", "=", "datetime", ".", "today", "(", ")", ",", "url_pattern", "=", "URL_PATTERN", ")", ":", "api_url", "=", "url_pattern", "%", "date", ".", "strftime", "(", "'%Y-%m-%d'", ")", "headers", "=", "{", "'Referer'", ":", "'http://n.pl/program-tv'", "}", "raw_result", "=", "requests", ".", "get", "(", "api_url", ",", "headers", "=", "headers", ")", ".", "json", "(", ")", "return", "raw_result" ]
calculate pressure from electronic contributions
def cal_pel ( self , v , temp ) : if ( self . eqn_el is None ) or ( self . params_el is None ) : return np . zeros_like ( v ) params = self . _set_params ( self . params_el ) return func_el [ self . eqn_el ] ( v , temp , * params , self . n , self . z , t_ref = self . t_ref , three_r = self . three_r )
7,266
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L141-L154
[ "def", "porthistory", "(", "port_number", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "return_format", "=", "None", ")", ":", "uri", "=", "'porthistory/{port}'", ".", "format", "(", "port", "=", "port_number", ")", "if", "not", "start_date", ":", "# default 30 days ago", "start_date", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "30", ")", "try", ":", "uri", "=", "'/'", ".", "join", "(", "[", "uri", ",", "start_date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "]", ")", "except", "AttributeError", ":", "uri", "=", "'/'", ".", "join", "(", "[", "uri", ",", "start_date", "]", ")", "if", "end_date", ":", "try", ":", "uri", "=", "'/'", ".", "join", "(", "[", "uri", ",", "end_date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "]", ")", "except", "AttributeError", ":", "uri", "=", "'/'", ".", "join", "(", "[", "uri", ",", "end_date", "]", ")", "response", "=", "_get", "(", "uri", ",", "return_format", ")", "if", "'bad port number'", "in", "str", "(", "response", ")", ":", "raise", "Error", "(", "'Bad port, {port}'", ".", "format", "(", "port", "=", "port_number", ")", ")", "else", ":", "return", "response" ]
calculate pressure from anharmonic contributions
def cal_panh ( self , v , temp ) : if ( self . eqn_anh is None ) or ( self . params_anh is None ) : return np . zeros_like ( v ) params = self . _set_params ( self . params_anh ) return func_anh [ self . eqn_anh ] ( v , temp , * params , self . n , self . z , t_ref = self . t_ref , three_r = self . three_r )
7,267
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L156-L169
[ "def", "list_keys", "(", "self", ")", ":", "return", "[", "k", "for", "k", ",", "el", "in", "self", ".", "_keystore", ".", "items", "(", ")", "if", "not", "el", ".", "is_expired", "]" ]
calculate Hugoniot temperature
def _hugoniot_t ( self , v ) : rho = self . _get_rho ( v ) params_h = self . _set_params ( self . params_hugoniot ) params_t = self . _set_params ( self . params_therm ) if self . nonlinear : return hugoniot_t ( rho , * params_h [ : - 1 ] , * params_t [ 1 : ] , self . n , self . mass , three_r = self . three_r , c_v = self . c_v ) else : return hugoniot_t ( rho , * params_h , * params_t [ 1 : ] , self . n , self . mass , three_r = self . three_r , c_v = self . c_v )
7,268
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L352-L375
[ "def", "add_parens", "(", "line", ",", "maxline", ",", "indent", ",", "statements", "=", "statements", ",", "count", "=", "count", ")", ":", "if", "line", "[", "0", "]", "in", "statements", ":", "index", "=", "1", "if", "not", "line", "[", "0", "]", ".", "endswith", "(", "' '", ")", ":", "index", "=", "2", "assert", "line", "[", "1", "]", "==", "' '", "line", ".", "insert", "(", "index", ",", "'('", ")", "if", "line", "[", "-", "1", "]", "==", "':'", ":", "line", ".", "insert", "(", "-", "1", ",", "')'", ")", "else", ":", "line", ".", "append", "(", "')'", ")", "# That was the easy stuff. Now for assignments.", "groups", "=", "list", "(", "get_assign_groups", "(", "line", ")", ")", "if", "len", "(", "groups", ")", "==", "1", ":", "# So sad, too bad", "return", "line", "counts", "=", "list", "(", "count", "(", "x", ")", "for", "x", "in", "groups", ")", "didwrap", "=", "False", "# If the LHS is large, wrap it first", "if", "sum", "(", "counts", "[", ":", "-", "1", "]", ")", ">=", "maxline", "-", "indent", "-", "4", ":", "for", "group", "in", "groups", "[", ":", "-", "1", "]", ":", "didwrap", "=", "False", "# Only want to know about last group", "if", "len", "(", "group", ")", ">", "1", ":", "group", ".", "insert", "(", "0", ",", "'('", ")", "group", ".", "insert", "(", "-", "1", ",", "')'", ")", "didwrap", "=", "True", "# Might not need to wrap the RHS if wrapped the LHS", "if", "not", "didwrap", "or", "counts", "[", "-", "1", "]", ">", "maxline", "-", "indent", "-", "10", ":", "groups", "[", "-", "1", "]", ".", "insert", "(", "0", ",", "'('", ")", "groups", "[", "-", "1", "]", ".", "append", "(", "')'", ")", "return", "[", "item", "for", "group", "in", "groups", "for", "item", "in", "group", "]" ]
calculate thermal pressure along hugoniot
def _hugoniot_pth ( self , v ) : temp = self . _hugoniot_t ( v ) return self . cal_pth ( v , temp )
7,269
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L389-L397
[ "def", "clusterstatus", "(", "self", ")", ":", "res", "=", "self", ".", "cluster_status_raw", "(", ")", "cluster", "=", "res", "[", "'cluster'", "]", "[", "'collections'", "]", "out", "=", "{", "}", "try", ":", "for", "collection", "in", "cluster", ":", "out", "[", "collection", "]", "=", "{", "}", "for", "shard", "in", "cluster", "[", "collection", "]", "[", "'shards'", "]", ":", "out", "[", "collection", "]", "[", "shard", "]", "=", "{", "}", "for", "replica", "in", "cluster", "[", "collection", "]", "[", "'shards'", "]", "[", "shard", "]", "[", "'replicas'", "]", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "=", "cluster", "[", "collection", "]", "[", "'shards'", "]", "[", "shard", "]", "[", "'replicas'", "]", "[", "replica", "]", "if", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'state'", "]", "!=", "'active'", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'doc_count'", "]", "=", "False", "else", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'doc_count'", "]", "=", "self", ".", "_get_collection_counts", "(", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "\"Couldn't parse response from clusterstatus API call\"", ")", "self", ".", "logger", ".", "exception", "(", "e", ")", "return", "out" ]
calculate unit - cell volume at given pressure and temperature
def cal_v ( self , p , temp , min_strain = 0.3 , max_strain = 1.0 ) : v0 = self . params_therm [ 'v0' ] . nominal_value self . force_norm = True pp = unp . nominal_values ( p ) ttemp = unp . nominal_values ( temp ) def _cal_v_single ( pp , ttemp ) : if ( pp <= 1.e-5 ) and ( ttemp == 300. ) : return v0 def f_diff ( v , ttemp , pp ) : return self . cal_p ( v , ttemp ) - pp # print(f_diff(v0 * 0.3, temp, p)) v = brenth ( f_diff , v0 * max_strain , v0 * min_strain , args = ( ttemp , pp ) ) return v f_vu = np . vectorize ( _cal_v_single ) v = f_vu ( pp , ttemp ) self . force_norm = False return v
7,270
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L409-L439
[ "def", "encode", "(", "data", ")", ":", "res", "=", "\"\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "3", ")", ":", "if", "(", "i", "+", "2", "==", "len", "(", "data", ")", ")", ":", "res", "+=", "_encode3bytes", "(", "ord", "(", "data", "[", "i", "]", ")", ",", "ord", "(", "data", "[", "i", "+", "1", "]", ")", ",", "0", ")", "elif", "(", "i", "+", "1", "==", "len", "(", "data", ")", ")", ":", "res", "+=", "_encode3bytes", "(", "ord", "(", "data", "[", "i", "]", ")", ",", "0", ",", "0", ")", "else", ":", "res", "+=", "_encode3bytes", "(", "ord", "(", "data", "[", "i", "]", ")", ",", "ord", "(", "data", "[", "i", "+", "1", "]", ")", ",", "ord", "(", "data", "[", "i", "+", "2", "]", ")", ")", "return", "res" ]
Parse path strings into a collection of Intervals .
def parse_intervals ( path , as_context = False ) : def _regions_from_range ( ) : if as_context : ctxs = list ( set ( pf . lines [ start - 1 : stop - 1 ] ) ) return [ ContextInterval ( filename , ctx ) for ctx in ctxs ] else : return [ LineInterval ( filename , start , stop ) ] if ':' in path : path , subpath = path . split ( ':' ) else : subpath = '' pf = PythonFile . from_modulename ( path ) filename = pf . filename rng = NUMBER_RE . match ( subpath ) if rng : # specified a line or line range start , stop = map ( int , rng . groups ( 0 ) ) stop = stop or start + 1 return _regions_from_range ( ) elif not subpath : # asked for entire module if as_context : return [ ContextInterval ( filename , pf . prefix ) ] start , stop = 1 , pf . line_count + 1 return _regions_from_range ( ) else : # specified a context name context = pf . prefix + ':' + subpath if context not in pf . lines : raise ValueError ( "%s is not a valid context for %s" % ( context , pf . prefix ) ) if as_context : return [ ContextInterval ( filename , context ) ] else : start , stop = pf . context_range ( context ) return [ LineInterval ( filename , start , stop ) ]
7,271
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/interval.py#L55-L127
[ "def", "_nodedev_event_lifecycle_cb", "(", "conn", ",", "dev", ",", "event", ",", "detail", ",", "opaque", ")", ":", "_salt_send_event", "(", "opaque", ",", "conn", ",", "{", "'nodedev'", ":", "{", "'name'", ":", "dev", ".", "name", "(", ")", "}", ",", "'event'", ":", "_get_libvirt_enum_string", "(", "'VIR_NODE_DEVICE_EVENT_'", ",", "event", ")", ",", "'detail'", ":", "'unknown'", "# currently unused", "}", ")" ]
Return the rest of the input
def p_suffix ( self , length = None , elipsis = False ) : if length is not None : result = self . input [ self . pos : self . pos + length ] if elipsis and len ( result ) == length : result += "..." return result return self . input [ self . pos : ]
7,272
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L65-L72
[ "def", "GetRendererForValueOrClass", "(", "cls", ",", "value", ",", "limit_lists", "=", "-", "1", ")", ":", "if", "inspect", ".", "isclass", "(", "value", ")", ":", "value_cls", "=", "value", "else", ":", "value_cls", "=", "value", ".", "__class__", "cache_key", "=", "\"%s_%d\"", "%", "(", "value_cls", ".", "__name__", ",", "limit_lists", ")", "try", ":", "renderer_cls", "=", "cls", ".", "_renderers_cache", "[", "cache_key", "]", "except", "KeyError", ":", "candidates", "=", "[", "]", "for", "candidate", "in", "itervalues", "(", "ApiValueRenderer", ".", "classes", ")", ":", "if", "candidate", ".", "value_class", ":", "candidate_class", "=", "candidate", ".", "value_class", "else", ":", "continue", "if", "inspect", ".", "isclass", "(", "value", ")", ":", "if", "issubclass", "(", "value_cls", ",", "candidate_class", ")", ":", "candidates", ".", "append", "(", "(", "candidate", ",", "candidate_class", ")", ")", "else", ":", "if", "isinstance", "(", "value", ",", "candidate_class", ")", ":", "candidates", ".", "append", "(", "(", "candidate", ",", "candidate_class", ")", ")", "if", "not", "candidates", ":", "raise", "RuntimeError", "(", "\"No renderer found for value %s.\"", "%", "value", ".", "__class__", ".", "__name__", ")", "candidates", "=", "sorted", "(", "candidates", ",", "key", "=", "lambda", "candidate", ":", "len", "(", "candidate", "[", "1", "]", ".", "mro", "(", ")", ")", ")", "renderer_cls", "=", "candidates", "[", "-", "1", "]", "[", "0", "]", "cls", ".", "_renderers_cache", "[", "cache_key", "]", "=", "renderer_cls", "return", "renderer_cls", "(", "limit_lists", "=", "limit_lists", ")" ]
Format and print debug messages
def p_debug ( self , message ) : print ( "{}{} `{}`" . format ( self . _debug_indent * " " , message , repr ( self . p_suffix ( 10 ) ) ) )
7,273
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L74-L77
[ "def", "percentile_ranks", "(", "self", ",", "affinities", ",", "allele", "=", "None", ",", "alleles", "=", "None", ",", "throw", "=", "True", ")", ":", "if", "allele", "is", "not", "None", ":", "try", ":", "transform", "=", "self", ".", "allele_to_percent_rank_transform", "[", "allele", "]", "return", "transform", ".", "transform", "(", "affinities", ")", "except", "KeyError", ":", "msg", "=", "\"Allele %s has no percentile rank information\"", "%", "allele", "if", "throw", ":", "raise", "ValueError", "(", "msg", ")", "else", ":", "warnings", ".", "warn", "(", "msg", ")", "# Return NaNs", "return", "numpy", ".", "ones", "(", "len", "(", "affinities", ")", ")", "*", "numpy", ".", "nan", "if", "alleles", "is", "None", ":", "raise", "ValueError", "(", "\"Specify allele or alleles\"", ")", "df", "=", "pandas", ".", "DataFrame", "(", "{", "\"affinity\"", ":", "affinities", "}", ")", "df", "[", "\"allele\"", "]", "=", "alleles", "df", "[", "\"result\"", "]", "=", "numpy", ".", "nan", "for", "(", "allele", ",", "sub_df", ")", "in", "df", ".", "groupby", "(", "\"allele\"", ")", ":", "df", ".", "loc", "[", "sub_df", ".", "index", ",", "\"result\"", "]", "=", "self", ".", "percentile_ranks", "(", "sub_df", ".", "affinity", ",", "allele", "=", "allele", ",", "throw", "=", "throw", ")", "return", "df", ".", "result", ".", "values" ]
Consume and return the next char
def p_next ( self ) : try : self . pos += 1 return self . input [ self . pos - 1 ] except IndexError : self . pos -= 1 return None
7,274
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L86-L93
[ "def", "create_dirs", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_path", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_path", ")", "for", "dir_name", "in", "[", "self", ".", "OBJ_DIR", ",", "self", ".", "TMP_OBJ_DIR", ",", "self", ".", "PKG_DIR", ",", "self", ".", "CACHE_DIR", "]", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "dir_name", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "mkdir", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_version_path", "(", ")", ")", ":", "self", ".", "_write_format_version", "(", ")" ]
Return currnet column in line
def p_current_col ( self ) : prefix = self . input [ : self . pos ] nlidx = prefix . rfind ( '\n' ) if nlidx == - 1 : return self . pos return self . pos - nlidx
7,275
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L116-L122
[ "def", "export_comps", "(", "request", ")", ":", "in_memory", "=", "BytesIO", "(", ")", "zip", "=", "ZipFile", "(", "in_memory", ",", "\"a\"", ")", "comps", "=", "settings", ".", "COMPS_DIR", "static", "=", "settings", ".", "STATIC_ROOT", "or", "\"\"", "context", "=", "RequestContext", "(", "request", ",", "{", "}", ")", "context", "[", "'debug'", "]", "=", "False", "# dump static resources", "# TODO: inspect each template and only pull in resources that are used", "for", "dirname", ",", "dirs", ",", "filenames", "in", "os", ".", "walk", "(", "static", ")", ":", "for", "filename", "in", "filenames", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "filename", ")", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "static", ")", "content", "=", "open", "(", "full_path", ",", "'rb'", ")", ".", "read", "(", ")", "try", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "except", "IndexError", ":", "pass", "if", "ext", "==", "'.css'", ":", "# convert static refs to relative links", "dotted_rel", "=", "os", ".", "path", ".", "relpath", "(", "static", ",", "full_path", ")", "new_rel_path", "=", "'{0}{1}'", ".", "format", "(", "dotted_rel", ",", "'/static'", ")", "content", "=", "content", ".", "replace", "(", "b'/static'", ",", "bytes", "(", "new_rel_path", ",", "'utf8'", ")", ")", "path", "=", "os", ".", "path", ".", "join", "(", "'static'", ",", "rel_path", ")", "zip", ".", "writestr", "(", "path", ",", "content", ")", "for", "dirname", ",", "dirs", ",", "filenames", "in", "os", ".", "walk", "(", "comps", ")", ":", "for", "filename", "in", "filenames", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "filename", ")", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "comps", ")", "template_path", "=", "os", ".", "path", ".", "join", "(", "comps", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ",", "rel_path", ")", "html", "=", "render_to_string", "(", "template_path", ",", "context", ")", "# convert static refs to relative links", "depth", "=", "len", "(", "rel_path", ".", "split", "(", "os", ".", "sep", ")", ")", "-", "1", "if", "depth", "==", "0", ":", "dotted_rel", "=", "'.'", "else", ":", "dotted_rel", "=", "''", "i", "=", "0", "while", "i", "<", "depth", ":", "dotted_rel", "+=", "'../'", "i", "+=", "1", "new_rel_path", "=", "'{0}{1}'", ".", "format", "(", "dotted_rel", ",", "'/static'", ")", "html", "=", "html", ".", "replace", "(", "'/static'", ",", "new_rel_path", ")", "if", "PY2", ":", "html", "=", "unicode", "(", "html", ")", "zip", ".", "writestr", "(", "rel_path", ",", "html", ".", "encode", "(", "'utf8'", ")", ")", "for", "item", "in", "zip", ".", "filelist", ":", "item", ".", "create_system", "=", "0", "zip", ".", "close", "(", ")", "response", "=", "HttpResponse", "(", "content_type", "=", "\"application/zip\"", ")", "response", "[", "\"Content-Disposition\"", "]", "=", "\"attachment; filename=comps.zip\"", "in_memory", ".", "seek", "(", "0", ")", "response", ".", "write", "(", "in_memory", ".", "read", "(", ")", ")", "return", "response" ]
Print current line and a pretty cursor below . Used in error messages
def p_pretty_pos ( self ) : col = self . p_current_col suffix = self . input [ self . pos - col : ] end = suffix . find ( "\n" ) if end != - 1 : suffix = suffix [ : end ] return "%s\n%s" % ( suffix , "-" * col + "^" )
7,276
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L124-L131
[ "def", "set_alternative", "(", "self", ",", "experiment_name", ",", "alternative", ")", ":", "experiment", "=", "experiment_manager", ".", "get_experiment", "(", "experiment_name", ")", "if", "experiment", ":", "self", ".", "_set_enrollment", "(", "experiment", ",", "alternative", ")" ]
Return True if the input starts with st at current position
def p_startswith ( self , st , ignorecase = False ) : length = len ( st ) matcher = result = self . input [ self . pos : self . pos + length ] if ignorecase : matcher = result . lower ( ) st = st . lower ( ) if matcher == st : self . pos += length return result return False
7,277
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L163-L173
[ "def", "from_thread", "(", "cls", ",", "thread", ")", ":", "new_classes", "=", "[", "]", "for", "new_cls", "in", "cls", ".", "__mro__", ":", "if", "new_cls", "not", "in", "thread", ".", "__class__", ".", "__mro__", ":", "new_classes", ".", "append", "(", "new_cls", ")", "if", "isinstance", "(", "thread", ",", "cls", ")", ":", "pass", "elif", "issubclass", "(", "cls", ",", "thread", ".", "__class__", ")", ":", "thread", ".", "__class__", "=", "cls", "else", ":", "class", "UpgradedThread", "(", "thread", ".", "__class__", ",", "cls", ")", ":", "pass", "thread", ".", "__class__", "=", "UpgradedThread", "for", "new_cls", "in", "new_classes", ":", "if", "hasattr", "(", "new_cls", ",", "\"_upgrade_thread\"", ")", ":", "new_cls", ".", "_upgrade_thread", "(", "thread", ")", "return", "thread" ]
Flatten a list of lists of lists ... of strings into a string
def p_flatten ( self , obj , * * kwargs ) : if isinstance ( obj , six . string_types ) : return obj result = "" for i in obj : result += self . p_flatten ( i ) return result
7,278
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L175-L196
[ "def", "kernelDriverActive", "(", "self", ",", "interface", ")", ":", "result", "=", "libusb1", ".", "libusb_kernel_driver_active", "(", "self", ".", "__handle", ",", "interface", ")", "if", "result", "==", "0", ":", "return", "False", "elif", "result", "==", "1", ":", "return", "True", "raiseUSBError", "(", "result", ")" ]
Parse the input using methodname as entry point .
def p_parse ( cls , input , methodname = None , parse_all = True ) : if methodname is None : methodname = cls . __default__ p = cls ( input ) result = getattr ( p , methodname ) ( ) if result is cls . NoMatch or parse_all and p . p_peek ( ) is not None : p . p_raise ( ) return result
7,279
https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L199-L212
[ "def", "_randomize_subject_list", "(", "data_list", ",", "random", ")", ":", "if", "random", "==", "RandomType", ".", "REPRODUCIBLE", ":", "for", "i", "in", "range", "(", "len", "(", "data_list", ")", ")", ":", "_randomize_single_subject", "(", "data_list", "[", "i", "]", ",", "seed", "=", "i", ")", "elif", "random", "==", "RandomType", ".", "UNREPRODUCIBLE", ":", "for", "data", "in", "data_list", ":", "_randomize_single_subject", "(", "data", ")" ]
Bulk delete items
def bulk_delete ( handler , request ) : ids = request . GET . getall ( 'ids' ) Message . delete ( ) . where ( Message . id << ids ) . execute ( ) raise muffin . HTTPFound ( handler . url )
7,280
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/example/admin.py#L47-L51
[ "def", "receive", "(", "uuid", ",", "source", ")", ":", "ret", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isdir", "(", "source", ")", ":", "ret", "[", "'Error'", "]", "=", "'Source must be a directory or host'", "return", "ret", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "source", ",", "'{0}.vmdata'", ".", "format", "(", "uuid", ")", ")", ")", ":", "ret", "[", "'Error'", "]", "=", "'Unknow vm with uuid in {0}'", ".", "format", "(", "source", ")", "return", "ret", "# vmadm receive", "cmd", "=", "'vmadm receive < {source}'", ".", "format", "(", "source", "=", "os", ".", "path", ".", "join", "(", "source", ",", "'{0}.vmdata'", ".", "format", "(", "uuid", ")", ")", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "retcode", "=", "res", "[", "'retcode'", "]", "if", "retcode", "!=", "0", "and", "not", "res", "[", "'stderr'", "]", ".", "endswith", "(", "'datasets'", ")", ":", "ret", "[", "'Error'", "]", "=", "res", "[", "'stderr'", "]", "if", "'stderr'", "in", "res", "else", "_exit_status", "(", "retcode", ")", "return", "ret", "vmobj", "=", "get", "(", "uuid", ")", "if", "'datasets'", "not", "in", "vmobj", ":", "return", "True", "log", ".", "warning", "(", "'one or more datasets detected, this is not supported!'", ")", "log", ".", "warning", "(", "'trying to restore datasets, mountpoints will need to be set again...'", ")", "for", "dataset", "in", "vmobj", "[", "'datasets'", "]", ":", "name", "=", "dataset", ".", "split", "(", "'/'", ")", "name", "=", "name", "[", "-", "1", "]", "cmd", "=", "'zfs receive {dataset} < {source}'", ".", "format", "(", "dataset", "=", "dataset", ",", "source", "=", "os", ".", "path", ".", "join", "(", "source", ",", "'{0}-{1}.zfsds'", ".", "format", "(", "uuid", ",", "name", ")", ")", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "retcode", "=", "res", "[", "'retcode'", "]", "if", "retcode", "!=", "0", ":", "ret", "[", "'Error'", "]", "=", "res", "[", "'stderr'", "]", "if", "'stderr'", "in", "res", "else", "_exit_status", "(", "retcode", ")", "return", "ret", "cmd", "=", "'vmadm install {0}'", ".", "format", "(", "uuid", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "retcode", "=", "res", "[", "'retcode'", "]", "if", "retcode", "!=", "0", "and", "not", "res", "[", "'stderr'", "]", ".", "endswith", "(", "'datasets'", ")", ":", "ret", "[", "'Error'", "]", "=", "res", "[", "'stderr'", "]", "if", "'stderr'", "in", "res", "else", "_exit_status", "(", "retcode", ")", "return", "ret", "return", "True" ]
provison Manila Share with HA
def make ( parser ) : s = parser . add_subparsers ( title = 'commands' , metavar = 'COMMAND' , help = 'description' , ) def install_f ( args ) : install ( args ) install_parser = install_subparser ( s ) install_parser . set_defaults ( func = install_f )
7,281
https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/cli/manila_share.py#L102-L113
[ "def", "convert_toml_outline_tables", "(", "parsed", ")", ":", "def", "convert_tomlkit_table", "(", "section", ")", ":", "for", "key", ",", "value", "in", "section", ".", "_body", ":", "if", "not", "key", ":", "continue", "if", "hasattr", "(", "value", ",", "\"keys\"", ")", "and", "not", "isinstance", "(", "value", ",", "tomlkit", ".", "items", ".", "InlineTable", ")", ":", "table", "=", "tomlkit", ".", "inline_table", "(", ")", "table", ".", "update", "(", "value", ".", "value", ")", "section", "[", "key", ".", "key", "]", "=", "table", "def", "convert_toml_table", "(", "section", ")", ":", "for", "package", ",", "value", "in", "section", ".", "items", "(", ")", ":", "if", "hasattr", "(", "value", ",", "\"keys\"", ")", "and", "not", "isinstance", "(", "value", ",", "toml", ".", "decoder", ".", "InlineTableDict", ")", ":", "table", "=", "toml", ".", "TomlDecoder", "(", ")", ".", "get_empty_inline_table", "(", ")", "table", ".", "update", "(", "value", ")", "section", "[", "package", "]", "=", "table", "is_tomlkit_parsed", "=", "isinstance", "(", "parsed", ",", "tomlkit", ".", "container", ".", "Container", ")", "for", "section", "in", "(", "\"packages\"", ",", "\"dev-packages\"", ")", ":", "table_data", "=", "parsed", ".", "get", "(", "section", ",", "{", "}", ")", "if", "not", "table_data", ":", "continue", "if", "is_tomlkit_parsed", ":", "convert_tomlkit_table", "(", "table_data", ")", "else", ":", "convert_toml_table", "(", "table_data", ")", "return", "parsed" ]
Launch parsing of children
def _parse_paginated_members ( self , direction = "children" ) : page = self . _last_page_parsed [ direction ] if not page : page = 1 else : page = int ( page ) while page : if page > 1 : response = self . _resolver . endpoint . get_collection ( collection_id = self . id , page = page , nav = direction ) else : response = self . _resolver . endpoint . get_collection ( collection_id = self . id , nav = direction ) response . raise_for_status ( ) data = response . json ( ) data = expand ( data ) [ 0 ] if direction == "children" : self . children . update ( { o . id : o for o in type ( self ) . parse_member ( obj = data , collection = self , direction = direction , resolver = self . _resolver ) } ) else : self . parents . update ( { o for o in type ( self ) . parse_member ( obj = data , collection = self , direction = direction , resolver = self . _resolver ) } ) self . _last_page_parsed [ direction ] = page page = None if "https://www.w3.org/ns/hydra/core#view" in data : if "https://www.w3.org/ns/hydra/core#next" in data [ "https://www.w3.org/ns/hydra/core#view" ] [ 0 ] : page = int ( _re_page . findall ( data [ "https://www.w3.org/ns/hydra/core#view" ] [ 0 ] [ "https://www.w3.org/ns/hydra/core#next" ] [ 0 ] [ "@value" ] ) [ 0 ] ) self . _parsed [ direction ] = True
7,282
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/dts/_resolver.py#L103-L154
[ "def", "_do_http", "(", "opts", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "url", "=", "__salt__", "[", "'config.get'", "]", "(", "'modjk:{0}:url'", ".", "format", "(", "profile", ")", ",", "''", ")", "user", "=", "__salt__", "[", "'config.get'", "]", "(", "'modjk:{0}:user'", ".", "format", "(", "profile", ")", ",", "''", ")", "passwd", "=", "__salt__", "[", "'config.get'", "]", "(", "'modjk:{0}:pass'", ".", "format", "(", "profile", ")", ",", "''", ")", "realm", "=", "__salt__", "[", "'config.get'", "]", "(", "'modjk:{0}:realm'", ".", "format", "(", "profile", ")", ",", "''", ")", "timeout", "=", "__salt__", "[", "'config.get'", "]", "(", "'modjk:{0}:timeout'", ".", "format", "(", "profile", ")", ",", "''", ")", "if", "not", "url", ":", "raise", "Exception", "(", "'missing url in profile {0}'", ".", "format", "(", "profile", ")", ")", "if", "user", "and", "passwd", ":", "auth", "=", "_auth", "(", "url", "=", "url", ",", "realm", "=", "realm", ",", "user", "=", "user", ",", "passwd", "=", "passwd", ")", "_install_opener", "(", "auth", ")", "url", "+=", "'?{0}'", ".", "format", "(", "_urlencode", "(", "opts", ")", ")", "for", "line", "in", "_urlopen", "(", "url", ",", "timeout", "=", "timeout", ")", ".", "read", "(", ")", ".", "splitlines", "(", ")", ":", "splt", "=", "line", ".", "split", "(", "'='", ",", "1", ")", "if", "splt", "[", "0", "]", "in", "ret", ":", "ret", "[", "splt", "[", "0", "]", "]", "+=", "',{0}'", ".", "format", "(", "splt", "[", "1", "]", ")", "else", ":", "ret", "[", "splt", "[", "0", "]", "]", "=", "splt", "[", "1", "]", "return", "ret" ]
Returns url request_token request_secret
def request_token ( self ) : logging . debug ( "Getting request token from %s:%d" , self . server , self . port ) token , secret = self . _token ( "/oauth/requestToken" ) return "{}/oauth/authorize?oauth_token={}" . format ( self . host , token ) , token , secret
7,283
https://github.com/erijo/tellive-py/blob/a84ebb1eb29ee4c69a085e55e523ac5fff0087fc/tellive/client.py#L65-L71
[ "def", "same_disks", "(", "self", ",", "count", "=", "2", ")", ":", "ret", "=", "self", "if", "len", "(", "self", ")", ">", "0", ":", "type_counter", "=", "Counter", "(", "self", ".", "drive_type", ")", "drive_type", ",", "counts", "=", "type_counter", ".", "most_common", "(", ")", "[", "0", "]", "self", ".", "set_drive_type", "(", "drive_type", ")", "if", "len", "(", "self", ")", ">", "0", ":", "size_counter", "=", "Counter", "(", "self", ".", "capacity", ")", "size", ",", "counts", "=", "size_counter", ".", "most_common", "(", ")", "[", "0", "]", "self", ".", "set_capacity", "(", "size", ")", "if", "len", "(", "self", ")", ">=", "count", ":", "indices", "=", "self", ".", "index", "[", ":", "count", "]", "self", ".", "set_indices", "(", "indices", ")", "else", ":", "self", ".", "set_indices", "(", "'N/A'", ")", "return", "ret" ]
Returns access_token access_secret
def access_token ( self , request_token , request_secret ) : logging . debug ( "Getting access token from %s:%d" , self . server , self . port ) self . access_token , self . access_secret = self . _token ( "/oauth/accessToken" , request_token , request_secret ) return self . access_token , self . access_secret
7,284
https://github.com/erijo/tellive-py/blob/a84ebb1eb29ee4c69a085e55e523ac5fff0087fc/tellive/client.py#L73-L79
[ "def", "_find_files", "(", "self", ",", "entries", ",", "root", ",", "relative_path", ",", "file_name_regex", ")", ":", "self", ".", "log", "(", "[", "u\"Finding files within root: '%s'\"", ",", "root", "]", ")", "target", "=", "root", "if", "relative_path", "is", "not", "None", ":", "self", ".", "log", "(", "[", "u\"Joining relative path: '%s'\"", ",", "relative_path", "]", ")", "target", "=", "gf", ".", "norm_join", "(", "root", ",", "relative_path", ")", "self", ".", "log", "(", "[", "u\"Finding files within target: '%s'\"", ",", "target", "]", ")", "files", "=", "[", "]", "target_len", "=", "len", "(", "target", ")", "for", "entry", "in", "entries", ":", "if", "entry", ".", "startswith", "(", "target", ")", ":", "self", ".", "log", "(", "[", "u\"Examining entry: '%s'\"", ",", "entry", "]", ")", "entry_suffix", "=", "entry", "[", "target_len", "+", "1", ":", "]", "self", ".", "log", "(", "[", "u\"Examining entry suffix: '%s'\"", ",", "entry_suffix", "]", ")", "if", "re", ".", "search", "(", "file_name_regex", ",", "entry_suffix", ")", "is", "not", "None", ":", "self", ".", "log", "(", "[", "u\"Match: '%s'\"", ",", "entry", "]", ")", "files", ".", "append", "(", "entry", ")", "else", ":", "self", ".", "log", "(", "[", "u\"No match: '%s'\"", ",", "entry", "]", ")", "return", "sorted", "(", "files", ")" ]
Opens a resource from the zoneinfo subdir for reading .
def open_resource ( self , name ) : # Import nested here so we can run setup.py without GAE. from google . appengine . api import memcache from pytz import OLSON_VERSION name_parts = name . lstrip ( '/' ) . split ( '/' ) if os . path . pardir in name_parts : raise ValueError ( 'Bad path segment: %r' % os . path . pardir ) cache_key = 'pytz.zoneinfo.%s.%s' % ( OLSON_VERSION , name ) zonedata = memcache . get ( cache_key ) if zonedata is None : zonedata = get_zoneinfo ( ) . read ( 'zoneinfo/' + '/' . join ( name_parts ) ) memcache . add ( cache_key , zonedata ) log . info ( 'Added timezone to memcache: %s' % cache_key ) else : log . info ( 'Loaded timezone from memcache: %s' % cache_key ) return StringIO ( zonedata )
7,285
https://github.com/potatolondon/gae-pytz/blob/24741951a7af3e79cd8727ae3f79265decc93fef/pytz/gae.py#L46-L65
[ "def", "broken_faces", "(", "mesh", ",", "color", "=", "None", ")", ":", "adjacency", "=", "nx", ".", "from_edgelist", "(", "mesh", ".", "face_adjacency", ")", "broken", "=", "[", "k", "for", "k", ",", "v", "in", "dict", "(", "adjacency", ".", "degree", "(", ")", ")", ".", "items", "(", ")", "if", "v", "!=", "3", "]", "broken", "=", "np", ".", "array", "(", "broken", ")", "if", "color", "is", "not", "None", ":", "# if someone passed a broken color", "color", "=", "np", ".", "array", "(", "color", ")", "if", "not", "(", "color", ".", "shape", "==", "(", "4", ",", ")", "or", "color", ".", "shape", "==", "(", "3", ",", ")", ")", ":", "color", "=", "[", "255", ",", "0", ",", "0", ",", "255", "]", "mesh", ".", "visual", ".", "face_colors", "[", "broken", "]", "=", "color", "return", "broken" ]
Return true if the given resource exists
def resource_exists ( self , name ) : if name not in self . available : try : get_zoneinfo ( ) . getinfo ( 'zoneinfo/' + name ) self . available [ name ] = True except KeyError : self . available [ name ] = False return self . available [ name ]
7,286
https://github.com/potatolondon/gae-pytz/blob/24741951a7af3e79cd8727ae3f79265decc93fef/pytz/gae.py#L67-L76
[ "def", "unitim", "(", "epoch", ",", "insys", ",", "outsys", ")", ":", "epoch", "=", "ctypes", ".", "c_double", "(", "epoch", ")", "insys", "=", "stypes", ".", "stringToCharP", "(", "insys", ")", "outsys", "=", "stypes", ".", "stringToCharP", "(", "outsys", ")", "return", "libspice", ".", "unitim_c", "(", "epoch", ",", "insys", ",", "outsys", ")" ]
Run tests matching keywords .
def bdd ( * keywords ) : settings = _personal_settings ( ) . data _storybook ( ) . with_params ( * * { "python version" : settings [ "params" ] [ "python version" ] } ) . only_uninherited ( ) . shortcut ( * keywords ) . play ( )
7,287
https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/hitch/key.py#L212-L219
[ "def", "make_ica_funs", "(", "observed_dimension", ",", "latent_dimension", ")", ":", "def", "sample", "(", "weights", ",", "n_samples", ",", "noise_std", ",", "rs", ")", ":", "latents", "=", "rs", ".", "randn", "(", "latent_dimension", ",", "n_samples", ")", "latents", "=", "np", ".", "array", "(", "sorted", "(", "latents", ".", "T", ",", "key", "=", "lambda", "a_entry", ":", "a_entry", "[", "0", "]", ")", ")", ".", "T", "noise", "=", "rs", ".", "randn", "(", "n_samples", ",", "observed_dimension", ")", "*", "noise_std", "observed", "=", "predict", "(", "weights", ",", "latents", ")", "+", "noise", "return", "latents", ",", "observed", "def", "predict", "(", "weights", ",", "latents", ")", ":", "return", "np", ".", "dot", "(", "weights", ",", "latents", ")", ".", "T", "def", "logprob", "(", "weights", ",", "latents", ",", "noise_std", ",", "observed", ")", ":", "preds", "=", "predict", "(", "weights", ",", "latents", ")", "log_lik", "=", "np", ".", "sum", "(", "t", ".", "logpdf", "(", "preds", ",", "2.4", ",", "observed", ",", "noise_std", ")", ")", "return", "log_lik", "num_weights", "=", "observed_dimension", "*", "latent_dimension", "def", "unpack_weights", "(", "weights", ")", ":", "return", "np", ".", "reshape", "(", "weights", ",", "(", "observed_dimension", ",", "latent_dimension", ")", ")", "return", "num_weights", ",", "sample", ",", "logprob", ",", "unpack_weights" ]
Do an Authentricate request and save the cookie returned to be used on the following requests . Return True if the request was successfull
def authenticate ( self , username : str , password : str ) -> bool : self . username = username self . password = password auth_payload = """<authenticate1 xmlns=\"utcs\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> <password>{password}</password> <username>{username}</username> <application>treeview</application> </authenticate1>""" payload = auth_payload . format ( password = self . password , username = self . username ) xdoc = self . connection . soap_action ( '/ws/AuthenticationService' , 'authenticate' , payload ) if xdoc : isok = xdoc . find ( './SOAP-ENV:Body/ns1:authenticate2/ns1:loginWasSuccessful' , IHCSoapClient . ihcns ) return isok . text == 'true' return False
7,288
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcclient.py#L27-L51
[ "def", "interfaces", "(", "self", ")", "->", "Iterable", "[", "ConstantClass", "]", ":", "return", "[", "self", ".", "_constants", "[", "idx", "]", "for", "idx", "in", "self", ".", "_interfaces", "]" ]
Get the ihc project
def get_project ( self ) -> str : xdoc = self . connection . soap_action ( '/ws/ControllerService' , 'getIHCProject' , "" ) if xdoc : base64data = xdoc . find ( './SOAP-ENV:Body/ns1:getIHCProject1/ns1:data' , IHCSoapClient . ihcns ) . text if not base64 : return False compresseddata = base64 . b64decode ( base64data ) return zlib . decompress ( compresseddata , 16 + zlib . MAX_WBITS ) . decode ( 'ISO-8859-1' ) return False
7,289
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcclient.py#L81-L94
[ "def", "get_storage", "(", "self", ",", "name", "=", "'main'", ",", "file_format", "=", "'pickle'", ",", "TTL", "=", "None", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_unsynced_storages'", ")", ":", "self", ".", "_unsynced_storages", "=", "{", "}", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "storage_path", ",", "name", ")", "try", ":", "storage", "=", "self", ".", "_unsynced_storages", "[", "filename", "]", "log", ".", "debug", "(", "'Loaded storage \"%s\" from memory'", ",", "name", ")", "except", "KeyError", ":", "if", "TTL", ":", "TTL", "=", "timedelta", "(", "minutes", "=", "TTL", ")", "try", ":", "storage", "=", "TimedStorage", "(", "filename", ",", "file_format", ",", "TTL", ")", "except", "ValueError", ":", "# Thrown when the storage file is corrupted and can't be read.", "# Prompt user to delete storage.", "choices", "=", "[", "'Clear storage'", ",", "'Cancel'", "]", "ret", "=", "xbmcgui", ".", "Dialog", "(", ")", ".", "select", "(", "'A storage file is corrupted. It'", "' is recommended to clear it.'", ",", "choices", ")", "if", "ret", "==", "0", ":", "os", ".", "remove", "(", "filename", ")", "storage", "=", "TimedStorage", "(", "filename", ",", "file_format", ",", "TTL", ")", "else", ":", "raise", "Exception", "(", "'Corrupted storage file at %s'", "%", "filename", ")", "self", ".", "_unsynced_storages", "[", "filename", "]", "=", "storage", "log", ".", "debug", "(", "'Loaded storage \"%s\" from disk'", ",", "name", ")", "return", "storage" ]
Traverse tree to node
def _get_node ( response , * ancestors ) : document = response for ancestor in ancestors : if ancestor not in document : return { } else : document = document [ ancestor ] return document
7,290
https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L20-L28
[ "def", "_get_env_var", "(", "env_var_name", ")", ":", "if", "env_var_name", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "env_var_name", "]", "fname", "=", "os", ".", "path", ".", "join", "(", "get_home", "(", ")", ",", "'.tangorc'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "fname", "=", "\"/etc/tangorc\"", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "None", "for", "line", "in", "open", "(", "fname", ")", ":", "strippedline", "=", "line", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "strippedline", ":", "# empty line", "continue", "tup", "=", "strippedline", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "tup", ")", "!=", "2", ":", "# illegal line!", "continue", "key", ",", "val", "=", "map", "(", "str", ".", "strip", ",", "tup", ")", "if", "key", "==", "env_var_name", ":", "return", "val" ]
Get token from key and secret
def update_token ( self ) : headers = { 'Content-Type' : 'application/x-www-form-urlencoded' , 'Authorization' : 'Basic ' + base64 . b64encode ( ( self . _key + ':' + self . _secret ) . encode ( ) ) . decode ( ) } data = { 'grant_type' : 'client_credentials' } response = requests . post ( TOKEN_URL , data = data , headers = headers ) obj = json . loads ( response . content . decode ( 'UTF-8' ) ) self . _token = obj [ 'access_token' ] self . _token_expire_date = ( datetime . now ( ) + timedelta ( minutes = self . _expiery ) )
7,291
https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L40-L54
[ "def", "_initialize_mtf_dimension_name_to_size_gcd", "(", "self", ",", "mtf_graph", ")", ":", "mtf_dimension_name_to_size_gcd", "=", "{", "}", "for", "mtf_operation", "in", "mtf_graph", ".", "operations", ":", "for", "mtf_tensor", "in", "mtf_operation", ".", "outputs", ":", "for", "mtf_dimension", "in", "mtf_tensor", ".", "shape", ".", "dims", ":", "mtf_dimension_name_to_size_gcd", "[", "mtf_dimension", ".", "name", "]", "=", "fractions", ".", "gcd", "(", "mtf_dimension_name_to_size_gcd", ".", "get", "(", "mtf_dimension", ".", "name", ",", "mtf_dimension", ".", "size", ")", ",", "mtf_dimension", ".", "size", ")", "return", "mtf_dimension_name_to_size_gcd" ]
location . nearbystops
def location_nearbystops ( self , origin_coord_lat , origin_coord_long ) : response = self . _request ( 'location.nearbystops' , originCoordLat = origin_coord_lat , originCoordLong = origin_coord_long ) return _get_node ( response , 'LocationList' , 'StopLocation' )
7,292
https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L64-L70
[ "def", "percentile_ranks", "(", "self", ",", "affinities", ",", "allele", "=", "None", ",", "alleles", "=", "None", ",", "throw", "=", "True", ")", ":", "if", "allele", "is", "not", "None", ":", "try", ":", "transform", "=", "self", ".", "allele_to_percent_rank_transform", "[", "allele", "]", "return", "transform", ".", "transform", "(", "affinities", ")", "except", "KeyError", ":", "msg", "=", "\"Allele %s has no percentile rank information\"", "%", "allele", "if", "throw", ":", "raise", "ValueError", "(", "msg", ")", "else", ":", "warnings", ".", "warn", "(", "msg", ")", "# Return NaNs", "return", "numpy", ".", "ones", "(", "len", "(", "affinities", ")", ")", "*", "numpy", ".", "nan", "if", "alleles", "is", "None", ":", "raise", "ValueError", "(", "\"Specify allele or alleles\"", ")", "df", "=", "pandas", ".", "DataFrame", "(", "{", "\"affinity\"", ":", "affinities", "}", ")", "df", "[", "\"allele\"", "]", "=", "alleles", "df", "[", "\"result\"", "]", "=", "numpy", ".", "nan", "for", "(", "allele", ",", "sub_df", ")", "in", "df", ".", "groupby", "(", "\"allele\"", ")", ":", "df", ".", "loc", "[", "sub_df", ".", "index", ",", "\"result\"", "]", "=", "self", ".", "percentile_ranks", "(", "sub_df", ".", "affinity", ",", "allele", "=", "allele", ",", "throw", "=", "throw", ")", "return", "df", ".", "result", ".", "values" ]
location . name
def location_name ( self , name ) : response = self . _request ( 'location.name' , input = name ) return _get_node ( response , 'LocationList' , 'StopLocation' )
7,293
https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/journy_planner.py#L80-L85
[ "def", "indication", "(", "self", ",", "apdu", ")", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\"indication %r\"", ",", "apdu", ")", "if", "self", ".", "state", "==", "IDLE", ":", "self", ".", "idle", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_REQUEST", ":", "self", ".", "segmented_request", "(", "apdu", ")", "elif", "self", ".", "state", "==", "AWAIT_RESPONSE", ":", "self", ".", "await_response", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_RESPONSE", ":", "self", ".", "segmented_response", "(", "apdu", ")", "else", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\" - invalid state\"", ")" ]
If the string starts with a known prefix in nsmap replace it by full URI
def expand_namespace ( nsmap , string ) : for ns in nsmap : if isinstance ( string , str ) and isinstance ( ns , str ) and string . startswith ( ns + ":" ) : return string . replace ( ns + ":" , nsmap [ ns ] ) return string
7,294
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_graph.py#L72-L82
[ "def", "flush_devices", "(", "self", ")", ":", "self", ".", "rom", ".", "program", "(", "[", "0", "for", "i", "in", "range", "(", "self", ".", "rom", ".", "size", ")", "]", ")", "self", ".", "flash", ".", "program", "(", "[", "0", "for", "i", "in", "range", "(", "self", ".", "flash", ".", "size", ")", "]", ")", "for", "i", "in", "range", "(", "self", ".", "ram", ".", "size", ")", ":", "self", ".", "ram", ".", "write", "(", "i", ",", "0", ")" ]
Iter on a graph to finds object connected
def graphiter ( self , graph , target , ascendants = 0 , descendants = 1 ) : asc = 0 + ascendants if asc != 0 : asc -= 1 desc = 0 + descendants if desc != 0 : desc -= 1 t = str ( target ) if descendants != 0 and self . downwards [ t ] is True : self . downwards [ t ] = False for pred , obj in graph . predicate_objects ( target ) : if desc == 0 and isinstance ( obj , BNode ) : continue self . add ( ( target , pred , obj ) ) # Retrieve triples about the object if desc != 0 and self . downwards [ str ( obj ) ] is True : self . graphiter ( graph , target = obj , ascendants = 0 , descendants = desc ) if ascendants != 0 and self . updwards [ t ] is True : self . updwards [ t ] = False for s , p in graph . subject_predicates ( object = target ) : if desc == 0 and isinstance ( s , BNode ) : continue self . add ( ( s , p , target ) ) # Retrieve triples about the parent as object if asc != 0 and self . updwards [ str ( s ) ] is True : self . graphiter ( graph , target = s , ascendants = asc , descendants = 0 )
7,295
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_graph.py#L21-L63
[ "def", "_bqschema_to_nullsafe_dtypes", "(", "schema_fields", ")", ":", "# If you update this mapping, also update the table at", "# `docs/source/reading.rst`.", "dtype_map", "=", "{", "\"FLOAT\"", ":", "np", ".", "dtype", "(", "float", ")", ",", "# pandas doesn't support timezone-aware dtype in DataFrame/Series", "# constructors. It's more idiomatic to localize after construction.", "# https://github.com/pandas-dev/pandas/issues/25843", "\"TIMESTAMP\"", ":", "\"datetime64[ns]\"", ",", "\"TIME\"", ":", "\"datetime64[ns]\"", ",", "\"DATE\"", ":", "\"datetime64[ns]\"", ",", "\"DATETIME\"", ":", "\"datetime64[ns]\"", ",", "}", "dtypes", "=", "{", "}", "for", "field", "in", "schema_fields", ":", "name", "=", "str", "(", "field", "[", "\"name\"", "]", ")", "if", "field", "[", "\"mode\"", "]", ".", "upper", "(", ")", "==", "\"REPEATED\"", ":", "continue", "dtype", "=", "dtype_map", ".", "get", "(", "field", "[", "\"type\"", "]", ".", "upper", "(", ")", ")", "if", "dtype", ":", "dtypes", "[", "name", "]", "=", "dtype", "return", "dtypes" ]
Return unique list of items preserving order .
def uniqued ( iterable ) : seen = set ( ) add = seen . add return [ i for i in iterable if i not in seen and not add ( i ) ]
7,296
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/tools.py#L10-L18
[ "def", "on_websocket_message", "(", "message", ":", "str", ")", "->", "None", ":", "msgs", "=", "json", ".", "loads", "(", "message", ")", "for", "msg", "in", "msgs", ":", "if", "not", "isinstance", "(", "msg", ",", "dict", ")", ":", "logger", ".", "error", "(", "'Invalid WS message format: {}'", ".", "format", "(", "message", ")", ")", "continue", "_type", "=", "msg", ".", "get", "(", "'type'", ")", "if", "_type", "==", "'log'", ":", "log_handler", "(", "msg", "[", "'level'", "]", ",", "msg", "[", "'message'", "]", ")", "elif", "_type", "==", "'event'", ":", "event_handler", "(", "msg", "[", "'event'", "]", ")", "elif", "_type", "==", "'response'", ":", "response_handler", "(", "msg", ")", "else", ":", "raise", "ValueError", "(", "'Unkown message type: {}'", ".", "format", "(", "message", ")", ")" ]
Yield all items from iterable except the last one .
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
7,297
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/tools.py#L21-L40
[ "def", "_start_console", "(", "self", ")", ":", "self", ".", "_remote_pipe", "=", "yield", "from", "asyncio_open_serial", "(", "self", ".", "_get_pipe_name", "(", ")", ")", "server", "=", "AsyncioTelnetServer", "(", "reader", "=", "self", ".", "_remote_pipe", ",", "writer", "=", "self", ".", "_remote_pipe", ",", "binary", "=", "True", ",", "echo", "=", "True", ")", "self", ".", "_telnet_server", "=", "yield", "from", "asyncio", ".", "start_server", "(", "server", ".", "run", ",", "self", ".", "_manager", ".", "port_manager", ".", "console_host", ",", "self", ".", "console", ")" ]
Return a translate function for strings and unicode .
def generic_translate ( frm = None , to = None , delete = '' ) : if PY2 : delete_dict = dict . fromkeys ( ord ( unicode ( d ) ) for d in delete ) if frm is None and to is None : string_trans = None unicode_table = delete_dict else : string_trans = string . maketrans ( frm , to ) unicode_table = dict ( ( ( ord ( unicode ( f ) ) , unicode ( t ) ) for f , t in zip ( frm , to ) ) , * * delete_dict ) string_args = ( string_trans , delete ) if delete else ( string_trans , ) translate_args = [ string_args , ( unicode_table , ) ] def translate ( basestr ) : args = translate_args [ isinstance ( basestr , unicode ) ] return basestr . translate ( * args ) else : string_trans = str . maketrans ( frm or '' , to or '' , delete or '' ) def translate ( basestr ) : return basestr . translate ( string_trans ) return translate
7,298
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/tools.py#L43-L79
[ "def", "previous", "(", "self", ")", ":", "if", "self", ".", "index", "-", "1", ">=", "0", ":", "# more main line?", "self", ".", "index", "=", "self", ".", "index", "-", "1", "elif", "self", ".", "stack", ":", "# were we in a variation?", "self", ".", "gametree", "=", "self", ".", "stack", ".", "pop", "(", ")", "self", ".", "index", "=", "len", "(", "self", ".", "gametree", ")", "-", "1", "else", ":", "raise", "GameTreeEndError", "self", ".", "node", "=", "self", ".", "gametree", "[", "self", ".", "index", "]", "self", ".", "nodenum", "=", "self", ".", "nodenum", "-", "1", "self", ".", "_setChildren", "(", ")", "self", ".", "_setFlags", "(", ")", "return", "self", ".", "node" ]
Build a cryptography TripleDES Cipher object .
def _cryptography_cipher ( key , iv ) : return Cipher ( algorithm = algorithms . TripleDES ( key ) , mode = modes . CBC ( iv ) , backend = default_backend ( ) )
7,299
https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/des3.py#L28-L40
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]