idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
51,300 | def update_redis ( project : str , environment : str , feature : str , state : str ) -> None : try : hosts = RedisWrapper . connection_string_parser ( os . environ . get ( 'REDIS_HOSTS' ) ) except RuntimeError as ex : LOG . error ( ex ) sys . exit ( 1 ) for host in hosts : LOG . info ( "connecting to %s:%s" , host . host , host . port ) try : if valid_state ( state ) : new_state = state . lower ( ) redis = RedisWrapper ( host . host , host . port , project , environment ) redis . update_flag_record ( new_state , feature ) create_file ( project , environment , feature , new_state ) LOG . info ( "%s was successfully updated." , feature ) else : raise Exception ( 'Invalid state: {0}, -s needs \ to be either on or off.' . format ( state ) ) except KeyError as ex : LOG . error ( "unable to update %s. Exception: %s" , host . host , ex ) sys . exit ( 1 ) | Update redis state for a feature flag . |
51,301 | def update_ld_api ( project : str , environment : str , feature : str , state : str ) : ld_api = LaunchDarklyApi ( os . environ . get ( 'LD_API_KEY' ) , project , environment ) if valid_state ( state ) : if state . lower ( ) == 'off' : new_state = False else : new_state = True ld_api . update_flag ( new_state , feature ) else : raise ValueError ( 'Invalid state: {0}, -s needs to be either \ on or off.' . format ( state ) ) | Execute command against the LaunchDarkly API . |
51,302 | def generate_relay_config ( project ) : ld_api = LaunchDarklyApi ( os . environ . get ( 'LD_API_KEY' ) , project_key = project ) config = ConfigGenerator ( ) envs = ld_api . get_environments ( project ) config . generate_relay_config ( envs ) | Generate Relay Proxy Configuration . |
51,303 | def dicomdir_info ( dirpath , * args , ** kwargs ) : dr = DicomReader ( dirpath = dirpath , * args , ** kwargs ) info = dr . dicomdirectory . get_stats_of_series_in_dir ( ) return info | Get information about series in dir |
51,304 | def is_dicom_dir ( datapath ) : retval = False datapath = op . expanduser ( datapath ) for f in os . listdir ( datapath ) : if f . endswith ( ( ".dcm" , ".DCM" ) ) : retval = True return True try : pydicom . read_file ( os . path . join ( datapath , f ) ) retval = True except Exception as e : logger . warning ( "Unable to read dicom file " + str ( f ) ) logger . warning ( e ) if retval : return True return False | Check if in dir is one or more dicom file . We use two methods . First is based on dcm extension detection . |
51,305 | def files_in_dir ( dirpath , wildcard = "*" , startpath = None ) : import glob filelist = [ ] if startpath is not None : completedirpath = os . path . join ( startpath , dirpath ) else : completedirpath = dirpath if os . path . exists ( completedirpath ) : logger . info ( 'completedirpath = ' + completedirpath ) else : logger . error ( 'Wrong path: ' + completedirpath ) raise Exception ( 'Wrong path : ' + completedirpath ) for infile in glob . glob ( os . path . join ( completedirpath , wildcard ) ) : filelist . append ( infile ) if len ( filelist ) == 0 : logger . error ( 'No required files in path: ' + completedirpath ) raise Exception ( 'No required file in path: ' + completedirpath ) return filelist | Function generates list of files from specific dir |
51,306 | def get_slice_location ( dcmdata , teil = None ) : slice_location = None if hasattr ( dcmdata , 'SliceLocation' ) : try : slice_location = float ( dcmdata . SliceLocation ) except Exception as exc : logger . info ( "It is not possible to use SliceLocation" ) logger . debug ( traceback . format_exc ( ) ) if slice_location is None and hasattr ( dcmdata , "SliceThickness" ) and teil is not None : logger . debug ( "Estimating SliceLocation wiht image number and SliceThickness" ) i = list ( map ( int , re . findall ( '\d+' , teil ) ) ) i = i [ - 1 ] try : slice_location = float ( i * float ( dcmdata . SliceThickness ) ) except ValueError as e : print ( type ( dcmdata . SliceThickness ) ) print ( dcmdata . SliceThickness ) logger . debug ( traceback . format_exc ( ) ) logger . debug ( "SliceThickness problem" ) if slice_location is None and hasattr ( dcmdata , "ImagePositionPatient" ) and hasattr ( dcmdata , "ImageOrientationPatient" ) : if dcmdata . ImageOrientationPatient == [ 1 , 0 , 0 , 0 , 1 , 0 ] : slice_location = dcmdata . ImagePositionPatient [ 2 ] else : logger . warning ( "Unknown ImageOrientationPatient" ) if slice_location is None : logger . warning ( "Problem with slice location" ) return slice_location | get location of the slice |
51,307 | def get_overlay ( self ) : overlay = { } dcmlist = self . files_in_serie for i in range ( len ( dcmlist ) ) : onefile = dcmlist [ i ] logger . info ( "reading '%s'" % onefile ) data = self . _read_file ( onefile ) if len ( overlay ) == 0 : for i_overlay in range ( 0 , 50 ) : try : data2d = decode_overlay_slice ( data , i_overlay ) shp2 = data2d . shape overlay [ i_overlay ] = np . zeros ( [ len ( dcmlist ) , shp2 [ 0 ] , shp2 [ 1 ] ] , dtype = np . int8 ) overlay [ i_overlay ] [ - i - 1 , : , : ] = data2d except Exception : pass else : for i_overlay in overlay . keys ( ) : try : data2d = decode_overlay_slice ( data , i_overlay ) overlay [ i_overlay ] [ - i - 1 , : , : ] = data2d except Exception : logger . warning ( 'Problem with overlay number ' + str ( i_overlay ) ) return overlay | Function make 3D data from dicom file slices . There are usualy more overlays in the data . |
51,308 | def get_stats_of_series_in_dir ( self , study_id = None ) : if study_id is not None : logger . error ( "study_id tag is not implemented yet" ) return import numpy as np dcmdir = self . files_with_info series_info = { line [ 'SeriesNumber' ] : line for line in dcmdir } try : dcmdirseries = [ line [ 'SeriesNumber' ] for line in dcmdir ] except : logger . debug ( 'Dicom tag SeriesNumber not found' ) series_info = { 0 : { 'Count' : 0 } } return series_info bins , counts = np . unique ( dcmdirseries , return_counts = True ) for i in range ( 0 , len ( bins ) ) : series_info [ bins [ i ] ] [ 'Count' ] = counts [ i ] lst = self . get_sorted_series_files ( series_number = bins [ i ] ) metadata = self . get_metaData ( dcmlist = lst , series_number = bins [ i ] ) series_info [ bins [ i ] ] = dict ( list ( series_info [ bins [ i ] ] . items ( ) ) + list ( metadata . items ( ) ) ) return series_info | Dicom series staticstics input is dcmdir not dirpath Information is generated from dicomdir . pkl and first files of series |
51,309 | def print_series_info ( self , series_info , minimal_series_number = 1 ) : strinfo = '' if len ( series_info ) > minimal_series_number : for serie_number in series_info . keys ( ) : strl = get_one_serie_info ( series_info , serie_number ) strinfo = strinfo + strl + '\n' return strinfo | Print series_info from dcmdirstats |
51,310 | def __prepare_info_from_dicomdir_file ( self , writedicomdirfile = True ) : createdcmdir = True dicomdirfile = os . path . join ( self . dirpath , self . dicomdir_filename ) ftype = 'pickle' if os . path . exists ( dicomdirfile ) : try : dcmdirplus = misc . obj_from_file ( dicomdirfile , ftype ) if dcmdirplus [ 'version' ] == __version__ : createdcmdir = False dcmdir = dcmdirplus [ 'filesinfo' ] except Exception : logger . debug ( 'Found dicomdir.pkl with wrong version' ) createdcmdir = True if createdcmdir or self . force_create_dicomdir : dcmdirplus = self . _create_dicomdir_info ( ) dcmdir = dcmdirplus [ 'filesinfo' ] if ( writedicomdirfile ) and len ( dcmdir ) > 0 : try : misc . obj_to_file ( dcmdirplus , dicomdirfile , ftype ) except : logger . warning ( 'Cannot write dcmdir file' ) traceback . print_exc ( ) dcmdir = dcmdirplus [ 'filesinfo' ] self . dcmdirplus = dcmdirplus self . files_with_info = dcmdir return dcmdir | Check if exists dicomdir file and load it or cerate it |
51,311 | def series_in_dir ( self ) : countsd = { } for line in self . files_with_info : if "SeriesNumber" in line : sn = line [ 'SeriesNumber' ] else : sn = None if sn in countsd : countsd [ sn ] += 1 else : countsd [ sn ] = 1 bins = list ( countsd ) counts = list ( countsd . values ( ) ) return counts , bins | input is dcmdir not dirpath |
51,312 | def get_sorted_series_files ( self , startpath = "" , series_number = None , return_files_with_info = False , sort_keys = "SliceLocation" , return_files = True , remove_doubled_slice_locations = True ) : dcmdir = self . files_with_info [ : ] if series_number is not None : dcmdir = [ line for line in dcmdir if line [ 'SeriesNumber' ] == series_number ] dcmdir = sort_list_of_dicts ( dcmdir , keys = sort_keys ) logger . debug ( 'SeriesNumber: ' + str ( series_number ) ) if remove_doubled_slice_locations : dcmdir = self . _remove_doubled_slice_locations ( dcmdir ) filelist = [ ] for onefile in dcmdir : filelist . append ( os . path . join ( startpath , self . dirpath , onefile [ 'filename' ] ) ) retval = [ ] if return_files : retval . append ( filelist ) if return_files_with_info : retval . append ( dcmdir ) if len ( retval ) == 0 : retval = None elif len ( retval ) == 1 : retval = retval [ 0 ] else : retval = tuple ( retval ) return retval | Function returns sorted list of dicom files . File paths are organized by SeriesUID StudyUID and FrameUID |
51,313 | def _create_dicomdir_info ( self ) : filelist = files_in_dir ( self . dirpath ) files = [ ] metadataline = { } for filepath in filelist : head , teil = os . path . split ( filepath ) dcmdata = None if os . path . isdir ( filepath ) : logger . debug ( "Subdirectory found in series dir is ignored: " + str ( filepath ) ) continue try : dcmdata = pydicom . read_file ( filepath ) except pydicom . errors . InvalidDicomError as e : try : dcmdata = pydicom . read_file ( filepath , force = self . force_read ) except Exception as e : if teil != self . dicomdir_filename : logger . info ( 'Dicom read problem with file ' + filepath ) import traceback logger . debug ( traceback . format_exc ( ) ) if hasattr ( dcmdata , "DirectoryRecordSequence" ) : dcmdata = None if dcmdata is not None : metadataline = _prepare_metadata_line ( dcmdata , teil ) files . append ( metadataline ) files . sort ( key = lambda x : ( x [ 'SliceLocation' ] is None , x [ "SliceLocation" ] ) ) dcmdirplus = { 'version' : __version__ , 'filesinfo' : files , } if "StudyDate" in metadataline : dcmdirplus [ "StudyDate" ] = metadataline [ "StudyDate" ] return dcmdirplus | Function crates list of all files in dicom dir with all IDs |
51,314 | def python_parser ( self , obj , * args ) : attr , args = args [ 0 ] , args [ 1 : ] item = getattr ( obj , attr ) if callable ( item ) : item = item ( * args ) return [ item ] | operate a python obj |
51,315 | def parse ( self ) : self . tree = self . _build_tree ( self . html_contents ) self . stylesheet = self . parser . parse_stylesheet ( self . css_contents ) self . cleaned_css = self . _clean_css ( ) | Parses the CSS contents and returns the cleaned CSS as a string |
51,316 | def rel_to_abs ( self , base_url ) : self . cleaned_css = self . rel_to_abs_re . sub ( lambda match : "url('%s')" % urljoin ( base_url , match . group ( 'path' ) . strip ( '\'"' ) ) , self . cleaned_css ) | Converts relative links from css contents to absolute links |
51,317 | def _clean_css ( self ) : css_rules = [ ] for rule in self . stylesheet . rules : try : cleaned_rule = self . _clean_rule ( rule ) if cleaned_rule is not None : css_rules . append ( cleaned_rule ) except : css_rules . append ( rule ) return self . _build_css ( css_rules ) | Returns the cleaned CSS |
51,318 | def _clean_rule ( self , rule ) : if rule . at_keyword is not None : return rule cleaned_token_list = [ ] for token_list in split_on_comma ( rule . selector ) : if self . _token_list_matches_tree ( token_list ) : if len ( cleaned_token_list ) > 0 : cleaned_token_list . append ( cssselect . parser . Token ( 'DELIM' , ',' , len ( cleaned_token_list ) + 1 ) ) cleaned_token_list += token_list if not cleaned_token_list : return None rule . selector = cleaned_token_list return rule | Cleans a css Rule by removing Selectors without matches on the tree Returns None if the whole rule do not match |
51,319 | def _token_list_matches_tree ( self , token_list ) : try : parsed_selector = cssselect . parse ( '' . join ( token . as_css ( ) for token in token_list ) ) [ 0 ] return bool ( self . tree . xpath ( self . xpath_translator . selector_to_xpath ( parsed_selector ) ) ) except : return True | Returns whether the token list matches the HTML tree |
51,320 | def _rule_as_string ( self , rule ) : if isinstance ( rule , RuleSet ) : return '%s{%s}' % ( self . _selector_as_string ( rule . selector ) , self . _declarations_as_string ( rule . declarations ) ) elif isinstance ( rule , ImportRule ) : return "@import url('%s') %s;" % ( rule . uri , ',' . join ( rule . media ) ) elif isinstance ( rule , FontFaceRule ) : return "@font-face{%s}" % self . _declarations_as_string ( rule . declarations ) elif isinstance ( rule , MediaRule ) : return "@media %s{%s}" % ( ',' . join ( rule . media ) , '' . join ( self . _rule_as_string ( r ) for r in rule . rules ) ) elif isinstance ( rule , PageRule ) : selector , pseudo = rule . selector return "@page%s%s{%s}" % ( ' %s' % selector if selector else '' , ' :%s' % pseudo if pseudo else '' , self . _declarations_as_string ( rule . declarations ) ) return '' | Converts a tinycss rule to a formatted CSS string |
51,321 | def _selector_as_string ( self , selector ) : return ',' . join ( '' . join ( token . as_css ( ) for token in strip_whitespace ( token_list ) ) for token_list in split_on_comma ( selector ) ) | Returns a selector as a CSS string |
51,322 | def _declarations_as_string ( self , declarations ) : return '' . join ( '%s:%s%s;' % ( d . name , d . value . as_css ( ) , ' !' + d . priority if d . priority else '' ) for d in declarations ) | Returns a list of declarations as a formatted CSS string |
51,323 | def envars_to_markdown ( envars , title = "Environment" ) : markdown = '' if envars not in [ None , '' , [ ] ] : markdown += '\n## %s\n' % title for envar in envars : markdown += ' - **%s**: %s\n' % ( envar [ 0 ] , envar [ 1 ] ) return markdown | generate a markdown list of a list of environment variable tuples |
51,324 | def get_default_commands ( self ) : commands = Application . get_default_commands ( self ) self . add ( ConstantsCommand ( ) ) self . add ( LoaderCommand ( ) ) self . add ( PyStratumCommand ( ) ) self . add ( WrapperCommand ( ) ) return commands | Returns the default commands of this application . |
51,325 | def discover ( service = "ssdp:all" , timeout = 1 , retries = 2 , ipAddress = "239.255.255.250" , port = 1900 ) : socket . setdefaulttimeout ( timeout ) messages = [ ] if isinstance ( service , str ) : services = [ service ] elif isinstance ( service , list ) : services = service for service in services : message = 'M-SEARCH * HTTP/1.1\r\nMX: 5\r\nMAN: "ssdp:discover"\r\nHOST: ' + ipAddress + ':' + str ( port ) + '\r\n' message += "ST: " + service + "\r\n\r\n" messages . append ( message ) responses = { } for _ in range ( retries ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP ) sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) sock . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_TTL , 2 ) for _ in range ( 2 ) : for message in messages : sock . sendto ( message . encode ( 'utf-8' ) , ( ipAddress , port ) ) while True : try : data = sock . recv ( 1024 ) except socket . timeout : break else : response = DiscoveryResponse ( data ) responses [ response . location ] = response return list ( responses . values ( ) ) | Discovers UPnP devices in the local network . |
51,326 | def discoverParticularHost ( host , service = "ssdp:all" , deviceDefinitionURL = None , timeout = 1 , retries = 2 , ipAddress = "239.255.255.250" , port = 1900 , proxies = None ) : ipResults = socket . getaddrinfo ( host , 80 ) if len ( ipResults ) == 0 : return None ipAddresses = [ ] for ipAdrTupple in ipResults : ipAddresses . append ( ipAdrTupple [ 4 ] [ 0 ] ) bestPick = None services = [ ] if deviceDefinitionURL is None : discoverResults = Discover . discover ( service = service , timeout = timeout , retries = retries , ipAddress = ipAddress , port = port ) for result in discoverResults : if result . locationHost in ipAddresses : if Discover . rateServiceTypeInResult ( result ) > Discover . rateServiceTypeInResult ( bestPick ) : bestPick = result if result . service not in services : services . append ( result . service ) if bestPick is None : return None else : bestPick = DiscoveryResponse . create ( deviceDefinitionURL , service = service ) headers = { "User-Agent" : "Mozilla/5.0; SimpleTR64-3" } request = requests . get ( bestPick . location , proxies = proxies , headers = headers , timeout = float ( timeout ) ) if request . status_code != 200 : errorStr = DeviceTR64 . _extractErrorString ( request ) raise ValueError ( 'Could not get CPE definitions for "' + bestPick . location + '": ' + str ( request . status_code ) + ' - ' + request . reason + " -- " + errorStr ) try : root = ET . fromstring ( request . text . encode ( 'utf-8' ) ) except Exception as e : raise ValueError ( "Could not parse CPE definitions for '" + bestPick . location + "': " + str ( e ) ) for element in root . getiterator ( ) : if element . tag . lower ( ) . endswith ( "devicetype" ) : serviceFound = element . text if serviceFound not in services : services . append ( serviceFound ) serviceFound = serviceFound . replace ( "schemas-upnp-org" , "dslforum-org" ) if serviceFound == bestPick . service : return bestPick for service in services : specificService = service . replace ( "schemas-upnp-org" , "dslforum-org" ) if specificService not in services : services . append ( specificService ) discoverResultsSpecific = Discover . discover ( service = services , timeout = float ( timeout ) , retries = retries , ipAddress = ipAddress , port = port ) evenBetterPick = None for specificResult in discoverResultsSpecific : if specificResult . locationHost in ipAddresses : if Discover . rateServiceTypeInResult ( specificResult ) > Discover . rateServiceTypeInResult ( evenBetterPick ) : evenBetterPick = specificResult if evenBetterPick is not None : return evenBetterPick break if deviceDefinitionURL is not None : return None return bestPick | Discover a particular host and find the best response . |
51,327 | def rateServiceTypeInResult ( discoveryResponse ) : if discoveryResponse is None : return 0 serviceType = discoveryResponse . service if serviceType . startswith ( "urn:dslforum-org:device" ) : return 11 if serviceType . startswith ( "urn:dslforum-org:service" ) : return 10 if serviceType . startswith ( "urn:dslforum-org:" ) : return 9 if serviceType . startswith ( "urn:schemas-upnp-org:device" ) : return 8 if serviceType . startswith ( "urn:schemas-upnp-org:service" ) : return 7 if serviceType . startswith ( "urn:schemas-upnp-org:" ) : return 6 if serviceType . startswith ( "urn:schemas-" ) : return 5 if serviceType . startswith ( "urn:" ) : return 4 if serviceType . startswith ( "upnp:rootdevice" ) : return 3 if serviceType . startswith ( "uuid:" ) : return 2 return 1 | Gives a quality rating for a given service type in a result higher is better . |
51,328 | def download ( self , url , file_name , headers = None , show_progress = True ) : fd , tmp_file = tempfile . mkstemp ( prefix = ( "%s.tmp." % file_name ) ) os . close ( fd ) verify = self . _verify ( ) if requests . head ( url , verify = verify ) . status_code in [ 200 , 401 ] : response = self . stream ( url , headers = headers , stream_to = tmp_file ) if isinstance ( response , HTTPError ) : bot . error ( "Error downloading %s, exiting." % url ) sys . exit ( 1 ) shutil . move ( tmp_file , file_name ) else : bot . error ( "Invalid url or permissions %s" % url ) return file_name | stream to a temporary file rename on successful completion |
51,329 | def getControlURL ( self , serviceType , default = None ) : if serviceType in self . __deviceServiceDefinitions . keys ( ) : return self . __deviceServiceDefinitions [ serviceType ] [ "controlURL" ] if self . __deviceXMLInitialized : raise ValueError ( "Device do not support given serviceType: " + serviceType ) return default | Returns the control URL for a given service type . |
51,330 | def getEventSubURL ( self , serviceType , default = None ) : if serviceType in self . __deviceServiceDefinitions . keys ( ) : return self . __deviceServiceDefinitions [ serviceType ] [ "eventSubURL" ] if self . __deviceXMLInitialized : raise ValueError ( "Device do not support given serviceType: " + serviceType ) return default | Returns the event URL for a given service type . |
51,331 | def execute ( self , uri , namespace , action , timeout = 2 , ** kwargs ) : if not uri : raise ValueError ( "No action URI has been defined." ) if not namespace : raise ValueError ( "No namespace has been defined." ) if not action : raise ValueError ( "No action has been defined." ) header = { 'Content-Type' : 'text/xml; charset="UTF-8"' , 'Soapaction' : '"' + namespace + "#" + action + '"' } body = body += " <u:" + action + ' xmlns="' + namespace + '">\n' arguments = { } for key in kwargs . keys ( ) : body += " <" + key + ">" + str ( kwargs [ key ] ) + "</" + key + ">\n" arguments [ key ] = str ( kwargs [ key ] ) body += " </u:" + action + ">\n" body += proxies = { } if self . __httpsProxy : proxies = { "https" : self . __httpsProxy } if self . __httpProxy : proxies = { "http" : self . __httpProxy } auth = None if self . __password : auth = HTTPDigestAuth ( self . __username , self . __password ) location = self . __protocol + "://" + self . __hostname + ":" + str ( self . port ) + uri request = requests . post ( location , data = body , headers = header , auth = auth , proxies = proxies , timeout = float ( timeout ) , verify = self . __verify ) if request . status_code != 200 : errorStr = DeviceTR64 . _extractErrorString ( request ) raise ValueError ( 'Could not execute "' + action + str ( arguments ) + '": ' + str ( request . status_code ) + ' - ' + request . reason + " -- " + errorStr ) try : root = ET . fromstring ( request . text . encode ( 'utf-8' ) ) except Exception as e : raise ValueError ( "Can not parse results for the action: " + str ( e ) ) actionNode = root [ 0 ] [ 0 ] namespaceLength = len ( namespace ) + 2 tag = actionNode . tag [ namespaceLength : ] if tag != ( action + "Response" ) : raise ValueError ( 'Soap result structure is wrong, expected action "' + action + 'Response" got "' + tag + '".' ) results = { } for resultNode in actionNode : results [ resultNode . tag ] = resultNode . text return results | Executes a given action with optional arguments . |
51,332 | def _extractErrorString ( request ) : errorStr = "" tag = None try : root = ET . fromstring ( request . text . encode ( 'utf-8' ) ) tag = root [ 0 ] [ 0 ] except : return errorStr for element in tag . getiterator ( ) : tagName = element . tag . lower ( ) if tagName . endswith ( "string" ) : errorStr += element . text + " " elif tagName . endswith ( "description" ) : errorStr += element . text + " " return errorStr | Extract error string from a failed UPnP call . |
51,333 | def setupTR64Device ( self , deviceType ) : if deviceType . lower ( ) != "fritz.box" : raise ValueError ( "Unknown device type given." ) self . __deviceServiceDefinitions = { } self . __deviceXMLInitialized = False self . deviceServiceDefinitions [ "urn:dslforum-org:service:DeviceConfig:1" ] = { "controlURL" : "/upnp/control/deviceconfig" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:ManagementServer:1" ] = { "controlURL" : "/upnp/control/mgmsrv" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:LANConfigSecurity:1" ] = { "controlURL" : "/upnp/control/lanconfigsecurity" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:Time:1" ] = { "controlURL" : "/upnp/control/time" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:LANHostConfigManagement:1" ] = { "controlURL" : "/upnp/control/lanhostconfigmgm" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:UserInterface:1" ] = { "controlURL" : "/upnp/control/userif" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:DeviceInfo:1" ] = { "controlURL" : "/upnp/control/deviceinfo" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_TAM:1" ] = { "controlURL" : "/upnp/control/x_tam" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_MyFritz:1" ] = { "controlURL" : "/upnp/control/x_myfritz" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_RemoteAccess:1" ] = { "controlURL" : "/upnp/control/x_remote" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WLANConfiguration:1" ] = { "controlURL" : "/upnp/control/wlanconfig1" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WLANConfiguration:3" ] = { "controlURL" : "/upnp/control/wlanconfig3" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WLANConfiguration:2" ] = { "controlURL" : "/upnp/control/wlanconfig2" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_WebDAVClient:1" ] = { "controlURL" : "/upnp/control/x_webdav" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WANDSLLinkConfig:1" ] = { "controlURL" : "/upnp/control/wandsllinkconfig1" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:Hosts:1" ] = { "controlURL" : "/upnp/control/hosts" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_VoIP:1" ] = { "controlURL" : "/upnp/control/x_voip" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:LANEthernetInterfaceConfig:1" ] = { "controlURL" : "/upnp/control/lanethernetifcfg" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:Layer3Forwarding:1" ] = { "controlURL" : "/upnp/control/layer3forwarding" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WANIPConnection:1" ] = { "controlURL" : "/upnp/control/wanipconnection1" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_OnTel:1" ] = { "controlURL" : "/upnp/control/x_contact" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WANCommonInterfaceConfig:1" ] = { "controlURL" : "/upnp/control/wancommonifconfig1" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_UPnP:1" ] = { "controlURL" : "/upnp/control/x_upnp" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WANDSLInterfaceConfig:1" ] = { "controlURL" : "/upnp/control/wandslifconfig1" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WANPPPConnection:1" ] = { "controlURL" : "/upnp/control/wanpppconn1" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:X_AVM-DE_Storage:1" ] = { "controlURL" : "/upnp/control/x_storage" } self . deviceServiceDefinitions [ "urn:dslforum-org:service:WANEthernetLinkConfig:1" ] = { "controlURL" : "/upnp/control/wanethlinkconfig1" } | Setup actions for known devices . |
51,334 | def loadDeviceDefinitions ( self , urlOfXMLDefinition , timeout = 3 ) : proxies = { } if self . __httpsProxy : proxies = { "https" : self . __httpsProxy } if self . __httpProxy : proxies = { "http" : self . __httpProxy } headers = { "User-Agent" : "Mozilla/5.0; SimpleTR64-1" } auth = None if self . __password : auth = HTTPDigestAuth ( self . __username , self . __password ) request = requests . get ( urlOfXMLDefinition , proxies = proxies , headers = headers , timeout = float ( timeout ) , auth = auth , verify = self . __verify ) if request . status_code != 200 : errorStr = DeviceTR64 . _extractErrorString ( request ) raise ValueError ( 'Could not get CPE definitions "' + urlOfXMLDefinition + '" : ' + str ( request . status_code ) + ' - ' + request . reason + " -- " + errorStr ) xml = request . text . encode ( 'utf-8' ) return self . _loadDeviceDefinitions ( urlOfXMLDefinition , xml ) | Loads the device definitions from a given URL which points to the root XML in the device . |
51,335 | def _loadDeviceDefinitions ( self , urlOfXMLDefinition , xml ) : url = urlparse ( urlOfXMLDefinition ) baseURIPath = url . path . rpartition ( '/' ) [ 0 ] + "/" try : root = ET . fromstring ( xml ) except Exception as e : raise ValueError ( "Can not parse CPE definitions '" + urlOfXMLDefinition + "': " + str ( e ) ) self . __deviceServiceDefinitions = { } self . __deviceSCPD = { } self . __deviceInformations = { 'rootURL' : urlOfXMLDefinition } self . __deviceUnknownKeys = { } self . __deviceXMLInitialized = False self . _iterateToFindSCPDElements ( root , baseURIPath ) self . __deviceXMLInitialized = True | Internal call to parse the XML of the device definition . |
51,336 | def _iterateToFindSCPDElements ( self , element , baseURIPath ) : for child in element . getchildren ( ) : tagName = child . tag . lower ( ) if tagName . endswith ( 'servicelist' ) : self . _processServiceList ( child , baseURIPath ) elif tagName . endswith ( 'devicetype' ) : if "deviceType" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "deviceType" ] = child . text elif tagName . endswith ( 'friendlyname' ) : if "friendlyName" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "friendlyName" ] = child . text elif tagName . endswith ( 'manufacturer' ) : if "manufacturer" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "manufacturer" ] = child . text elif tagName . endswith ( 'manufacturerurl' ) : if "manufacturerURL" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "manufacturerURL" ] = child . text elif tagName . endswith ( 'modeldescription' ) : if "modelDescription" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "modelDescription" ] = child . text elif tagName . endswith ( 'modelname' ) : if "modelName" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "modelName" ] = child . text elif tagName . endswith ( 'modelurl' ) : if "modelURL" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "modelURL" ] = child . text elif tagName . endswith ( 'modelnumber' ) : if "modelNumber" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "modelNumber" ] = child . text elif tagName . endswith ( 'serialnumber' ) : if "serialNumber" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "serialNumber" ] = child . text elif tagName . endswith ( 'presentationurl' ) : if "presentationURL" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "presentationURL" ] = child . text elif tagName . endswith ( 'udn' ) : if "UDN" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "UDN" ] = child . text elif tagName . endswith ( 'upc' ) : if "UPC" not in self . __deviceInformations . keys ( ) : self . __deviceInformations [ "UPC" ] = child . text elif tagName . endswith ( 'iconlist' ) or tagName . endswith ( 'specversion' ) : pass else : if not tagName . endswith ( 'device' ) and not tagName . endswith ( 'devicelist' ) : self . __deviceUnknownKeys [ child . tag ] = child . text self . _iterateToFindSCPDElements ( child , baseURIPath ) | Internal method to iterate through device definition XML tree . |
51,337 | def _processServiceList ( self , serviceList , baseURIPath ) : for service in serviceList . getchildren ( ) : if not service . tag . lower ( ) . endswith ( "service" ) : raise ValueError ( "Non service tag in servicelist: " + service . tag ) serviceType = None controlURL = None scpdURL = None eventURL = None for child in service : tag = child . tag . lower ( ) if tag . endswith ( "servicetype" ) or ( serviceType is None and tag . endswith ( "spectype" ) ) : serviceType = child . text elif tag . endswith ( "controlurl" ) : controlURL = str ( child . text ) if not controlURL . startswith ( "/" ) and not controlURL . startswith ( "http" ) : controlURL = baseURIPath + controlURL elif tag . endswith ( "scpdurl" ) : scpdURL = str ( child . text ) if not scpdURL . startswith ( "/" ) and not scpdURL . startswith ( "http" ) : scpdURL = baseURIPath + scpdURL elif tag . endswith ( "eventsuburl" ) : eventURL = str ( child . text ) if not eventURL . startswith ( "/" ) and not eventURL . startswith ( "http" ) : eventURL = baseURIPath + eventURL if serviceType is None or controlURL is None : raise ValueError ( "Service is not complete: " + str ( serviceType ) + " - " + str ( controlURL ) + " - " + str ( scpdURL ) ) if serviceType in self . __deviceServiceDefinitions . keys ( ) : raise ValueError ( "Service type '" + serviceType + "' is defined twice." ) self . __deviceServiceDefinitions [ serviceType ] = { "controlURL" : controlURL } if scpdURL is not None : self . __deviceServiceDefinitions [ serviceType ] [ "scpdURL" ] = scpdURL if eventURL is not None : self . __deviceServiceDefinitions [ serviceType ] [ "eventSubURL" ] = eventURL | Internal method to iterate in the device definition XML tree through the service list . |
51,338 | def _loadSCPD ( self , serviceType , timeout ) : if serviceType not in self . __deviceServiceDefinitions . keys ( ) : raise ValueError ( "Can not load SCPD, no service type defined for: " + serviceType ) if "scpdURL" not in self . __deviceServiceDefinitions [ serviceType ] . keys ( ) : raise ValueError ( "No SCPD URL defined for: " + serviceType ) self . __deviceSCPD . pop ( serviceType , None ) uri = self . __deviceServiceDefinitions [ serviceType ] [ "scpdURL" ] proxies = { } if self . __httpsProxy : proxies = { "https" : self . __httpsProxy } if self . __httpProxy : proxies = { "http" : self . __httpProxy } auth = None if self . __password : auth = HTTPDigestAuth ( self . __username , self . __password ) location = self . __protocol + "://" + self . __hostname + ":" + str ( self . port ) + uri headers = { "User-Agent" : "Mozilla/5.0; SimpleTR64-2" } request = requests . get ( location , auth = auth , proxies = proxies , headers = headers , timeout = timeout , verify = self . __verify ) if request . status_code != 200 : errorStr = DeviceTR64 . _extractErrorString ( request ) raise ValueError ( 'Could not load SCPD for "' + serviceType + '" from ' + location + ': ' + str ( request . status_code ) + ' - ' + request . reason + " -- " + errorStr ) data = request . text . encode ( 'utf-8' ) if len ( data ) == 0 : return try : root = ET . fromstring ( data ) except Exception as e : raise ValueError ( "Can not parse SCPD content for '" + serviceType + "' from '" + location + "': " + str ( e ) ) actions = { } variableTypes = { } variableParameterDict = { } for element in root . getchildren ( ) : tagName = element . tag . lower ( ) if tagName . endswith ( "actionlist" ) : self . _parseSCPDActions ( element , actions , variableParameterDict ) elif tagName . endswith ( "servicestatetable" ) : self . _parseSCPDVariableTypes ( element , variableTypes ) for name in variableParameterDict . keys ( ) : if name not in variableTypes . keys ( ) : raise ValueError ( "Variable reference in action can not be resolved: " + name ) for argument in variableParameterDict [ name ] : argument [ "dataType" ] = variableTypes [ name ] [ "dataType" ] if "defaultValue" in variableTypes [ name ] . keys ( ) : argument [ "defaultValue" ] = variableTypes [ name ] [ "defaultValue" ] self . __deviceSCPD [ serviceType ] = actions | Internal method to load the action definitions . |
51,339 | def createFromURL ( urlOfXMLDefinition ) : url = urlparse ( urlOfXMLDefinition ) if not url . port : if url . scheme . lower ( ) == "https" : port = 443 else : port = 80 else : port = url . port return Wifi ( url . hostname , port , url . scheme ) | Factory method to create a DeviceTR64 from an URL to the XML device definitions . |
51,340 | def getWifiInfo ( self , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getWifiInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetInfo" , timeout = timeout ) return WifiBasicInfo ( results ) | Execute GetInfo action to get Wifi basic information s . |
51,341 | def getTotalAssociations ( self , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getTotalAssociations" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetTotalAssociations" , timeout = timeout ) return int ( results [ "NewTotalAssociations" ] ) | Execute GetTotalAssociations action to get the amount of associated Wifi clients . |
51,342 | def getGenericAssociatedDeviceInfo ( self , index , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getGenericAssociatedDeviceInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetGenericAssociatedDeviceInfo" , timeout = timeout , NewAssociatedDeviceIndex = index ) return WifiDeviceInfo ( results ) | Execute GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client . |
51,343 | def getSpecificAssociatedDeviceInfo ( self , macAddress , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getSpecificAssociatedDeviceInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetSpecificAssociatedDeviceInfo" , timeout = timeout , NewAssociatedDeviceMACAddress = macAddress ) return WifiDeviceInfo ( results , macAddress = macAddress ) | Execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client . |
51,344 | def setEnable ( self , status , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "setEnable" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) if status : setStatus = 1 else : setStatus = 0 self . execute ( uri , namespace , "SetEnable" , timeout = timeout , NewEnable = setStatus ) | Set enable status for a Wifi interface be careful you don t cut yourself off . |
51,345 | def setChannel ( self , channel , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "setChannel" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) self . execute ( uri , namespace , "SetChannel" , timeout = timeout , NewChannel = channel ) | Set the channel of this Wifi interface |
51,346 | def enabled_checker ( func ) : @ wraps ( func ) def wrap ( self , * args , ** kwargs ) : if self . allowed_methods and isinstance ( self . allowed_methods , list ) and func . __name__ not in self . allowed_methods : raise Exception ( "Method {} is disabled" . format ( func . __name__ ) ) return func ( self , * args , ** kwargs ) return wrap | Access decorator which checks if a RPC method is enabled by our configuration |
51,347 | async def list_vms ( self , preset ) : vmshepherd = self . request . app . vmshepherd preset = vmshepherd . preset_manager . get_preset ( preset ) result_vms = { vm . id : { 'ip' : vm . ip [ 0 ] , 'state' : vm . state . value } for vm in preset . vms } return preset . count , result_vms | Listing virtual machines in a given preset |
51,348 | async def terminate_vm ( self , preset , vm_id ) : vmshepherd = self . request . app . vmshepherd preset = vmshepherd . preset_manager . get_preset ( preset ) await preset . iaas . terminate_vm ( vm_id ) return 'OK' | Discard vm in specified preset |
51,349 | async def get_vm_metadata ( self , preset , vm_id ) : vmshepherd = self . request . app . vmshepherd preset = vmshepherd . preset_manager . get_preset ( preset ) vm_info = await preset . iaas . get_vm ( vm_id ) ret_info = copy . deepcopy ( vm_info . metadata ) if vm_info . metadata else { } ret_info [ 'tags' ] = vm_info . tags ret_info [ 'iaas_shutdown' ] = vm_info . timed_shutdown_at return ret_info | Get vm metadata |
51,350 | def linkify ( text , attrs = { } ) : def separate_parentheses ( s ) : start = re_find ( r'^\(*' , s ) end = re_find ( r'\)*$' , s ) n = min ( len ( start ) , len ( end ) ) if n : return s [ : n ] , s [ n : - n ] , s [ - n : ] else : return '' , s , '' def link_repl ( url , proto = 'http://' ) : opening , url , closing = separate_parentheses ( url ) punct = re_find ( punct_re , url ) if punct : url = url [ : - len ( punct ) ] if re . search ( proto_re , url ) : href = url else : href = proto + url href = escape_url ( href ) repl = u'{0!s}<a href="{1!s}"{2!s}>{3!s}</a>{4!s}{5!s}' return repl . format ( opening , href , attrs_text , url , punct , closing ) def repl ( match ) : matches = match . groupdict ( ) if matches [ 'url' ] : return link_repl ( matches [ 'url' ] ) else : return link_repl ( matches [ 'email' ] , proto = 'mailto:' ) attr = ' {0!s}="{1!s}"' attrs_text = '' . join ( starmap ( attr . format , attrs . items ( ) ) ) return re . sub ( combined_re , repl , force_unicode ( text ) ) | Convert URL - like and email - like strings into links . |
51,351 | def get_environments ( self , project_key : str ) -> dict : try : resp = self . client . get_project ( project_key ) except launchdarkly_api . rest . ApiException as ex : msg = "Unable to get environments." resp = "API response was {0} {1}." . format ( ex . status , ex . reason ) LOG . error ( "%s %s" , msg , resp ) sys . exit ( 1 ) envs = [ ] for env in resp . environments : env = dict ( key = env . key , api_key = env . api_key , client_id = env . id ) envs . append ( env ) return envs | Retrieve all environments for a given project . |
51,352 | def update_flag ( self , state : str , feature_key : str ) -> launchdarkly_api . FeatureFlag : build_env = "/environments/" + self . environment_key + "/on" patch_comment = [ { "op" : "replace" , "path" : build_env , "value" : state } ] try : resp = self . feature . patch_feature_flag ( self . project_key , feature_key , patch_comment ) except launchdarkly_api . rest . ApiException as ex : msg = "Unable to update flag." resp = "API response was {0} {1}." . format ( ex . status , ex . reason ) LOG . error ( "%s %s" , msg , resp ) sys . exit ( 1 ) return resp | Update the flag status for the specified feature flag . |
51,353 | def _write_result_handler ( self , routine ) : self . _write_line ( 'ret = {}' ) self . _write_execute_rows ( routine ) self . _write_line ( 'for row in rows:' ) num_of_dict = len ( routine [ 'columns' ] ) i = 0 while i < num_of_dict : value = "row['{0!s}']" . format ( routine [ 'columns' ] [ i ] ) stack = '' j = 0 while j < i : stack += "[row['{0!s}']]" . format ( routine [ 'columns' ] [ j ] ) j += 1 line = 'if {0!s} in ret{1!s}:' . format ( value , stack ) self . _write_line ( line ) i += 1 line = "raise Exception('Duplicate key for %s.' % str(({0!s})))" . format ( ", " . join ( [ "row['{0!s}']" . format ( column_name ) for column_name in routine [ 'columns' ] ] ) ) self . _write_line ( line ) self . _indent_level_down ( ) i = num_of_dict while i > 0 : self . _write_line ( 'else:' ) part1 = '' j = 0 while j < i - 1 : part1 += "[row['{0!s}']]" . format ( routine [ 'columns' ] [ j ] ) j += 1 part1 += "[row['{0!s}']]" . format ( routine [ 'columns' ] [ j ] ) part2 = '' j = i - 1 while j < num_of_dict : if j + 1 != i : part2 += "{{row['{0!s}']: " . format ( routine [ 'columns' ] [ j ] ) j += 1 part2 += "row" + ( '}' * ( num_of_dict - i ) ) line = "ret{0!s} = {1!s}" . format ( part1 , part2 ) self . _write_line ( line ) self . _indent_level_down ( ) if i > 1 : self . _indent_level_down ( ) i -= 1 self . _write_line ( ) self . _write_line ( 'return ret' ) | Generates code for calling the stored routine in the wrapper method . |
51,354 | def _log_query ( query ) : query = query . strip ( ) if os . linesep in query : MetadataDataLayer . io . log_very_verbose ( 'Executing query:' ) MetadataDataLayer . io . log_very_verbose ( '<sql>{0}</sql>' . format ( query ) ) else : MetadataDataLayer . io . log_very_verbose ( 'Executing query: <sql>{0}</sql>' . format ( query ) ) | Logs the query on the console . |
51,355 | def request_token ( self , board ) : nonce = str ( uuid . uuid4 ( ) ) data = { 'scopes' : 'write' , 'client_id' : self . client_id , 'application_name' : 'HelpMe' , 'public_key' : self . public_key . replace ( "'" , "" ) , 'nonce' : nonce } url = ( board + "/user-api-key/new?scopes=write&application_name=HelpMe&public_key=" + self . public_key . replace ( "'" , "" ) + "&client_id=" + self . client_id + "&nonce=" + nonce ) bot . newline ( ) bot . info ( 'Open browser to:' ) bot . info ( url ) bot . newline ( ) bot . info ( 'Copy paste token, press Ctrl-D to save it:' ) lines = [ ] while True : try : line = enter_input ( ) except EOFError : break if line : lines . append ( line ) message = "\n" . join ( lines ) tmpfile = mktemp ( ) with open ( tmpfile , 'w' ) as filey : filey . write ( message ) with open ( tmpfile , 'rb' ) as filey : message = filey . read ( ) cipher = Cipher_PKCS1_v1_5 . new ( self . key ) decrypted = json . loads ( cipher . decrypt ( b64decode ( message ) , None ) . decode ( ) ) if "nonce" not in decrypted : bot . exit ( 'Missing nonce field in response for token, invalid.' ) if decrypted [ 'nonce' ] != nonce : bot . exit ( 'Invalid nonce, exiting.' ) return decrypted [ 'key' ] | send a public key to request a token . When we call this function we already have an RSA key at self . key |
51,356 | def create_post ( self , title , body , board , category , username ) : category_url = "%s/categories.json" % board response = requests . get ( category_url ) if response . status_code != 200 : print ( 'Error with retrieving %s' % category_url ) sys . exit ( 1 ) categories = response . json ( ) [ 'category_list' ] [ 'categories' ] categories = { c [ 'name' ] : c [ 'id' ] for c in categories } if category not in categories : bot . warning ( '%s is not valid, will use default' % category ) category_id = categories . get ( category , None ) headers = { "Content-Type" : "application/json" , "User-Api-Client-Id" : self . client_id , "User-Api-Key" : self . token } data = { 'title' : title , 'raw' : body , 'category' : category_id } response = requests . post ( "%s/posts.json" % board , headers = headers , data = json . dumps ( data ) ) if response . status_code in [ 200 , 201 , 202 ] : topic = response . json ( ) url = "%s/t/%s/%s" % ( board , topic [ 'topic_slug' ] , topic [ 'topic_id' ] ) bot . info ( url ) return url elif response . status_code == 404 : bot . error ( 'Cannot post to board, not found. Do you have permission?' ) sys . exit ( 1 ) else : bot . error ( 'Cannot post to board %s' % board ) bot . error ( response . content ) sys . exit ( 1 ) | create a Discourse post given a title body board and token . |
51,357 | def main ( self , config_filename , file_names = None ) : self . _io . title ( 'Loader' ) if file_names : self . __load_list ( config_filename , file_names ) else : self . __load_all ( config_filename ) if self . error_file_names : self . __log_overview_errors ( ) return 1 else : return 0 | Loads stored routines into the current schema . |
51,358 | def __log_overview_errors ( self ) : if self . error_file_names : self . _io . warning ( 'Routines in the files below are not loaded:' ) self . _io . listing ( sorted ( self . error_file_names ) ) | Show info about sources files of stored routines that were not loaded successfully . |
51,359 | def _add_replace_pair ( self , name , value , quote ) : key = '@' + name + '@' key = key . lower ( ) class_name = value . __class__ . __name__ if class_name in [ 'int' , 'float' ] : value = str ( value ) elif class_name in [ 'bool' ] : value = '1' if value else '0' elif class_name in [ 'str' ] : if quote : value = "'" + value + "'" else : self . _io . log_verbose ( "Ignoring constant {} which is an instance of {}" . format ( name , class_name ) ) self . _replace_pairs [ key ] = value | Adds a replace part to the map of replace pairs . |
51,360 | def __load_list ( self , config_filename , file_names ) : self . _read_configuration_file ( config_filename ) self . connect ( ) self . find_source_files_from_list ( file_names ) self . _get_column_type ( ) self . __read_stored_routine_metadata ( ) self . __get_constants ( ) self . _get_old_stored_routine_info ( ) self . _get_correct_sql_mode ( ) self . __load_stored_routines ( ) self . __write_stored_routine_metadata ( ) self . disconnect ( ) | Loads all stored routines in a list into the RDBMS instance . |
51,361 | def __find_source_files ( self ) : for dir_path , _ , files in os . walk ( self . _source_directory ) : for name in files : if name . lower ( ) . endswith ( self . _source_file_extension ) : basename = os . path . splitext ( os . path . basename ( name ) ) [ 0 ] relative_path = os . path . relpath ( os . path . join ( dir_path , name ) ) if basename in self . _source_file_names : self . _io . error ( "Files '{0}' and '{1}' have the same basename." . format ( self . _source_file_names [ basename ] , relative_path ) ) self . error_file_names . add ( relative_path ) else : self . _source_file_names [ basename ] = relative_path | Searches recursively for all source files in a directory . |
51,362 | def __read_stored_routine_metadata ( self ) : if os . path . isfile ( self . _pystratum_metadata_filename ) : with open ( self . _pystratum_metadata_filename , 'r' ) as file : self . _pystratum_metadata = json . load ( file ) | Reads the metadata of stored routines from the metadata file . |
51,363 | def __remove_obsolete_metadata ( self ) : clean = { } for key , _ in self . _source_file_names . items ( ) : if key in self . _pystratum_metadata : clean [ key ] = self . _pystratum_metadata [ key ] self . _pystratum_metadata = clean | Removes obsolete entries from the metadata of all stored routines . |
51,364 | def __write_stored_routine_metadata ( self ) : with open ( self . _pystratum_metadata_filename , 'w' ) as stream : json . dump ( self . _pystratum_metadata , stream , indent = 4 , sort_keys = True ) | Writes the metadata of all stored routines to the metadata file . |
51,365 | def find_source_files_from_list ( self , file_names ) : for file_name in file_names : if os . path . exists ( file_name ) : routine_name = os . path . splitext ( os . path . basename ( file_name ) ) [ 0 ] if routine_name not in self . _source_file_names : self . _source_file_names [ routine_name ] = file_name else : self . _io . error ( "Files '{0}' and '{1}' have the same basename." . format ( self . _source_file_names [ routine_name ] , file_name ) ) self . error_file_names . add ( file_name ) else : self . _io . error ( "File not exists: '{0}'" . format ( file_name ) ) self . error_file_names . add ( file_name ) | Finds all source files that actually exists from a list of file names . |
51,366 | def __get_constants ( self ) : helper = ConstantClass ( self . _constants_class_name , self . _io ) helper . reload ( ) constants = helper . constants ( ) for name , value in constants . items ( ) : self . _add_replace_pair ( name , value , True ) self . _io . text ( 'Read {0} constants for substitution from <fso>{1}</fso>' . format ( len ( constants ) , helper . file_name ( ) ) ) | Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs . |
51,367 | async def terminate ( self ) : logging . debug ( 'Terminate: %s' , self ) self . state = VmState . TERMINATED return await self . manager . terminate_vm ( self . id ) | Terminate vm . |
51,368 | def init_logger ( name = "" , handler_path_levels = None , level = logging . INFO , formatter = None , formatter_str = None , datefmt = "%Y-%m-%d %H:%M:%S" , ) : levels = { "NOTSET" : logging . NOTSET , "DEBUG" : logging . DEBUG , "INFO" : logging . INFO , "WARNING" : logging . WARNING , "ERROR" : logging . ERROR , "CRITICAL" : logging . CRITICAL , } if not formatter : if formatter_str : formatter_str = formatter_str else : formatter_str = "%(asctime)s %(levelname)-5s [%(name)s] %(filename)s(%(lineno)s): %(message)s" formatter = logging . Formatter ( formatter_str , datefmt = datefmt ) logger = name if isinstance ( name , logging . Logger ) else logging . getLogger ( str ( name ) ) logger . setLevel ( level ) handler_path_levels = handler_path_levels or [ [ "" , "INFO" ] ] for each_handler in handler_path_levels : path , handler_level = each_handler handler = logging . FileHandler ( path ) if path else logging . StreamHandler ( ) handler . setLevel ( levels . get ( handler_level . upper ( ) , 1 ) if isinstance ( handler_level , str ) else handler_level ) handler . setFormatter ( formatter ) logger . addHandler ( handler ) return logger | Add a default handler for logger . |
51,369 | def get_fields ( model ) : try : if hasattr ( model , "knockout_fields" ) : fields = model . knockout_fields ( ) else : try : fields = model_to_dict ( model ) . keys ( ) except Exception as e : fields = model . _meta . get_fields ( ) return fields except Exception as e : logger . exception ( e ) return [ ] | Returns a Model s knockout_fields or the default set of field names . |
51,370 | def get_object_data ( obj , fields , safe ) : temp_dict = dict ( ) for field in fields : try : attribute = getattr ( obj , str ( field ) ) if isinstance ( attribute , list ) and all ( [ isinstance ( item , models . Model ) for item in attribute ] ) : temp_dict [ field ] = [ ] for item in attribute : temp_dict [ field ] . append ( get_object_data ( item , get_fields ( item ) , safe ) ) elif isinstance ( attribute , models . Model ) : attribute_fields = get_fields ( attribute ) object_data = get_object_data ( attribute , attribute_fields , safe ) temp_dict [ field ] = object_data else : if not safe : if isinstance ( attribute , basestring ) : attribute = cgi . escape ( attribute ) temp_dict [ field ] = attribute except Exception as e : logger . info ( "Unable to get attribute." ) logger . error ( e ) continue return temp_dict | Given an object and a list of fields recursively build an object for serialization . |
51,371 | def ko_model ( model , field_names = None , data = None ) : try : if isinstance ( model , str ) : modelName = model else : modelName = model . __class__ . __name__ if field_names : fields = field_names else : fields = get_fields ( model ) if hasattr ( model , "comparator" ) : comparator = str ( model . comparator ( ) ) else : comparator = 'id' modelViewString = render_to_string ( "knockout_modeler/model.js" , { 'modelName' : modelName , 'fields' : fields , 'data' : data , 'comparator' : comparator } ) return modelViewString except Exception as e : logger . exception ( e ) return '' | Given a model returns the Knockout Model and the Knockout ViewModel . Takes optional field names and data . |
51,372 | def ko_bindings ( model ) : try : if isinstance ( model , str ) : modelName = model else : modelName = model . __class__ . __name__ modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#" + modelName . lower ( ) + "s')[0]);" return modelBindingsString except Exception as e : logger . error ( e ) return '' | Given a model returns the Knockout data bindings . |
51,373 | def ko_data ( queryset , field_names = None , name = None , safe = False , return_json = False ) : try : try : queryset_instance = queryset [ 0 ] except TypeError as e : queryset_instance = queryset queryset = [ queryset ] except IndexError as e : if not isinstance ( queryset , list ) : queryset_instance = queryset . model else : return '[]' modelName = queryset_instance . __class__ . __name__ modelNameData = [ ] if field_names is not None : fields = field_names else : fields = get_fields ( queryset_instance ) for obj in queryset : object_data = get_object_data ( obj , fields , safe ) modelNameData . append ( object_data ) if name : modelNameString = name else : modelNameString = modelName + "Data" dthandler = lambda obj : obj . isoformat ( ) if isinstance ( obj , ( datetime . date , datetime . datetime ) ) else None dumped_json = json . dumps ( modelNameData , default = dthandler ) if return_json : return dumped_json return "var " + modelNameString + " = " + dumped_json + ';' except Exception as e : logger . exception ( e ) return '[]' | Given a QuerySet return just the serialized representation based on the knockout_fields as JavaScript . |
51,374 | def ko ( queryset , field_names = None ) : try : koDataString = ko_data ( queryset , field_names ) koModelString = ko_model ( queryset [ 0 ] . __class__ . __name__ , field_names , data = True ) koBindingsString = ko_bindings ( queryset [ 0 ] ) koString = koDataString + '\n' + koModelString + '\n' + koBindingsString return koString except Exception as e : logger . error ( e ) return '' | Converts a Django QuerySet into a complete Knockout implementation . |
51,375 | def generate_keypair ( keypair_file ) : from Crypto . PublicKey import RSA key = RSA . generate ( 2048 ) keypair_dir = os . path . dirname ( keypair_file ) if not os . path . exists ( keypair_dir ) : os . makedirs ( keypair_dir ) with open ( keypair_file , 'wb' ) as filey : filey . write ( key . exportKey ( 'PEM' ) ) return key | generate_keypair is used by some of the helpers that need a keypair . The function should be used if the client doesn t have the attribute self . key . We generate the key and return it . |
51,376 | def __message ( expected_row_count , actual_row_count , query ) : query = query . strip ( ) message = 'Wrong number of rows selected' message += os . linesep message += 'Expected number of rows: {}' . format ( expected_row_count ) message += os . linesep message += 'Actual number of rows: {}' . format ( actual_row_count ) message += os . linesep message += 'Query:' message += os . linesep if os . linesep in query else ' ' message += query return message | Composes the exception message . |
51,377 | def main ( args , extras ) : from helpme . main import get_helper name = args . command if name in HELPME_HELPERS : helper = get_helper ( name = name ) if args . asciinema is not None : if os . path . exists ( args . asciinema ) : helper . data [ 'record_asciinema' ] = args . asciinema helper . run ( positionals = extras ) | This is the actual driver for the helper . |
51,378 | def extract ( self , html_contents , css_contents = None , base_url = None ) : html_extractor = self . html_extractor ( html_contents , self . _xpaths_to_keep , self . _xpaths_to_discard ) has_matches = html_extractor . parse ( ) if has_matches : if base_url is not None : html_extractor . rel_to_abs ( base_url ) cleaned_html = html_extractor . to_string ( ) else : cleaned_html = None if css_contents is not None : if cleaned_html is not None : css_extractor = self . css_extractor ( css_contents , cleaned_html ) css_extractor . parse ( ) if base_url is not None : css_extractor . rel_to_abs ( base_url ) cleaned_css = css_extractor . to_string ( ) else : cleaned_css = None else : return cleaned_html return ( cleaned_html , cleaned_css ) | Extracts the cleaned html tree as a string and only css rules matching the cleaned html tree |
51,379 | def __add ( self , dest , xpath ) : assert isinstance ( xpath , string_types ) dest . append ( xpath ) | Adds a Xpath expression to the dest list |
51,380 | def _write_line ( self , line = None ) : if line is None : self . _write ( "\n" ) if self . __indent_level > 1 : self . __indent_level -= 1 elif line == '' : self . _write ( "\n" ) else : line = ( ' ' * 4 * self . __indent_level ) + line if line [ - 1 : ] == ':' : self . __indent_level += 1 self . _write ( line + "\n" ) | Appends a line of code to the generated code and adjust the indent level of the generated code . |
51,381 | def write_routine_method ( self , routine ) : if self . _lob_as_string_flag : return self . _write_routine_method_without_lob ( routine ) else : if self . is_lob_parameter ( routine [ 'parameters' ] ) : return self . _write_routine_method_with_lob ( routine ) else : return self . _write_routine_method_without_lob ( routine ) | Returns a complete wrapper method . |
51,382 | def _write_docstring_parameters ( self , routine ) : if routine [ 'pydoc' ] [ 'parameters' ] : self . _write_line ( '' ) for param in routine [ 'pydoc' ] [ 'parameters' ] : lines = param [ 'description' ] . split ( os . linesep ) self . _write_line ( ':param {0} {1}: {2}' . format ( param [ 'python_type' ] , param [ 'parameter_name' ] , lines [ 0 ] ) ) del lines [ 0 ] tmp = ':param {0} {1}:' . format ( param [ 'python_type' ] , param [ 'parameter_name' ] ) indent = ' ' * len ( tmp ) for line in lines : self . _write_line ( '{0} {1}' . format ( indent , line ) ) self . _write_line ( '{0} {1}' . format ( indent , param [ 'data_type_descriptor' ] ) ) | Writes the parameters part of the docstring for the wrapper method of a stored routine . |
51,383 | def __write_docstring_return_type ( self ) : rtype = self . _get_docstring_return_type ( ) if rtype : self . _write_line ( '' ) self . _write_line ( ':rtype: {0}' . format ( rtype ) ) | Writes the return type part of the docstring for the wrapper method of a stored routine . |
51,384 | def __write_docstring ( self , routine ) : self . _write_line ( '' ) | Writes the docstring for the wrapper method of a stored routine . |
51,385 | def _get_wrapper_args ( routine ) : ret = '' for parameter_info in routine [ 'parameters' ] : if ret : ret += ', ' ret += parameter_info [ 'name' ] return ret | Returns code for the parameters of the wrapper method for the stored routine . |
51,386 | def generate_relay_config ( self , environments : list ) -> None : template = self . env . get_template ( 'ld-relay.conf.jinja' ) with open ( 'ld-relay.conf' , 'w' ) as ld_relay_config : template = template . render ( envs = environments ) ld_relay_config . write ( template ) | Generate ld - relay . conf file . |
51,387 | def __load ( self ) : parts = self . __class_name . split ( '.' ) module_name = "." . join ( parts [ : - 1 ] ) module = __import__ ( module_name ) modules = [ ] for comp in parts [ 1 : ] : module = getattr ( module , comp ) modules . append ( module ) self . __module = modules [ - 2 ] | Loads dynamically the class that acts like a namespace for constants . |
51,388 | def constants ( self ) : ret = { } name = self . __class_name . split ( '.' ) [ - 1 ] constant_class = getattr ( self . __module , name ) for name , value in constant_class . __dict__ . items ( ) : if re . match ( r'^[A-Z][A-Z0-9_]*$' , name ) : ret [ name ] = value return ret | Gets the constants from the class that acts like a namespace for constants . |
51,389 | def source_with_constants ( self , constants ) : old_lines = self . source ( ) . split ( "\n" ) info = self . __extract_info ( old_lines ) new_lines = old_lines [ 0 : info [ 'start_line' ] ] for constant , value in sorted ( constants . items ( ) ) : new_lines . append ( "{0}{1} = {2}" . format ( info [ 'indent' ] , str ( constant ) , str ( value ) ) ) new_lines . extend ( old_lines [ info [ 'last_line' ] : ] ) return "\n" . join ( new_lines ) | Returns the source of the module with the class that acts like a namespace for constants with new constants . |
51,390 | def get_configfile_user ( ) : from helpme . defaults import HELPME_CLIENT_SECRETS if not os . path . exists ( HELPME_CLIENT_SECRETS ) : bot . debug ( 'Generating settings file at %s' % HELPME_CLIENT_SECRETS ) config_dir = os . path . dirname ( HELPME_CLIENT_SECRETS ) if not os . path . exists ( config_dir ) : mkdir_p ( config_dir ) name = RobotNamer ( ) . generate ( ) config = configparser . ConfigParser ( ) config [ 'DEFAULT' ] = { 'Alias' : name } write_config ( HELPME_CLIENT_SECRETS , config ) return HELPME_CLIENT_SECRETS | return the full path for the user configuration file . If doesn t exist create it for the user . |
51,391 | def remove_user_setting ( self , section , name , save = False ) : configfile = get_configfile_user ( ) return _remove_setting ( section , name , configfile , save ) | remove a setting from the user config |
51,392 | def _load_config ( configfile , section = None ) : if os . path . exists ( configfile ) : config = read_config ( configfile ) if section is not None : if section in config : return config . _sections [ section ] else : bot . warning ( '%s not found in %s' % ( section , configfile ) ) return config | general function to load and return a configuration given a helper name . This function is used for both the user config and global help me config files . |
51,393 | def get_settings ( self ) : config = self . _load_config_user ( ) if self . name in config : return config [ self . name ] | get all settings for a client if defined in config . |
51,394 | def run ( app , argv = sys . argv , extra_args = None ) : if app not in argv [ : 2 ] : argv . insert ( 1 , app ) if len ( argv ) < 3 and 'test' not in argv [ : 2 ] : argv . insert ( 2 , 'test' ) if extra_args : argv . extend ( extra_args ) return runner ( argv ) | Run commands in a plain django environment |
51,395 | def cms ( app , argv = sys . argv , extra_args = None ) : try : import cms except ImportError : print ( 'runner.cms is available only if django CMS is installed' ) raise if app not in argv [ : 2 ] : argv . insert ( 1 , app ) if len ( argv ) < 3 and 'test' not in argv [ : 2 ] : argv . insert ( 2 , 'test' ) if '--cms' not in argv : argv . append ( '--cms' ) if extra_args : argv . extend ( extra_args ) return runner ( argv ) | Run commands in a django cMS environment |
51,396 | def parse ( self ) : self . tree = self . _build_tree ( self . html_contents ) self . elts_to_keep = self . _get_elements_to_keep ( ) self . elts_to_discard = self . _get_elements_to_discard ( ) self . elts_to_remove = [ ] is_root = self . _is_keep ( self . tree ) has_descendant = self . _has_keep_elt_in_descendants ( self . tree ) if not ( is_root or has_descendant ) : return False self . _parse_element ( self . tree , parent_is_keep = is_root ) self . _remove_elements ( self . elts_to_remove ) return True | Returns a cleaned lxml ElementTree |
51,397 | def rel_to_abs ( self , base_url ) : strip_attributes ( self . tree , 'target' ) self . tree . rewrite_links ( lambda link : urljoin ( base_url , link ) if not link . startswith ( self . rel_to_abs_excluded_prefixes ) else link ) onclick_elements = self . tree . xpath ( '//*[@onclick]' ) for element in onclick_elements : element . set ( 'onclick' , self . javascript_open_re . sub ( lambda match : '%s%s%s' % ( match . group ( 'opening' ) , urljoin ( base_url , match . group ( 'url' ) ) , match . group ( 'ending' ) ) , element . get ( 'onclick' ) ) ) | Converts relative links from html contents to absolute links |
51,398 | def _get_elements ( self , source ) : return list ( chain ( * [ self . tree . xpath ( xpath ) for xpath in source ] ) ) | Returns the list of HtmlElements for the source |
51,399 | def _parse_element ( self , elt , parent_is_keep = False ) : for e in elt . iterchildren ( ) : is_discard_element = self . _is_discard ( e ) is_keep_element = self . _is_keep ( e ) if is_discard_element and not is_keep_element : self . elts_to_remove . append ( e ) continue if not parent_is_keep : if is_keep_element : self . _parse_element ( e , parent_is_keep = True ) continue if self . _has_keep_elt_in_descendants ( e ) : self . _parse_element ( e ) continue self . elts_to_remove . append ( e ) else : self . _parse_element ( e , parent_is_keep = True ) | Parses an Element recursively |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.