idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
52,000 | def pending ( ) : signalbus = current_app . extensions [ 'signalbus' ] pending = [ ] total_pending = 0 for signal_model in signalbus . get_signal_models ( ) : count = signal_model . query . count ( ) if count > 0 : pending . append ( ( count , signal_model . __name__ ) ) total_pending += count if pending : pending . sort ( ) max_chars = len ( str ( pending [ - 1 ] [ 0 ] ) ) for n , signal_name in pending : click . echo ( '{} of type "{}"' . format ( str ( n ) . rjust ( max_chars ) , signal_name ) ) click . echo ( 25 * '-' ) click . echo ( 'Total pending: {} ' . format ( total_pending ) ) | Show the number of pending signals by signal type . |
52,001 | def create_thumbnail ( uuid , thumbnail_width ) : size = thumbnail_width + ',' thumbnail = IIIFImageAPI . get ( 'v2' , uuid , size , 0 , 'default' , 'jpg' ) | Create the thumbnail for an image . |
52,002 | def price_str ( raw_price , default = _not_defined , dec_point = '.' ) : def _error_or_default ( err_msg ) : if default == _not_defined : raise ValueError ( err_msg ) return default if not isinstance ( raw_price , str ) : return _error_or_default ( 'Wrong raw price type "{price_type}" ' '(expected type "str")' . format ( price_type = type ( raw_price ) ) ) price = re . sub ( '\s' , '' , raw_price ) cleaned_price = _CLEANED_PRICE_RE . findall ( price ) if len ( cleaned_price ) == 0 : return _error_or_default ( 'Raw price value "{price}" does not contain ' 'valid price digits' . format ( price = raw_price ) ) if len ( cleaned_price ) > 1 : return _error_or_default ( 'Raw price value "{price}" contains ' 'more than one price value' . format ( price = raw_price ) ) price = cleaned_price [ 0 ] price = price . rstrip ( '.,' ) sign = '' if price [ 0 ] in { '-' , '+' } : sign , price = price [ 0 ] , price [ 1 : ] sign = '-' if sign == '-' else '' fractional = _FRACTIONAL_PRICE_RE . match ( price ) if fractional : integer , fraction = fractional . groups ( ) else : integer , fraction = price , '' integer = re . sub ( '\D' , '' , integer ) integer = integer . lstrip ( '0' ) if integer == '' : integer = '0' price = sign + integer if fraction : price = '' . join ( ( price , dec_point , fraction ) ) return price | Search and clean price value . |
52,003 | def price_dec ( raw_price , default = _not_defined ) : try : price = price_str ( raw_price ) return decimal . Decimal ( price ) except ValueError as err : if default == _not_defined : raise err return default | Price decimal value from raw string . |
52,004 | def metric ( self , measurement_name , values , tags = None , timestamp = None ) : if not measurement_name or values in ( None , { } ) : return tags = tags or { } all_tags = dict ( self . tags , ** tags ) line = Line ( measurement_name , values , all_tags , timestamp ) self . send ( line . to_line_protocol ( ) ) | Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket |
52,005 | def send ( self , data ) : try : self . socket . sendto ( data . encode ( 'utf8' ) + b'\n' , ( self . host , self . port ) ) except ( socket . error , RuntimeError ) : pass | Sends the given data to the socket via UDP |
52,006 | def send ( self , data ) : self . future_session . post ( url = self . url , data = data ) | Send the data in a separate thread via HTTP POST . HTTP introduces some overhead so to avoid blocking the main thread this issues the request in the background . |
52,007 | def to_line_protocol ( self ) : tags = self . get_output_tags ( ) return u"{0}{1} {2}{3}" . format ( self . get_output_measurement ( ) , "," + tags if tags else '' , self . get_output_values ( ) , self . get_output_timestamp ( ) ) | Converts the given metrics as a single line of InfluxDB line protocol |
52,008 | def format_string ( key ) : if isinstance ( key , basestring ) : key = key . replace ( "," , "\," ) key = key . replace ( " " , "\ " ) key = key . replace ( "=" , "\=" ) return key | Formats either measurement names tag names or tag values . |
52,009 | def _process_equation ( value , fmt ) : global Nreferences global cursec attrs = value [ 0 ] eq = { 'is_unnumbered' : False , 'is_unreferenceable' : False , 'is_tagged' : False , 'attrs' : attrs } if not LABEL_PATTERN . match ( attrs [ 0 ] ) : eq [ 'is_unnumbered' ] = True eq [ 'is_unreferenceable' ] = True return eq if attrs [ 0 ] == 'eq:' : attrs [ 0 ] = attrs [ 0 ] + str ( uuid . uuid4 ( ) ) eq [ 'is_unreferenceable' ] = True unreferenceable . append ( attrs [ 0 ] ) kvs = PandocAttributes ( attrs , 'pandoc' ) . kvs if numbersections and fmt in [ 'html' , 'html5' ] and 'tag' not in kvs : if kvs [ 'secno' ] != cursec : cursec = kvs [ 'secno' ] Nreferences = 1 kvs [ 'tag' ] = cursec + '.' + str ( Nreferences ) Nreferences += 1 eq [ 'is_tagged' ] = 'tag' in kvs if eq [ 'is_tagged' ] : if kvs [ 'tag' ] [ 0 ] == '"' and kvs [ 'tag' ] [ - 1 ] == '"' : kvs [ 'tag' ] = kvs [ 'tag' ] . strip ( '"' ) elif kvs [ 'tag' ] [ 0 ] == "'" and kvs [ 'tag' ] [ - 1 ] == "'" : kvs [ 'tag' ] = kvs [ 'tag' ] . strip ( "'" ) references [ attrs [ 0 ] ] = kvs [ 'tag' ] else : Nreferences += 1 references [ attrs [ 0 ] ] = Nreferences if fmt in [ 'latex' , 'beamer' ] : if not eq [ 'is_unreferenceable' ] : value [ - 1 ] += r'\tag{%s}\label{%s}' % ( references [ attrs [ 0 ] ] . replace ( ' ' , r'\ ' ) , attrs [ 0 ] ) if eq [ 'is_tagged' ] else r'\label{%s}' % attrs [ 0 ] elif fmt in ( 'html' , 'html5' ) : pass else : if isinstance ( references [ attrs [ 0 ] ] , int ) : value [ - 1 ] += r'\qquad (%d)' % references [ attrs [ 0 ] ] else : assert isinstance ( references [ attrs [ 0 ] ] , STRTYPES ) text = references [ attrs [ 0 ] ] . replace ( ' ' , r'\ ' ) if text . startswith ( '$' ) and text . endswith ( '$' ) : tag = text [ 1 : - 1 ] else : tag = r'\text{%s}' % text value [ - 1 ] += r'\qquad (%s)' % tag return eq | Processes the equation . Returns a dict containing eq properties . |
52,010 | def process_equations ( key , value , fmt , meta ) : if key == 'Math' and len ( value ) == 3 : eq = _process_equation ( value , fmt ) attrs = eq [ 'attrs' ] label = attrs [ 0 ] if eq [ 'is_unreferenceable' ] : attrs [ 0 ] = '' if eq [ 'is_unnumbered' ] : return None elif fmt in [ 'latex' , 'beamer' ] : return RawInline ( 'tex' , r'\begin{equation}%s\end{equation}' % value [ - 1 ] ) elif fmt in ( 'html' , 'html5' ) and LABEL_PATTERN . match ( label ) : text = str ( references [ label ] ) outerspan = RawInline ( 'html' , '<span %s style="display: inline-block; ' 'position: relative; width: 100%%">' % ( '' if eq [ 'is_unreferenceable' ] else 'id="%s"' % label ) ) innerspan = RawInline ( 'html' , '<span style="position: absolute; ' 'right: 0em; top: %s; line-height:0; ' 'text-align: right">' % ( '0' if text . startswith ( '$' ) and text . endswith ( '$' ) else '50%' , ) ) num = Math ( { "t" : "InlineMath" } , '(%s)' % text [ 1 : - 1 ] ) if text . startswith ( '$' ) and text . endswith ( '$' ) else Str ( '(%s)' % text ) endspans = RawInline ( 'html' , '</span></span>' ) return [ outerspan , AttrMath ( * value ) , innerspan , num , endspans ] elif fmt == 'docx' : bookmarkstart = RawInline ( 'openxml' , '<w:bookmarkStart w:id="0" w:name="%s"/><w:r><w:t>' % label ) bookmarkend = RawInline ( 'openxml' , '</w:t></w:r><w:bookmarkEnd w:id="0"/>' ) return [ bookmarkstart , AttrMath ( * value ) , bookmarkend ] return None | Processes the attributed equations . |
52,011 | def process ( meta ) : global capitalize global use_cleveref_default global plusname global starname global numbersections for name in [ 'eqnos-cleveref' , 'xnos-cleveref' , 'cleveref' ] : if name in meta : use_cleveref_default = check_bool ( get_meta ( meta , name ) ) break for name in [ 'eqnos-capitalize' , 'eqnos-capitalise' , 'xnos-capitalize' , 'xnos-capitalise' ] : if name in meta : capitalize = check_bool ( get_meta ( meta , name ) ) break if 'eqnos-plus-name' in meta : tmp = get_meta ( meta , 'eqnos-plus-name' ) if isinstance ( tmp , list ) : plusname = tmp else : plusname [ 0 ] = tmp assert len ( plusname ) == 2 for name in plusname : assert isinstance ( name , STRTYPES ) if 'eqnos-star-name' in meta : tmp = get_meta ( meta , 'eqnos-star-name' ) if isinstance ( tmp , list ) : starname = tmp else : starname [ 0 ] = tmp assert len ( starname ) == 2 for name in starname : assert isinstance ( name , STRTYPES ) if 'xnos-number-sections' in meta : numbersections = check_bool ( get_meta ( meta , 'xnos-number-sections' ) ) | Saves metadata fields in global variables and returns a few computed fields . |
52,012 | def check_debug ( ) : from django . conf import settings if not settings . configured : return False from django . apps import apps if not apps . ready : return False if not hasattr ( django . template , "backends" ) : return False if not hasattr ( django . template . backends , "django" ) : return False if not hasattr ( django . template . backends . django , "DjangoTemplates" ) : raise DjangoTemplatePluginException ( "Can't use non-Django templates." ) for engine in django . template . engines . all ( ) : if not isinstance ( engine , django . template . backends . django . DjangoTemplates ) : raise DjangoTemplatePluginException ( "Can't use non-Django templates." ) if not engine . engine . debug : raise DjangoTemplatePluginException ( "Template debugging must be enabled in settings." ) return True | Check that Django s template debugging is enabled . |
52,013 | def read_template_source ( filename ) : from django . conf import settings if not settings . configured : settings . configure ( ) with open ( filename , "rb" ) as f : text = f . read ( ) . decode ( settings . FILE_CHARSET ) return text | Read the source of a Django template returning the Unicode text . |
52,014 | def get_line_number ( line_map , offset ) : for lineno , line_offset in enumerate ( line_map , start = 1 ) : if line_offset > offset : return lineno return - 1 | Find a line number given a line map and a character offset . |
52,015 | def dump_frame ( frame , label = "" ) : locals = dict ( frame . f_locals ) self = locals . get ( 'self' , None ) context = locals . get ( 'context' , None ) if "__builtins__" in locals : del locals [ "__builtins__" ] if label : label = " ( %s ) " % label print ( "-- frame --%s---------------------" % label ) print ( "{}:{}:{}" . format ( os . path . basename ( frame . f_code . co_filename ) , frame . f_lineno , type ( self ) , ) ) print ( locals ) if self : print ( "self:" , self . __dict__ ) if context : print ( "context:" , context . __dict__ ) print ( "\\--" ) | Dump interesting information about this frame . |
52,016 | def get_line_map ( self , filename ) : if filename not in self . source_map : template_source = read_template_source ( filename ) if 0 : for i in range ( 0 , len ( template_source ) , 10 ) : print ( "%3d: %r" % ( i , template_source [ i : i + 10 ] ) ) self . source_map [ filename ] = make_line_map ( template_source ) return self . source_map [ filename ] | The line map for filename . |
52,017 | def init ( size = 250 ) : player = mpv . MPV ( start_event_thread = False ) player [ "force-window" ] = "immediate" player [ "keep-open" ] = "yes" player [ "geometry" ] = f"{size}x{size}" player [ "autofit" ] = f"{size}x{size}" player [ "title" ] = "bum" return player | Initialize mpv . |
52,018 | def bytes_to_file ( input_data , output_file ) : pathlib . Path ( output_file . parent ) . mkdir ( parents = True , exist_ok = True ) with open ( output_file , "wb" ) as file : file . write ( input_data ) | Save bytes to a file . |
52,019 | def init ( port = 6600 , server = "localhost" ) : client = mpd . MPDClient ( ) try : client . connect ( server , port ) return client except ConnectionRefusedError : print ( "error: Connection refused to mpd/mopidy." ) os . _exit ( 1 ) | Initialize mpd . |
52,020 | def get_art ( cache_dir , size , client ) : song = client . currentsong ( ) if len ( song ) < 2 : print ( "album: Nothing currently playing." ) return file_name = f"{song['artist']}_{song['album']}_{size}.jpg" . replace ( "/" , "" ) file_name = cache_dir / file_name if file_name . is_file ( ) : shutil . copy ( file_name , cache_dir / "current.jpg" ) print ( "album: Found cached art." ) else : print ( "album: Downloading album art..." ) brainz . init ( ) album_art = brainz . get_cover ( song , size ) if album_art : util . bytes_to_file ( album_art , cache_dir / file_name ) util . bytes_to_file ( album_art , cache_dir / "current.jpg" ) print ( f"album: Swapped art to {song['artist']}, {song['album']}." ) | Get the album art . |
52,021 | def get_cover ( song , size = 250 ) : try : data = mus . search_releases ( artist = song [ "artist" ] , release = song [ "album" ] , limit = 1 ) release_id = data [ "release-list" ] [ 0 ] [ "release-group" ] [ "id" ] print ( f"album: Using release-id: {data['release-list'][0]['id']}" ) return mus . get_release_group_image_front ( release_id , size = size ) except mus . NetworkError : get_cover ( song , size ) except mus . ResponseError : print ( "error: Couldn't find album art for" , f"{song['artist']} - {song['album']}" ) | Download the cover art . |
52,022 | def convertforinput ( self , filepath , metadata ) : assert isinstance ( metadata , CLAMMetaData ) if not metadata . __class__ in self . acceptforinput : raise Exception ( "Convertor " + self . __class__ . __name__ + " can not convert input files to " + metadata . __class__ . __name__ + "!" ) return False | Convert from target format into one of the source formats . Relevant if converters are used in InputTemplates . Metadata already is metadata for the to - be - generated file . filepath is both the source and the target file the source file will be erased and overwritten with the conversion result! |
52,023 | def convertforoutput ( self , outputfile ) : assert isinstance ( outputfile , CLAMOutputFile ) if not outputfile . metadata . __class__ in self . acceptforoutput : raise Exception ( "Convertor " + self . __class__ . __name__ + " can not convert input files to " + outputfile . metadata . __class__ . __name__ + "!" ) return [ ] | Convert from one of the source formats into target format . Relevant if converters are used in OutputTemplates . Sourcefile is a CLAMOutputFile instance . |
52,024 | def convertforinput ( self , filepath , metadata = None ) : super ( CharEncodingConverter , self ) . convertforinput ( filepath , metadata ) shutil . copy ( filepath , filepath + '.convertsource' ) try : fsource = io . open ( filepath + '.convertsource' , 'r' , encoding = self . charset ) ftarget = io . open ( filepath , 'w' , encoding = metadata [ 'encoding' ] ) for line in fsource : ftarget . write ( line + "\n" ) success = True except : ftarget . close ( ) fsource . fclose ( ) success = False finally : os . unlink ( filepath + '.convertsource' ) return success | Convert from target format into one of the source formats . Relevant if converters are used in InputTemplates . Metadata already is metadata for the to - be - generated file . |
52,025 | def convertforoutput ( self , outputfile ) : super ( CharEncodingConverter , self ) . convertforoutput ( outputfile ) return withheaders ( flask . make_response ( ( line . encode ( self . charset ) for line in outputfile ) ) , 'text/plain; charset=' + self . charset ) | Convert from one of the source formats into target format . Relevant if converters are used in OutputTemplates . Outputfile is a CLAMOutputFile instance . |
52,026 | def getclamdata ( filename , custom_formats = None ) : global CUSTOM_FORMATS f = io . open ( filename , 'r' , encoding = 'utf-8' ) xml = f . read ( os . path . getsize ( filename ) ) f . close ( ) if custom_formats : CUSTOM_FORMATS = custom_formats return CLAMData ( xml , None , True ) | This function reads the CLAM Data from an XML file . Use this to read the clam . xml file from your system wrapper . It returns a CLAMData instance . |
52,027 | def sanitizeparameters ( parameters ) : if not isinstance ( parameters , dict ) : d = { } for x in parameters : if isinstance ( x , tuple ) and len ( x ) == 2 : for parameter in x [ 1 ] : d [ parameter . id ] = parameter elif isinstance ( x , clam . common . parameters . AbstractParameter ) : d [ x . id ] = x return d else : return parameters | Construct a dictionary of parameters for internal use only |
52,028 | def loadmetadata ( self ) : if not self . remote : metafile = self . projectpath + self . basedir + '/' + self . metafilename ( ) if os . path . exists ( metafile ) : f = io . open ( metafile , 'r' , encoding = 'utf-8' ) xml = "" . join ( f . readlines ( ) ) f . close ( ) else : raise IOError ( 2 , "No metadata found, expected " + metafile ) else : if self . client : requestparams = self . client . initrequest ( ) else : requestparams = { } response = requests . get ( self . projectpath + self . basedir + '/' + self . filename + '/metadata' , ** requestparams ) if response . status_code != 200 : extramsg = "" if not self . client : extramsg = "No client was associated with this CLAMFile, associating a client is necessary when authentication is needed" raise HTTPError ( 2 , "Can't download metadata for " + self . filename + ". " + extramsg ) xml = response . text try : self . metadata = CLAMMetaData . fromxml ( xml , self ) except ElementTree . XMLSyntaxError : raise ValueError ( "Metadata is not XML! Contents: " + xml ) | Load metadata for this file . This is usually called automatically upon instantiation except if explicitly disabled . Works both locally as well as for clients connecting to a CLAM service . |
52,029 | def delete ( self ) : if not self . remote : if not os . path . exists ( self . projectpath + self . basedir + '/' + self . filename ) : return False else : os . unlink ( self . projectpath + self . basedir + '/' + self . filename ) metafile = self . projectpath + self . basedir + '/' + self . metafilename ( ) if os . path . exists ( metafile ) : os . unlink ( metafile ) for linkf , realf in clam . common . util . globsymlinks ( self . projectpath + self . basedir + '/.*.INPUTTEMPLATE.*' ) : if not os . path . exists ( realf ) : os . unlink ( linkf ) return True else : if self . client : requestparams = self . client . initrequest ( ) else : requestparams = { } requests . delete ( self . projectpath + self . basedir + '/' + self . filename , ** requestparams ) return True | Delete this file |
52,030 | def read ( self ) : lines = self . readlines ( ) if self . metadata and 'encoding' in self . metadata : encoding = self . metadata [ 'encoding' ] else : encoding = 'utf-8' if sys . version < '3' : return "\n" . join ( unicode ( line , 'utf-8' ) if isinstance ( line , str ) else line for line in lines ) else : return "\n" . join ( str ( line , 'utf-8' ) if isinstance ( line , bytes ) else line for line in lines ) | Loads all lines in memory |
52,031 | def copy ( self , target , timeout = 500 ) : if self . metadata and 'encoding' in self . metadata : with io . open ( target , 'w' , encoding = self . metadata [ 'encoding' ] ) as f : for line in self : f . write ( line ) else : with io . open ( target , 'wb' ) as f : for line in self : if sys . version < '3' and isinstance ( line , unicode ) : f . write ( line . encode ( 'utf-8' ) ) elif sys . version >= '3' and isinstance ( line , str ) : f . write ( line . encode ( 'utf-8' ) ) else : f . write ( line ) | Copy or download this file to a new local file |
52,032 | def outputtemplate ( self , template_id ) : for profile in self . profiles : for outputtemplate in profile . outputtemplates ( ) : if outputtemplate . id == template_id : return outputtemplate return KeyError ( "Outputtemplate " + template_id + " not found" ) | Get an output template by ID |
52,033 | def commandlineargs ( self ) : commandlineargs = [ ] for parametergroup , parameters in self . parameters : for parameter in parameters : p = parameter . compilearg ( ) if p : commandlineargs . append ( p ) return " " . join ( commandlineargs ) | Obtain a string of all parameters using the paramater flags they were defined with in order to pass to an external command . This is shell - safe by definition . |
52,034 | def parametererror ( self ) : for parametergroup , parameters in self . parameters : for parameter in parameters : if parameter . error : return parameter . error return False | Return the first parameter error or False if there is none |
52,035 | def inputtemplate ( self , template_id ) : for profile in self . profiles : for inputtemplate in profile . input : if inputtemplate . id == template_id : return inputtemplate raise Exception ( "No such input template: " + repr ( template_id ) ) | Return the inputtemplate with the specified ID . This is used to resolve a inputtemplate ID to an InputTemplate object instance |
52,036 | def inputfiles ( self , inputtemplate = None ) : if isinstance ( inputtemplate , InputTemplate ) : inputtemplate = inputtemplate . id for inputfile in self . input : if not inputtemplate or inputfile . metadata . inputtemplate == inputtemplate : yield inputfile | Generator yielding all inputfiles for the specified inputtemplate if inputtemplate = None inputfiles are returned regardless of inputtemplate . |
52,037 | def outputtemplates ( self ) : outputtemplates = [ ] for o in self . output : if isinstance ( o , ParameterCondition ) : outputtemplates += o . allpossibilities ( ) else : assert isinstance ( o , OutputTemplate ) outputtemplates . append ( o ) return outputtemplates | Returns all outputtemplates resolving ParameterConditions to all possibilities |
52,038 | def generate ( self , projectpath , parameters , serviceid , servicename , serviceurl ) : parameters = sanitizeparameters ( parameters ) program = Program ( projectpath , [ self ] ) match , optional_absent = self . match ( projectpath , parameters ) if match : inputfiles = self . matchingfiles ( projectpath ) inputfiles_full = [ ] for seqnr , filename , inputtemplate in inputfiles : inputfiles_full . append ( CLAMInputFile ( projectpath , filename ) ) for outputtemplate in self . output : if isinstance ( outputtemplate , ParameterCondition ) : outputtemplate = outputtemplate . evaluate ( parameters ) if outputtemplate : if isinstance ( outputtemplate , OutputTemplate ) : provenancedata = CLAMProvenanceData ( serviceid , servicename , serviceurl , outputtemplate . id , outputtemplate . label , inputfiles_full , parameters ) create = True if outputtemplate . parent : if outputtemplate . getparent ( self ) in optional_absent : create = False if create : for inputtemplate , inputfilename , outputfilename , metadata in outputtemplate . generate ( self , parameters , projectpath , inputfiles , provenancedata ) : clam . common . util . printdebug ( "Writing metadata for outputfile " + outputfilename ) metafilename = os . path . dirname ( outputfilename ) if metafilename : metafilename += '/' metafilename += '.' + os . path . basename ( outputfilename ) + '.METADATA' f = io . open ( projectpath + '/output/' + metafilename , 'w' , encoding = 'utf-8' ) f . write ( metadata . xml ( ) ) f . close ( ) program . add ( outputfilename , outputtemplate , inputfilename , inputtemplate ) else : raise TypeError ( "OutputTemplate expected, but got " + outputtemplate . __class__ . __name__ ) return program | Generate output metadata on the basis of input files and parameters . Projectpath must be absolute . Returns a Program instance . |
52,039 | def xml ( self , indent = "" ) : xml = "\n" + indent + "<profile>\n" xml += indent + " <input>\n" for inputtemplate in self . input : xml += inputtemplate . xml ( indent + " " ) + "\n" xml += indent + " </input>\n" xml += indent + " <output>\n" for outputtemplate in self . output : xml += outputtemplate . xml ( indent + " " ) + "\n" xml += indent + " </output>\n" xml += indent + "</profile>\n" return xml | Produce XML output for the profile |
52,040 | def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) args = [ ] if node . tag == 'profile' : for node in node : if node . tag == 'input' : for subnode in node : if subnode . tag . lower ( ) == 'inputtemplate' : args . append ( InputTemplate . fromxml ( subnode ) ) elif node . tag == 'output' : for subnode in node : if subnode . tag . lower ( ) == 'outputtemplate' : args . append ( OutputTemplate . fromxml ( subnode ) ) elif subnode . tag . lower ( ) == 'parametercondition' : args . append ( ParameterCondition . fromxml ( subnode ) ) return Profile ( * args ) | Return a profile instance from the given XML description . Node can be a string or an etree . _Element . |
52,041 | def add ( self , outputfilename , outputtemplate , inputfilename = None , inputtemplate = None ) : if isinstance ( outputtemplate , OutputTemplate ) : outputtemplate = outputtemplate . id if isinstance ( inputtemplate , InputTemplate ) : inputtemplate = inputtemplate . id if outputfilename in self : outputtemplate , inputfiles = self [ outputfilename ] if inputfilename and inputtemplate : inputfiles [ inputfilename ] = inputtemplate else : if inputfilename and inputtemplate : self [ outputfilename ] = ( outputtemplate , { inputfilename : inputtemplate } ) else : self [ outputfilename ] = ( outputtemplate , { } ) | Add a new path to the program |
52,042 | def xml ( self , indent = "" ) : xml = indent + "<provenance type=\"clam\" id=\"" + self . serviceid + "\" name=\"" + self . servicename + "\" url=\"" + self . serviceurl + "\" outputtemplate=\"" + self . outputtemplate_id + "\" outputtemplatelabel=\"" + self . outputtemplate_label + "\" timestamp=\"" + str ( self . timestamp ) + "\">" for filename , metadata in self . inputfiles : xml += indent + " <inputfile name=\"" + clam . common . util . xmlescape ( filename ) + "\">" xml += metadata . xml ( indent + " " ) + "\n" xml += indent + " </inputfile>\n" if self . parameters : xml += indent + " <parameters>\n" if isinstance ( self . parameters , dict ) : parameters = self . parameters . values ( ) elif isinstance ( self . parameters , list ) : parameters = self . parameters for parameter in parameters : xml += parameter . xml ( indent + " " ) + "\n" xml += indent + " </parameters>\n" xml += indent + "</provenance>" return xml | Serialise provenance data to XML . This is included in CLAM Metadata files |
52,043 | def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) if node . tag == 'provenance' : if node . attrib [ 'type' ] == 'clam' : serviceid = node . attrib [ 'id' ] servicename = node . attrib [ 'name' ] serviceurl = node . attrib [ 'url' ] timestamp = node . attrib [ 'timestamp' ] outputtemplate = node . attrib [ 'outputtemplate' ] outputtemplatelabel = node . attrib [ 'outputtemplatelabel' ] inputfiles = [ ] parameters = [ ] for subnode in node : if subnode . tag == 'inputfile' : filename = node . attrib [ 'name' ] metadata = None for subsubnode in subnode : if subsubnode . tag == 'CLAMMetaData' : metadata = CLAMMetaData . fromxml ( subsubnode ) break inputfiles . append ( ( filename , metadata ) ) elif subnode . tag == 'parameters' : for subsubnode in subnode : if subsubnode . tag in vars ( clam . common . parameters ) : parameters . append ( vars ( clam . common . parameters ) [ subsubnode . tag ] . fromxml ( subsubnode ) ) else : raise Exception ( "Expected parameter class '" + subsubnode . tag + "', but not defined!" ) return CLAMProvenanceData ( serviceid , servicename , serviceurl , outputtemplate , outputtemplatelabel , inputfiles , parameters , timestamp ) else : raise NotImplementedError | Return a CLAMProvenanceData instance from the given XML description . Node can be a string or an lxml . etree . _Element . |
52,044 | def xml ( self , indent = "" ) : if not indent : xml = '<?xml version="1.0" encoding="UTF-8"?>\n' else : xml = "" xml += indent + "<CLAMMetaData format=\"" + self . __class__ . __name__ + "\"" if self . mimetype : xml += " mimetype=\"" + self . mimetype + "\"" if self . schema : xml += " schema=\"" + self . schema + "\"" if self . inputtemplate : xml += " inputtemplate=\"" + self . inputtemplate + "\"" xml += ">\n" for key , value in self . data . items ( ) : xml += indent + " <meta id=\"" + clam . common . util . xmlescape ( key ) + "\">" + clam . common . util . xmlescape ( str ( value ) ) + "</meta>\n" if self . provenance : xml += self . provenance . xml ( indent + " " ) xml += indent + "</CLAMMetaData>" return xml | Render an XML representation of the metadata |
52,045 | def save ( self , filename ) : with io . open ( filename , 'w' , encoding = 'utf-8' ) as f : f . write ( self . xml ( ) ) | Save metadata to XML file |
52,046 | def json ( self ) : d = { 'id' : self . id , 'format' : self . formatclass . __name__ , 'label' : self . label , 'mimetype' : self . formatclass . mimetype , 'schema' : self . formatclass . schema } if self . unique : d [ 'unique' ] = True if self . filename : d [ 'filename' ] = self . filename if self . extension : d [ 'extension' ] = self . extension if self . acceptarchive : d [ 'acceptarchive' ] = self . acceptarchive parametersxml = '' for parameter in self . parameters : parametersxml += parameter . xml ( ) d [ 'parametersxml' ] = '<?xml version="1.0" encoding="utf-8" ?><parameters>' + parametersxml + '</parameters>' d [ 'converters' ] = [ { 'id' : x . id , 'label' : x . label } for x in self . converters ] d [ 'inputsources' ] = [ { 'id' : x . id , 'label' : x . label } for x in self . inputsources ] return json . dumps ( d ) | Produce a JSON representation for the web interface |
52,047 | def validate ( self , postdata , user = None ) : clam . common . util . printdebug ( "Validating inputtemplate " + self . id + "..." ) errors , parameters , _ = processparameters ( postdata , self . parameters , user ) return errors , parameters | Validate posted data against the inputtemplate |
52,048 | def xml ( self , operator = 'set' , indent = "" ) : xml = indent + "<meta id=\"" + self . key + "\"" if operator != 'set' : xml += " operator=\"" + operator + "\"" if not self . value : xml += " />" else : xml += ">" + self . value + "</meta>" return xml | Serialize the metadata field to XML |
52,049 | def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'outputtemplate' template_id = node . attrib [ 'id' ] dataformat = node . attrib [ 'format' ] label = node . attrib [ 'label' ] kwargs = { } if 'filename' in node . attrib : kwargs [ 'filename' ] = node . attrib [ 'filename' ] if 'extension' in node . attrib : kwargs [ 'extension' ] = node . attrib [ 'extension' ] if 'unique' in node . attrib : kwargs [ 'unique' ] = node . attrib [ 'unique' ] . lower ( ) == 'yes' or node . attrib [ 'unique' ] . lower ( ) == 'true' or node . attrib [ 'unique' ] . lower ( ) == '1' if 'parent' in node . attrib : kwargs [ 'parent' ] = node . attrib [ 'parent' ] formatcls = None for C in CUSTOM_FORMATS : if C . __name__ == dataformat : formatcls = C break if formatcls is None : if dataformat in vars ( clam . common . formats ) : formatcls = vars ( clam . common . formats ) [ dataformat ] else : raise Exception ( "Specified format not defined! (" + dataformat + ")" ) args = [ ] for subnode in node : if subnode . tag == 'parametercondition' : args . append ( ParameterCondition . fromxml ( subnode ) ) elif subnode . tag == 'converter' : pass elif subnode . tag == 'viewer' : pass else : args . append ( AbstractMetaField . fromxml ( subnode ) ) return OutputTemplate ( template_id , formatcls , label , * args , ** kwargs ) | Static method return an OutputTemplate instance from the given XML description . Node can be a string or an etree . _Element . |
52,050 | def getparent ( self , profile ) : assert self . parent for inputtemplate in profile . input : if inputtemplate == self . parent : return inputtemplate raise Exception ( "Parent InputTemplate '" + self . parent + "' not found!" ) | Resolve a parent ID |
52,051 | def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'parametercondition' kwargs = { } found = False for node in node : if node . tag == 'if' : for subnode in node : operator = subnode . tag parameter = subnode . attrib [ 'parameter' ] value = subnode . text kwargs [ parameter + '_' + operator ] = value found = True elif node . tag == 'then' or node . tag == 'else' or node . tag == 'otherwise' : for subnode in node : if subnode . tag . lower ( ) == 'parametercondition' : kwargs [ node . tag ] = ParameterCondition . fromxml ( subnode ) elif subnode . tag == 'meta' : kwargs [ node . tag ] = AbstractMetaField . fromxml ( subnode ) elif subnode . tag . lower ( ) == 'outputtemplate' : kwargs [ node . tag ] = OutputTemplate . fromxml ( subnode ) if not found : raise Exception ( "No condition found in ParameterCondition!" ) return ParameterCondition ( ** kwargs ) | Static method returning a ParameterCondition instance from the given XML description . Node can be a string or an etree . _Element . |
52,052 | def fromxml ( node ) : if not isinstance ( node , ElementTree . _Element ) : node = parsexmlstring ( node ) assert node . tag . lower ( ) == 'action' kwargs = { } args = [ ] if 'id' in node . attrib : kwargs [ 'id' ] = node . attrib [ 'id' ] elif 'name' in node . attrib : kwargs [ 'name' ] = node . attrib [ 'name' ] elif 'description' in node . attrib : kwargs [ 'description' ] = node . attrib [ 'description' ] elif 'method' in node . attrib : kwargs [ 'method' ] = node . attrib [ 'method' ] elif 'mimetype' in node . attrib : kwargs [ 'mimetype' ] = node . attrib [ 'mimetype' ] elif 'allowanonymous' in node . attrib : if node . attrib [ 'allowanonymous' ] == "yes" : kwargs [ 'allowanonymous' ] = True found = False for subnode in node : if subnode . tag . lower ( ) == 'parametercondition' : kwargs [ node . tag ] = ParameterCondition . fromxml ( subnode ) elif subnode . tag in vars ( clam . common . parameters ) : args . append ( vars ( clam . common . parameters ) [ subnode . tag ] . fromxml ( subnode ) ) if not found : raise Exception ( "No condition found in ParameterCondition!" ) return Action ( * args , ** kwargs ) | Static method returning an Action instance from the given XML description . Node can be a string or an etree . _Element . |
52,053 | def crude_tokenizer ( line ) : tokens = [ ] buffer = '' for c in line . strip ( ) : if c == ' ' or c in string . punctuation : if buffer : tokens . append ( buffer ) buffer = '' else : buffer += c if buffer : tokens . append ( buffer ) return tokens | This is a very crude tokenizer from pynlpl |
52,054 | def initauth ( self ) : headers = { 'User-agent' : 'CLAMClientAPI-' + clam . common . data . VERSION } if self . oauth : if not self . oauth_access_token : r = requests . get ( self . url , headers = headers , verify = self . verify ) if r . status_code == 404 : raise clam . common . data . NotFound ( "Authorization provider not found" ) elif r . status_code == 403 : raise clam . common . data . PermissionDenied ( "Authorization provider denies access" ) elif not ( r . status_code >= 200 and r . status_code <= 299 ) : raise Exception ( "An error occured, return code " + str ( r . status_code ) ) data = self . _parse ( r . text ) if data is True : raise Exception ( "No access token provided, but Authorization Provider requires manual user input. Unable to authenticate automatically. Obtain an access token from " + r . geturl ( ) ) else : self . oauth_access_token = data . oauth_access_token headers [ 'Authorization' ] = 'Bearer ' + self . oauth_access_token return headers | Initialise authentication for internal use |
52,055 | def request ( self , url = '' , method = 'GET' , data = None , parse = True , encoding = None ) : requestparams = self . initrequest ( data ) if method == 'POST' : request = requests . post elif method == 'DELETE' : request = requests . delete elif method == 'PUT' : request = requests . put else : request = requests . get r = request ( self . url + url , ** requestparams ) if encoding is not None : r . encoding = encoding if r . status_code == 400 : raise clam . common . data . BadRequest ( ) elif r . status_code == 401 : raise clam . common . data . AuthRequired ( ) elif r . status_code == 403 : content = r . text if parse : data = self . _parse ( content ) if data : if data . errors : error = data . parametererror ( ) if error : raise clam . common . data . ParameterError ( error ) raise clam . common . data . PermissionDenied ( data ) else : raise clam . common . data . PermissionDenied ( content ) else : raise clam . common . data . PermissionDenied ( content ) elif r . status_code == 404 and data : raise clam . common . data . NotFound ( r . text ) elif r . status_code == 500 : raise clam . common . data . ServerError ( r . text ) elif r . status_code == 405 : raise clam . common . data . ServerError ( "Server returned 405: Method not allowed for " + method + " on " + self . url + url ) elif r . status_code == 408 : raise clam . common . data . TimeOut ( ) elif not ( r . status_code >= 200 and r . status_code <= 299 ) : raise Exception ( "An error occured, return code " + str ( r . status_code ) ) if parse : return self . _parse ( r . text ) else : return r . text | Issue a HTTP request and parse CLAM XML response this is a low - level function called by all of the higher - level communication methods in this class use those instead |
52,056 | def _parse ( self , content ) : if content . find ( '<clam' ) != - 1 : data = clam . common . data . CLAMData ( content , self , loadmetadata = self . loadmetadata ) if data . errors : error = data . parametererror ( ) if error : raise clam . common . data . ParameterError ( error ) return data else : return True | Parses CLAM XML data and returns a CLAMData object . For internal use . Raises ParameterError exception on parameter errors . |
52,057 | def get ( self , project ) : try : data = self . request ( project + '/' ) except : raise if not isinstance ( data , clam . common . data . CLAMData ) : raise Exception ( "Unable to retrieve CLAM Data" ) else : return data | Query the project status . Returns a CLAMData instance or raises an exception according to the returned HTTP Status code |
52,058 | def getinputfilename ( self , inputtemplate , filename ) : if inputtemplate . filename : filename = inputtemplate . filename elif inputtemplate . extension : if filename . lower ( ) [ - 4 : ] == '.zip' or filename . lower ( ) [ - 7 : ] == '.tar.gz' or filename . lower ( ) [ - 8 : ] == '.tar.bz2' : return filename if filename [ - len ( inputtemplate . extension ) - 1 : ] . lower ( ) != '.' + inputtemplate . extension . lower ( ) : filename += '.' + inputtemplate . extension return filename | Determine the final filename for an input file given an inputtemplate and a given filename . |
52,059 | def _parseupload ( self , node ) : if not isinstance ( node , ElementTree . _Element ) : try : node = clam . common . data . parsexmlstring ( node ) except : raise Exception ( node ) if node . tag != 'clamupload' : raise Exception ( "Not a valid CLAM upload response" ) for node2 in node : if node2 . tag == 'upload' : for subnode in node2 : if subnode . tag == 'error' : raise clam . common . data . UploadError ( subnode . text ) if subnode . tag == 'parameters' : if 'errors' in subnode . attrib and subnode . attrib [ 'errors' ] == 'yes' : errormsg = "The submitted metadata did not validate properly" for parameternode in subnode : if 'error' in parameternode . attrib : errormsg = parameternode . attrib [ 'error' ] raise clam . common . data . ParameterError ( errormsg + " (parameter=" + parameternode . attrib [ 'id' ] + ")" ) raise clam . common . data . ParameterError ( errormsg ) return True | Parse CLAM Upload XML Responses . For internal use |
52,060 | def download ( self , project , filename , targetfilename , loadmetadata = None ) : if loadmetadata is None : loadmetadata = self . loadmetadata f = clam . common . data . CLAMOutputFile ( self . url + project , filename , loadmetadata , self ) f . copy ( targetfilename ) | Download an output file |
52,061 | def validate ( self , value ) : if self . validator is not None : try : valid = self . validator ( value ) except Exception as e : import pdb pdb . set_trace ( ) if isinstance ( valid , tuple ) and len ( valid ) == 2 : valid , errormsg = valid elif isinstance ( valid , bool ) : errormsg = "Invalid value" else : raise TypeError ( "Custom validator must return a boolean or a (bool, errormsg) tuple." ) if valid : self . error = None else : self . error = errormsg return valid else : self . error = None return True | Validate the parameter |
52,062 | def set ( self , value = True ) : value = value in ( True , 1 ) or ( ( isinstance ( value , str ) or ( sys . version < '3' and isinstance ( value , unicode ) ) ) and ( value . lower ( ) in ( "1" , "yes" , "true" , "enabled" ) ) ) return super ( BooleanParameter , self ) . set ( value ) | Set the boolean parameter |
52,063 | def compilearg ( self ) : if isinstance ( self . value , list ) : value = self . delimiter . join ( self . value ) else : value = self . value if value . find ( " " ) >= 0 : value = '"' + value + '"' if self . paramflag and self . paramflag [ - 1 ] == '=' or self . nospace : sep = '' elif self . paramflag : sep = ' ' else : return str ( value ) return self . paramflag + sep + str ( value ) | This method compiles the parameter into syntax that can be used on the shell such as - paramflag = value |
52,064 | def index ( credentials = None ) : shortcutresponse = entryshortcut ( credentials ) if shortcutresponse is not None : return shortcutresponse projects = [ ] user , oauth_access_token = parsecredentials ( credentials ) totalsize = 0.0 if settings . LISTPROJECTS : projects , totalsize = getprojects ( user ) errors = "no" errormsg = "" corpora = CLAMService . corpusindex ( ) return withheaders ( flask . make_response ( flask . render_template ( 'response.xml' , version = VERSION , system_id = settings . SYSTEM_ID , system_name = settings . SYSTEM_NAME , system_description = settings . SYSTEM_DESCRIPTION , system_author = settings . SYSTEM_AUTHOR , system_version = settings . SYSTEM_VERSION , system_email = settings . SYSTEM_EMAIL , user = user , project = None , url = getrooturl ( ) , statuscode = - 1 , statusmessage = "" , statuslog = [ ] , completion = 0 , errors = errors , errormsg = errormsg , parameterdata = settings . PARAMETERS , inputsources = corpora , outputpaths = None , inputpaths = None , profiles = settings . PROFILES , datafile = None , projects = projects , totalsize = totalsize , actions = settings . ACTIONS , disableinterface = not settings . ENABLEWEBAPP , info = False , accesstoken = None , interfaceoptions = settings . INTERFACEOPTIONS , customhtml = settings . CUSTOMHTML_INDEX , allow_origin = settings . ALLOW_ORIGIN , oauth_access_token = oauth_encrypt ( oauth_access_token ) , auth_type = auth_type ( ) ) ) , headers = { 'allow_origin' : settings . ALLOW_ORIGIN } ) | Get list of projects or shortcut to other functionality |
52,065 | def run_wsgi ( settings_module ) : global settingsmodule , DEBUG printdebug ( "Initialising WSGI service" ) globals ( ) [ 'settings' ] = settings_module settingsmodule = settings_module . __name__ try : if settings . DEBUG : DEBUG = True setdebug ( True ) except : pass test_version ( ) if DEBUG : setlog ( sys . stderr ) else : setlog ( None ) try : if settings . LOGFILE : setlogfile ( settings . LOGFILE ) except : pass set_defaults ( ) test_dirs ( ) if DEBUG : from werkzeug . debug import DebuggedApplication return DebuggedApplication ( CLAMService ( 'wsgi' ) . service . wsgi_app , True ) else : return CLAMService ( 'wsgi' ) . service . wsgi_app | Run CLAM in WSGI mode |
52,066 | def index ( credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) if not settings . ADMINS or user not in settings . ADMINS : return flask . make_response ( 'You shall not pass!!! You are not an administrator!' , 403 ) usersprojects = { } totalsize = { } for f in glob . glob ( settings . ROOT + "projects/*" ) : if os . path . isdir ( f ) : u = os . path . basename ( f ) usersprojects [ u ] , totalsize [ u ] = getprojects ( u ) usersprojects [ u ] . sort ( ) return withheaders ( flask . make_response ( flask . render_template ( 'admin.html' , version = VERSION , system_id = settings . SYSTEM_ID , system_name = settings . SYSTEM_NAME , system_description = settings . SYSTEM_DESCRIPTION , system_author = settings . SYSTEM_AUTHOR , system_version = settings . SYSTEM_VERSION , system_email = settings . SYSTEM_EMAIL , user = user , url = getrooturl ( ) , usersprojects = sorted ( usersprojects . items ( ) ) , totalsize = totalsize , allow_origin = settings . ALLOW_ORIGIN , oauth_access_token = oauth_encrypt ( oauth_access_token ) ) ) , "text/html; charset=UTF-8" , { 'allow_origin' : settings . ALLOW_ORIGIN } ) | Get list of projects |
52,067 | def exists ( project , credentials ) : user , oauth_access_token = parsecredentials ( credentials ) printdebug ( "Checking if project " + project + " exists for " + user ) return os . path . isdir ( Project . path ( project , user ) ) | Check if the project exists |
52,068 | def new ( project , credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) response = Project . create ( project , user ) if response is not None : return response msg = "Project " + project + " has been created for user " + user if oauth_access_token : extraloc = '?oauth_access_token=' + oauth_access_token else : extraloc = '' return flask . make_response ( msg , 201 , { 'Location' : getrooturl ( ) + '/' + project + '/' + extraloc , 'Content-Type' : 'text/plain' , 'Content-Length' : len ( msg ) , 'Access-Control-Allow-Origin' : settings . ALLOW_ORIGIN , 'Access-Control-Allow-Methods' : 'GET, POST, PUT, DELETE' , 'Access-Control-Allow-Headers' : 'Authorization' } ) | Create an empty project |
52,069 | def deleteoutputfile ( project , filename , credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) if filename : filename = filename . replace ( ".." , "" ) if not filename or len ( filename ) == 0 : Project . reset ( project , user ) msg = "Deleted" return withheaders ( flask . make_response ( msg ) , 'text/plain' , { 'Content-Length' : len ( msg ) , 'allow_origin' : settings . ALLOW_ORIGIN } ) elif os . path . isdir ( Project . path ( project , user ) + filename ) : shutil . rmtree ( Project . path ( project , user ) + filename ) msg = "Deleted" return withheaders ( flask . make_response ( msg ) , 'text/plain' , { 'Content-Length' : len ( msg ) , 'allow_origin' : settings . ALLOW_ORIGIN } ) else : try : file = clam . common . data . CLAMOutputFile ( Project . path ( project , user ) , filename ) except : raise flask . abort ( 404 ) success = file . delete ( ) if not success : raise flask . abort ( 404 ) else : msg = "Deleted" return withheaders ( flask . make_response ( msg ) , 'text/plain' , { 'Content-Length' : len ( msg ) , 'allow_origin' : settings . ALLOW_ORIGIN } ) | Delete an output file |
52,070 | def reset ( project , user ) : d = Project . path ( project , user ) + "output" if os . path . isdir ( d ) : shutil . rmtree ( d ) os . makedirs ( d ) else : raise flask . abort ( 404 ) if os . path . exists ( Project . path ( project , user ) + ".done" ) : os . unlink ( Project . path ( project , user ) + ".done" ) if os . path . exists ( Project . path ( project , user ) + ".status" ) : os . unlink ( Project . path ( project , user ) + ".status" ) | Reset system delete all output files and prepare for a new run |
52,071 | def deleteinputfile ( project , filename , credentials = None ) : user , oauth_access_token = parsecredentials ( credentials ) filename = filename . replace ( ".." , "" ) if len ( filename ) == 0 : shutil . rmtree ( Project . path ( project , user ) + 'input' ) os . makedirs ( Project . path ( project , user ) + 'input' ) return "Deleted" elif os . path . isdir ( Project . path ( project , user ) + filename ) : shutil . rmtree ( Project . path ( project , user ) + filename ) return "Deleted" else : try : file = clam . common . data . CLAMInputFile ( Project . path ( project , user ) , filename ) except : raise flask . abort ( 404 ) success = file . delete ( ) if not success : raise flask . abort ( 404 ) else : msg = "Deleted" return withheaders ( flask . make_response ( msg ) , 'text/plain' , { 'Content-Length' : len ( msg ) , 'allow_origin' : settings . ALLOW_ORIGIN } ) | Delete an input file |
52,072 | def corpusindex ( ) : corpora = [ ] for f in glob . glob ( settings . ROOT + "corpora/*" ) : if os . path . isdir ( f ) : corpora . append ( os . path . basename ( f ) ) return corpora | Get list of pre - installed corpora |
52,073 | def validate ( self , nonce ) : if self . debug : print ( "Checking nonce " + str ( nonce ) , file = sys . stderr ) try : opaque , ip , expiretime = self . get ( nonce ) if expiretime < time . time ( ) : if self . debug : print ( "Nonce expired" , file = sys . stderr ) self . remove ( nonce ) return False elif ip != flask . request . remote_addr : if self . debug : print ( "Nonce IP mismatch" , file = sys . stderr ) self . remove ( nonce ) return False else : return True except KeyError : if self . debug : print ( "Nonce " + nonce + " does not exist" , file = sys . stderr ) return False | Does the nonce exist and is it valid for the request? |
52,074 | def cleanup ( self ) : t = time . time ( ) for noncefile in glob ( self . path + '/*.nonce' ) : if os . path . getmtime ( noncefile ) + self . expiration > t : os . unlink ( noncefile ) | Delete expired nonces |
52,075 | def json ( self ) : return { "id" : self . ID , "steps" : self . steps , "graph_source" : self . source , "errored" : self . errored } | Retrun JSON representation for this run |
52,076 | def new_run ( self ) : self . current_run += 1 self . runs . append ( RunData ( self . current_run + 1 ) ) | Creates a new RunData object and increments pointers |
52,077 | def update_frontend ( self , info ) : headers = { 'Content-Type' : 'text/event-stream' } if info . get ( 'when' ) : info [ 'when' ] = info [ 'when' ] . isoformat ( ) requests . post ( self . base_url + '/publish' , data = json . dumps ( info ) , headers = headers ) | Updates frontend with info from the log |
52,078 | def get_summary ( self ) : if not self . analysis_finished : return [ ] summary = { 'times_summary' : [ ] } for i in range ( len ( self . runs [ self . current_run ] . steps ) - 1 ) : step = self . runs [ self . current_run ] . steps [ i ] begin = parse ( step [ 'when' ] ) end = parse ( self . runs [ self . current_run ] . steps [ i + 1 ] [ 'when' ] ) duration = end - begin summary [ 'times_summary' ] . append ( ( step [ 'step' ] , duration . seconds ) ) return summary | Returns some summary data for a finished analysis |
52,079 | def _handle_rundebug_from_shell ( cmd_line ) : command , args = parse_shell_command ( cmd_line ) if len ( args ) >= 1 : get_workbench ( ) . get_editor_notebook ( ) . save_all_named_editors ( ) origcommand = command if command == "Ev3RemoteRun" : command = "Run" if command == "Ev3RemoteDebug" : command = "Debug" cmd = ToplevelCommand ( command = command , filename = args [ 0 ] , args = args [ 1 : ] ) if origcommand == "Ev3RemoteRun" or origcommand == "Ev3RemoteDebug" : cmd . environment = { "EV3MODE" : "remote" , "EV3IP" : get_workbench ( ) . get_option ( "ev3.ip" ) } if os . path . isabs ( cmd . filename ) : cmd . full_filename = cmd . filename else : runner = get_runner ( ) cmd . full_filename = os . path . join ( runner . get_cwd ( ) , cmd . filename ) if command in [ "Run" , "run" , "Debug" , "debug" ] : with tokenize . open ( cmd . full_filename ) as fp : cmd . source = fp . read ( ) get_runner ( ) . send_command ( cmd ) else : print_error_in_backend ( "Command '{}' takes at least one argument" . format ( command ) ) | Handles all commands that take a filename and 0 or more extra arguments . Passes the command to backend . |
52,080 | def download_log ( currentfile = None ) : if currentfile == None : return if not currentfile . endswith ( ".err.log" ) : currentfile = currentfile + ".err.log" list = get_base_ev3dev_cmd ( ) + [ 'download' , '--force' ] list . append ( currentfile ) env = os . environ . copy ( ) env [ "PYTHONUSERBASE" ] = THONNY_USER_BASE proc = subprocess . Popen ( list , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , env = env ) dlg = MySubprocessDialog ( get_workbench ( ) , proc , "Downloading log of program from EV3" , autoclose = True ) dlg . wait_window ( ) if dlg . returncode == 0 : from pathlib import Path home = str ( Path . home ( ) ) open_file ( currentfile , home , True ) | downloads log of given . py file from EV3 . |
52,081 | def download_log_of_current_script ( ) : try : src_file = get_workbench ( ) . get_current_editor ( ) . get_filename ( False ) if src_file is None : return download_log ( src_file ) except Exception : error_msg = traceback . format_exc ( 0 ) + '\n' showerror ( "Error" , error_msg ) | download log of current python script from EV3 |
52,082 | def cleanup_files_on_ev3 ( ) : list = get_base_ev3dev_cmd ( ) + [ 'cleanup' ] env = os . environ . copy ( ) env [ "PYTHONUSERBASE" ] = THONNY_USER_BASE proc = subprocess . Popen ( list , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , env = env ) dlg = MySubprocessDialog ( get_workbench ( ) , proc , "Delete files in homedir on EV3" , autoclose = False ) dlg . wait_window ( ) | cleanup files in homedir on EV3 . |
52,083 | def init ( base_url , username = None , password = None , verify = True ) : handler = RequestHandler ( base_url , username , password , verify ) set_default_request_handler ( handler ) return handler | Initialize ubersmith API module with HTTP request handler . |
52,084 | def getConfigPath ( configFileName = None ) : if configFileName != None : if sys . platform == 'win32' : return os . path . expanduser ( os . path . join ( '~\\' , 'Deepify' , configFileName ) ) else : return os . path . expanduser ( os . path . join ( '~/' , '.config' , 'Deepify' , configFileName ) ) else : if sys . platform == 'win32' : return os . path . expanduser ( os . path . join ( '~\\' , 'Deepify' ) ) else : return os . path . expanduser ( os . path . join ( '~/' , '.config' , 'Deepify' ) ) | Auxiliar function to get the configuration path depending on the system . |
52,085 | def new_log_file ( logger , suffix , file_type = 'tcl' ) : file_handler = None for handler in logger . handlers : if isinstance ( handler , logging . FileHandler ) : file_handler = handler new_logger = logging . getLogger ( file_type + suffix ) if file_handler : logger_file_name = path . splitext ( file_handler . baseFilename ) [ 0 ] tcl_logger_file_name = logger_file_name + '-' + suffix + '.' + file_type new_logger . addHandler ( logging . FileHandler ( tcl_logger_file_name , 'w' ) ) new_logger . setLevel ( logger . getEffectiveLevel ( ) ) return new_logger | Create new logger and log file from existing logger . |
52,086 | def process_request ( self , method , data = None ) : self . _validate_request_method ( method ) attempts = 3 for i in range ( attempts ) : response = self . _send_request ( method , data ) if self . _is_token_response ( response ) : if i < attempts - 1 : time . sleep ( 2 ) continue else : raise UpdatingTokenResponse break resp = BaseResponse ( response ) if response . headers . get ( 'content-type' ) == 'application/json' : if not resp . json . get ( 'status' ) : if all ( [ resp . json . get ( 'error_code' ) == 1 , resp . json . get ( 'error_message' ) == u"We are currently " "undergoing maintenance, please check back shortly." , ] ) : raise MaintenanceResponse ( response = resp . json ) else : raise ResponseError ( response = resp . json ) return resp | Process request over HTTP to ubersmith instance . |
52,087 | def _encode_data ( data ) : data = data if data is not None else { } data = to_nested_php_args ( data ) files = dict ( [ ( key , value ) for key , value in data . items ( ) if isinstance ( value , file_type ) ] ) for fname in files : del data [ fname ] return data , files or None , None | URL encode data . |
52,088 | def get_objects_or_children_by_type ( self , * types ) : objects = self . get_objects_by_type ( * types ) return objects if objects else self . get_children ( * types ) | Get objects if children already been read or get children . |
52,089 | def get_object_or_child_by_type ( self , * types ) : objects = self . get_objects_or_children_by_type ( * types ) return objects [ 0 ] if any ( objects ) else None | Get object if child already been read or get child . |
52,090 | def del_object_from_parent ( self ) : if self . parent : self . parent . objects . pop ( self . ref ) | Delete object from parent object . |
52,091 | def _idToStr ( self , x ) : if x < 0 : sign = - 1 elif x == 0 : return self . _idChars [ 0 ] else : sign = 1 x *= sign digits = [ ] while x : digits . append ( self . _idChars [ x % self . _idCharsCnt ] ) x //= self . _idCharsCnt if sign < 0 : digits . append ( '-' ) digits . reverse ( ) return '' . join ( digits ) | Convert VCD id in int to string |
52,092 | def addVar ( self , sig : object , name : str , sigType : VCD_SIG_TYPE , width : int , valueFormatter : Callable [ [ "Value" ] , str ] ) : vInf = self . _writer . _idScope . registerVariable ( sig , name , self , width , sigType , valueFormatter ) self . children [ vInf . name ] = vInf self . _writer . _oFile . write ( "$var %s %d %s %s $end\n" % ( sigType , vInf . width , vInf . vcdId , vInf . name ) ) | Add variable to scope |
52,093 | def varScope ( self , name ) : ch = VcdVarWritingScope ( name , self . _writer , parent = self ) assert name not in self . children , name self . children [ name ] = ch return ch | Create sub variable scope with defined name |
52,094 | def append_qs ( url , query_string ) : parsed_url = urlsplit ( url ) parsed_qs = parse_qsl ( parsed_url . query , True ) if isstr ( query_string ) : parsed_qs += parse_qsl ( query_string ) elif isdict ( query_string ) : for item in list ( query_string . items ( ) ) : if islist ( item [ 1 ] ) : for val in item [ 1 ] : parsed_qs . append ( ( item [ 0 ] , val ) ) else : parsed_qs . append ( item ) elif islist ( query_string ) : parsed_qs += query_string else : raise TypeError ( 'Unexpected query_string type' ) return urlunsplit ( ( parsed_url . scheme , parsed_url . netloc , parsed_url . path , urlencode_unicode ( parsed_qs ) , parsed_url . fragment , ) ) | Append query_string values to an existing URL and return it as a string . |
52,095 | def urlencode_unicode ( data , doseq = 0 ) : data_iter = None if isdict ( data ) : data_iter = list ( data . items ( ) ) elif islist ( data ) : data_iter = data if data_iter : for i , ( key , value ) in enumerate ( data_iter ) : if isinstance ( value , text_type ) : try : safe_val = str ( value ) except UnicodeEncodeError : safe_val = value . encode ( 'utf-8' ) finally : if isdict ( data ) : data [ key ] = safe_val else : data [ i ] = ( key , safe_val ) return urlencode ( data , doseq = doseq ) | urllib . urlencode can t handle unicode this is a hack to fix it . |
52,096 | def to_nested_php_args ( data , prefix_key = None ) : is_root = prefix_key is None prefix_key = prefix_key if prefix_key else '' if islist ( data ) : data_iter = data if is_root else enumerate ( data ) new_data = [ ] if is_root else { } elif isdict ( data ) : data_iter = list ( data . items ( ) ) new_data = { } else : raise TypeError ( 'expected dict or list, got {0}' . format ( type ( data ) ) ) if islist ( new_data ) : def data_set ( k , v ) : new_data . append ( ( k , v ) ) def data_update ( d ) : for k , v in list ( d . items ( ) ) : new_data . append ( ( k , v ) ) else : def data_set ( k , v ) : new_data [ k ] = v data_update = new_data . update for key , value in data_iter : end_key = prefix_key + ( str ( key ) if is_root else '[{0}]' . format ( key ) ) if _is_leaf ( value ) : data_set ( end_key , value ) else : nested_args = to_nested_php_args ( value , end_key ) data_update ( nested_args ) return new_data | This function will take either a dict or list and will recursively loop through the values converting it into a format similar to a PHP array which Ubersmith requires for the info portion of the API s order . create method . |
52,097 | def get_filename ( disposition ) : if disposition : params = [ param . strip ( ) for param in disposition . split ( ';' ) [ 1 : ] ] for param in params : if '=' in param : name , value = param . split ( '=' , 1 ) if name == 'filename' : return value . strip ( '"' ) | Parse Content - Disposition header to pull out the filename bit . |
52,098 | def tcl_list_2_py_list ( tcl_list , within_tcl_str = False ) : if not within_tcl_str : tcl_list = tcl_str ( tcl_list ) return tcl_interp_g . eval ( 'join ' + tcl_list + ' LiStSeP' ) . split ( 'LiStSeP' ) if tcl_list else [ ] | Convert Tcl list to Python list using Tcl interpreter . |
52,099 | def py_list_to_tcl_list ( py_list ) : py_list_str = [ str ( s ) for s in py_list ] return tcl_str ( tcl_interp_g . eval ( 'split' + tcl_str ( '\t' . join ( py_list_str ) ) + '\\t' ) ) | Convert Python list to Tcl list using Tcl interpreter . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.