code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.cleanup() except CloudComposeException as ex: print(ex)
def cleanup()
deletes launch configs and auto scaling group
5.240907
5.089688
1.029711
try: cloud_config = CloudConfig() config_data = cloud_config.config_data('cluster') cloud_init = CloudInit() print(cloud_init.build(config_data)) except CloudComposeException as ex: print(ex)
def build()
builds the cloud_init script
5.573759
4.822722
1.155729
signalbus = current_app.extensions['signalbus'] signal_names = set(signal_names) exclude = set(exclude) models_to_flush = signalbus.get_signal_models() if signal_names and exclude: click.echo('Warning: Specified both SIGNAL_NAMES and exclude option.') if signal_names: wrong...
def flush(signal_names, exclude, wait)
Send pending signals over the message bus. If a list of SIGNAL_NAMES is specified, flushes only those signals. If no SIGNAL_NAMES are specified, flushes all signals.
2.486552
2.375081
1.046934
signalbus = current_app.extensions['signalbus'] signal_count = signalbus.flushmany() logger = logging.getLogger(__name__) if signal_count == 1: logger.warning('%i signal has been successfully processed.', signal_count) elif signal_count > 1: logger.warning('%i signals have been...
def flushmany()
Send a potentially huge number of pending signals over the message bus. This command assumes that the number of pending signals might be huge, so that they might not fit into memory. However, it is not very smart in handling concurrent senders. It is mostly useful when recovering from long periods of d...
4.09674
3.474452
1.179104
signalbus = current_app.extensions['signalbus'] for signal_model in signalbus.get_signal_models(): click.echo(signal_model.__name__)
def signals()
Show all signal types.
7.386849
5.543513
1.332521
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 pendin...
def pending()
Show the number of pending signals by signal type.
3.434284
3.007216
1.142015
model_name = instance.__class__.__name__ return "{0}__{1}_{2}".format(lang,model_name,instance.id)
def _create_key(lang, instance)
Crea la clave única de la caché
4.68298
4.175585
1.121515
now = timezone.now() timediff = TransCache.SINGLETON_CREATION_DATETIME - now return (timediff.total_seconds() > TransCache.SINGLETON_EXPIRATION_MAX_SECONDS)
def _cache_is_expired()
Indica si la caché está caducada
8.957524
8.586763
1.043178
if not TransCache.SINGLETON or TransCache._cache_is_expired(): TransCache.SINGLETON = TransCache() TransCache.SINGLETON_CREATION_DATETIME = timezone.now() return TransCache.SINGLETON
def factory()
Factoría del singleton, o crea una nueva o devuelve la existente
6.793158
5.427169
1.251695
if self._cache_is_too_big(): self.cache = {} instance_key = TransCache._create_key(lang, instance) instance._translations_are_cached = True instance.load_translations(lang=lang) self.cache[instance_key] = instance
def set(self, lang, instance)
Establece en la instancia actual los atributos de traducción y la almacena en un diccionario de claves _create_key y valores el objeto con los atributos dinámicos.
6.075742
4.975985
1.221013
instance_key = TransCache._create_key(lang, instance) return instance_key in self.cache
def has(self, lang, instance)
Indica si la caché tiene un objeto igual a éste con los atributos dinámicos de traducción
9.365453
9.04131
1.035851
instance_key = TransCache._create_key(lang, instance) return self.cache[instance_key]
def get(self, lang, instance)
Obtiene una instancia igual a ésta, pero con los atributos dinámicos de traduccción
8.974596
9.341911
0.960681
# size = '!' + thumbnail_width + ',' size = thumbnail_width + ',' # flask_iiif doesn't support ! at the moment thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg')
def create_thumbnail(uuid, thumbnail_width)
Create the thumbnail for an image.
14.69426
16.507124
0.890177
def _error_or_default(err_msg): if default == _not_defined: raise ValueError(err_msg) return default # check and clean if not isinstance(raw_price, str): return _error_or_default( 'Wrong raw price type "{price_type}" ' '(expected type "str")'...
def price_str(raw_price, default=_not_defined, dec_point='.')
Search and clean price value. Convert raw price string presented in any localization as a valid number string with an optional decimal point. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value not set, then raise Value...
2.626578
2.547348
1.031103
try: price = price_str(raw_price) return decimal.Decimal(price) except ValueError as err: if default == _not_defined: raise err return default
def price_dec(raw_price, default=_not_defined)
Price decimal value from raw string. Extract price value from input raw string and present as Decimal number. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value not set, then raise ValueError. :param str raw_price...
3.579751
4.213232
0.849645
results = list(TestResult.objects.filter(test=result.test, site=result.site)[:num]) results.reverse() return [[get_timestamp(result.run_date), result.duration/1000] for result in results]
def flotify(result, num=50)
Return a list of (timestamp, duration) sets for test result.
5.623096
4.590374
1.224976
try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check func_code.co_argcount rather than try/excepting the # function and catching the TypeError, because something inside # the funct...
def __get_dynamic_attr(self, attname, arg, default=None)
Gets "something" from self, which could be an attribute or a callable with either 0 or 1 arguments (besides self). Stolen from django.contrib.syntication.feeds.Feed.
3.388864
3.244156
1.044606
if not measurement_name or values in (None, {}): # Don't try to send empty data return tags = tags or {} # Do a shallow merge of the metric tags and global tags all_tags = dict(self.tags, **tags) # Create a metric line from the input and then s...
def metric(self, measurement_name, values, tags=None, timestamp=None)
Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket
4.848241
4.331499
1.119299
try: self.socket.sendto(data.encode('utf8') + b'\n', (self.host, self.port)) except (socket.error, RuntimeError): # Socket errors should fail silently so they don't affect anything else pass
def send(self, data)
Sends the given data to the socket via UDP
4.973425
4.778554
1.04078
self.future_session.post(url=self.url, data=data)
def send(self, 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.
11.424234
7.524676
1.518236
# Handle primitive values here and implicitly convert them to a dict because # it allows the API to be simpler. # Also influxDB mandates that each value also has a name so the default name # for any non-dict value is "value" if not isinstance(self.values, dict): ...
def get_output_values(self)
Return an escaped string of comma separated value_name: value pairs
5.837314
5.245586
1.112805
# Sort the tags in lexicographically by tag name sorted_tags = sorted(self.tags.items()) # Finally render, escape and return the tag string return u",".join(u"{0}={1}".format(format_string(k), format_string(v)) for k, v in sorted_tags)
def get_output_tags(self)
Return an escaped string of comma separated tag_name: tag_value pairs Tags should be sorted by key before being sent for best performance. The sort should match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare).
5.599847
4.356897
1.285283
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() )
def to_line_protocol(self)
Converts the given metrics as a single line of InfluxDB line protocol
5.097359
4.127712
1.234912
if isinstance(key, basestring): key = key.replace(",", "\,") key = key.replace(" ", "\ ") key = key.replace("=", "\=") return key
def format_string(key)
Formats either measurement names, tag names or tag values. Measurement name and any optional tags separated by commas. Measurement names, tag keys, and tag values must escape any spaces, commas or equal signs using a backslash (\). For example: \ and \,. All tag values are stored as strings and should...
3.009128
3.252462
0.925185
if isinstance(value, basestring): value = value.replace('"', '\"') value = u'"{0}"'.format(value) elif isinstance(value, bool): value = str(value) elif isinstance(value, int): value = "{0}i".format(value) elif isinstance(value, float): value = str(value) ...
def format_value(value)
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted (e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i. If they do not they will be written as floats. Floats are numeric values that are not followed by a trailing i. (e.g. 1, 1.0, -...
2.183547
2.596732
0.840883
# pylint: disable=global-statement global Nreferences # Global references counter global cursec # Current section # Parse the equation attrs = value[0] # Initialize the return value eq = {'is_unnumbered': False, 'is_unreferenceable': False, 'is_tagged': Fal...
def _process_equation(value, fmt)
Processes the equation. Returns a dict containing eq properties.
3.929607
3.855535
1.019212
if key == 'Math' and len(value) == 3: # Process the equation eq = _process_equation(value, fmt) # Get the attributes and label attrs = eq['attrs'] label = attrs[0] if eq['is_unreferenceable']: attrs[0] = '' # The label isn't needed outside this fu...
def process_equations(key, value, fmt, meta)
Processes the attributed equations.
5.384673
5.34587
1.007258
# pylint: disable=global-statement global capitalize global use_cleveref_default global plusname global starname global numbersections # Read in the metadata fields and do some checking for name in ['eqnos-cleveref', 'xnos-cleveref', 'cleveref']: # 'xnos-cleveref' enables...
def process(meta)
Saves metadata fields in global variables and returns a few computed fields.
3.09481
3.088932
1.001903
# pylint: disable=global-statement global PANDOCVERSION global AttrMath # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-function-args PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)...
def main()
Filters the document AST.
5.896154
5.822467
1.012656
from django.conf import settings if not settings.configured: return False # I _think_ this check is all that's needed and the 3 "hasattr" checks # below can be removed, but it's not clear how to verify that from django.apps import apps if not apps.ready: return False ...
def check_debug()
Check that Django's template debugging is enabled. Django's built-in "template debugging" records information the plugin needs to do its work. Check that the setting is correct, and raise an exception if it is not. Returns True if the debug check was performed, False otherwise
4.092027
3.862342
1.059468
# Import this late to be sure we don't trigger settings machinery too # early. 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
def read_template_source(filename)
Read the source of a Django template, returning the Unicode text.
5.622598
5.304739
1.05992
for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1
def get_line_number(line_map, offset)
Find a line number, given a line map and a character offset.
3.152336
3.027699
1.041166
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( ...
def dump_frame(frame, label="")
Dump interesting information about this frame.
3.486437
3.457536
1.008359
if filename not in self.source_map: template_source = read_template_source(filename) if 0: # change to see the template text for i in range(0, len(template_source), 10): print("%3d: %r" % (i, template_source[i:i+10])) self.source...
def get_line_map(self, filename)
The line map for `filename`. A line map is a list of character offsets, indicating where each line in the text begins. For example, a line map like this:: [13, 19, 30] means that line 2 starts at character 13, line 3 starts at 19, etc. Line 1 always starts at character 0.
3.340414
3.456666
0.966369
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
def init(size=250)
Initialize mpv.
6.966558
5.780146
1.205256
pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True) with open(output_file, "wb") as file: file.write(input_data)
def bytes_to_file(input_data, output_file)
Save bytes to a file.
2.064683
2.026461
1.018862
client = mpd.MPDClient() try: client.connect(server, port) return client except ConnectionRefusedError: print("error: Connection refused to mpd/mopidy.") os._exit(1)
def init(port=6600, server="localhost")
Initialize mpd.
4.608021
3.953477
1.165562
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 / "cu...
def get_art(cache_dir, size, client)
Get the album art.
3.566014
3.394008
1.050679
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']}") ...
def get_cover(song, size=250)
Download the cover art.
4.75469
4.415184
1.076895
description = "bum - Download and display album art \ for mpd tracks." arg = argparse.ArgumentParser(description=description) arg.add_argument("--size", metavar="\"px\"", help="what size to display the album art in.", default=250) arg.a...
def get_args()
Get the script arguments.
4.007851
3.92284
1.021671
args = get_args() process_args(args) if not args.no_display: disp = display.init(args.size) client = song.init(args.port, args.server) while True: song.get_art(args.cache_dir, args.size, client) if not args.no_display: display.launch(disp, args.cache_dir /...
def main()
Main script function.
9.686504
9.551813
1.014101
assert isinstance(metadata, CLAMMetaData) #metadata of the destination file (file to be generated here) if not metadata.__class__ in self.acceptforinput: raise Exception("Convertor " + self.__class__.__name__ + " can not convert input files to " + metadata.__class__.__name__ + "!") ...
def convertforinput(self,filepath, metadata)
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!
10.886056
8.972037
1.213332
assert isinstance(outputfile, CLAMOutputFile) #metadata of the destination file (file to be generated here) if not outputfile.metadata.__class__ in self.acceptforoutput: raise Exception("Convertor " + self.__class__.__name__ + " can not convert input files to " + outputfile.metadata...
def convertforoutput(self,outputfile)
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance.
11.444582
8.001638
1.43028
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']) ...
def convertforinput(self,filepath, metadata=None)
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.
3.516239
3.458464
1.016705
super(CharEncodingConverter,self).convertforoutput(outputfile) return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , 'text/plain; charset=' + self.charset)
def convertforoutput(self,outputfile)
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance.
10.521309
10.099195
1.041797
global CUSTOM_FORMATS #pylint: disable=global-statement f = io.open(filename,'r',encoding='utf-8') xml = f.read(os.path.getsize(filename)) f.close() if custom_formats: CUSTOM_FORMATS = custom_formats #dependency injection for CUSTOM_FORMATS return CLAMData(xml, None, True)
def getclamdata(filename, custom_formats=None)
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. If you make use of CUSTOM_FORMATS, you need to pass the CUSTOM_FORMATS list as 2nd argument.
5.002405
4.457478
1.12225
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[...
def sanitizeparameters(parameters)
Construct a dictionary of parameters, for internal use only
3.707384
3.517597
1.053954
parameters = sanitizeparameters(parameters) matched = [] program = Program(projectpath) for profile in profiles: if profile.match(projectpath, parameters)[0]: matched.append(profile) program.update( profile.generate(projectpath,parameters,serviceid,servicename,serv...
def profiler(profiles, projectpath,parameters,serviceid,servicename,serviceurl,printdebug=None)
Given input files and parameters, produce metadata for outputfiles. Returns a list of matched profiles (empty if none match), and a program.
5.305658
4.078147
1.300997
if sys.version[0] == '2' and not isinstance(s,unicode): #pylint: disable=undefined-variable s = unicode(s,'utf-8') #pylint: disable=undefined-variable if len(s) > 1024: raise ValueError("Variable value rejected for security reasons: too long") if quote: if quote in s: ...
def shellsafe(s, quote='', doescape=True)
Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection
3.164136
3.158715
1.001716
if self.metadata: template = None for profile in profiles: if isinstance(self, CLAMInputFile): for t in profile.input: if self.metadata.inputtemplate == t.id: template = t ...
def attachviewers(self, profiles)
Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate
4.337981
3.641099
1.191393
metafilename = os.path.dirname(self.filename) if metafilename: metafilename += '/' metafilename += '.' + os.path.basename(self.filename) + '.METADATA' return metafilename
def metafilename(self)
Returns the filename for the metadata file (not full path). Only used for local files.
3.808036
3.602075
1.057179
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: ...
def loadmetadata(self)
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.
4.941585
4.449292
1.110645
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) #Remove metadata metafile = self.project...
def delete(self)
Delete this file
4.716775
4.617358
1.021531
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...
def read(self)
Loads all lines in memory
2.509005
2.433715
1.030936
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: ...
def copy(self, target, timeout=500)
Copy or download this file to a new local file
2.156415
2.135631
1.009732
for profile in self.profiles: for outputtemplate in profile.outputtemplates(): if outputtemplate.id == template_id: return outputtemplate return KeyError("Outputtemplate " + template_id + " not found")
def outputtemplate(self, template_id)
Get an output template by ID
3.884185
3.691252
1.052268
commandlineargs = [] for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: p = parameter.compilearg() if p: commandlineargs.append(p) return " ".join(commandlinearg...
def commandlineargs(self)
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.
4.329846
3.881315
1.115562
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.id == parameter_id: return parameter raise KeyError("No such parameter exists: " + parameter_id )
def parameter(self, parameter_id)
Return the specified global parameter (the entire object, not just the value)
4.560326
4.255216
1.071703
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.error: return parameter.error return False
def parametererror(self)
Return the first parameter error, or False if there is none
5.356985
4.257809
1.258155
paramdict = {} for parametergroup, params in self.parameters: #pylint: disable=unused-variable for parameter in params: if parameter.value: if isinstance(parameter.value, list): paramdict[parameter.id] = ",".join(parameter....
def passparameters(self)
Return all parameters as {id: value} dictionary
3.030259
2.752913
1.100746
l = [] for profile in self.profiles: l += profile.input return l
def inputtemplates(self)
Return all input templates as a list (of InputTemplate instances)
8.968466
7.221131
1.241975
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))
def inputtemplate(self,template_id)
Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance
3.447498
3.332518
1.034502
inputfiles = list(self.inputfiles(inputtemplate)) if len(inputfiles) < 1: raise Exception("No such input file") elif len(inputfiles) > 1: raise Exception("Multiple input files matched. Use inputfiles() instead!") return inputfiles[0]
def inputfile(self, inputtemplate=None)
Return the inputfile for the specified inputtemplate, if ``inputtemplate=None``, inputfile is returned regardless of inputtemplate. This function may only return 1 and returns an error when multiple input files can be returned, use ``inputfiles()`` instead.
3.310282
2.67957
1.235378
if isinstance(inputtemplate, InputTemplate): #ID suffices: inputtemplate = inputtemplate.id for inputfile in self.input: if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate: yield inputfile
def inputfiles(self, inputtemplate=None)
Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate.
6.577404
5.058377
1.300299
parameters = sanitizeparameters(parameters) mandatory_absent = [] #list of input templates that are missing but mandatory optional_absent = [] #list of absent but optional input templates #check if profile matches inputdata (if there are no inputtemplate, this always matches i...
def match(self, projectpath, parameters)
Check if the profile matches all inputdata *and* produces output given the set parameters. Returns a boolean
4.484518
4.016902
1.116412
l = [] for inputtemplate in self.input: l += inputtemplate.matchingfiles(projectpath) return l
def matchingfiles(self, projectpath)
Return a list of all inputfiles matching the profile (filenames)
6.712726
5.213637
1.287532
outputtemplates = [] for o in self.output: if isinstance(o, ParameterCondition): outputtemplates += o.allpossibilities() else: assert isinstance(o, OutputTemplate) outputtemplates.append(o) return outputtemplates
def outputtemplates(self)
Returns all outputtemplates, resolving ParameterConditions to all possibilities
4.362589
2.35964
1.848837
#Make dictionary of parameters parameters = sanitizeparameters(parameters) program = Program(projectpath, [self]) match, optional_absent = self.match(projectpath, parameters) #Does the profile match? if match: #pylint: disable=too-many-nested-blocks #gath...
def generate(self, projectpath, parameters, serviceid, servicename,serviceurl)
Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance.
5.359761
5.054629
1.060367
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: ...
def xml(self, indent = "")
Produce XML output for the profile
2.85605
2.590593
1.10247
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) args = [] if node.tag == 'profile': for node in node: if node.tag == 'input': for subnode in node: ...
def fromxml(node)
Return a profile instance from the given XML description. Node can be a string or an etree._Element.
2.460699
2.232366
1.102283
if isinstance(outputtemplate,OutputTemplate): outputtemplate = outputtemplate.id if isinstance(inputtemplate,InputTemplate): inputtemplate = inputtemplate.id if outputfilename in self: outputtemplate, inputfiles = self[outputfilename] if i...
def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None)
Add a new path to the program
2.249303
2.308512
0.974352
for outputfilename, outputtemplate in self.outputpairs(): yield CLAMOutputFile(self.projectpath, outputfilename, loadmetadata,client,requiremetadata), outputtemplate
def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False)
Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor.
15.174916
5.749013
2.639569
if isinstance(outputfile, CLAMOutputFile): outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'') else: outputfilename = outputfile outputtemplate, inputfiles = self[outputfilename] for inputfilename, inputtemplate in inputf...
def getinputfiles(self, outputfile, loadmetadata=True, client=None,requiremetadata=False)
Iterates over all input files for the specified outputfile (you may pass a CLAMOutputFile instance or a filename string). Yields (CLAMInputFile,str:inputtemplate_id) tuples. The last three arguments are passed to its constructor.
5.359953
3.457512
1.550234
if isinstance(outputfile, CLAMOutputFile): outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'') else: outputfilename = outputfile if outputfilename not in self: raise KeyError("No such outputfile " + outputfilename) ...
def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False)
Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()
4.08322
3.200267
1.2759
return next(self.getoutputfiles(loadmetadata,client,requiremetadata))
def getoutputfile(self, loadmetadata=True, client=None,requiremetadata=False)
Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()
6.441443
2.913139
2.21117
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 ...
def xml(self, indent = "")
Serialise provenance data to XML. This is included in CLAM Metadata files
3.402477
3.126628
1.088226
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) if node.tag == 'provenance': #pylint: disable=too-many-nested-blocks if node.attrib['type'] == 'clam': serviceid = node.attrib['id'] ...
def fromxml(node)
Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element.
2.861652
2.56119
1.117314
#(independent of web.py for support in CLAM API) 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=\""+...
def xml(self, indent = "")
Render an XML representation of the metadata
3.64791
3.463242
1.053322
with io.open(filename,'w',encoding='utf-8') as f: f.write(self.xml())
def save(self, filename)
Save metadata to XML file
3.476297
3.209659
1.083074
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) if node.tag == 'CLAMMetaData': dataformat = node.attrib['format'] formatclass = None for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be inje...
def fromxml(node, file=None)
Read metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element.
3.248089
2.939199
1.105093
xml = indent + "<InputTemplate id=\""+self.id+"\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\"" if self.formatclass.mimetype: xml +=" mimetype=\""+self.formatclass.mimetype+"\"" if self.formatclass.schema: xml +=" schema=\""+self...
def xml(self, indent = "")
Produce Template XML
2.305717
2.244693
1.027186
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:...
def json(self)
Produce a JSON representation for the web interface
3.935278
3.824797
1.028885
assert isinstance(metadata, self.formatclass) return self.generate(metadata,user)
def match(self, metadata, user = None)
Does the specified metadata match this template? returns (success,metadata,parameters)
15.011039
13.086278
1.147082
results = [] if projectpath[-1] == '/': inputpath = projectpath + 'input/' else: inputpath = projectpath + '/input/' for linkf,realf in clam.common.util.globsymlinks(inputpath + '/.*.INPUTTEMPLATE.' + self.id + '.*'): seqnr = int(linkf.split...
def matchingfiles(self, projectpath)
Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate).
6.191602
4.075521
1.519217
clam.common.util.printdebug("Validating inputtemplate " + self.id + "...") errors, parameters, _ = processparameters(postdata, self.parameters, user) return errors, parameters
def validate(self, postdata, user = None)
Validate posted data against the inputtemplate
21.27124
14.524565
1.464501
metadata = {} if not validatedata: assert inputdata errors, parameters = self.validate(inputdata,user) #pylint: disable=unused-variable else: errors, parameters = validatedata #pylint: disable=unused-variable #scan errors and set metadata ...
def generate(self, file, validatedata = None, inputdata=None, user = None)
Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters), error messages can be extracted from parameters[].error. Validatedata is a (errors,pa...
4.901037
3.890714
1.259675
xml = indent + "<meta id=\"" + self.key + "\"" if operator != 'set': xml += " operator=\"" + operator + "\"" if not self.value: xml += " />" else: xml += ">" + self.value + "</meta>" return xml
def xml(self, operator='set', indent = "")
Serialize the metadata field to XML
2.987231
2.542646
1.174851
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) if node.tag.lower() != 'meta': raise Exception("Expected meta tag but got '" + node.tag + "' instead") key = node.attrib['id'] if node.text: ...
def fromxml(node)
Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element.
2.998098
2.723884
1.10067
xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\"" if self.formatclass.mimetype: xml +=" mimetype=\""+self.formatclass.mimetype+"\"" if self.formatclass.schema: xml +=" schema=\""...
def xml(self, indent = "")
Produce Template XML
2.505612
2.420791
1.035039
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) assert node.tag.lower() == 'outputtemplate' template_id = node.attrib['id'] dataformat = node.attrib['format'] label = node.attrib['label'] kw...
def fromxml(node)
Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element.
3.144163
2.965037
1.060412
for inputtemplate in inputtemplates: if self.unique == inputtemplate.unique: return inputtemplate.id return None
def findparent(self, inputtemplates)
Find the most suitable parent, that is: the first matching unique/multi inputtemplate
4.59877
3.985895
1.153761
assert self.parent for inputtemplate in profile.input: if inputtemplate == self.parent: return inputtemplate raise Exception("Parent InputTemplate '"+self.parent+"' not found!")
def getparent(self, profile)
Resolve a parent ID
7.390945
7.800183
0.947535
project = os.path.basename(projectpath) if self.parent: #pylint: disable=too-many-nested-blocks #We have a parent, infer the correct filename #copy filename from parent parent = self.getparent(profile) #get input files for the parent InputTemp...
def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None)
Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples
4.133833
4.008675
1.031222
assert isinstance(provenancedata,CLAMProvenanceData) or provenancedata is None data = {} if self.copymetadata: #Copy parent metadata for key, value in parentfile.metadata.items(): data[key] = value for metafield in self.metafields: ...
def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None)
Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we copy from it)
4.40139
4.506439
0.976689
l = [] if isinstance(self.then, ParameterCondition): #recursive parametercondition l += self.then.allpossibilities() elif self.then: l.append(self.then) if self.otherwise: if isinstance(self.otherwise, ParameterCondition): ...
def allpossibilities(self)
Returns all possible outputtemplates that may occur (recusrively applied)
3.221691
2.917995
1.104077
if self.match(parameters): if isinstance(self.then, ParameterCondition): #recursive parametercondition return self.then.evaluate(parameters) else: return self.then elif self.otherwise: if isinstance(self.otherwi...
def evaluate(self, parameters)
Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!)
3.435333
2.334181
1.471751
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) assert node.tag.lower() == 'parametercondition' kwargs = {} found = False for node in node: if node.tag == 'if': #interpr...
def fromxml(node)
Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element.
3.930605
3.619839
1.085851
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) assert node.tag.lower() == 'action' kwargs = {} args = [] if 'id' in node.attrib: kwargs['id'] = node.attrib['id'] elif 'name' in ...
def fromxml(node)
Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element.
2.539384
2.430425
1.044831
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
def crude_tokenizer(line)
This is a very crude tokenizer from pynlpl
2.183307
2.139374
1.020536
if sort: f = lambda x: sorted(x, key=lambda y: -1 * y[1]) else: f = lambda x: x output = "" for i, (key, value) in enumerate(f(d.items())): output += key + "\t" + str(value) + "\n" if max != 0 and i >= max: break return output
def dicttotext(d, sort=False, max = 0)
Function for converting dictionary to plaintext output, optionally with some (reverse) sorting
2.315892
2.264006
1.022918