query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Returns the version of file name or None if it doesn t exist .
def stored_version ( self , name ) : link_path = self . _link_path ( name ) if not _path_exists ( link_path ) : return None return _file_version ( link_path )
6,700
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L289-L294
[ "def", "user_deleted_from_site_event", "(", "event", ")", ":", "userid", "=", "event", ".", "principal", "catalog", "=", "api", ".", "portal", ".", "get_tool", "(", "'portal_catalog'", ")", "query", "=", "{", "'object_provides'", ":", "WORKSPACE_INTERFACE", "}", "query", "[", "'workspace_members'", "]", "=", "userid", "workspaces", "=", "[", "IWorkspace", "(", "b", ".", "_unrestrictedGetObject", "(", ")", ")", "for", "b", "in", "catalog", ".", "unrestrictedSearchResults", "(", "query", ")", "]", "for", "workspace", "in", "workspaces", ":", "workspace", ".", "remove_from_team", "(", "userid", ")" ]
Moves or creates the file with stream contents to a new location .
def save ( self , new_path = None ) : self . saved_in_temp = new_path is None if new_path is None : fd , new_path = tempfile . mkstemp ( ) os . close ( fd ) if self . current_path : shutil . move ( self . current_path , new_path ) else : with open ( new_path , 'wb' ) as dest : _copy_stream ( self . _data , dest , self . _size ) self . current_path = new_path
6,701
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L353-L369
[ "def", "get_crab", "(", "registry", ")", ":", "# argument might be a config or a request", "regis", "=", "getattr", "(", "registry", ",", "'registry'", ",", "None", ")", "if", "regis", "is", "None", ":", "regis", "=", "registry", "return", "regis", ".", "queryUtility", "(", "ICrab", ")" ]
Iterator that returns all the lp objects from linguistic processors layers from the header
def get_lps ( self ) : if self . header is not None : for linguisticProcessor in self . header : for lp in linguisticProcessor : yield lp
6,702
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L404-L412
[ "def", "_check_total_z_extents", "(", "self", ",", "ds", ",", "z_variable", ")", ":", "msgs", "=", "[", "]", "total", "=", "2", "try", ":", "vert_min", "=", "float", "(", "ds", ".", "geospatial_vertical_min", ")", "except", "ValueError", ":", "msgs", ".", "append", "(", "'geospatial_vertical_min cannot be cast to float'", ")", "try", ":", "vert_max", "=", "float", "(", "ds", ".", "geospatial_vertical_max", ")", "except", "ValueError", ":", "msgs", ".", "append", "(", "'geospatial_vertical_max cannot be cast to float'", ")", "if", "len", "(", "msgs", ")", ">", "0", ":", "return", "Result", "(", "BaseCheck", ".", "MEDIUM", ",", "(", "0", ",", "total", ")", ",", "'geospatial_vertical_extents_match'", ",", "msgs", ")", "zvalue", "=", "ds", ".", "variables", "[", "z_variable", "]", "[", ":", "]", "# If the array has fill values, which is allowed in the case of point", "# features", "if", "hasattr", "(", "zvalue", ",", "'mask'", ")", ":", "zvalue", "=", "zvalue", "[", "~", "zvalue", ".", "mask", "]", "if", "zvalue", ".", "size", "==", "0", ":", "msgs", ".", "append", "(", "\"Cannot compare geospatial vertical extents \"", "\"against min/max of data, as non-masked data \"", "\"length is zero\"", ")", "return", "Result", "(", "BaseCheck", ".", "MEDIUM", ",", "(", "0", ",", "total", ")", ",", "'geospatial_vertical_extents_match'", ",", "msgs", ")", "else", ":", "zmin", "=", "zvalue", ".", "min", "(", ")", "zmax", "=", "zvalue", ".", "max", "(", ")", "if", "not", "np", ".", "isclose", "(", "vert_min", ",", "zmin", ")", ":", "msgs", ".", "append", "(", "\"geospatial_vertical_min != min(%s) values, %s != %s\"", "%", "(", "z_variable", ",", "vert_min", ",", "zmin", ")", ")", "if", "not", "np", ".", "isclose", "(", "vert_max", ",", "zmax", ")", ":", "msgs", ".", "append", "(", "\"geospatial_vertical_max != max(%s) values, %s != %s\"", "%", "(", "z_variable", ",", "vert_min", ",", "zmax", ")", ")", "return", "Result", "(", "BaseCheck", ".", "MEDIUM", ",", "(", "total", "-", "len", "(", "msgs", ")", ",", "total", ")", ",", "'geospatial_vertical_extents_match'", ",", "msgs", ")" ]
Iterator that returns the constituency trees
def get_trees_as_list ( self ) : mytrees = [ ] if self . constituency_layer is not None : for tree in self . constituency_layer . get_trees ( ) : mytrees . append ( tree ) return mytrees
6,703
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L425-L435
[ "def", "_handle_websocket_headers", "(", "self", ",", "handler", ":", "WebSocketHandler", ")", "->", "None", ":", "fields", "=", "(", "\"Host\"", ",", "\"Sec-Websocket-Key\"", ",", "\"Sec-Websocket-Version\"", ")", "if", "not", "all", "(", "map", "(", "lambda", "f", ":", "handler", ".", "request", ".", "headers", ".", "get", "(", "f", ")", ",", "fields", ")", ")", ":", "raise", "ValueError", "(", "\"Missing/Invalid WebSocket headers\"", ")" ]
Takes information from factuality layer in old representation Creates new factuality representation and removes the old layer
def convert_factualitylayer_to_factualities ( self ) : if self . factuality_layer is not None : this_node = self . factuality_layer . get_node ( ) if this_node . tag == 'factualitylayer' : new_node = Cfactualities ( ) #create dictionary from token ids to the term ids token2term = { } for t in self . get_terms ( ) : s = t . get_span ( ) for w in s . get_span_ids ( ) : token2term [ w ] = t . get_id ( ) fnr = 0 for fv in self . get_factvalues ( ) : fnr += 1 conf = fv . get_confidence ( ) wid = fv . get_id ( ) tid = token2term . get ( wid ) fnode = Cfactuality ( ) #set span with tid as element fspan = Cspan ( ) fspan . add_target_id ( tid ) fnode . set_span ( fspan ) #add factVal element with val, resource = factbank, + confidence if present fVal = Cfactval ( ) fVal . set_resource ( 'factbank' ) fVal . set_value ( fv . get_prediction ( ) ) if conf : fVal . set_confidence ( conf ) fnode . set_id ( 'f' + str ( fnr ) ) fnode . add_factval ( fVal ) new_node . add_factuality ( fnode ) self . root . remove ( this_node ) self . root . append ( new_node . get_node ( ) ) self . factuality_layer = new_node
6,704
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L914-L951
[ "def", "is_registration_possible", "(", "self", ",", "user_info", ")", ":", "return", "self", ".", "get_accessibility", "(", ")", ".", "is_open", "(", ")", "and", "self", ".", "_registration", ".", "is_open", "(", ")", "and", "self", ".", "is_user_accepted_by_access_control", "(", "user_info", ")" ]
Returns a constituency extractor object
def get_constituency_extractor ( self ) : if self . constituency_layer is not None : ##Otherwise there are no constituens if self . my_constituency_extractor is None : self . my_constituency_extractor = Cconstituency_extractor ( self ) return self . my_constituency_extractor else : return None
6,705
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L954-L966
[ "def", "minutes_for_sessions_in_range", "(", "self", ",", "start_session_label", ",", "end_session_label", ")", ":", "first_minute", ",", "_", "=", "self", ".", "open_and_close_for_session", "(", "start_session_label", ")", "_", ",", "last_minute", "=", "self", ".", "open_and_close_for_session", "(", "end_session_label", ")", "return", "self", ".", "minutes_in_range", "(", "first_minute", ",", "last_minute", ")" ]
Returns a dependency extractor object
def get_dependency_extractor ( self ) : if self . dependency_layer is not None : #otherwise there are no dependencies if self . my_dependency_extractor is None : self . my_dependency_extractor = Cdependency_extractor ( self ) return self . my_dependency_extractor else : return None
6,706
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L968-L979
[ "def", "to_disk_indices", "(", "value", ")", ":", "ret", "=", "[", "]", "p", "=", "re", ".", "compile", "(", "r'Bus\\s+(\\w+)\\s+Enclosure\\s+(\\w+)\\s+Disk\\s+(\\w+)'", ")", "if", "value", "is", "not", "None", ":", "for", "line", "in", "value", ".", "split", "(", "'\\n'", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "line", ")", "==", "0", ":", "continue", "matched", "=", "re", ".", "search", "(", "p", ",", "line", ")", "if", "matched", "is", "None", "or", "len", "(", "matched", ".", "groups", "(", ")", ")", "<", "3", ":", "continue", "else", ":", "ret", ".", "append", "(", "'{}_{}_{}'", ".", "format", "(", "*", "matched", ".", "groups", "(", ")", ")", ")", "return", "ret" ]
Adds a token to the text layer
def add_wf ( self , wf_obj ) : if self . text_layer is None : self . text_layer = Ctext ( type = self . type ) self . root . append ( self . text_layer . get_node ( ) ) self . text_layer . add_wf ( wf_obj )
6,707
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L982-L991
[ "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", ")" ]
Adds a term to the term layer
def add_term ( self , term_obj ) : if self . term_layer is None : self . term_layer = Cterms ( type = self . type ) self . root . append ( self . term_layer . get_node ( ) ) self . term_layer . add_term ( term_obj )
6,708
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1022-L1031
[ "def", "launcher", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-f'", ",", "'--file'", ",", "dest", "=", "'filename'", ",", "default", "=", "'agents.csv'", ",", "help", "=", "'snmposter configuration file'", ")", "options", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "factory", "=", "SNMPosterFactory", "(", ")", "snmpd_status", "=", "subprocess", ".", "Popen", "(", "[", "\"service\"", ",", "\"snmpd\"", ",", "\"status\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "if", "\"is running\"", "in", "snmpd_status", ":", "message", "=", "\"snmd service is running. Please stop it and try again.\"", "print", ">>", "sys", ".", "stderr", ",", "message", "sys", ".", "exit", "(", "1", ")", "try", ":", "factory", ".", "configure", "(", "options", ".", "filename", ")", "except", "IOError", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Error opening %s.\"", "%", "options", ".", "filename", "sys", ".", "exit", "(", "1", ")", "factory", ".", "start", "(", ")" ]
Adds a chunk to the chunk layer
def add_chunk ( self , chunk_obj ) : if self . chunk_layer is None : self . chunk_layer = Cchunks ( type = self . type ) self . root . append ( self . chunk_layer . get_node ( ) ) self . chunk_layer . add_chunk ( chunk_obj )
6,709
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1034-L1043
[ "def", "_get_configured_repos", "(", "root", "=", "None", ")", ":", "repos", "=", "os", ".", "path", ".", "join", "(", "root", ",", "os", ".", "path", ".", "relpath", "(", "REPOS", ",", "os", ".", "path", ".", "sep", ")", ")", "if", "root", "else", "REPOS", "repos_cfg", "=", "configparser", ".", "ConfigParser", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "repos", ")", ":", "repos_cfg", ".", "read", "(", "[", "repos", "+", "'/'", "+", "fname", "for", "fname", "in", "os", ".", "listdir", "(", "repos", ")", "if", "fname", ".", "endswith", "(", "\".repo\"", ")", "]", ")", "else", ":", "log", ".", "warning", "(", "'Repositories not found in %s'", ",", "repos", ")", "return", "repos_cfg" ]
Create a new term and add it to the term layer
def create_term ( self , lemma , pos , morphofeat , tokens , id = None ) : if id is None : n = 1 if self . term_layer is None else len ( self . term_layer . idx ) + 1 id = "t{n}" . format ( * * locals ( ) ) new_term = Cterm ( type = self . type ) new_term . set_id ( id ) new_term . set_lemma ( lemma ) new_term . set_pos ( pos ) new_term . set_morphofeat ( morphofeat ) new_span = Cspan ( ) for token in tokens : new_span . add_target_id ( token . get_id ( ) ) new_term . set_span ( new_span ) self . add_term ( new_term ) return new_term
6,710
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1045-L1072
[ "def", "launcher", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-f'", ",", "'--file'", ",", "dest", "=", "'filename'", ",", "default", "=", "'agents.csv'", ",", "help", "=", "'snmposter configuration file'", ")", "options", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "factory", "=", "SNMPosterFactory", "(", ")", "snmpd_status", "=", "subprocess", ".", "Popen", "(", "[", "\"service\"", ",", "\"snmpd\"", ",", "\"status\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "if", "\"is running\"", "in", "snmpd_status", ":", "message", "=", "\"snmd service is running. Please stop it and try again.\"", "print", ">>", "sys", ".", "stderr", ",", "message", "sys", ".", "exit", "(", "1", ")", "try", ":", "factory", ".", "configure", "(", "options", ".", "filename", ")", "except", "IOError", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Error opening %s.\"", "%", "options", ".", "filename", "sys", ".", "exit", "(", "1", ")", "factory", ".", "start", "(", ")" ]
Adds a markable to the markable layer
def add_markable ( self , markable_obj ) : if self . markable_layer is None : self . markable_layer = Cmarkables ( type = self . type ) self . root . append ( self . markable_layer . get_node ( ) ) self . markable_layer . add_markable ( markable_obj )
6,711
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1074-L1083
[ "def", "get_all", "(", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "sessions", "=", "{", "}", "for", "name", "in", "conf", ".", "sections", "(", ")", ":", "sessions", "[", "name", "]", "=", "{", "'type'", ":", "conf", ".", "get", "(", "name", ",", "'type'", ")", ",", "'host'", ":", "conf", ".", "get", "(", "name", ",", "'host'", ")", ",", "'protocol'", ":", "conf", ".", "get", "(", "name", ",", "'protocol'", ")", ",", "'port'", ":", "conf", ".", "getint", "(", "name", ",", "'port'", ")", ",", "'timeout'", ":", "conf", ".", "getfloat", "(", "name", ",", "'timeout'", ")", ",", "'user'", ":", "conf", ".", "get", "(", "name", ",", "'user'", ")", ",", "'passwd'", ":", "conf", ".", "get", "(", "name", ",", "'passwd'", ")", ",", "'database'", ":", "conf", ".", "get", "(", "name", ",", "'database'", ")", ",", "}", "return", "sessions" ]
Adds an opinion to the opinion layer
def add_opinion ( self , opinion_obj ) : if self . opinion_layer is None : self . opinion_layer = Copinions ( ) self . root . append ( self . opinion_layer . get_node ( ) ) self . opinion_layer . add_opinion ( opinion_obj )
6,712
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1086-L1095
[ "def", "_ParseWtmp", "(", ")", ":", "users", "=", "{", "}", "wtmp_struct_size", "=", "UtmpStruct", ".", "GetSize", "(", ")", "filenames", "=", "glob", ".", "glob", "(", "\"/var/log/wtmp*\"", ")", "+", "[", "\"/var/run/utmp\"", "]", "for", "filename", "in", "filenames", ":", "try", ":", "wtmp", "=", "open", "(", "filename", ",", "\"rb\"", ")", ".", "read", "(", ")", "except", "IOError", ":", "continue", "for", "offset", "in", "range", "(", "0", ",", "len", "(", "wtmp", ")", ",", "wtmp_struct_size", ")", ":", "try", ":", "record", "=", "UtmpStruct", "(", "wtmp", "[", "offset", ":", "offset", "+", "wtmp_struct_size", "]", ")", "except", "utils", ".", "ParsingError", ":", "break", "# Users only appear for USER_PROCESS events, others are system.", "if", "record", ".", "ut_type", "!=", "7", ":", "continue", "try", ":", "if", "users", "[", "record", ".", "ut_user", "]", "<", "record", ".", "tv_sec", ":", "users", "[", "record", ".", "ut_user", "]", "=", "record", ".", "tv_sec", "except", "KeyError", ":", "users", "[", "record", ".", "ut_user", "]", "=", "record", ".", "tv_sec", "return", "users" ]
Adds a statement to the attribution layer
def add_statement ( self , statement_obj ) : if self . attribution_layer is None : self . attribution_layer = Cattribution ( ) self . root . append ( self . attribution_layer . get_node ( ) ) self . attribution_layer . add_statement ( statement_obj )
6,713
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1097-L1106
[ "def", "load", "(", "cls", ",", "fname", ",", "args", ")", ":", "if", "args", ".", "type", "==", "JSON", ":", "if", "fname", ".", "endswith", "(", "'.bz2'", ")", ":", "open_", "=", "bz2", ".", "open", "else", ":", "open_", "=", "open", "if", "args", ".", "progress", ":", "print", "(", "'Loading JSON data...'", ")", "with", "open_", "(", "fname", ",", "'rt'", ")", "as", "fp", ":", "storage", "=", "JsonStorage", ".", "load", "(", "fp", ")", "else", ":", "storage", "=", "SqliteStorage", ".", "load", "(", "fname", ")", "if", "args", ".", "settings", "is", "not", "None", ":", "extend", "(", "storage", ".", "settings", ",", "args", ".", "settings", ")", "return", "cls", ".", "from_storage", "(", "storage", ")" ]
Adds a predicate to the semantic layer
def add_predicate ( self , predicate_obj ) : if self . srl_layer is None : self . srl_layer = Csrl ( ) self . root . append ( self . srl_layer . get_node ( ) ) self . srl_layer . add_predicate ( predicate_obj )
6,714
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1110-L1119
[ "def", "_create_projects_file", "(", "project_name", ",", "data_source", ",", "items", ")", ":", "repositories", "=", "[", "]", "for", "item", "in", "items", ":", "if", "item", "[", "'origin'", "]", "not", "in", "repositories", ":", "repositories", ".", "append", "(", "item", "[", "'origin'", "]", ")", "projects", "=", "{", "project_name", ":", "{", "data_source", ":", "repositories", "}", "}", "projects_file", ",", "projects_file_path", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "'track_items_'", ")", "with", "open", "(", "projects_file_path", ",", "\"w\"", ")", "as", "pfile", ":", "json", ".", "dump", "(", "projects", ",", "pfile", ",", "indent", "=", "True", ")", "return", "projects_file_path" ]
Adds a timex entry to the time layer
def add_timex ( self , time_obj ) : if self . timex_layer is None : self . timex_layer = CtimeExpressions ( ) self . root . append ( self . timex_layer . get_node ( ) ) self . timex_layer . add_timex ( time_obj )
6,715
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1121-L1130
[ "def", "split_markers_from_line", "(", "line", ")", ":", "# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]", "if", "not", "any", "(", "line", ".", "startswith", "(", "uri_prefix", ")", "for", "uri_prefix", "in", "SCHEME_LIST", ")", ":", "marker_sep", "=", "\";\"", "else", ":", "marker_sep", "=", "\"; \"", "markers", "=", "None", "if", "marker_sep", "in", "line", ":", "line", ",", "markers", "=", "line", ".", "split", "(", "marker_sep", ",", "1", ")", "markers", "=", "markers", ".", "strip", "(", ")", "if", "markers", "else", "None", "return", "line", ",", "markers" ]
Sets the header of the object
def set_header ( self , header ) : self . header = header self . root . insert ( 0 , header . get_node ( ) )
6,716
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1133-L1140
[ "def", "delete", "(", "name", ",", "timeout", "=", "90", ")", ":", "handle_scm", "=", "win32service", ".", "OpenSCManager", "(", "None", ",", "None", ",", "win32service", ".", "SC_MANAGER_CONNECT", ")", "try", ":", "handle_svc", "=", "win32service", ".", "OpenService", "(", "handle_scm", ",", "name", ",", "win32service", ".", "SERVICE_ALL_ACCESS", ")", "except", "pywintypes", ".", "error", "as", "exc", ":", "win32service", ".", "CloseServiceHandle", "(", "handle_scm", ")", "if", "exc", ".", "winerror", "!=", "1060", ":", "raise", "CommandExecutionError", "(", "'Failed to open {0}. {1}'", ".", "format", "(", "name", ",", "exc", ".", "strerror", ")", ")", "log", ".", "debug", "(", "'Service \"%s\" is not present'", ",", "name", ")", "return", "True", "try", ":", "win32service", ".", "DeleteService", "(", "handle_svc", ")", "except", "pywintypes", ".", "error", "as", "exc", ":", "raise", "CommandExecutionError", "(", "'Failed to delete {0}. {1}'", ".", "format", "(", "name", ",", "exc", ".", "strerror", ")", ")", "finally", ":", "log", ".", "debug", "(", "'Cleaning up'", ")", "win32service", ".", "CloseServiceHandle", "(", "handle_scm", ")", "win32service", ".", "CloseServiceHandle", "(", "handle_svc", ")", "end_time", "=", "time", ".", "time", "(", ")", "+", "int", "(", "timeout", ")", "while", "name", "in", "get_all", "(", ")", "and", "time", ".", "time", "(", ")", "<", "end_time", ":", "time", ".", "sleep", "(", "1", ")", "return", "name", "not", "in", "get_all", "(", ")" ]
Adds a linguistic processor to the header
def add_linguistic_processor ( self , layer , my_lp ) : if self . header is None : self . header = CHeader ( type = self . type ) self . root . insert ( 0 , self . header . get_node ( ) ) self . header . add_linguistic_processor ( layer , my_lp )
6,717
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1142-L1153
[ "def", "flatten", "(", "weights", ",", "start", "=", "0", ",", "stop", "=", "2", ")", ":", "for", "key", ",", "val", "in", "weights", ".", "items", "(", ")", ":", "new_shape", "=", "val", ".", "shape", "[", "0", ":", "start", "]", "+", "(", "-", "1", ",", ")", "+", "val", ".", "shape", "[", "stop", ":", "]", "weights", "[", "key", "]", "=", "val", ".", "reshape", "(", "new_shape", ")", "return", "weights" ]
Create a new linguistic processor element and add it to the header
def create_linguistic_processor ( self , layer , name , version , * * kwargs ) : lp = Clp ( name = name , version = version , * * kwargs ) self . add_linguistic_processor ( layer , lp ) return lp
6,718
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1155-L1168
[ "def", "get_roles", "(", ")", ":", "roles", "=", "[", "]", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "'roles'", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", "\".json\"", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", "[", "len", "(", "'roles'", ")", ":", "]", ",", "filename", "[", ":", "-", "len", "(", "'.json'", ")", "]", ")", "roles", ".", "append", "(", "_get_role", "(", "path", ")", ")", "return", "sorted", "(", "roles", ",", "key", "=", "lambda", "x", ":", "x", "[", "'fullname'", "]", ")" ]
Adds a dependency to the dependency layer
def add_dependency ( self , my_dep ) : if self . dependency_layer is None : self . dependency_layer = Cdependencies ( ) self . root . append ( self . dependency_layer . get_node ( ) ) self . dependency_layer . add_dependency ( my_dep )
6,719
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1170-L1179
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "ClassRegistrationView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'user'", "]", "=", "self", ".", "request", ".", "user", "if", "hasattr", "(", "self", ".", "request", ",", "'user'", ")", "else", "None", "listing", "=", "self", ".", "get_listing", "(", ")", "kwargs", ".", "update", "(", "{", "'openEvents'", ":", "listing", "[", "'openEvents'", "]", ",", "'closedEvents'", ":", "listing", "[", "'closedEvents'", "]", ",", "}", ")", "return", "kwargs" ]
Create a new dependency object and add it to the dependency layer
def create_dependency ( self , _from , to , function , comment = None ) : new_dependency = Cdependency ( ) new_dependency . set_from ( _from ) new_dependency . set_to ( to ) new_dependency . set_function ( function ) if comment : new_dependency . set_comment ( comment ) self . add_dependency ( new_dependency ) return new_dependency
6,720
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1181-L1200
[ "def", "on_close", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"> Calling '{0}' Component Framework 'on_close' method.\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "map", "(", "self", ".", "unregister_file", ",", "self", ".", "list_files", "(", ")", ")", "if", "self", ".", "store_session", "(", ")", "and", "self", ".", "close_all_files", "(", "leave_first_editor", "=", "False", ")", ":", "return", "True" ]
Adds a tlink to the temporalRelations layer
def add_tlink ( self , my_tlink ) : if self . temporalRelations_layer is None : self . temporalRelations_layer = CtemporalRelations ( ) self . root . append ( self . temporalRelations_layer . get_node ( ) ) self . temporalRelations_layer . add_tlink ( my_tlink )
6,721
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1202-L1211
[ "def", "config", "(", "name", ",", "config", ",", "edit", "=", "True", ")", ":", "configs", "=", "[", "]", "for", "entry", "in", "config", ":", "key", "=", "next", "(", "six", ".", "iterkeys", "(", "entry", ")", ")", "configs", ".", "append", "(", "_parse_config", "(", "entry", "[", "key", "]", ",", "key", ")", ")", "# Python auto-correct line endings", "configstext", "=", "'\\n'", ".", "join", "(", "salt", ".", "utils", ".", "data", ".", "decode", "(", "configs", ")", ")", "if", "edit", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "name", ",", "'w'", ")", "as", "configfile", ":", "configfile", ".", "write", "(", "'# This file is managed by Salt.\\n'", ")", "configfile", ".", "write", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "configstext", ")", ")", "return", "configstext" ]
Adds a predAnch to the temporalRelations layer
def add_predicateAnchor ( self , my_predAnch ) : if self . temporalRelations_layer is None : self . temporalRelations_layer = CtemporalRelations ( ) self . root . append ( self . temporalRelations_layer . get_node ( ) ) self . temporalRelations_layer . add_predicateAnchor ( my_predAnch )
6,722
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1213-L1222
[ "def", "clean_file", "(", "config_file", ")", ":", "logging", ".", "info", "(", "'[begin] Cleaning config file'", ")", "config", "=", "GroupConfigFile", "(", "config_file", "=", "config_file", ")", "if", "config", ".", "is_fresh", "(", ")", "is", "True", ":", "raise", "ValueError", "(", "\"Config is already clean.\"", ")", "config", ".", "make_fresh", "(", ")", "logging", ".", "info", "(", "'[end] Cleaned config file:{0}'", ".", "format", "(", "config_file", ")", ")" ]
Adds a clink to the causalRelations layer
def add_clink ( self , my_clink ) : if self . causalRelations_layer is None : self . causalRelations_layer = CcausalRelations ( ) self . root . append ( self . causalRelations_layer . get_node ( ) ) self . causalRelations_layer . add_clink ( my_clink )
6,723
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1224-L1233
[ "def", "edit_config", "(", "filename", ",", "settings", ",", "dry_run", "=", "False", ")", ":", "log", ".", "debug", "(", "\"Reading configuration from %s\"", ",", "filename", ")", "opts", "=", "configparser", ".", "RawConfigParser", "(", ")", "opts", ".", "read", "(", "[", "filename", "]", ")", "for", "section", ",", "options", "in", "settings", ".", "items", "(", ")", ":", "if", "options", "is", "None", ":", "log", ".", "info", "(", "\"Deleting section [%s] from %s\"", ",", "section", ",", "filename", ")", "opts", ".", "remove_section", "(", "section", ")", "else", ":", "if", "not", "opts", ".", "has_section", "(", "section", ")", ":", "log", ".", "debug", "(", "\"Adding new section [%s] to %s\"", ",", "section", ",", "filename", ")", "opts", ".", "add_section", "(", "section", ")", "for", "option", ",", "value", "in", "options", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "log", ".", "debug", "(", "\"Deleting %s.%s from %s\"", ",", "section", ",", "option", ",", "filename", ")", "opts", ".", "remove_option", "(", "section", ",", "option", ")", "if", "not", "opts", ".", "options", "(", "section", ")", ":", "log", ".", "info", "(", "\"Deleting empty [%s] section from %s\"", ",", "section", ",", "filename", ")", "opts", ".", "remove_section", "(", "section", ")", "else", ":", "log", ".", "debug", "(", "\"Setting %s.%s to %r in %s\"", ",", "section", ",", "option", ",", "value", ",", "filename", ")", "opts", ".", "set", "(", "section", ",", "option", ",", "value", ")", "log", ".", "info", "(", "\"Writing %s\"", ",", "filename", ")", "if", "not", "dry_run", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "opts", ".", "write", "(", "f", ")" ]
Adds a factuality to the factuality layer
def add_factuality ( self , my_fact ) : if self . factuality_layer is None : self . factuality_layer = Cfactualities ( ) self . root . append ( self . factuality_layer . get_node ( ) ) self . factuality_layer . add_factuality ( my_fact )
6,724
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1235-L1244
[ "def", "json_parse", "(", "self", ",", "response", ")", ":", "try", ":", "data", "=", "response", ".", "json", "(", ")", "except", "ValueError", ":", "data", "=", "{", "'meta'", ":", "{", "'status'", ":", "500", ",", "'msg'", ":", "'Server Error'", "}", ",", "'response'", ":", "{", "\"error\"", ":", "\"Malformed JSON or HTML was returned.\"", "}", "}", "# We only really care about the response if we succeed", "# and the error if we fail", "if", "200", "<=", "data", "[", "'meta'", "]", "[", "'status'", "]", "<=", "399", ":", "return", "data", "[", "'response'", "]", "else", ":", "return", "data" ]
Adds an entity to the entity layer
def add_entity ( self , entity ) : if self . entity_layer is None : self . entity_layer = Centities ( type = self . type ) self . root . append ( self . entity_layer . get_node ( ) ) self . entity_layer . add_entity ( entity )
6,725
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1246-L1255
[ "def", "compute_score", "(", "self", ")", ":", "# LOGGER.info(\"Begin scoring\")", "cases", "=", "self", ".", "get_configured_tests", "(", ")", "|", "set", "(", "self", ".", "result", ".", "cases", ")", "scores", "=", "DataFrame", "(", "{", "\"score\"", ":", "0.0", ",", "\"max\"", ":", "1.0", "}", ",", "index", "=", "sorted", "(", "cases", ")", ")", "self", ".", "result", ".", "setdefault", "(", "\"score\"", ",", "dict", "(", ")", ")", "self", ".", "result", "[", "\"score\"", "]", "[", "\"sections\"", "]", "=", "list", "(", ")", "# Calculate the scores for each test individually.", "for", "test", ",", "result", "in", "iteritems", "(", "self", ".", "result", ".", "cases", ")", ":", "# LOGGER.info(\"Calculate score for test: '%s'.\", test)", "# Test metric may be a dictionary for a parametrized test.", "metric", "=", "result", "[", "\"metric\"", "]", "if", "hasattr", "(", "metric", ",", "\"items\"", ")", ":", "result", "[", "\"score\"", "]", "=", "test_score", "=", "dict", "(", ")", "total", "=", "0.0", "for", "key", ",", "value", "in", "iteritems", "(", "metric", ")", ":", "value", "=", "1.0", "-", "value", "total", "+=", "value", "test_score", "[", "key", "]", "=", "value", "# For some reason there are parametrized tests without cases.", "if", "len", "(", "metric", ")", "==", "0", ":", "metric", "=", "0.0", "else", ":", "metric", "=", "total", "/", "len", "(", "metric", ")", "else", ":", "metric", "=", "1.0", "-", "metric", "scores", ".", "at", "[", "test", ",", "\"score\"", "]", "=", "metric", "scores", ".", "loc", "[", "test", ",", ":", "]", "*=", "self", ".", "config", "[", "\"weights\"", "]", ".", "get", "(", "test", ",", "1.0", ")", "score", "=", "0.0", "maximum", "=", "0.0", "# Calculate the scores for each section considering the individual test", "# case scores.", "for", "section_id", ",", "card", "in", "iteritems", "(", "self", ".", "config", "[", "'cards'", "]", "[", "'scored'", "]", "[", "'sections'", "]", ")", ":", "# LOGGER.info(\"Calculate score for section: '%s'.\", section_id)", "cases", "=", "card", ".", "get", "(", "\"cases\"", ",", "None", ")", "if", "cases", "is", "None", ":", "continue", "card_score", "=", "scores", ".", "loc", "[", "cases", ",", "\"score\"", "]", ".", "sum", "(", ")", "card_total", "=", "scores", ".", "loc", "[", "cases", ",", "\"max\"", "]", ".", "sum", "(", ")", "# Format results nicely to work immediately with Vega Bar Chart.", "section_score", "=", "{", "\"section\"", ":", "section_id", ",", "\"score\"", ":", "card_score", "/", "card_total", "}", "self", ".", "result", "[", "\"score\"", "]", "[", "\"sections\"", "]", ".", "append", "(", "section_score", ")", "# Calculate the final score for the entire model.", "weight", "=", "card", ".", "get", "(", "\"weight\"", ",", "1.0", ")", "score", "+=", "card_score", "*", "weight", "maximum", "+=", "card_total", "*", "weight", "self", ".", "result", "[", "\"score\"", "]", "[", "\"total_score\"", "]", "=", "score", "/", "maximum" ]
Adds an coreference to the coreference layer
def add_coreference ( self , coreference ) : if self . coreference_layer is None : self . coreference_layer = Ccoreferences ( type = self . type ) self . root . append ( self . coreference_layer . get_node ( ) ) self . coreference_layer . add_coreference ( coreference )
6,726
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1279-L1288
[ "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" ]
Create a new coreference object and add it to the coreferences layer
def create_coreference ( self , coref_type , term_ids , id = None ) : if id is None : if self . coreference_layer is None : i = 1 else : corefs = ( l for l in self . coreference_layer . get_corefs ( ) if l . get_type == coref_type ) i = len ( list ( corefs ) ) + 1 id = "co{coref_type}{i}" . format ( * * locals ( ) ) new_coref = Ccoreference ( type = self . type ) new_coref . set_id ( id ) new_coref . set_type ( coref_type ) new_coref . add_span ( term_ids ) self . add_coreference ( new_coref ) return new_coref
6,727
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1290-L1313
[ "def", "launcher", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-f'", ",", "'--file'", ",", "dest", "=", "'filename'", ",", "default", "=", "'agents.csv'", ",", "help", "=", "'snmposter configuration file'", ")", "options", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "factory", "=", "SNMPosterFactory", "(", ")", "snmpd_status", "=", "subprocess", ".", "Popen", "(", "[", "\"service\"", ",", "\"snmpd\"", ",", "\"status\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "if", "\"is running\"", "in", "snmpd_status", ":", "message", "=", "\"snmd service is running. Please stop it and try again.\"", "print", ">>", "sys", ".", "stderr", ",", "message", "sys", ".", "exit", "(", "1", ")", "try", ":", "factory", ".", "configure", "(", "options", ".", "filename", ")", "except", "IOError", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Error opening %s.\"", "%", "options", ".", "filename", "sys", ".", "exit", "(", "1", ")", "factory", ".", "start", "(", ")" ]
Adds a constituency tree to the constituency layer
def add_constituency_tree ( self , my_tree ) : if self . constituency_layer is None : self . constituency_layer = Cconstituency ( ) self . root . append ( self . constituency_layer . get_node ( ) ) self . constituency_layer . add_tree ( my_tree )
6,728
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1315-L1324
[ "def", "sort2groups", "(", "array", ",", "gpat", "=", "[", "'_R1'", ",", "'_R2'", "]", ")", ":", "groups", "=", "[", "REGroup", "(", "gp", ")", "for", "gp", "in", "gpat", "]", "unmatched", "=", "[", "]", "for", "item", "in", "array", ":", "matched", "=", "False", "for", "m", "in", "groups", ":", "if", "m", ".", "match", "(", "item", ")", ":", "matched", "=", "True", "break", "if", "not", "matched", ":", "unmatched", ".", "append", "(", "item", ")", "return", "[", "sorted", "(", "m", ".", "list", ")", "for", "m", "in", "groups", "]", ",", "sorted", "(", "unmatched", ")" ]
Adds a property to the property layer
def add_property ( self , label , term_span , pid = None ) : if self . features_layer is None : self . features_layer = Cfeatures ( type = self . type ) self . root . append ( self . features_layer . get_node ( ) ) self . features_layer . add_property ( pid , label , term_span )
6,729
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1327-L1340
[ "def", "_find_start_time", "(", "hdr", ",", "s_freq", ")", ":", "start_time", "=", "hdr", "[", "'stc'", "]", "[", "'creation_time'", "]", "for", "one_stamp", "in", "hdr", "[", "'stamps'", "]", ":", "if", "one_stamp", "[", "'segment_name'", "]", ".", "decode", "(", ")", "==", "hdr", "[", "'erd'", "]", "[", "'filename'", "]", ":", "offset", "=", "one_stamp", "[", "'start_stamp'", "]", "break", "erd_time", "=", "(", "hdr", "[", "'erd'", "]", "[", "'creation_time'", "]", "-", "timedelta", "(", "seconds", "=", "offset", "/", "s_freq", ")", ")", ".", "replace", "(", "microsecond", "=", "0", ")", "stc_erd_diff", "=", "(", "start_time", "-", "erd_time", ")", ".", "total_seconds", "(", ")", "if", "stc_erd_diff", ">", "START_TIME_TOL", ":", "lg", ".", "warn", "(", "'Time difference between ERD and STC is {} s so using ERD time'", "' at {}'", ".", "format", "(", "stc_erd_diff", ",", "erd_time", ")", ")", "start_time", "=", "erd_time", "return", "start_time" ]
Returns the tokens ids that are the span of the term specified
def get_dict_tokens_for_termid ( self , term_id ) : if self . dict_tokens_for_tid is None : self . dict_tokens_for_tid = { } for term in self . get_terms ( ) : self . dict_tokens_for_tid [ term . get_id ( ) ] = term . get_span ( ) . get_span_ids ( ) return self . dict_tokens_for_tid . get ( term_id , [ ] )
6,730
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1344-L1357
[ "def", "_connect", "(", "self", ")", ":", "try", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">=", "(", "2", ",", "6", ")", ":", "self", ".", "_conn", "=", "telnetlib", ".", "Telnet", "(", "self", ".", "_amihost", ",", "self", ".", "_amiport", ",", "connTimeout", ")", "else", ":", "self", ".", "_conn", "=", "telnetlib", ".", "Telnet", "(", "self", ".", "_amihost", ",", "self", ".", "_amiport", ")", "except", ":", "raise", "Exception", "(", "\"Connection to Asterisk Manager Interface on \"", "\"host %s and port %s failed.\"", "%", "(", "self", ".", "_amihost", ",", "self", ".", "_amiport", ")", ")" ]
Maps a list of token ids to the corresponding term ids
def map_tokens_to_terms ( self , list_tokens ) : if self . terms_for_token is None : self . terms_for_token = { } for term in self . get_terms ( ) : termid = term . get_id ( ) token_ids = term . get_span ( ) . get_span_ids ( ) for tokid in token_ids : if tokid not in self . terms_for_token : self . terms_for_token [ tokid ] = [ termid ] else : self . terms_for_token [ tokid ] . append ( termid ) ret = set ( ) for my_id in list_tokens : term_ids = self . terms_for_token . get ( my_id , [ ] ) ret |= set ( term_ids ) return sorted ( list ( ret ) )
6,731
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1360-L1383
[ "def", "CheckLocation", "(", ")", ":", "for", "url", "in", "(", "config", ".", "CONFIG", "[", "\"Client.server_urls\"", "]", "+", "config", ".", "CONFIG", "[", "\"Client.control_urls\"", "]", ")", ":", "if", "\"staging\"", "in", "url", "or", "\"localhost\"", "in", "url", ":", "# This is ok.", "return", "logging", ".", "error", "(", "\"Poolclient should only be run against test or staging.\"", ")", "exit", "(", ")" ]
Adds an external reference to the given term identifier
def add_external_reference_to_term ( self , term_id , external_ref ) : if self . term_layer is not None : self . term_layer . add_external_reference ( term_id , external_ref )
6,732
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1406-L1415
[ "def", "config_diff", "(", "args", ")", ":", "config_1", "=", "config_get", "(", "args", ")", ".", "splitlines", "(", ")", "args", ".", "project", "=", "args", ".", "Project", "args", ".", "workspace", "=", "args", ".", "Workspace", "cfg_1_name", "=", "args", ".", "config", "if", "args", ".", "Config", "is", "not", "None", ":", "args", ".", "config", "=", "args", ".", "Config", "if", "args", ".", "Namespace", "is", "not", "None", ":", "args", ".", "namespace", "=", "args", ".", "Namespace", "config_2", "=", "config_get", "(", "args", ")", ".", "splitlines", "(", ")", "if", "not", "args", ".", "verbose", ":", "config_1", "=", "skip_cfg_ver", "(", "config_1", ")", "config_2", "=", "skip_cfg_ver", "(", "config_2", ")", "return", "list", "(", "unified_diff", "(", "config_1", ",", "config_2", ",", "cfg_1_name", ",", "args", ".", "config", ",", "lineterm", "=", "''", ")", ")" ]
Adds an external reference to the given role identifier in the SRL layer
def add_external_reference_to_role ( self , role_id , external_ref ) : if self . srl_layer is not None : self . srl_layer . add_external_reference_to_role ( role_id , external_ref )
6,733
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1426-L1435
[ "def", "start", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_running", "(", ")", ":", "self", ".", "websock_url", "=", "self", ".", "chrome", ".", "start", "(", "*", "*", "kwargs", ")", "self", ".", "websock", "=", "websocket", ".", "WebSocketApp", "(", "self", ".", "websock_url", ")", "self", ".", "websock_thread", "=", "WebsockReceiverThread", "(", "self", ".", "websock", ",", "name", "=", "'WebsockThread:%s'", "%", "self", ".", "chrome", ".", "port", ")", "self", ".", "websock_thread", ".", "start", "(", ")", "self", ".", "_wait_for", "(", "lambda", ":", "self", ".", "websock_thread", ".", "is_open", ",", "timeout", "=", "30", ")", "# tell browser to send us messages we're interested in", "self", ".", "send_to_chrome", "(", "method", "=", "'Network.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'Page.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'Console.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'Runtime.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'ServiceWorker.enable'", ")", "self", ".", "send_to_chrome", "(", "method", "=", "'ServiceWorker.setForceUpdateOnPageLoad'", ")", "# disable google analytics", "self", ".", "send_to_chrome", "(", "method", "=", "'Network.setBlockedURLs'", ",", "params", "=", "{", "'urls'", ":", "[", "'*google-analytics.com/analytics.js'", ",", "'*google-analytics.com/ga.js'", "]", "}", ")" ]
Removes all external references present in the term layer
def remove_external_references_from_srl_layer ( self ) : if self . srl_layer is not None : for pred in self . srl_layer . get_predicates ( ) : pred . remove_external_references ( ) pred . remove_external_references_from_roles ( )
6,734
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1439-L1446
[ "def", "_is_robot", "(", ")", ":", "robot_regex", "=", "current_app", ".", "config", "[", "'SPLIT_ROBOT_REGEX'", "]", "user_agent", "=", "request", ".", "headers", ".", "get", "(", "'User-Agent'", ",", "''", ")", "return", "re", ".", "search", "(", "robot_regex", ",", "user_agent", ",", "flags", "=", "re", ".", "VERBOSE", ")" ]
Adds an external reference to the given entity identifier in the entity layer
def add_external_reference_to_entity ( self , entity_id , external_ref ) : if self . entity_layer is not None : self . entity_layer . add_external_reference_to_entity ( entity_id , external_ref )
6,735
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1448-L1457
[ "def", "_ensure_file_path", "(", "self", ")", ":", "storage_root", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "file_path", ")", "needs_storage_root", "=", "storage_root", "and", "not", "os", ".", "path", ".", "isdir", "(", "storage_root", ")", "if", "needs_storage_root", ":", "# pragma: no cover", "os", ".", "makedirs", "(", "storage_root", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "file_path", ")", ":", "# create the file without group/world permissions", "with", "open", "(", "self", ".", "file_path", ",", "'w'", ")", ":", "pass", "user_read_write", "=", "0o600", "os", ".", "chmod", "(", "self", ".", "file_path", ",", "user_read_write", ")" ]
read a number of bytes from the file and return it as a string
def read ( self , size = - 1 ) : chunksize = size < 0 and self . CHUNKSIZE or min ( self . CHUNKSIZE , size ) buf = self . _rbuf buf . seek ( 0 , os . SEEK_END ) collected = buf . tell ( ) while 1 : if size >= 0 and collected >= size : # we have read enough already break output = self . _read_chunk ( chunksize ) if output is None : continue if not output : # nothing more to read break collected += len ( output ) buf . write ( output ) # get rid of the old buffer rc = buf . getvalue ( ) buf . seek ( 0 ) buf . truncate ( ) if size >= 0 : # leave the overflow in the buffer buf . write ( rc [ size : ] ) return rc [ : size ] return rc
6,736
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L48-L91
[ "def", "updateSeriesRegistrationStatus", "(", ")", ":", "from", ".", "models", "import", "Series", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "logger", ".", "info", "(", "'Checking status of Series that are open for registration.'", ")", "open_series", "=", "Series", ".", "objects", ".", "filter", "(", ")", ".", "filter", "(", "*", "*", "{", "'registrationOpen'", ":", "True", "}", ")", "for", "series", "in", "open_series", ":", "series", ".", "updateRegistrationStatus", "(", ")" ]
read from the file until a newline is encountered
def readline ( self , max_len = - 1 ) : buf = self . _rbuf newline , chunksize = self . NEWLINE , self . CHUNKSIZE buf . seek ( 0 ) text = buf . read ( ) if len ( text ) >= max_len >= 0 : buf . seek ( 0 ) buf . truncate ( ) buf . write ( text [ max_len : ] ) return text [ : max_len ] while text . find ( newline ) < 0 : text = self . _read_chunk ( chunksize ) if text is None : text = '' continue if buf . tell ( ) + len ( text ) >= max_len >= 0 : text = buf . getvalue ( ) + text buf . seek ( 0 ) buf . truncate ( ) buf . write ( text [ max_len : ] ) return text [ : max_len ] if not text : break buf . write ( text ) else : # found a newline rc = buf . getvalue ( ) index = rc . find ( newline ) + len ( newline ) buf . seek ( 0 ) buf . truncate ( ) buf . write ( rc [ index : ] ) return rc [ : index ] # hit the end of the file, no more newlines rc = buf . getvalue ( ) buf . seek ( 0 ) buf . truncate ( ) return rc
6,737
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L93-L147
[ "def", "catalogFactory", "(", "name", ",", "*", "*", "kwargs", ")", ":", "fn", "=", "lambda", "member", ":", "inspect", ".", "isclass", "(", "member", ")", "and", "member", ".", "__module__", "==", "__name__", "catalogs", "=", "odict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "fn", ")", ")", "if", "name", "not", "in", "list", "(", "catalogs", ".", "keys", "(", ")", ")", ":", "msg", "=", "\"%s not found in catalogs:\\n %s\"", "%", "(", "name", ",", "list", "(", "kernels", ".", "keys", "(", ")", ")", ")", "logger", ".", "error", "(", "msg", ")", "msg", "=", "\"Unrecognized catalog: %s\"", "%", "name", "raise", "Exception", "(", "msg", ")", "return", "catalogs", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
write data to the file
def write ( self , data ) : while data : went = self . _write_chunk ( data ) if went is None : continue data = data [ went : ]
6,738
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L161-L173
[ "def", "_get_available_letters", "(", "field_name", ",", "queryset", ")", ":", "if", "django", ".", "VERSION", "[", "1", "]", "<=", "4", ":", "result", "=", "queryset", ".", "values", "(", "field_name", ")", ".", "annotate", "(", "fl", "=", "FirstLetter", "(", "field_name", ")", ")", ".", "values", "(", "'fl'", ")", ".", "distinct", "(", ")", "return", "set", "(", "[", "res", "[", "'fl'", "]", "for", "res", "in", "result", "if", "res", "[", "'fl'", "]", "is", "not", "None", "]", ")", "else", ":", "from", "django", ".", "db", "import", "connection", "qn", "=", "connection", ".", "ops", ".", "quote_name", "db_table", "=", "queryset", ".", "model", ".", "_meta", ".", "db_table", "sql", "=", "\"SELECT DISTINCT UPPER(SUBSTR(%s, 1, 1)) as letter FROM %s\"", "%", "(", "qn", "(", "field_name", ")", ",", "qn", "(", "db_table", ")", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "sql", ")", "rows", "=", "cursor", ".", "fetchall", "(", ")", "or", "(", ")", "return", "set", "(", "[", "row", "[", "0", "]", "for", "row", "in", "rows", "if", "row", "[", "0", "]", "is", "not", "None", "]", ")" ]
wait on our events
def _wait_event ( self , reading ) : with self . _registered ( reading , not reading ) : ( self . _readable if reading else self . _writable ) . wait ( ) if scheduler . state . interrupted : raise IOError ( errno . EINTR , "interrupted system call" )
6,739
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L273-L279
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "base_path", ")", "admin_metadata_fpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\".dtool\"", ",", "\"dtool\"", ")", "with", "open", "(", "admin_metadata_fpath", ")", "as", "fh", ":", "admin_metadata", "=", "json", ".", "load", "(", "fh", ")", "http_manifest", "=", "{", "\"admin_metadata\"", ":", "admin_metadata", ",", "\"manifest_url\"", ":", "self", ".", "generate_url", "(", "\".dtool/manifest.json\"", ")", ",", "\"readme_url\"", ":", "self", ".", "generate_url", "(", "\"README.yml\"", ")", ",", "\"overlays\"", ":", "self", ".", "generate_overlay_urls", "(", ")", ",", "\"item_urls\"", ":", "self", ".", "generate_item_urls", "(", ")", "}", "return", "bytes", "(", "json", ".", "dumps", "(", "http_manifest", ")", ",", "\"utf-8\"", ")" ]
create a cooperating greenhouse file from an existing descriptor
def fromfd ( cls , fd , mode = 'rb' , bufsize = - 1 ) : fp = object . __new__ ( cls ) # bypass __init__ fp . _rbuf = StringIO ( ) fp . encoding = None fp . mode = mode fp . _fileno = fd fp . _closed = False cls . _add_flags ( fd , cls . _mode_to_flags ( mode ) ) fp . _set_up_waiting ( ) return fp
6,740
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L310-L333
[ "def", "is_restricted", "(", "self", ",", "assets", ",", "dt", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "return", "self", ".", "_is_restricted_for_asset", "(", "assets", ",", "dt", ")", "is_restricted", "=", "partial", "(", "self", ".", "_is_restricted_for_asset", ",", "dt", "=", "dt", ")", "return", "pd", ".", "Series", "(", "index", "=", "pd", ".", "Index", "(", "assets", ")", ",", "data", "=", "vectorize", "(", "is_restricted", ",", "otypes", "=", "[", "bool", "]", ")", "(", "assets", ")", ")" ]
return whether the file is connected to a tty or not
def isatty ( self ) : try : return os . isatty ( self . _fileno ) except OSError , e : raise IOError ( * e . args )
6,741
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L357-L362
[ "def", "in_chain", "(", "cls", ",", "client", ",", "chain_id", ",", "expiration_dates", "=", "[", "]", ")", ":", "request_url", "=", "\"https://api.robinhood.com/options/instruments/\"", "params", "=", "{", "\"chain_id\"", ":", "chain_id", ",", "\"expiration_dates\"", ":", "\",\"", ".", "join", "(", "expiration_dates", ")", "}", "data", "=", "client", ".", "get", "(", "request_url", ",", "params", "=", "params", ")", "results", "=", "data", "[", "'results'", "]", "while", "data", "[", "'next'", "]", ":", "data", "=", "client", ".", "get", "(", "data", "[", "'next'", "]", ")", "results", ".", "extend", "(", "data", "[", "'results'", "]", ")", "return", "results" ]
move the cursor on the file descriptor to a different location
def seek ( self , position , modifier = 0 ) : os . lseek ( self . _fileno , position , modifier ) # clear out the buffer buf = self . _rbuf buf . seek ( 0 ) buf . truncate ( )
6,742
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L364-L384
[ "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", ")" ]
get the file descriptor s position relative to the file s beginning
def tell ( self ) : with _fdopen ( os . dup ( self . _fileno ) ) as fp : return fp . tell ( )
6,743
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/files.py#L386-L389
[ "def", "date_archive_year", "(", "request", ")", ":", "oldest_animal", "=", "Animal", ".", "objects", ".", "filter", "(", "Born__isnull", "=", "False", ")", ".", "order_by", "(", "'Born'", ")", "[", "0", "]", "archive_dict", "=", "{", "}", "tested_year", "=", "oldest_animal", ".", "Born", ".", "year", "while", "tested_year", "<=", "datetime", ".", "date", ".", "today", "(", ")", ".", "year", ":", "archive_dict", "[", "tested_year", "]", "=", "Animal", ".", "objects", ".", "filter", "(", "Born__year", "=", "tested_year", ")", ".", "count", "(", ")", "tested_year", "=", "tested_year", "+", "1", "return", "render", "(", "request", ",", "'animal_archive.html'", ",", "{", "\"archive_dict\"", ":", "archive_dict", "}", ")" ]
Fit the classifier with labels y and observations X
def fit ( self , labels , samples , pstates ) : assert len ( labels ) == len ( samples ) == len ( pstates ) for label in set ( labels ) : label_samples = [ s for l , s in zip ( labels , samples ) if l == label ] label_pstates = [ p for l , p in zip ( labels , pstates ) if l == label ] pohmm = self . pohmm_factory ( ) pohmm . fit ( label_samples , label_pstates ) self . pohmms [ label ] = pohmm return self
6,744
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/classification.py#L16-L30
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Fit the classifier with labels y and DataFrames dfs
def fit_df ( self , labels , dfs , pstate_col = PSTATE_COL ) : assert len ( labels ) == len ( dfs ) for label in set ( labels ) : label_dfs = [ s for l , s in zip ( labels , dfs ) if l == label ] pohmm = self . pohmm_factory ( ) pohmm . fit_df ( label_dfs , pstate_col = pstate_col ) self . pohmms [ label ] = pohmm return self
6,745
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/classification.py#L32-L45
[ "def", "waitForEvent", "(", "self", ",", "event_name", ",", "predicate", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "deadline", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "time", ".", "time", "(", ")", "<=", "deadline", ":", "# Calculate the max timeout for the next event rpc call.", "rpc_timeout", "=", "deadline", "-", "time", ".", "time", "(", ")", "if", "rpc_timeout", "<", "0", ":", "break", "# A single RPC call cannot exceed MAX_TIMEOUT.", "rpc_timeout", "=", "min", "(", "rpc_timeout", ",", "MAX_TIMEOUT", ")", "try", ":", "event", "=", "self", ".", "waitAndGet", "(", "event_name", ",", "rpc_timeout", ")", "except", "TimeoutError", ":", "# Ignoring TimeoutError since we need to throw one with a more", "# specific message.", "break", "if", "predicate", "(", "event", ")", ":", "return", "event", "raise", "TimeoutError", "(", "self", ".", "_ad", ",", "'Timed out after %ss waiting for an \"%s\" event that satisfies the '", "'predicate \"%s\".'", "%", "(", "timeout", ",", "event_name", ",", "predicate", ".", "__name__", ")", ")" ]
Predict the class label of X
def predict ( self , sample , pstates ) : scores = { } for label , pohmm in self . pohmms . items ( ) : scores [ label ] = pohmm . score ( sample , pstates ) max_score_label = max ( scores . items ( ) , key = itemgetter ( 1 ) ) [ 0 ] return max_score_label , scores
6,746
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/classification.py#L47-L55
[ "def", "insert", "(", "self", ",", "crc", ",", "toc", ")", ":", "if", "self", ".", "_rw_cache", ":", "try", ":", "filename", "=", "'%s/%08X.json'", "%", "(", "self", ".", "_rw_cache", ",", "crc", ")", "cache", "=", "open", "(", "filename", ",", "'w'", ")", "cache", ".", "write", "(", "json", ".", "dumps", "(", "toc", ",", "indent", "=", "2", ",", "default", "=", "self", ".", "_encoder", ")", ")", "cache", ".", "close", "(", ")", "logger", ".", "info", "(", "'Saved cache to [%s]'", ",", "filename", ")", "self", ".", "_cache_files", "+=", "[", "filename", "]", "except", "Exception", "as", "exp", ":", "logger", ".", "warning", "(", "'Could not save cache to file [%s]: %s'", ",", "filename", ",", "str", "(", "exp", ")", ")", "else", ":", "logger", ".", "warning", "(", "'Could not save cache, no writable directory'", ")" ]
Predict the class label of DataFrame df
def predict_df ( self , df , pstate_col = PSTATE_COL ) : scores = { } for label , pohmm in self . pohmms . items ( ) : scores [ label ] = pohmm . score_df ( df , pstate_col = pstate_col ) max_score_label = max ( scores . items ( ) , key = itemgetter ( 1 ) ) [ 0 ] return max_score_label , scores
6,747
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/classification.py#L57-L65
[ "def", "insert", "(", "self", ",", "crc", ",", "toc", ")", ":", "if", "self", ".", "_rw_cache", ":", "try", ":", "filename", "=", "'%s/%08X.json'", "%", "(", "self", ".", "_rw_cache", ",", "crc", ")", "cache", "=", "open", "(", "filename", ",", "'w'", ")", "cache", ".", "write", "(", "json", ".", "dumps", "(", "toc", ",", "indent", "=", "2", ",", "default", "=", "self", ".", "_encoder", ")", ")", "cache", ".", "close", "(", ")", "logger", ".", "info", "(", "'Saved cache to [%s]'", ",", "filename", ")", "self", ".", "_cache_files", "+=", "[", "filename", "]", "except", "Exception", "as", "exp", ":", "logger", ".", "warning", "(", "'Could not save cache to file [%s]: %s'", ",", "filename", ",", "str", "(", "exp", ")", ")", "else", ":", "logger", ".", "warning", "(", "'Could not save cache, no writable directory'", ")" ]
render secrets into config object
def load_secrets ( self , secret_path ) : self . _config = p_config . render_secrets ( self . config_path , secret_path )
6,748
https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/prosper_cli.py#L57-L59
[ "def", "Nu_vertical_cylinder", "(", "Pr", ",", "Gr", ",", "L", "=", "None", ",", "D", "=", "None", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "for", "key", ",", "values", "in", "vertical_cylinder_correlations", ".", "items", "(", ")", ":", "if", "values", "[", "4", "]", "or", "all", "(", "(", "L", ",", "D", ")", ")", ":", "methods", ".", "append", "(", "key", ")", "if", "'Popiel & Churchill'", "in", "methods", ":", "methods", ".", "remove", "(", "'Popiel & Churchill'", ")", "methods", ".", "insert", "(", "0", ",", "'Popiel & Churchill'", ")", "elif", "'McAdams, Weiss & Saunders'", "in", "methods", ":", "methods", ".", "remove", "(", "'McAdams, Weiss & Saunders'", ")", "methods", ".", "insert", "(", "0", ",", "'McAdams, Weiss & Saunders'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "in", "vertical_cylinder_correlations", ":", "if", "vertical_cylinder_correlations", "[", "Method", "]", "[", "4", "]", ":", "return", "vertical_cylinder_correlations", "[", "Method", "]", "[", "0", "]", "(", "Pr", "=", "Pr", ",", "Gr", "=", "Gr", ")", "else", ":", "return", "vertical_cylinder_correlations", "[", "Method", "]", "[", "0", "]", "(", "Pr", "=", "Pr", ",", "Gr", "=", "Gr", ",", "L", "=", "L", ",", "D", "=", "D", ")", "else", ":", "raise", "Exception", "(", "\"Correlation name not recognized; see the \"", "\"documentation for the available options.\"", ")" ]
uses global logger for logging
def logger ( self ) : if self . _logger : return self . _logger else : log_builder = p_logging . ProsperLogger ( self . PROGNAME , self . config . get_option ( 'LOGGING' , 'log_path' ) , config_obj = self . config ) if self . verbose : log_builder . configure_debug_logger ( ) else : id_string = '({platform}--{version})' . format ( platform = platform . node ( ) , version = self . VERSION ) if self . config . get_option ( 'LOGGING' , 'discord_webhook' ) : log_builder . configure_discord_logger ( custom_args = id_string ) if self . config . get_option ( 'LOGGING' , 'slack_webhook' ) : log_builder . configure_slack_logger ( custom_args = id_string ) if self . config . get_option ( 'LOGGING' , 'hipchat_webhook' ) : log_builder . configure_hipchat_logger ( custom_args = id_string ) self . _logger = log_builder . get_logger ( ) return self . _logger
6,749
https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/prosper_cli.py#L63-L95
[ "def", "createAltHistoryPlot", "(", "self", ")", ":", "self", ".", "altHistRect", "=", "patches", ".", "Rectangle", "(", "(", "self", ".", "leftPos", "+", "(", "self", ".", "vertSize", "/", "10.0", ")", ",", "-", "0.25", ")", ",", "0.5", ",", "0.5", ",", "facecolor", "=", "'grey'", ",", "edgecolor", "=", "'none'", ",", "alpha", "=", "0.4", ",", "zorder", "=", "4", ")", "self", ".", "axes", ".", "add_patch", "(", "self", ".", "altHistRect", ")", "self", ".", "altPlot", ",", "=", "self", ".", "axes", ".", "plot", "(", "[", "self", ".", "leftPos", "+", "(", "self", ".", "vertSize", "/", "10.0", ")", ",", "self", ".", "leftPos", "+", "(", "self", ".", "vertSize", "/", "10.0", ")", "+", "0.5", "]", ",", "[", "0.0", ",", "0.0", "]", ",", "color", "=", "'k'", ",", "marker", "=", "None", ",", "zorder", "=", "4", ")", "self", ".", "altMarker", ",", "=", "self", ".", "axes", ".", "plot", "(", "self", ".", "leftPos", "+", "(", "self", ".", "vertSize", "/", "10.0", ")", "+", "0.5", ",", "0.0", ",", "marker", "=", "'o'", ",", "color", "=", "'k'", ",", "zorder", "=", "4", ")", "self", ".", "altText2", "=", "self", ".", "axes", ".", "text", "(", "self", ".", "leftPos", "+", "(", "4", "*", "self", ".", "vertSize", "/", "10.0", ")", "+", "0.5", ",", "0.0", ",", "'%.f m'", "%", "self", ".", "relAlt", ",", "color", "=", "'k'", ",", "size", "=", "self", ".", "fontSize", ",", "ha", "=", "'left'", ",", "va", "=", "'center'", ",", "zorder", "=", "4", ")" ]
uses global config for cfg
def config ( self ) : if self . _config : return self . _config else : self . _config = p_config . ProsperConfig ( self . config_path ) return self . _config
6,750
https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/prosper_cli.py#L99-L105
[ "def", "delete_container_service", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "service_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourcegroups/'", ",", "resource_group", ",", "'/providers/Microsoft.ContainerService/ContainerServices/'", ",", "service_name", ",", "'?api-version='", ",", "ACS_API", "]", ")", "return", "do_delete", "(", "endpoint", ",", "access_token", ")" ]
logs launcher message before startup
def notify_launch ( self , log_level = 'ERROR' ) : if not self . debug : self . logger . log ( logging . getLevelName ( log_level ) , 'LAUNCHING %s -- %s' , self . PROGNAME , platform . node ( ) ) flask_options = { key : getattr ( self , key ) for key in OPTION_ARGS } flask_options [ 'host' ] = self . get_host ( ) self . logger . info ( 'OPTIONS: %s' , flask_options )
6,751
https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/prosper_cli.py#L146-L163
[ "def", "deleteByOrigIndex", "(", "self", ",", "index", ")", ":", "result", "=", "[", "]", "result_tracker", "=", "[", "]", "for", "counter", ",", "row", "in", "enumerate", "(", "self", ".", "table", ")", ":", "if", "self", ".", "index_track", "[", "counter", "]", "!=", "index", ":", "result", ".", "append", "(", "row", ")", "result_tracker", ".", "append", "(", "self", ".", "index_track", "[", "counter", "]", ")", "self", ".", "table", "=", "result", "self", ".", "index_track", "=", "result_tracker", "return", "self" ]
Extract cloud mask from the Landsat Collection 1 TOA BQA band
def landsat_c1_toa_cloud_mask ( input_img , snow_flag = False , cirrus_flag = False , cloud_confidence = 2 , shadow_confidence = 3 , snow_confidence = 3 , cirrus_confidence = 3 ) : qa_img = input_img . select ( [ 'BQA' ] ) cloud_mask = qa_img . rightShift ( 4 ) . bitwiseAnd ( 1 ) . neq ( 0 ) . And ( qa_img . rightShift ( 5 ) . bitwiseAnd ( 3 ) . gte ( cloud_confidence ) ) . Or ( qa_img . rightShift ( 7 ) . bitwiseAnd ( 3 ) . gte ( shadow_confidence ) ) if snow_flag : cloud_mask = cloud_mask . Or ( qa_img . rightShift ( 9 ) . bitwiseAnd ( 3 ) . gte ( snow_confidence ) ) if cirrus_flag : cloud_mask = cloud_mask . Or ( qa_img . rightShift ( 11 ) . bitwiseAnd ( 3 ) . gte ( cirrus_confidence ) ) # Set cloudy pixels to 0 and clear to 1 return cloud_mask . Not ( )
6,752
https://github.com/Open-ET/openet-core-beta/blob/f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db/openet/core/common.py#L6-L80
[ "def", "set_variable", "(", "self", ",", "name", ",", "value", ")", ":", "name_arg", "=", "\"\\\\\"", "+", "name", "variable_exists", "=", "False", "for", "variable", "in", "self", ".", "variables", ":", "if", "name_arg", "==", "variable", ".", "arguments", ".", "_positional_args", "[", "0", "]", ":", "variable_exists", "=", "True", "break", "if", "variable_exists", ":", "renew", "=", "Command", "(", "command", "=", "\"renewcommand\"", ",", "arguments", "=", "[", "NoEscape", "(", "name_arg", ")", ",", "value", "]", ")", "self", ".", "append", "(", "renew", ")", "else", ":", "new", "=", "Command", "(", "command", "=", "\"newcommand\"", ",", "arguments", "=", "[", "NoEscape", "(", "name_arg", ")", ",", "value", "]", ")", "self", ".", "variables", ".", "append", "(", "new", ")" ]
Extract cloud mask from the Landsat Collection 1 SR pixel_qa band
def landsat_c1_sr_cloud_mask ( input_img , cloud_confidence = 3 , snow_flag = False ) : qa_img = input_img . select ( [ 'pixel_qa' ] ) cloud_mask = qa_img . rightShift ( 5 ) . bitwiseAnd ( 1 ) . neq ( 0 ) . And ( qa_img . rightShift ( 6 ) . bitwiseAnd ( 3 ) . gte ( cloud_confidence ) ) . Or ( qa_img . rightShift ( 3 ) . bitwiseAnd ( 1 ) . neq ( 0 ) ) if snow_flag : cloud_mask = cloud_mask . Or ( qa_img . rightShift ( 4 ) . bitwiseAnd ( 1 ) . neq ( 0 ) ) # Set cloudy pixels to 0 and clear to 1 return cloud_mask . Not ( )
6,753
https://github.com/Open-ET/openet-core-beta/blob/f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db/openet/core/common.py#L83-L135
[ "def", "on_pause", "(", "self", ")", ":", "self", ".", "engine", ".", "commit", "(", ")", "self", ".", "strings", ".", "save", "(", ")", "self", ".", "funcs", ".", "save", "(", ")", "self", ".", "config", ".", "write", "(", ")" ]
Extract cloud mask from the Sentinel 2 TOA QA60 band
def sentinel2_toa_cloud_mask ( input_img ) : qa_img = input_img . select ( [ 'QA60' ] ) cloud_mask = qa_img . rightShift ( 10 ) . bitwiseAnd ( 1 ) . neq ( 0 ) . Or ( qa_img . rightShift ( 11 ) . bitwiseAnd ( 1 ) . neq ( 0 ) ) # Set cloudy pixels to 0 and clear to 1 return cloud_mask . Not ( )
6,754
https://github.com/Open-ET/openet-core-beta/blob/f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db/openet/core/common.py#L138-L172
[ "def", "start", "(", "self", ")", ":", "for", "config_class", "in", "self", ".", "watched_configurables", ":", "monitor", "=", "ConfigFileMonitor", "(", "config_class", ",", "self", ".", "config_dir", ")", "self", ".", "observers", ".", "append", "(", "monitor", ".", "start", "(", "self", ".", "add_configurable", ",", "self", ".", "update_configurable", ",", "self", ".", "remove_configurable", ")", ")", "wait_on_event", "(", "self", ".", "shutdown", ")" ]
A function to wrap shutil . which for universal usage
def where ( cmd , path = None ) : raw_result = shutil . which ( cmd , os . X_OK , path ) if raw_result : return os . path . abspath ( raw_result ) else : raise ValueError ( "Could not find '{}' in the path" . format ( cmd ) )
6,755
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/searcher.py#L23-L31
[ "def", "render_items", "(", "self", ",", "placeholder", ",", "items", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ")", ":", "# Unless it was done before, disable polymorphic effects.", "is_queryset", "=", "False", "if", "hasattr", "(", "items", ",", "\"non_polymorphic\"", ")", ":", "is_queryset", "=", "True", "if", "not", "items", ".", "polymorphic_disabled", "and", "items", ".", "_result_cache", "is", "None", ":", "items", "=", "items", ".", "non_polymorphic", "(", ")", "# See if the queryset contained anything.", "# This test is moved here, to prevent earlier query execution.", "if", "not", "items", ":", "logger", ".", "debug", "(", "\"- no items in placeholder '%s'\"", ",", "get_placeholder_debug_name", "(", "placeholder", ")", ")", "return", "ContentItemOutput", "(", "mark_safe", "(", "u\"<!-- no items in placeholder '{0}' -->\"", ".", "format", "(", "escape", "(", "get_placeholder_name", "(", "placeholder", ")", ")", ")", ")", ",", "cacheable", "=", "True", ")", "# Tracked data during rendering:", "result", "=", "self", ".", "result_class", "(", "request", "=", "self", ".", "request", ",", "parent_object", "=", "parent_object", ",", "placeholder", "=", "placeholder", ",", "items", "=", "items", ",", "all_cacheable", "=", "self", ".", "_can_cache_merged_output", "(", "template_name", ",", "cachable", ")", ",", ")", "if", "self", ".", "edit_mode", ":", "result", ".", "set_uncachable", "(", ")", "if", "is_queryset", ":", "# Phase 1: get cached output", "self", ".", "_fetch_cached_output", "(", "items", ",", "result", "=", "result", ")", "result", ".", "fetch_remaining_instances", "(", ")", "else", ":", "# The items is either a list of manually created items, or it's a QuerySet.", "# Can't prevent reading the subclasses only, so don't bother with caching here.", "result", ".", "add_remaining_list", "(", "items", ")", "# Start the actual rendering of remaining items.", "if", "result", ".", "remaining_items", ":", "# Phase 2: render remaining items", "self", ".", "_render_uncached_items", "(", "result", ".", "remaining_items", ",", "result", "=", "result", ")", "# And merge all items together.", "return", "self", ".", "merge_output", "(", "result", ",", "items", ",", "template_name", ")" ]
Search a given file s contents for the regex pattern given as pattern
def search_file ( pattern , file_path ) : try : with open ( file_path ) as file : string = file . read ( ) except PermissionError : return [ ] matches = re . findall ( pattern , string ) return matches
6,756
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/searcher.py#L34-L46
[ "def", "cublasDestroy", "(", "handle", ")", ":", "status", "=", "_libcublas", ".", "cublasDestroy_v2", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", "cublasCheckStatus", "(", "status", ")" ]
Will call a set of commands and wrangle the output how you choose
def call ( commands , * , print_result = False , raise_exception = False , print_commands = False ) : if isinstance ( commands , str ) : commands = commands . split ( ) if not ( isinstance ( commands , tuple ) or isinstance ( commands , list ) ) : raise ValueError ( "Function 'call' does not accept a 'commands'" "argument of type '{}'" . format ( type ( commands ) ) ) if raise_exception : print_result = False try : process = subprocess . Popen ( commands , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) if print_commands : _print_commands ( commands ) except : # TODO Why couldn't we just do 'except Exception as output' output = traceback . format_exc ( ) result = Result ( 1 , stderr = output ) if print_result and not raise_exception : print ( output , file = sys . stderr ) else : result = _extract_output ( process , print_result , raise_exception ) if raise_exception and ( result . returncode == 1 ) : message = "An error occurred in an external process:\n\n{}" raise Exception ( message . format ( result . getStderr ( ) ) ) return result
6,757
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/launcher.py#L105-L140
[ "def", "assert_tz_offset", "(", "tz", ")", ":", "tz_offset", "=", "get_tz_offset", "(", "tz", ")", "system_offset", "=", "get_system_offset", "(", ")", "if", "tz_offset", "!=", "system_offset", ":", "msg", "=", "(", "'Timezone offset does not match system offset: {0} != {1}. '", "'Please, check your config files.'", ")", ".", "format", "(", "tz_offset", ",", "system_offset", ")", "raise", "ValueError", "(", "msg", ")" ]
Calls the function call multiple times given sets of commands
def multiCall ( * commands , dependent = True , bundle = False , print_result = False , print_commands = False ) : results = [ ] dependent_failed = False for command in commands : if not dependent_failed : response = call ( command , print_result = print_result , print_commands = print_commands ) # TODO Will an error ever return a code other than '1'? if ( response . returncode == 1 ) and dependent : dependent_failed = True else : response = None results . append ( response ) if bundle : result = Result ( ) for response in results : if not response : continue elif response . returncode == 1 : result . returncode = 1 result . extendInformation ( response ) processed_response = result else : processed_response = results return processed_response
6,758
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/launcher.py#L145-L177
[ "def", "guess_extension", "(", "amimetype", ",", "normalize", "=", "False", ")", ":", "ext", "=", "_mimes", ".", "guess_extension", "(", "amimetype", ")", "if", "ext", "and", "normalize", ":", "# Normalize some common magic mis-interpreation", "ext", "=", "{", "'.asc'", ":", "'.txt'", ",", "'.obj'", ":", "'.bin'", "}", ".", "get", "(", "ext", ",", "ext", ")", "from", "invenio", ".", "legacy", ".", "bibdocfile", ".", "api_normalizer", "import", "normalize_format", "return", "normalize_format", "(", "ext", ")", "return", "ext" ]
A version of multiprocessing . Pool . map that works using dill to pickle the function and iterable
def distribute ( function , iterable , * , workers = 4 ) : with multiprocessing . Pool ( workers ) as pool : processes = [ ] for item in iterable : pickled = dill . dumps ( ( function , item ) ) process = pool . apply_async ( _run_pickled , ( pickled , ) ) processes . append ( process ) results = [ process . get ( ) for process in processes ] return results
6,759
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/launcher.py#L185-L198
[ "def", "fun_wv", "(", "xchannel", ",", "crpix1", ",", "crval1", ",", "cdelt1", ")", ":", "wv", "=", "crval1", "+", "(", "xchannel", "-", "crpix1", ")", "*", "cdelt1", "return", "wv" ]
Returns the combined output of stdout and stderr
def getOutput ( self ) : output = self . stdout if self . stdout : output += '\r\n' output += self . stderr return output
6,760
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/launcher.py#L54-L62
[ "def", "main", "(", "args", ")", ":", "print_in_box", "(", "'Validating submission '", "+", "args", ".", "submission_filename", ")", "random", ".", "seed", "(", ")", "temp_dir", "=", "args", ".", "temp_dir", "delete_temp_dir", "=", "False", "if", "not", "temp_dir", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "logging", ".", "info", "(", "'Created temporary directory: %s'", ",", "temp_dir", ")", "delete_temp_dir", "=", "True", "validator", "=", "submission_validator_lib", ".", "SubmissionValidator", "(", "temp_dir", ",", "args", ".", "use_gpu", ")", "if", "validator", ".", "validate_submission", "(", "args", ".", "submission_filename", ",", "args", ".", "submission_type", ")", ":", "print_in_box", "(", "'Submission is VALID!'", ")", "else", ":", "print_in_box", "(", "'Submission is INVALID, see log messages for details'", ")", "if", "delete_temp_dir", ":", "logging", ".", "info", "(", "'Deleting temporary directory: %s'", ",", "temp_dir", ")", "subprocess", ".", "call", "(", "[", "'rm'", ",", "'-rf'", ",", "temp_dir", "]", ")" ]
This extends the objects stdout and stderr by response s stdout and stderr
def extendInformation ( self , response ) : if response . stdout : self . stdout += '\r\n' + response . stdout if response . stderr : self . stderr += '\r\n' + response . stderr
6,761
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/launcher.py#L64-L72
[ "def", "get_temp_min_and_max", "(", "wxlist", ":", "[", "str", "]", ")", "->", "(", "[", "str", "]", ",", "str", ",", "str", ")", ":", "# type: ignore", "temp_max", ",", "temp_min", "=", "''", ",", "''", "for", "i", ",", "item", "in", "reversed", "(", "list", "(", "enumerate", "(", "wxlist", ")", ")", ")", ":", "if", "len", "(", "item", ")", ">", "6", "and", "item", "[", "0", "]", "==", "'T'", "and", "'/'", "in", "item", ":", "# TX12/1316Z", "if", "item", "[", "1", "]", "==", "'X'", ":", "temp_max", "=", "wxlist", ".", "pop", "(", "i", ")", "# TNM03/1404Z", "elif", "item", "[", "1", "]", "==", "'N'", ":", "temp_min", "=", "wxlist", ".", "pop", "(", "i", ")", "# TM03/1404Z T12/1316Z -> Will fix TN/TX", "elif", "item", "[", "1", "]", "==", "'M'", "or", "item", "[", "1", "]", ".", "isdigit", "(", ")", ":", "if", "temp_min", ":", "if", "int", "(", "temp_min", "[", "2", ":", "temp_min", ".", "find", "(", "'/'", ")", "]", ".", "replace", "(", "'M'", ",", "'-'", ")", ")", ">", "int", "(", "item", "[", "1", ":", "item", ".", "find", "(", "'/'", ")", "]", ".", "replace", "(", "'M'", ",", "'-'", ")", ")", ":", "temp_max", "=", "'TX'", "+", "temp_min", "[", "2", ":", "]", "temp_min", "=", "'TN'", "+", "item", "[", "1", ":", "]", "else", ":", "temp_max", "=", "'TX'", "+", "item", "[", "1", ":", "]", "else", ":", "temp_min", "=", "'TN'", "+", "item", "[", "1", ":", "]", "wxlist", ".", "pop", "(", "i", ")", "return", "wxlist", ",", "temp_max", ",", "temp_min" ]
wait on a combination of zeromq sockets normal sockets and fds
def wait_socks ( sock_events , inmask = 1 , outmask = 2 , timeout = None ) : results = [ ] for sock , mask in sock_events : if isinstance ( sock , zmq . backend . Socket ) : mask = _check_events ( sock , mask , inmask , outmask ) if mask : results . append ( ( sock , mask ) ) if results : return results fd_map = { } fd_events = [ ] for sock , mask in sock_events : if isinstance ( sock , zmq . backend . Socket ) : fd = sock . getsockopt ( zmq . FD ) elif isinstance ( sock , int ) : fd = sock else : fd = sock . fileno ( ) fd_map [ fd ] = sock fd_events . append ( ( fd , mask ) ) while 1 : started = time . time ( ) active = descriptor . wait_fds ( fd_events , inmask , outmask , timeout ) if not active : # timed out return [ ] results = [ ] for fd , mask in active : sock = fd_map [ fd ] if isinstance ( sock , zmq . backend . Socket ) : mask = _check_events ( sock , mask , inmask , outmask ) if not mask : continue results . append ( ( sock , mask ) ) if results : return results timeout -= time . time ( ) - started
6,762
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/ext/zmq.py#L12-L79
[ "def", "refresh", "(", "self", ")", ":", "if", "self", ".", "_expired", ":", "raise", "Expired", "(", ")", "obj", "=", "{", "# ID is the lease ID for the lease to keep alive.", "u'ID'", ":", "self", ".", "lease_id", ",", "}", "data", "=", "json", ".", "dumps", "(", "obj", ")", ".", "encode", "(", "'utf8'", ")", "url", "=", "u'{}/v3alpha/lease/keepalive'", ".", "format", "(", "self", ".", "_client", ".", "_url", ")", ".", "encode", "(", ")", "response", "=", "yield", "treq", ".", "post", "(", "url", ",", "data", ",", "headers", "=", "self", ".", "_client", ".", "_REQ_HEADERS", ")", "obj", "=", "yield", "treq", ".", "json_content", "(", "response", ")", "if", "u'result'", "not", "in", "obj", ":", "raise", "Exception", "(", "'bogus lease refresh response (missing \"result\") in {}'", ".", "format", "(", "obj", ")", ")", "ttl", "=", "obj", "[", "u'result'", "]", ".", "get", "(", "u'TTL'", ",", "None", ")", "if", "not", "ttl", ":", "self", ".", "_expired", "=", "True", "raise", "Expired", "(", ")", "header", "=", "Header", ".", "_parse", "(", "obj", "[", "u'result'", "]", "[", "u'header'", "]", ")", "if", "u'header'", "in", "obj", "[", "u'result'", "]", "else", "None", "self", ".", "_expired", "=", "False", "returnValue", "(", "header", ")" ]
Removes the factuality for the given factuality identifier
def remove_this_factuality ( self , factuality_id ) : for fact in self . get_factualities ( ) : if fact . get_id ( ) == factuality_id : self . node . remove ( fact . get_node ( ) ) break
6,763
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/factuality_data.py#L224-L233
[ "def", "ValidateEndConfig", "(", "self", ",", "config_obj", ",", "errors_fatal", "=", "True", ")", ":", "errors", "=", "super", "(", "WindowsClientRepacker", ",", "self", ")", ".", "ValidateEndConfig", "(", "config_obj", ",", "errors_fatal", "=", "errors_fatal", ")", "install_dir", "=", "config_obj", "[", "\"Client.install_path\"", "]", "for", "path", "in", "config_obj", "[", "\"Client.tempdir_roots\"", "]", ":", "if", "path", ".", "startswith", "(", "\"/\"", ")", ":", "errors", ".", "append", "(", "\"Client.tempdir_root %s starts with /, probably has Unix path.\"", "%", "path", ")", "if", "not", "path", ".", "startswith", "(", "install_dir", ")", ":", "errors", ".", "append", "(", "\"Client.tempdir_root %s is not inside the install_dir %s, this is \"", "\"a security risk\"", "%", "(", "(", "path", ",", "install_dir", ")", ")", ")", "if", "config_obj", ".", "Get", "(", "\"Logging.path\"", ")", ".", "startswith", "(", "\"/\"", ")", ":", "errors", ".", "append", "(", "\"Logging.path starts with /, probably has Unix path. %s\"", "%", "config_obj", "[", "\"Logging.path\"", "]", ")", "if", "\"Windows\\\\\"", "in", "config_obj", ".", "GetRaw", "(", "\"Logging.path\"", ")", ":", "errors", ".", "append", "(", "\"Windows in Logging.path, you probably want \"", "\"%(WINDIR|env) instead\"", ")", "if", "not", "config_obj", "[", "\"Client.binary_name\"", "]", ".", "endswith", "(", "\".exe\"", ")", ":", "errors", ".", "append", "(", "\"Missing .exe extension on binary_name %s\"", "%", "config_obj", "[", "\"Client.binary_name\"", "]", ")", "if", "not", "config_obj", "[", "\"Nanny.binary\"", "]", ".", "endswith", "(", "\".exe\"", ")", ":", "errors", ".", "append", "(", "\"Missing .exe extension on nanny_binary\"", ")", "if", "errors_fatal", "and", "errors", ":", "for", "error", "in", "errors", ":", "logging", ".", "error", "(", "\"Build Config Error: %s\"", ",", "error", ")", "raise", "RuntimeError", "(", "\"Bad configuration generated. Terminating.\"", ")", "else", ":", "return", "errors" ]
Removes a factuality element with a specific id from the layer
def remove_factuality ( self , fid ) : for node_pre in self . node . findall ( 'factuality' ) : if node_pre . get ( 'id' ) == fid : self . node . remove ( node_pre )
6,764
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/factuality_data.py#L236-L242
[ "def", "servertoken", "(", "self", ",", "serverURL", ",", "referer", ")", ":", "if", "self", ".", "_server_token", "is", "None", "or", "self", ".", "_server_token_expires_on", "is", "None", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ">=", "self", ".", "_server_token_expires_on", "or", "self", ".", "_server_url", "!=", "serverURL", ":", "self", ".", "_server_url", "=", "serverURL", "result", "=", "self", ".", "_generateForServerTokenSecurity", "(", "serverURL", "=", "serverURL", ",", "token", "=", "self", ".", "token", ",", "tokenUrl", "=", "self", ".", "_token_url", ",", "referer", "=", "referer", ")", "if", "'error'", "in", "result", ":", "self", ".", "_valid", "=", "False", "self", ".", "_message", "=", "result", "else", ":", "self", ".", "_valid", "=", "True", "self", ".", "_message", "=", "\"Server Token Generated\"", "return", "self", ".", "_server_token" ]
Removes the factvalue for the given factvalue identifier
def remove_this_factvalue ( self , factvalue_id ) : for fact in self . get_factvalues ( ) : if fact . get_id ( ) == factvalue_id : self . node . remove ( fact . get_node ( ) ) break
6,765
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/factuality_data.py#L393-L402
[ "def", "get_segmented_raw_data", "(", "top_n", "=", "10000", ")", ":", "cfg", "=", "utils", ".", "get_database_configuration", "(", ")", "mysql", "=", "cfg", "[", "'mysql_online'", "]", "connection", "=", "pymysql", ".", "connect", "(", "host", "=", "mysql", "[", "'host'", "]", ",", "user", "=", "mysql", "[", "'user'", "]", ",", "passwd", "=", "mysql", "[", "'passwd'", "]", ",", "db", "=", "mysql", "[", "'db'", "]", ",", "cursorclass", "=", "pymysql", ".", "cursors", ".", "DictCursor", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "sql", "=", "(", "\"SELECT `id`, `data`, `segmentation` \"", "\"FROM `wm_raw_draw_data` WHERE \"", "\"(`segmentation` IS NOT NULL OR `accepted_formula_id` IS NOT NULL) \"", "\"AND `wild_point_count` = 0 \"", "\"AND `stroke_segmentable` = 1 \"", "\"ORDER BY `id` LIMIT 0, %i\"", ")", "%", "top_n", "logging", ".", "info", "(", "sql", ")", "cursor", ".", "execute", "(", "sql", ")", "datasets", "=", "cursor", ".", "fetchall", "(", ")", "logging", ".", "info", "(", "\"Fetched %i recordings. Add missing segmentations.\"", ",", "len", "(", "datasets", ")", ")", "for", "i", "in", "range", "(", "len", "(", "datasets", ")", ")", ":", "if", "datasets", "[", "i", "]", "[", "'segmentation'", "]", "is", "None", ":", "stroke_count", "=", "len", "(", "json", ".", "loads", "(", "datasets", "[", "i", "]", "[", "'data'", "]", ")", ")", "if", "stroke_count", ">", "10", ":", "print", "(", "\"Massive stroke count! %i\"", "%", "stroke_count", ")", "datasets", "[", "i", "]", "[", "'segmentation'", "]", "=", "str", "(", "[", "[", "s", "for", "s", "in", "range", "(", "stroke_count", ")", "]", "]", ")", "return", "datasets" ]
Adds version to either url or headers depending on protocol .
def _add_version_to_request ( self , url , headers , version ) : if self . _has_capability ( SERVER_REQUIRES_VERSION_HEADER ) : new_headers = headers . copy ( ) new_headers [ 'Last-Modified' ] = email . utils . formatdate ( version ) return url , new_headers else : url_params = { 'last_modified' : email . utils . formatdate ( version ) } new_url = url + "?" + urlencode ( url_params ) return new_url , headers
6,766
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/remote_data_store.py#L216-L227
[ "def", "_error_messages", "(", "self", ",", "driver_id", ")", ":", "assert", "isinstance", "(", "driver_id", ",", "ray", ".", "DriverID", ")", "message", "=", "self", ".", "redis_client", ".", "execute_command", "(", "\"RAY.TABLE_LOOKUP\"", ",", "ray", ".", "gcs_utils", ".", "TablePrefix", ".", "ERROR_INFO", ",", "\"\"", ",", "driver_id", ".", "binary", "(", ")", ")", "# If there are no errors, return early.", "if", "message", "is", "None", ":", "return", "[", "]", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "message", ",", "0", ")", "error_messages", "=", "[", "]", "for", "i", "in", "range", "(", "gcs_entries", ".", "EntriesLength", "(", ")", ")", ":", "error_data", "=", "ray", ".", "gcs_utils", ".", "ErrorTableData", ".", "GetRootAsErrorTableData", "(", "gcs_entries", ".", "Entries", "(", "i", ")", ",", "0", ")", "assert", "driver_id", ".", "binary", "(", ")", "==", "error_data", ".", "DriverId", "(", ")", "error_message", "=", "{", "\"type\"", ":", "decode", "(", "error_data", ".", "Type", "(", ")", ")", ",", "\"message\"", ":", "decode", "(", "error_data", ".", "ErrorMessage", "(", ")", ")", ",", "\"timestamp\"", ":", "error_data", ".", "Timestamp", "(", ")", ",", "}", "error_messages", ".", "append", "(", "error_message", ")", "return", "error_messages" ]
Returns the protocol version that should be used .
def _protocol_version ( self ) : if hasattr ( self , '_protocol_ver' ) : return self . _protocol_ver response = requests . get ( self . base_url + '/version/' ) if response . status_code == 404 : server_versions = { 1 } elif response . status_code == 200 : server_versions = set ( response . json ( ) [ 'protocol_versions' ] ) if not server_versions : raise FiletrackerError ( 'Server hasn\'t reported any supported protocols' ) else : response . raise_for_status ( ) common_versions = _SUPPORTED_VERSIONS . intersection ( server_versions ) if not common_versions : raise FiletrackerError ( 'Couldn\'t agree on protocol version: client supports ' '{}, server supports {}.' . format ( _PROTOCOL_CAPABILITIES , server_versions ) ) self . _protocol_ver = max ( common_versions ) print ( 'Settled for protocol version {}' . format ( self . _protocol_ver ) ) return self . _protocol_ver
6,767
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/remote_data_store.py#L229-L260
[ "def", "setOverlayTransformAbsolute", "(", "self", ",", "ulOverlayHandle", ",", "eTrackingOrigin", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTransformAbsolute", "pmatTrackingOriginToOverlayTransform", "=", "HmdMatrix34_t", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "eTrackingOrigin", ",", "byref", "(", "pmatTrackingOriginToOverlayTransform", ")", ")", "return", "result", ",", "pmatTrackingOriginToOverlayTransform" ]
Starts cleaning cache in infinite loop .
def run ( self ) : logger . info ( "Starting daemon." ) while True : try : self . _scan_disk ( ) do_cleaning , delete_from_index = self . _analyze_file_index ( ) if do_cleaning : self . _clean_cache ( delete_from_index ) except Exception : logger . exception ( "Following exception occurred:" ) sleeping_until_time = datetime . datetime . now ( ) + self . scan_interval logger . info ( "Sleeping until %s." , sleeping_until_time ) time . sleep ( self . scan_interval . total_seconds ( ) )
6,768
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/scripts/cachecleaner.py#L73-L87
[ "def", "Open", "(", "self", ",", "file_object", ")", ":", "file_object", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "signature_data", "=", "file_object", ".", "read", "(", "6", ")", "self", ".", "file_format", "=", "None", "if", "len", "(", "signature_data", ")", ">", "2", ":", "if", "signature_data", "[", ":", "2", "]", "==", "self", ".", "_CPIO_SIGNATURE_BINARY_BIG_ENDIAN", ":", "self", ".", "file_format", "=", "'bin-big-endian'", "elif", "signature_data", "[", ":", "2", "]", "==", "self", ".", "_CPIO_SIGNATURE_BINARY_LITTLE_ENDIAN", ":", "self", ".", "file_format", "=", "'bin-little-endian'", "elif", "signature_data", "==", "self", ".", "_CPIO_SIGNATURE_PORTABLE_ASCII", ":", "self", ".", "file_format", "=", "'odc'", "elif", "signature_data", "==", "self", ".", "_CPIO_SIGNATURE_NEW_ASCII", ":", "self", ".", "file_format", "=", "'newc'", "elif", "signature_data", "==", "self", ".", "_CPIO_SIGNATURE_NEW_ASCII_WITH_CHECKSUM", ":", "self", ".", "file_format", "=", "'crc'", "if", "self", ".", "file_format", "is", "None", ":", "raise", "IOError", "(", "'Unsupported CPIO format.'", ")", "self", ".", "_file_object", "=", "file_object", "self", ".", "_file_size", "=", "file_object", ".", "get_size", "(", ")", "self", ".", "_ReadFileEntries", "(", "self", ".", "_file_object", ")" ]
Prepares a path name to be worked with . Path name must not be empty . This function will return the normpath ed path and the identity of the path . This function takes an optional overriding argument for the identity .
def normalize ( path_name , override = None ) : identity = identify ( path_name , override = override ) new_path_name = os . path . normpath ( os . path . expanduser ( path_name ) ) return new_path_name , identity
6,769
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L36-L50
[ "def", "_download_file", "(", "url", ",", "local_filename", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "with", "open", "(", "local_filename", ",", "'wb'", ")", "as", "outfile", ":", "for", "chunk", "in", "response", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chunk", ":", "# filter out keep-alive new chunks", "outfile", ".", "write", "(", "chunk", ")" ]
Joins a given name with an extension . If the extension doesn t have a . it will add it for you
def join_ext ( name , extension ) : if extension [ 0 ] == EXT : ret = name + extension else : ret = name + EXT + extension return ret
6,770
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L98-L107
[ "def", "ideal_gas", "(", "target", ",", "pressure", "=", "'pore.pressure'", ",", "temperature", "=", "'pore.temperature'", ")", ":", "R", "=", "8.31447", "P", "=", "target", "[", "pressure", "]", "T", "=", "target", "[", "temperature", "]", "value", "=", "P", "/", "(", "R", "*", "T", ")", "return", "value" ]
Determine if the given path name has an extension
def has_ext ( path_name , * , multiple = None , if_all_ext = False ) : base = os . path . basename ( path_name ) count = base . count ( EXT ) if not if_all_ext and base [ 0 ] == EXT and count != 0 : count -= 1 if multiple is None : return count >= 1 elif multiple : return count > 1 else : return count == 1
6,771
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L118-L133
[ "def", "_calculate_values", "(", "self", ",", "tree", ",", "bar_d", ")", ":", "if", "all", "(", "[", "isinstance", "(", "tree", ",", "dict", ")", ",", "type", "(", "tree", ")", "!=", "BarDescriptor", "]", ")", ":", "# Calculate value and max_value", "max_val", "=", "0", "value", "=", "0", "for", "k", "in", "tree", ":", "# Get descriptor by recursing", "bar_desc", "=", "self", ".", "_calculate_values", "(", "tree", "[", "k", "]", ",", "bar_d", ")", "# Reassign to tuple of (new descriptor, tree below)", "tree", "[", "k", "]", "=", "(", "bar_desc", ",", "tree", "[", "k", "]", ")", "value", "+=", "bar_desc", "[", "\"value\"", "]", ".", "value", "max_val", "+=", "bar_desc", ".", "get", "(", "\"kwargs\"", ",", "{", "}", ")", ".", "get", "(", "\"max_value\"", ",", "100", ")", "# Merge in values from ``bar_d`` before returning descriptor", "kwargs", "=", "merge_dicts", "(", "[", "bar_d", ".", "get", "(", "\"kwargs\"", ",", "{", "}", ")", ",", "dict", "(", "max_value", "=", "max_val", ")", "]", ",", "deepcopy", "=", "True", ")", "ret_d", "=", "merge_dicts", "(", "[", "bar_d", ",", "dict", "(", "value", "=", "Value", "(", "floor", "(", "value", ")", ")", ",", "kwargs", "=", "kwargs", ")", "]", ",", "deepcopy", "=", "True", ")", "return", "BarDescriptor", "(", "ret_d", ")", "elif", "isinstance", "(", "tree", ",", "BarDescriptor", ")", ":", "return", "tree", "else", ":", "raise", "TypeError", "(", "\"Unexpected type {}\"", ".", "format", "(", "type", "(", "tree", ")", ")", ")" ]
Get an extension from the given path name . If an extension cannot be found it will return an empty string
def get_ext ( path_name , * , if_all_ext = False ) : if has_ext ( path_name ) : return os . path . splitext ( path_name ) [ EXTENSION ] elif if_all_ext and has_ext ( path_name , if_all_ext = True ) : return os . path . splitext ( path_name ) [ NAME ] else : return ''
6,772
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L136-L146
[ "def", "_threaded_copy_data", "(", "instream", ",", "outstream", ")", ":", "copy_thread", "=", "threading", ".", "Thread", "(", "target", "=", "_copy_data", ",", "args", "=", "(", "instream", ",", "outstream", ")", ")", "copy_thread", ".", "setDaemon", "(", "True", ")", "log", ".", "debug", "(", "'%r, %r, %r'", ",", "copy_thread", ",", "instream", ",", "outstream", ")", "copy_thread", ".", "start", "(", ")", "return", "copy_thread" ]
Gets the directory path of the given path name . If the argument greedy is specified as True then if the path name represents a directory itself the function will return the whole path
def get_dir ( path_name , * , greedy = False , override = None , identity = None ) : if identity is None : identity = identify ( path_name , override = override ) path_name = os . path . normpath ( path_name ) if greedy and identity == ISDIR : return path_name else : return os . path . dirname ( path_name )
6,773
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L157-L171
[ "def", "_start_update_server", "(", "auth_token", ")", ":", "server", "=", "AccumulatorServer", "(", "(", "\"localhost\"", ",", "0", ")", ",", "_UpdateRequestHandler", ",", "auth_token", ")", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "server", ".", "serve_forever", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")", "return", "server" ]
Get the available drive names on the system . Always returns a list .
def get_system_drives ( ) : drives = [ ] if os . name == 'nt' : import ctypes bitmask = ctypes . windll . kernel32 . GetLogicalDrives ( ) letter = ord ( 'A' ) while bitmask > 0 : if bitmask & 1 : name = chr ( letter ) + ':' + os . sep if os . path . isdir ( name ) : drives . append ( name ) bitmask >>= 1 letter += 1 else : current_drive = get_drive ( os . getcwd ( ) ) if current_drive : drive = current_drive else : drive = os . sep drives . append ( drive ) return drives
6,774
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L206-L230
[ "def", "acceptmergerequest", "(", "self", ",", "project_id", ",", "mergerequest_id", ",", "merge_commit_message", "=", "None", ")", ":", "data", "=", "{", "'merge_commit_message'", ":", "merge_commit_message", "}", "request", "=", "requests", ".", "put", "(", "'{0}/{1}/merge_request/{2}/merge'", ".", "format", "(", "self", ".", "projects_url", ",", "project_id", ",", "mergerequest_id", ")", ",", "data", "=", "data", ",", "headers", "=", "self", ".", "headers", ",", "verify", "=", "self", ".", "verify_ssl", ",", "auth", "=", "self", ".", "auth", ",", "timeout", "=", "self", ".", "timeout", ")", "if", "request", ".", "status_code", "==", "200", ":", "return", "request", ".", "json", "(", ")", "else", ":", "return", "False" ]
Determines if path_name has a suffix of at least suffix
def has_suffix ( path_name , suffix ) : if isinstance ( suffix , str ) : suffix = disintegrate ( suffix ) components = disintegrate ( path_name ) for i in range ( - 1 , - ( len ( suffix ) + 1 ) , - 1 ) : if components [ i ] != suffix [ i ] : break else : return True return False
6,775
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L233-L247
[ "def", "from_session", "(", "cls", ",", "session", ")", ":", "session", ".", "error_wrapper", "=", "lambda", "e", ":", "NvimError", "(", "e", "[", "1", "]", ")", "channel_id", ",", "metadata", "=", "session", ".", "request", "(", "b'vim_get_api_info'", ")", "if", "IS_PYTHON3", ":", "# decode all metadata strings for python3", "metadata", "=", "walk", "(", "decode_if_bytes", ",", "metadata", ")", "types", "=", "{", "metadata", "[", "'types'", "]", "[", "'Buffer'", "]", "[", "'id'", "]", ":", "Buffer", ",", "metadata", "[", "'types'", "]", "[", "'Window'", "]", "[", "'id'", "]", ":", "Window", ",", "metadata", "[", "'types'", "]", "[", "'Tabpage'", "]", "[", "'id'", "]", ":", "Tabpage", ",", "}", "return", "cls", "(", "session", ",", "channel_id", ",", "metadata", ",", "types", ")" ]
Path manipulation black magic
def path ( path_name = None , override = None , * , root = None , name = None , ext = None , inject = None , relpath = None , reduce = False ) : path_name , identity , root = _initialize ( path_name , override , root , inject ) new_name = _process_name ( path_name , identity , name , ext ) new_directory = _process_directory ( path_name , identity , root , inject ) full_path = os . path . normpath ( os . path . join ( new_directory , new_name ) ) if APPEND_SEP_TO_DIRS and not new_name and full_path [ - 1 ] != os . sep : full_path += os . sep final_path = _format_path ( full_path , root , relpath , reduce ) return final_path
6,776
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L364-L376
[ "def", "find_similar", "(", "self", ",", "doc", ",", "min_score", "=", "0.0", ",", "max_results", "=", "100", ")", ":", "logger", ".", "debug", "(", "\"received query call with %r\"", "%", "doc", ")", "if", "self", ".", "is_locked", "(", ")", ":", "msg", "=", "\"cannot query while the server is being updated\"", "logger", ".", "error", "(", "msg", ")", "raise", "RuntimeError", "(", "msg", ")", "sims_opt", ",", "sims_fresh", "=", "None", ",", "None", "for", "index", "in", "[", "self", ".", "fresh_index", ",", "self", ".", "opt_index", "]", ":", "if", "index", "is", "not", "None", ":", "index", ".", "topsims", "=", "max_results", "if", "isinstance", "(", "doc", ",", "basestring", ")", ":", "# query by direct document id", "docid", "=", "doc", "if", "self", ".", "opt_index", "is", "not", "None", "and", "docid", "in", "self", ".", "opt_index", ":", "sims_opt", "=", "self", ".", "opt_index", ".", "sims_by_id", "(", "docid", ")", "if", "self", ".", "fresh_index", "is", "not", "None", ":", "vec", "=", "self", ".", "opt_index", ".", "vec_by_id", "(", "docid", ")", "sims_fresh", "=", "self", ".", "fresh_index", ".", "sims_by_vec", "(", "vec", ",", "normalize", "=", "False", ")", "elif", "self", ".", "fresh_index", "is", "not", "None", "and", "docid", "in", "self", ".", "fresh_index", ":", "sims_fresh", "=", "self", ".", "fresh_index", ".", "sims_by_id", "(", "docid", ")", "if", "self", ".", "opt_index", "is", "not", "None", ":", "vec", "=", "self", ".", "fresh_index", ".", "vec_by_id", "(", "docid", ")", "sims_opt", "=", "self", ".", "opt_index", ".", "sims_by_vec", "(", "vec", ",", "normalize", "=", "False", ")", "else", ":", "raise", "ValueError", "(", "\"document %r not in index\"", "%", "docid", ")", "else", ":", "if", "'topics'", "in", "doc", ":", "# user supplied vector directly => use that", "vec", "=", "gensim", ".", "matutils", ".", "any2sparse", "(", "doc", "[", "'topics'", "]", ")", "else", ":", "# query by an arbitrary text (=tokens) inside doc['tokens']", "vec", "=", "self", ".", "model", ".", "doc2vec", "(", "doc", ")", "# convert document (text) to vector", "if", "self", ".", "opt_index", "is", "not", "None", ":", "sims_opt", "=", "self", ".", "opt_index", ".", "sims_by_vec", "(", "vec", ")", "if", "self", ".", "fresh_index", "is", "not", "None", ":", "sims_fresh", "=", "self", ".", "fresh_index", ".", "sims_by_vec", "(", "vec", ")", "merged", "=", "merge_sims", "(", "sims_opt", ",", "sims_fresh", ")", "logger", ".", "debug", "(", "\"got %s raw similars, pruning with max_results=%s, min_score=%s\"", "%", "(", "len", "(", "merged", ")", ",", "max_results", ",", "min_score", ")", ")", "result", "=", "[", "]", "for", "docid", ",", "score", "in", "merged", ":", "if", "score", "<", "min_score", "or", "0", "<", "max_results", "<=", "len", "(", "result", ")", ":", "break", "result", ".", "append", "(", "(", "docid", ",", "float", "(", "score", ")", ",", "self", ".", "payload", ".", "get", "(", "docid", ",", "None", ")", ")", ")", "return", "result" ]
Returns a different object with the specified changes applied to it . This object is not changed in the process .
def path ( self , * * kwargs ) : new_path = path ( self . getPath ( ) , * * kwargs ) return File ( new_path )
6,777
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L408-L414
[ "def", "get_file_url", "(", "self", ",", "fid", ",", "public", "=", "None", ")", ":", "try", ":", "volume_id", ",", "rest", "=", "fid", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "except", "ValueError", ":", "raise", "BadFidFormat", "(", "\"fid must be in format: <volume_id>,<file_name_hash>\"", ")", "file_location", "=", "self", ".", "get_file_location", "(", "volume_id", ")", "if", "public", "is", "None", ":", "public", "=", "self", ".", "use_public_url", "volume_url", "=", "file_location", ".", "public_url", "if", "public", "else", "file_location", ".", "url", "url", "=", "\"http://{volume_url}/{fid}\"", ".", "format", "(", "volume_url", "=", "volume_url", ",", "fid", "=", "fid", ")", "return", "url" ]
Figures out if Cyther should compile the given FileInfo object by checking the both of the modified times
def isOutDated ( self , output_file ) : if output_file . exists ( ) : source_time = self . getmtime ( ) output_time = output_file . getmtime ( ) return source_time > output_time else : return True
6,778
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L416-L426
[ "async", "def", "unmount", "(", "self", ",", "device", ")", ":", "device", "=", "self", ".", "_find_device", "(", "device", ")", "if", "not", "self", ".", "is_handleable", "(", "device", ")", "or", "not", "device", ".", "is_filesystem", ":", "self", ".", "_log", ".", "warn", "(", "_", "(", "'not unmounting {0}: unhandled device'", ",", "device", ")", ")", "return", "False", "if", "not", "device", ".", "is_mounted", ":", "self", ".", "_log", ".", "info", "(", "_", "(", "'not unmounting {0}: not mounted'", ",", "device", ")", ")", "return", "True", "self", ".", "_log", ".", "debug", "(", "_", "(", "'unmounting {0}'", ",", "device", ")", ")", "await", "device", ".", "unmount", "(", ")", "self", ".", "_log", ".", "info", "(", "_", "(", "'unmounted {0}'", ",", "device", ")", ")", "return", "True" ]
Figures out if the file had previously errored and hasn t been fixed since given a numerical time
def isUpdated ( self ) : modified_time = self . getmtime ( ) valid = modified_time > self . __stamp return valid
6,779
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/pathway.py#L434-L441
[ "def", "create_result", "(", "self", ",", "env_name", ",", "other_val", ",", "meta", ",", "val", ",", "dividers", ")", ":", "args", "=", "[", "env_name", "]", "if", "other_val", "is", "NotSpecified", ":", "other_val", "=", "None", "if", "not", "dividers", ":", "args", ".", "extend", "(", "[", "None", ",", "None", "]", ")", "elif", "dividers", "[", "0", "]", "==", "':'", ":", "args", ".", "extend", "(", "[", "other_val", ",", "None", "]", ")", "elif", "dividers", "[", "0", "]", "==", "'='", ":", "args", ".", "extend", "(", "[", "None", ",", "other_val", "]", ")", "return", "Environment", "(", "*", "args", ")" ]
Returns the translations requested by the user
def get_translations ( self , status = None ) : if status is not None : result = self . api_call ( 'translation/?status=%s' % status ) else : result = self . api_call ( 'translation/' ) if result . status_code == 200 : translations_json = json . loads ( result . content ) [ "objects" ] translations = [ Translation ( * * tj ) for tj in translations_json ] else : log . critical ( 'Error status when fetching translation from server: {' '}!' . format ( result . status_code ) ) translations = [ ] return translations
6,780
https://github.com/Unbabel/unbabel-py/blob/3bd6397174e184d89d2a11149d87be5d12570c64/unbabel/api.py#L370-L387
[ "def", "attach_socket", "(", "self", ",", "container", ",", "params", "=", "None", ",", "ws", "=", "False", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "'stdout'", ":", "1", ",", "'stderr'", ":", "1", ",", "'stream'", ":", "1", "}", "if", "'detachKeys'", "not", "in", "params", "and", "'detachKeys'", "in", "self", ".", "_general_configs", ":", "params", "[", "'detachKeys'", "]", "=", "self", ".", "_general_configs", "[", "'detachKeys'", "]", "if", "ws", ":", "return", "self", ".", "_attach_websocket", "(", "container", ",", "params", ")", "headers", "=", "{", "'Connection'", ":", "'Upgrade'", ",", "'Upgrade'", ":", "'tcp'", "}", "u", "=", "self", ".", "_url", "(", "\"/containers/{0}/attach\"", ",", "container", ")", "return", "self", ".", "_get_raw_response_socket", "(", "self", ".", "post", "(", "u", ",", "None", ",", "params", "=", "self", ".", "_attach_params", "(", "params", ")", ",", "stream", "=", "True", ",", "headers", "=", "headers", ")", ")" ]
Returns a translation with the given id
def get_translation ( self , uid ) : result = self . api_call ( 'translation/{}/' . format ( uid ) ) if result . status_code == 200 : translation = Translation ( * * json . loads ( result . content ) ) else : log . critical ( 'Error status when fetching translation from server: {' '}!' . format ( result . status_code ) ) raise ValueError ( result . content ) return translation
6,781
https://github.com/Unbabel/unbabel-py/blob/3bd6397174e184d89d2a11149d87be5d12570c64/unbabel/api.py#L389-L402
[ "def", "_render_round_end", "(", "self", ",", "rewards", ":", "np", ".", "array", ")", "->", "None", ":", "print", "(", "\"*********************************************************\"", ")", "print", "(", "\">>> ROUND END\"", ")", "print", "(", "\"*********************************************************\"", ")", "total_reward", "=", "np", ".", "sum", "(", "rewards", ")", "print", "(", "\"==> Objective value = {}\"", ".", "format", "(", "total_reward", ")", ")", "print", "(", "\"==> rewards = {}\"", ".", "format", "(", "list", "(", "rewards", ")", ")", ")", "print", "(", ")" ]
Returns the language pairs available on unbabel
def get_language_pairs ( self , train_langs = None ) : if train_langs is None : result = self . api_call ( 'language_pair/' ) else : result = self . api_call ( 'language_pair/?train_langs={}' . format ( train_langs ) ) try : langs_json = json . loads ( result . content ) if 'error' in langs_json : return [ ] languages = [ LangPair ( Language ( shortname = lang_json [ "lang_pair" ] [ "source_language" ] [ "shortname" ] , name = lang_json [ "lang_pair" ] [ "source_language" ] [ "name" ] ) , Language ( shortname = lang_json [ "lang_pair" ] [ "target_language" ] [ "shortname" ] , name = lang_json [ "lang_pair" ] [ "target_language" ] [ "name" ] ) ) for lang_json in langs_json [ "objects" ] ] except Exception , e : log . exception ( "Error decoding get language pairs" ) raise e return languages
6,782
https://github.com/Unbabel/unbabel-py/blob/3bd6397174e184d89d2a11149d87be5d12570c64/unbabel/api.py#L451-L476
[ "def", "_CheckFileEntryType", "(", "self", ",", "file_entry", ")", ":", "if", "not", "self", ".", "_file_entry_types", ":", "return", "None", "return", "(", "self", ".", "_CheckIsDevice", "(", "file_entry", ")", "or", "self", ".", "_CheckIsDirectory", "(", "file_entry", ")", "or", "self", ".", "_CheckIsFile", "(", "file_entry", ")", "or", "self", ".", "_CheckIsLink", "(", "file_entry", ")", "or", "self", ".", "_CheckIsPipe", "(", "file_entry", ")", "or", "self", ".", "_CheckIsSocket", "(", "file_entry", ")", ")" ]
Returns the tones available on unbabel
def get_tones ( self ) : result = self . api_call ( 'tone/' ) tones_json = json . loads ( result . content ) tones = [ Tone ( name = tone_json [ "tone" ] [ "name" ] , description = tone_json [ "tone" ] [ "description" ] ) for tone_json in tones_json [ "objects" ] ] return tones
6,783
https://github.com/Unbabel/unbabel-py/blob/3bd6397174e184d89d2a11149d87be5d12570c64/unbabel/api.py#L478-L487
[ "def", "dump_webdriver_cookies_into_requestdriver", "(", "requestdriver", ",", "webdriverwrapper", ")", ":", "for", "cookie", "in", "webdriverwrapper", ".", "get_cookies", "(", ")", ":", "# Wedbriver uses \"expiry\"; requests uses \"expires\", adjust for this", "expires", "=", "cookie", ".", "pop", "(", "'expiry'", ",", "{", "'expiry'", ":", "None", "}", ")", "cookie", ".", "update", "(", "{", "'expires'", ":", "expires", "}", ")", "requestdriver", ".", "session", ".", "cookies", ".", "set", "(", "*", "*", "cookie", ")" ]
Returns the topics available on unbabel
def get_topics ( self ) : result = self . api_call ( 'topic/' ) topics_json = json . loads ( result . content ) topics = [ Topic ( name = topic_json [ "topic" ] [ "name" ] ) for topic_json in topics_json [ "objects" ] ] return topics
6,784
https://github.com/Unbabel/unbabel-py/blob/3bd6397174e184d89d2a11149d87be5d12570c64/unbabel/api.py#L489-L497
[ "def", "CreateGRRTempFile", "(", "filename", "=", "None", ",", "lifetime", "=", "0", ",", "mode", "=", "\"w+b\"", ",", "suffix", "=", "\"\"", ")", ":", "directory", "=", "GetDefaultGRRTempDirectory", "(", ")", "EnsureTempDirIsSane", "(", "directory", ")", "prefix", "=", "config", ".", "CONFIG", ".", "Get", "(", "\"Client.tempfile_prefix\"", ")", "if", "filename", "is", "None", ":", "outfile", "=", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "prefix", ",", "suffix", "=", "suffix", ",", "dir", "=", "directory", ",", "delete", "=", "False", ")", "else", ":", "if", "filename", ".", "startswith", "(", "\"/\"", ")", "or", "filename", ".", "startswith", "(", "\"\\\\\"", ")", ":", "raise", "ValueError", "(", "\"Filename must be relative\"", ")", "if", "suffix", ":", "filename", "=", "\"%s.%s\"", "%", "(", "filename", ",", "suffix", ")", "outfile", "=", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", ",", "mode", ")", "if", "lifetime", ">", "0", ":", "cleanup", "=", "threading", ".", "Timer", "(", "lifetime", ",", "DeleteGRRTempFile", ",", "(", "outfile", ".", "name", ",", ")", ")", "cleanup", ".", "start", "(", ")", "# Fix perms on the file, since this code is used for writing executable blobs", "# we apply RWX.", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "from", "grr_response_client", "import", "client_utils_windows", "# pylint: disable=g-import-not-at-top", "client_utils_windows", ".", "WinChmod", "(", "outfile", ".", "name", ",", "[", "\"FILE_ALL_ACCESS\"", "]", ")", "else", ":", "os", ".", "chmod", "(", "outfile", ".", "name", ",", "stat", ".", "S_IXUSR", "|", "stat", ".", "S_IRUSR", "|", "stat", ".", "S_IWUSR", ")", "return", "outfile" ]
Randomize the POHMM parameters
def rand ( self , unique_pstates , random_state = None ) : self . _init_pstates ( unique_pstates ) self . _init_random ( random_state = random_state ) self . _compute_marginals ( ) return self
6,785
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/pohmm.py#L662-L669
[ "def", "match_color_index", "(", "self", ",", "color", ")", ":", "from", "jcvi", ".", "utils", ".", "webcolors", "import", "color_diff", "if", "isinstance", "(", "color", ",", "int", ")", ":", "return", "color", "if", "color", ":", "if", "isinstance", "(", "color", ",", "six", ".", "string_types", ")", ":", "rgb", "=", "map", "(", "int", ",", "color", ".", "split", "(", "','", ")", ")", "else", ":", "rgb", "=", "color", ".", "Get", "(", ")", "logging", ".", "disable", "(", "logging", ".", "DEBUG", ")", "distances", "=", "[", "color_diff", "(", "rgb", ",", "x", ")", "for", "x", "in", "self", ".", "xlwt_colors", "]", "logging", ".", "disable", "(", "logging", ".", "NOTSET", ")", "result", "=", "distances", ".", "index", "(", "min", "(", "distances", ")", ")", "self", ".", "unused_colors", ".", "discard", "(", "self", ".", "xlwt_colors", "[", "result", "]", ")", "return", "result" ]
Compute the log probability of each event under the model .
def score_events ( self , obs , pstates ) : pstates_idx = np . array ( [ self . e [ p ] for p in pstates ] ) framelogprob = self . _compute_log_likelihood ( obs , pstates_idx ) _ , fwdlattice = self . _do_forward_pass ( framelogprob , pstates_idx ) L = logsumexp ( fwdlattice , axis = 1 ) return np . concatenate ( [ L [ [ 0 ] ] , np . diff ( L ) ] )
6,786
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/pohmm.py#L742-L751
[ "def", "iter", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", "and", "vd", ":", "obj", "=", "vd", ".", "sheet", "for", "o", "in", "self", ".", "_mappings", "(", "obj", ")", ":", "for", "k", "in", "self", ".", "keys", "(", ")", ":", "for", "o2", "in", "self", "[", "k", "]", ":", "if", "o", "==", "o2", ":", "yield", "(", "k", ",", "o", ")", ",", "self", "[", "k", "]", "[", "o2", "]" ]
Predict the next observation
def predict ( self , obs , pstates , next_pstate = None ) : assert len ( obs ) == len ( pstates ) pstates_idx = np . array ( [ self . e [ ei ] for ei in pstates ] ) next_pstate_idx = self . e [ next_pstate ] if len ( obs ) == 0 : # No history, use the starting probas next_hstate_prob = self . startprob [ next_pstate_idx ] else : # With a history, determine the hidden state posteriors using # the last posteriors and transition matrix framelogprob = self . _compute_log_likelihood ( obs , pstates_idx ) _ , fwdlattice = self . _do_forward_pass ( framelogprob , pstates_idx ) next_hstate_prob = np . zeros ( self . n_hidden_states ) alpha_n = fwdlattice [ - 1 ] vmax = alpha_n . max ( axis = 0 ) alpha_n = np . exp ( alpha_n - vmax ) alpha_n = alpha_n / alpha_n . sum ( ) trans = self . transmat [ pstates_idx [ - 1 ] , next_pstate_idx ] for i in range ( self . n_hidden_states ) : next_hstate_prob [ i ] = np . sum ( [ alpha_n [ j ] * trans [ j , i ] for j in range ( self . n_hidden_states ) ] ) assert next_hstate_prob . sum ( ) - 1 < TOLERANCE # Make the prediction prediction = np . array ( [ self . expected_value ( feature , pstate = next_pstate , hstate_prob = next_hstate_prob ) for feature in self . emission_name ] ) # next_hstate = np.argmax(next_hstate_prob) # prediction = np.array( # [self.expected_value(feature, pstate=next_pstate, hstate=next_hstate) for feature in # self.emission_name]) return prediction
6,787
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/pohmm.py#L759-L800
[ "def", "BuildChecks", "(", "self", ",", "request", ")", ":", "result", "=", "[", "]", "if", "request", ".", "HasField", "(", "\"start_time\"", ")", "or", "request", ".", "HasField", "(", "\"end_time\"", ")", ":", "def", "FilterTimestamp", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "HasField", "(", "\"st_mtime\"", ")", "and", "(", "file_stat", ".", "st_mtime", "<", "request", ".", "start_time", "or", "file_stat", ".", "st_mtime", ">", "request", ".", "end_time", ")", "result", ".", "append", "(", "FilterTimestamp", ")", "if", "request", ".", "HasField", "(", "\"min_file_size\"", ")", "or", "request", ".", "HasField", "(", "\"max_file_size\"", ")", ":", "def", "FilterSize", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "HasField", "(", "\"st_size\"", ")", "and", "(", "file_stat", ".", "st_size", "<", "request", ".", "min_file_size", "or", "file_stat", ".", "st_size", ">", "request", ".", "max_file_size", ")", "result", ".", "append", "(", "FilterSize", ")", "if", "request", ".", "HasField", "(", "\"perm_mode\"", ")", ":", "def", "FilterPerms", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "(", "file_stat", ".", "st_mode", "&", "request", ".", "perm_mask", ")", "!=", "request", ".", "perm_mode", "result", ".", "append", "(", "FilterPerms", ")", "if", "request", ".", "HasField", "(", "\"uid\"", ")", ":", "def", "FilterUID", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "st_uid", "!=", "request", ".", "uid", "result", ".", "append", "(", "FilterUID", ")", "if", "request", ".", "HasField", "(", "\"gid\"", ")", ":", "def", "FilterGID", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "st_gid", "!=", "request", ".", "gid", "result", ".", "append", "(", "FilterGID", ")", "if", "request", ".", "HasField", "(", "\"path_regex\"", ")", ":", "regex", "=", "request", ".", "path_regex", "def", "FilterPath", "(", "file_stat", ",", "regex", "=", "regex", ")", ":", "\"\"\"Suppress any filename not matching the regular expression.\"\"\"", "return", "not", "regex", ".", "Search", "(", "file_stat", ".", "pathspec", ".", "Basename", "(", ")", ")", "result", ".", "append", "(", "FilterPath", ")", "if", "request", ".", "HasField", "(", "\"data_regex\"", ")", ":", "def", "FilterData", "(", "file_stat", ",", "*", "*", "_", ")", ":", "\"\"\"Suppress files that do not match the content.\"\"\"", "return", "not", "self", ".", "TestFileContent", "(", "file_stat", ")", "result", ".", "append", "(", "FilterData", ")", "return", "result" ]
Convenience function to fit a model from a list of dataframes
def fit_df ( self , dfs , pstate_col = PSTATE_COL ) : obs_cols = list ( self . emission_name ) obs = [ df [ df . columns . difference ( [ pstate_col ] ) ] [ obs_cols ] . values for df in dfs ] pstates = [ df [ pstate_col ] . values for df in dfs ] return self . fit ( obs , pstates )
6,788
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/pohmm.py#L876-L883
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_access", "is", "not", "None", ":", "_logger", ".", "debug", "(", "\"Cleaning up\"", ")", "pci_cleanup", "(", "self", ".", "_access", ")", "self", ".", "_access", "=", "None" ]
Convenience function to generate samples a model and create a dataframe
def sample_df ( self , pstates = None , n_obs = None , random_state = None , pstate_col = PSTATE_COL , hstate_col = HSTATE_COL ) : try : import pandas as pd except Exception as e : raise e obs , pstates , hstates = self . sample ( pstates , n_obs , random_state ) items = [ ] if pstate_col is not None : items . append ( ( pstate_col , pstates ) ) if hstate_col is not None : items . append ( ( hstate_col , hstates ) ) items = items + [ ( self . emission_name [ i ] , obs [ : , i ] ) for i in range ( self . n_features ) ] df = pd . DataFrame . from_items ( items ) return df
6,789
https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/pohmm.py#L919-L939
[ "async", "def", "open", "(", "self", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'StorageRecordSearch.open >>>'", ")", "if", "self", ".", "opened", ":", "LOGGER", ".", "debug", "(", "'StorageRecordSearch.open <!< Search is already opened'", ")", "raise", "BadSearch", "(", "'Search is already opened'", ")", "if", "not", "self", ".", "_wallet", ".", "opened", ":", "LOGGER", ".", "debug", "(", "'StorageRecordSearch.open <!< Wallet %s is closed'", ",", "self", ".", "_wallet", ".", "name", ")", "raise", "WalletState", "(", "'Wallet {} is closed'", ".", "format", "(", "self", ".", "_wallet", ".", "name", ")", ")", "self", ".", "_handle", "=", "await", "non_secrets", ".", "open_wallet_search", "(", "self", ".", "_wallet", ".", "handle", ",", "self", ".", "_type", ",", "self", ".", "_query_json", ",", "StorageRecordSearch", ".", "OPTIONS_JSON", ")", "LOGGER", ".", "debug", "(", "'StorageRecordSearch.open <<<'", ")" ]
Entry point for cyther - script generated by setup . py on installation
def main ( args = None ) : if args is None : args = sys . argv [ 1 : ] if not args : args = [ '-h' ] namespace = parser . parse_args ( args ) entry_function = namespace . func del namespace . func kwargs = namespace . __dict__ return entry_function ( * * kwargs )
6,790
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/__main__.py#L11-L25
[ "def", "busday_count_mask_NaT", "(", "begindates", ",", "enddates", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "empty", "(", "broadcast", "(", "begindates", ",", "enddates", ")", ".", "shape", ",", "dtype", "=", "float", ")", "beginmask", "=", "isnat", "(", "begindates", ")", "endmask", "=", "isnat", "(", "enddates", ")", "out", "=", "busday_count", "(", "# Temporarily fill in non-NaT values.", "where", "(", "beginmask", ",", "_notNaT", ",", "begindates", ")", ",", "where", "(", "endmask", ",", "_notNaT", ",", "enddates", ")", ",", "out", "=", "out", ",", ")", "# Fill in entries where either comparison was NaT with nan in the output.", "out", "[", "beginmask", "|", "endmask", "]", "=", "nan", "return", "out" ]
Retrieve user data from LDAP server .
def get_ldap_users ( self ) : if ( not self . conf_LDAP_SYNC_USER ) : return ( None , None ) user_keys = set ( self . conf_LDAP_SYNC_USER_ATTRIBUTES . keys ( ) ) user_keys . update ( self . conf_LDAP_SYNC_USER_EXTRA_ATTRIBUTES ) uri_users_server , users = self . ldap_search ( self . conf_LDAP_SYNC_USER_FILTER , user_keys , self . conf_LDAP_SYNC_USER_INCREMENTAL , self . conf_LDAP_SYNC_USER_FILTER_INCREMENTAL ) logger . debug ( "Retrieved %d users from %s LDAP server" % ( len ( users ) , uri_users_server ) ) return ( uri_users_server , users )
6,791
https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/management/commands/syncldap.py#L290-L298
[ "def", "setWindowTitle", "(", "self", ",", "newTitle", "=", "''", ")", ":", "title", "=", "'Rampage - '", "+", "newTitle", "super", "(", "MainWindow", ",", "self", ")", ".", "setWindowTitle", "(", "title", ")" ]
Retrieve groups from LDAP server .
def get_ldap_groups ( self ) : if ( not self . conf_LDAP_SYNC_GROUP ) : return ( None , None ) uri_groups_server , groups = self . ldap_search ( self . conf_LDAP_SYNC_GROUP_FILTER , self . conf_LDAP_SYNC_GROUP_ATTRIBUTES . keys ( ) , self . conf_LDAP_SYNC_GROUP_INCREMENTAL , self . conf_LDAP_SYNC_GROUP_FILTER_INCREMENTAL ) logger . debug ( "Retrieved %d groups from %s LDAP server" % ( len ( groups ) , uri_groups_server ) ) return ( uri_groups_server , groups )
6,792
https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/management/commands/syncldap.py#L558-L564
[ "def", "create_image", "(", "self", ",", "image_file", ",", "caption", ")", ":", "suffix", "=", "'png'", "if", "image_file", ":", "img", "=", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "gallery", ",", "image_file", ")", ")", "width", ",", "height", "=", "img", ".", "size", "ratio", "=", "width", "/", "WIDTH", "img", "=", "img", ".", "resize", "(", "(", "int", "(", "width", "//", "ratio", ")", ",", "int", "(", "height", "//", "ratio", ")", ")", ",", "Image", ".", "ANTIALIAS", ")", "else", ":", "img", "=", "Image", ".", "new", "(", "'RGB'", ",", "(", "WIDTH", ",", "HEIGHT", ")", ",", "'black'", ")", "image", "=", "self", ".", "add_caption", "(", "img", ",", "caption", ")", "image", "=", "img", "return", "image" ]
Retrieve user membership from LDAP server .
def get_ldap_user_membership ( self , user_dn ) : #Escape parenthesis in DN membership_filter = self . conf_LDAP_SYNC_GROUP_MEMBERSHIP_FILTER . replace ( '{distinguishedName}' , user_dn . replace ( '(' , "\(" ) . replace ( ')' , "\)" ) ) try : uri , groups = self . ldap_search ( membership_filter , self . conf_LDAP_SYNC_GROUP_ATTRIBUTES . keys ( ) , False , membership_filter ) except Exception as e : logger . error ( "Error reading membership: Filter %s, Keys %s" % ( membership_filter , str ( self . conf_LDAP_SYNC_GROUP_ATTRIBUTES . keys ( ) ) ) ) return None #logger.debug("AD Membership: Retrieved %d groups for user '%s'" % (len(groups), user_dn)) return ( uri , groups )
6,793
https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/management/commands/syncldap.py#L603-L613
[ "def", "create_track", "(", "self", ",", "href", "=", "None", ",", "media_url", "=", "None", ",", "label", "=", "None", ",", "audio_channel", "=", "None", ")", ":", "# Argument error checking.", "assert", "href", "is", "not", "None", "assert", "media_url", "is", "not", "None", "# Prepare the data we're going to write.", "data", "=", "None", "fields", "=", "{", "}", "fields", "[", "'media_url'", "]", "=", "media_url", "if", "label", "is", "not", "None", ":", "fields", "[", "'label'", "]", "=", "label", "if", "audio_channel", "is", "not", "None", ":", "fields", "[", "'audio_channel'", "]", "=", "audio_channel", "if", "len", "(", "fields", ")", ">", "0", ":", "data", "=", "fields", "raw_result", "=", "self", ".", "post", "(", "href", ",", "data", ")", "if", "raw_result", ".", "status", "<", "200", "or", "raw_result", ".", "status", ">", "202", ":", "raise", "APIException", "(", "raw_result", ".", "status", ",", "raw_result", ".", "json", ")", "# Convert the JSON to a python data struct.", "return", "self", ".", "_parse_json", "(", "raw_result", ".", "json", ")" ]
Synchronize LDAP membership to Django membership
def sync_ldap_user_membership ( self , user , ldap_groups ) : groupname_field = 'name' actualGroups = user . groups . values_list ( 'name' , flat = True ) user_Membership_total = len ( ldap_groups ) user_Membership_added = 0 user_Membership_deleted = 0 user_Membership_errors = 0 ldap_groups += self . conf_LDAP_SYNC_GROUP_MEMBERSHIP_ADD_DEFAULT ldap_name_groups = [ ] for cname , ldap_attributes in ldap_groups : defaults = { } try : for name , attribute in ldap_attributes . items ( ) : defaults [ self . conf_LDAP_SYNC_GROUP_ATTRIBUTES [ name ] ] = attribute [ 0 ] . decode ( 'utf-8' ) except AttributeError : # In some cases attrs is a list instead of a dict; skip these invalid groups continue try : groupname = defaults [ groupname_field ] ldap_name_groups . append ( groupname ) except KeyError : logger . warning ( "Group is missing a required attribute '%s'" % groupname_field ) user_Membership_errors += 1 continue if ( groupname not in actualGroups ) : kwargs = { groupname_field + '__iexact' : groupname , 'defaults' : defaults , } #Adding Group Membership try : if ( self . conf_LDAP_SYNC_GROUP_MEMBERSHIP_CREATE_IF_NOT_EXISTS ) : group , created = Group . objects . get_or_create ( * * kwargs ) else : group = Group . objects . get ( name = groupname ) created = False except ( ObjectDoesNotExist ) : #Doesn't exist and not autocreate groups, we pass the error continue except ( IntegrityError , DataError ) as e : logger . error ( "Error creating group %s: %s" % ( groupname , e ) ) user_Membership_errors += 1 else : if created : logger . debug ( "Created group %s" % groupname ) #Now well assign the user group . user_set . add ( user ) user_Membership_added += 1 #Default Primary Group: Temporary is fixed #removing group membership for check_group in actualGroups : if ( check_group not in ldap_name_groups ) : group = Group . objects . get ( name = check_group ) group . user_set . remove ( user ) user_Membership_deleted += 1 if ( ( user_Membership_deleted > 0 ) or ( user_Membership_added > 0 ) ) : group . save ( ) logger . info ( "Group membership for user %s synchronized: %d Added, %d Removed" % ( user . username , user_Membership_added , user_Membership_deleted ) ) #Return statistics self . stats_membership_total += user_Membership_total self . stats_membership_added += user_Membership_added self . stats_membership_deleted += user_Membership_deleted self . stats_membership_errors += user_Membership_errors
6,794
https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/management/commands/syncldap.py#L615-L686
[ "def", "write_file_to_descriptor", "(", "input_queue", ",", "descriptor", ")", ":", "try", ":", "file_name", "=", "input_queue", ".", "get", "(", "timeout", "=", "2", ")", "descriptor", ".", "write", "(", "\"{}\\n\"", ".", "format", "(", "file_name", ")", ")", "descriptor", ".", "flush", "(", ")", "input_queue", ".", "task_done", "(", ")", "return", "True", "except", "Empty", ":", "# no more files in queue", "descriptor", ".", "close", "(", ")", "return", "False", "except", "IOError", ":", "return", "False" ]
Query the configured LDAP server with the provided search filter and attribute list .
def ldap_search ( self , filter , attributes , incremental , incremental_filter ) : for uri in self . conf_LDAP_SYNC_BIND_URI : #Read record of this uri if ( self . working_uri == uri ) : adldap_sync = self . working_adldap_sync created = False else : adldap_sync , created = ADldap_Sync . objects . get_or_create ( ldap_sync_uri = uri ) if ( ( adldap_sync . syncs_to_full > 0 ) and incremental ) : filter_to_use = incremental_filter . replace ( '?' , self . whenchanged . strftime ( self . conf_LDAP_SYNC_INCREMENTAL_TIMESTAMPFORMAT ) ) logger . debug ( "Using an incremental search. Filter is:'%s'" % filter_to_use ) else : filter_to_use = filter ldap . set_option ( ldap . OPT_REFERRALS , 0 ) #ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 10) l = PagedLDAPObject ( uri ) l . protocol_version = 3 if ( uri . startswith ( 'ldaps:' ) ) : l . set_option ( ldap . OPT_X_TLS , ldap . OPT_X_TLS_DEMAND ) l . set_option ( ldap . OPT_X_TLS_REQUIRE_CERT , ldap . OPT_X_TLS_DEMAND ) l . set_option ( ldap . OPT_X_TLS_DEMAND , True ) else : l . set_option ( ldap . OPT_X_TLS , ldap . OPT_X_TLS_NEVER ) l . set_option ( ldap . OPT_X_TLS_REQUIRE_CERT , ldap . OPT_X_TLS_NEVER ) l . set_option ( ldap . OPT_X_TLS_DEMAND , False ) try : l . simple_bind_s ( self . conf_LDAP_SYNC_BIND_DN , self . conf_LDAP_SYNC_BIND_PASS ) except ldap . LDAPError as e : logger . error ( "Error connecting to LDAP server %s : %s" % ( uri , e ) ) continue results = l . paged_search_ext_s ( self . conf_LDAP_SYNC_BIND_SEARCH , ldap . SCOPE_SUBTREE , filter_to_use , attrlist = attributes , serverctrls = None ) l . unbind_s ( ) if ( self . working_uri is None ) : self . working_uri = uri self . conf_LDAP_SYNC_BIND_URI . insert ( 0 , uri ) self . working_adldap_sync = adldap_sync return ( uri , results ) # Return both the LDAP server URI used and the request. This is for incremental sync purposes #if not connected correctly, raise error raise
6,795
https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/management/commands/syncldap.py#L688-L735
[ "def", "writearff", "(", "data", ",", "filename", ",", "relation_name", "=", "None", ",", "index", "=", "True", ")", ":", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "fp", "=", "open", "(", "filename", ",", "'w'", ")", "if", "relation_name", "is", "None", ":", "relation_name", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "else", ":", "fp", "=", "filename", "if", "relation_name", "is", "None", ":", "relation_name", "=", "\"pandas\"", "try", ":", "data", "=", "_write_header", "(", "data", ",", "fp", ",", "relation_name", ",", "index", ")", "fp", ".", "write", "(", "\"\\n\"", ")", "_write_data", "(", "data", ",", "fp", ")", "finally", ":", "fp", ".", "close", "(", ")" ]
Generator for reading sliver data from directory structure .
def sliver_reader ( filename_end_mask = "*[0-9].mhd" , sliver_reference_dir = "~/data/medical/orig/sliver07/training/" , read_orig = True , read_seg = False ) : sliver_reference_dir = op . expanduser ( sliver_reference_dir ) orig_fnames = glob . glob ( sliver_reference_dir + "*orig" + filename_end_mask ) ref_fnames = glob . glob ( sliver_reference_dir + "*seg" + filename_end_mask ) orig_fnames . sort ( ) ref_fnames . sort ( ) output = [ ] for i in range ( 0 , len ( orig_fnames ) ) : oname = orig_fnames [ i ] rname = ref_fnames [ i ] vs_mm = None ref_data = None orig_data = None if read_orig : orig_data , metadata = io3d . datareader . read ( oname ) vs_mm = metadata [ 'voxelsize_mm' ] if read_seg : ref_data , metadata = io3d . datareader . read ( rname ) vs_mm = metadata [ 'voxelsize_mm' ] import re numeric_label = re . search ( ".*g(\d+)" , oname ) . group ( 1 ) out = ( numeric_label , vs_mm , oname , orig_data , rname , ref_data ) yield out
6,796
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/datasets.py#L14-L47
[ "def", "on_trial_complete", "(", "self", ",", "trial_id", ",", "result", "=", "None", ",", "error", "=", "False", ",", "early_terminated", "=", "False", ")", ":", "if", "result", ":", "self", ".", "conn", ".", "experiments", "(", "self", ".", "experiment", ".", "id", ")", ".", "observations", "(", ")", ".", "create", "(", "suggestion", "=", "self", ".", "_live_trial_mapping", "[", "trial_id", "]", ".", "id", ",", "value", "=", "result", "[", "self", ".", "_reward_attr", "]", ",", ")", "# Update the experiment object", "self", ".", "experiment", "=", "self", ".", "conn", ".", "experiments", "(", "self", ".", "experiment", ".", "id", ")", ".", "fetch", "(", ")", "elif", "error", "or", "early_terminated", ":", "# Reports a failed Observation", "self", ".", "conn", ".", "experiments", "(", "self", ".", "experiment", ".", "id", ")", ".", "observations", "(", ")", ".", "create", "(", "failed", "=", "True", ",", "suggestion", "=", "self", ".", "_live_trial_mapping", "[", "trial_id", "]", ".", "id", ")", "del", "self", ".", "_live_trial_mapping", "[", "trial_id", "]" ]
makes gunicorn . conf file for launching in docker
def make_gunicorn_config ( _gunicorn_config_path = '' , ) : gunicorn_py = '''"""AUTOGENERATED BY: prosper.common.flask_utils:gunicorn_config Based off: https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/ """ from os import environ for key, value in environ.items(): if key.startswith('GUNICORN_'): gunicorn_key = key.split('_', 1)[1].lower() locals()[gunicorn_key] = value ''' gunicorn_file = 'gunicorn.conf' if _gunicorn_config_path : gunicorn_file = _gunicorn_config_path with open ( gunicorn_file , 'w' ) as gunicorn_cfg : gunicorn_cfg . write ( gunicorn_py )
6,797
https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/flask_utils.py#L4-L34
[ "def", "DropTables", "(", "self", ")", ":", "rows", ",", "_", "=", "self", ".", "ExecuteQuery", "(", "\"SELECT table_name FROM information_schema.tables \"", "\"WHERE table_schema='%s'\"", "%", "self", ".", "database_name", ")", "for", "row", "in", "rows", ":", "self", ".", "ExecuteQuery", "(", "\"DROP TABLE `%s`\"", "%", "row", "[", "\"table_name\"", "]", ")" ]
Return a function that prints node details .
def _print_details ( extra = None ) : def print_node_handler ( name , node , depth ) : """Standard printer for a node.""" line = "{0}{1} {2} ({3}:{4})" . format ( depth , ( " " * depth ) , name , node . line , node . col ) if extra is not None : line += " [{0}]" . format ( extra ( node ) ) sys . stdout . write ( line + "\n" ) return print_node_handler
6,798
https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/printer.py#L24-L38
[ "def", "getInitialSample", "(", "self", ",", "wmg", ")", ":", "cands", "=", "range", "(", "len", "(", "wmg", ")", ")", "allPairs", "=", "itertools", ".", "combinations", "(", "cands", ",", "2", ")", "V", "=", "self", ".", "createBinaryRelation", "(", "len", "(", "cands", ")", ")", "for", "pair", "in", "allPairs", ":", "if", "wmg", "[", "pair", "[", "0", "]", "+", "1", "]", "[", "pair", "[", "1", "]", "+", "1", "]", ">", "0", ":", "V", "[", "pair", "[", "0", "]", "]", "[", "pair", "[", "1", "]", "]", "=", "1", "V", "[", "pair", "[", "1", "]", "]", "[", "pair", "[", "0", "]", "]", "=", "0", "else", ":", "V", "[", "pair", "[", "0", "]", "]", "[", "pair", "[", "1", "]", "]", "=", "0", "V", "[", "pair", "[", "1", "]", "]", "[", "pair", "[", "0", "]", "]", "=", "1", "return", "V" ]
Print the AST of filename .
def do_print ( filename ) : with open ( filename ) as cmake_file : body = ast . parse ( cmake_file . read ( ) ) word_print = _print_details ( lambda n : "{0} {1}" . format ( n . type , n . contents ) ) ast_visitor . recurse ( body , while_stmnt = _print_details ( ) , foreach = _print_details ( ) , function_def = _print_details ( ) , macro_def = _print_details ( ) , if_block = _print_details ( ) , if_stmnt = _print_details ( ) , elseif_stmnt = _print_details ( ) , else_stmnt = _print_details ( ) , function_call = _print_details ( lambda n : n . name ) , word = word_print )
6,799
https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/printer.py#L41-L58
[ "def", "_intersection", "(", "self", ",", "keys", ",", "rows", ")", ":", "# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.", "if", "not", "keys", ":", "return", "rows", "ret", "=", "list", "(", ")", "for", "row", "in", "rows", ":", "start_date", "=", "row", "[", "self", ".", "_key_start_date", "]", "end_date", "=", "row", "[", "self", ".", "_key_end_date", "]", "for", "key_start_date", ",", "key_end_date", "in", "keys", ":", "start_date", ",", "end_date", "=", "Type2JoinHelper", ".", "_intersect", "(", "start_date", ",", "end_date", ",", "row", "[", "key_start_date", "]", ",", "row", "[", "key_end_date", "]", ")", "if", "not", "start_date", ":", "break", "if", "key_start_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_start_date", "]", "if", "key_end_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_end_date", "]", "if", "start_date", ":", "row", "[", "self", ".", "_key_start_date", "]", "=", "start_date", "row", "[", "self", ".", "_key_end_date", "]", "=", "end_date", "ret", ".", "append", "(", "row", ")", "return", "ret" ]