repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
epandurski/flask_signalbus
flask_signalbus/signalbus_cli.py
pending
def pending(): """Show the number of pending signals by signal type.""" 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))
python
def pending(): """Show the number of pending signals by signal type.""" 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))
[ "def", "pending", "(", ")", ":", "signalbus", "=", "current_app", ".", "extensions", "[", "'signalbus'", "]", "pending", "=", "[", "]", "total_pending", "=", "0", "for", "signal_model", "in", "signalbus", ".", "get_signal_models", "(", ")", ":", "count", "...
Show the number of pending signals by signal type.
[ "Show", "the", "number", "of", "pending", "signals", "by", "signal", "type", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L92-L109
train
52,000
inveniosoftware/invenio-iiif
invenio_iiif/tasks.py
create_thumbnail
def create_thumbnail(uuid, thumbnail_width): """Create the thumbnail for an image.""" # size = '!' + thumbnail_width + ',' size = thumbnail_width + ',' # flask_iiif doesn't support ! at the moment thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg')
python
def create_thumbnail(uuid, thumbnail_width): """Create the thumbnail for an image.""" # 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", ")", ":", "# size = '!' + thumbnail_width + ','", "size", "=", "thumbnail_width", "+", "','", "# flask_iiif doesn't support ! at the moment", "thumbnail", "=", "IIIFImageAPI", ".", "get", "(", "'v2'", ",", ...
Create the thumbnail for an image.
[ "Create", "the", "thumbnail", "for", "an", "image", "." ]
e4f2f93eaabdc8e2efea81c239ab76d481191959
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/tasks.py#L18-L22
train
52,001
kserhii/money-parser
money_parser/__init__.py
price_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 ValueError. Examples: 12.007 => 12007 00012,33 => 12.33 +1 => 1 - 520.05 => -520.05 1,000,777.5 => 1000777.5 1.777.000,99 => 1777000.99 1 234 567.89 => 1234567.89 99.77.11.000,1 => 997711000.1 NIO5,242 => 5242 Not a MINUS-.45 => 45 42 \t \n => 42 => <default> 1...2 => <default> :param str raw_price: string that contains price value. :param default: value that will be returned if raw price not valid. :param str dec_point: symbol that separate integer and fractional parts. :return: cleaned price string. :raise ValueError: error if raw price not valid and default value not set. """ 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")'.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] # clean truncated decimal (e.g. 99. -> 99) price = price.rstrip('.,') # get sign sign = '' if price[0] in {'-', '+'}: sign, price = price[0], price[1:] sign = '-' if sign == '-' else '' # extract fractional digits fractional = _FRACTIONAL_PRICE_RE.match(price) if fractional: integer, fraction = fractional.groups() else: integer, fraction = price, '' # leave only digits in the integer part of the price integer = re.sub('\D', '', integer) # remove leading zeros (e.g. 007 -> 7, but 0.1 -> 0.1) integer = integer.lstrip('0') if integer == '': integer = '0' # construct price price = sign + integer if fraction: price = ''.join((price, dec_point, fraction)) return price
python
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 ValueError. Examples: 12.007 => 12007 00012,33 => 12.33 +1 => 1 - 520.05 => -520.05 1,000,777.5 => 1000777.5 1.777.000,99 => 1777000.99 1 234 567.89 => 1234567.89 99.77.11.000,1 => 997711000.1 NIO5,242 => 5242 Not a MINUS-.45 => 45 42 \t \n => 42 => <default> 1...2 => <default> :param str raw_price: string that contains price value. :param default: value that will be returned if raw price not valid. :param str dec_point: symbol that separate integer and fractional parts. :return: cleaned price string. :raise ValueError: error if raw price not valid and default value not set. """ 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")'.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] # clean truncated decimal (e.g. 99. -> 99) price = price.rstrip('.,') # get sign sign = '' if price[0] in {'-', '+'}: sign, price = price[0], price[1:] sign = '-' if sign == '-' else '' # extract fractional digits fractional = _FRACTIONAL_PRICE_RE.match(price) if fractional: integer, fraction = fractional.groups() else: integer, fraction = price, '' # leave only digits in the integer part of the price integer = re.sub('\D', '', integer) # remove leading zeros (e.g. 007 -> 7, but 0.1 -> 0.1) integer = integer.lstrip('0') if integer == '': integer = '0' # construct price price = sign + integer if fraction: price = ''.join((price, dec_point, fraction)) return price
[ "def", "price_str", "(", "raw_price", ",", "default", "=", "_not_defined", ",", "dec_point", "=", "'.'", ")", ":", "def", "_error_or_default", "(", "err_msg", ")", ":", "if", "default", "==", "_not_defined", ":", "raise", "ValueError", "(", "err_msg", ")", ...
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 ValueError. Examples: 12.007 => 12007 00012,33 => 12.33 +1 => 1 - 520.05 => -520.05 1,000,777.5 => 1000777.5 1.777.000,99 => 1777000.99 1 234 567.89 => 1234567.89 99.77.11.000,1 => 997711000.1 NIO5,242 => 5242 Not a MINUS-.45 => 45 42 \t \n => 42 => <default> 1...2 => <default> :param str raw_price: string that contains price value. :param default: value that will be returned if raw price not valid. :param str dec_point: symbol that separate integer and fractional parts. :return: cleaned price string. :raise ValueError: error if raw price not valid and default value not set.
[ "Search", "and", "clean", "price", "value", "." ]
d02da58eb3065c55b73c9a7e601ffb3e1448bcd1
https://github.com/kserhii/money-parser/blob/d02da58eb3065c55b73c9a7e601ffb3e1448bcd1/money_parser/__init__.py#L15-L101
train
52,002
kserhii/money-parser
money_parser/__init__.py
price_dec
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: string that contains price value. :param default: value that will be returned if raw price not valid. :return: Decimal price value. :raise ValueError: error if raw price not valid and default value not set. """ try: price = price_str(raw_price) return decimal.Decimal(price) except ValueError as err: if default == _not_defined: raise err return default
python
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: string that contains price value. :param default: value that will be returned if raw price not valid. :return: Decimal price value. :raise ValueError: error if raw price not valid and default value not set. """ 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", ")", ":", "try", ":", "price", "=", "price_str", "(", "raw_price", ")", "return", "decimal", ".", "Decimal", "(", "price", ")", "except", "ValueError", "as", "err", ":", "if", "de...
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: string that contains price value. :param default: value that will be returned if raw price not valid. :return: Decimal price value. :raise ValueError: error if raw price not valid and default value not set.
[ "Price", "decimal", "value", "from", "raw", "string", "." ]
d02da58eb3065c55b73c9a7e601ffb3e1448bcd1
https://github.com/kserhii/money-parser/blob/d02da58eb3065c55b73c9a7e601ffb3e1448bcd1/money_parser/__init__.py#L104-L127
train
52,003
paksu/pytelegraf
telegraf/client.py
ClientBase.metric
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 """ 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 send it to socket line = Line(measurement_name, values, all_tags, timestamp) self.send(line.to_line_protocol())
python
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 """ 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 send it to socket line = Line(measurement_name, values, all_tags, timestamp) self.send(line.to_line_protocol())
[ "def", "metric", "(", "self", ",", "measurement_name", ",", "values", ",", "tags", "=", "None", ",", "timestamp", "=", "None", ")", ":", "if", "not", "measurement_name", "or", "values", "in", "(", "None", ",", "{", "}", ")", ":", "# Don't try to send emp...
Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket
[ "Append", "global", "tags", "configured", "for", "the", "client", "to", "the", "tags", "given", "then", "converts", "the", "data", "into", "InfluxDB", "Line", "protocol", "and", "sends", "to", "to", "socket" ]
a5a326bd99902768be2bf10da7dde2dfa165c013
https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/client.py#L13-L29
train
52,004
paksu/pytelegraf
telegraf/client.py
TelegrafClient.send
def send(self, data): """ Sends the given data to the socket via UDP """ 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
python
def send(self, data): """ Sends the given data to the socket via UDP """ 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", ")", ":", "try", ":", "self", ".", "socket", ".", "sendto", "(", "data", ".", "encode", "(", "'utf8'", ")", "+", "b'\\n'", ",", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "except", "("...
Sends the given data to the socket via UDP
[ "Sends", "the", "given", "data", "to", "the", "socket", "via", "UDP" ]
a5a326bd99902768be2bf10da7dde2dfa165c013
https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/client.py#L44-L52
train
52,005
paksu/pytelegraf
telegraf/client.py
HttpClient.send
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. """ self.future_session.post(url=self.url, data=data)
python
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. """ self.future_session.post(url=self.url, data=data)
[ "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.
[ "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", "." ]
a5a326bd99902768be2bf10da7dde2dfa165c013
https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/client.py#L73-L79
train
52,006
paksu/pytelegraf
telegraf/protocol.py
Line.to_line_protocol
def to_line_protocol(self): """ Converts the given metrics as a single line of InfluxDB line protocol """ 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() )
python
def to_line_protocol(self): """ Converts the given metrics as a single line of InfluxDB line protocol """ 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", ")", ":", "tags", "=", "self", ".", "get_output_tags", "(", ")", "return", "u\"{0}{1} {2}{3}\"", ".", "format", "(", "self", ".", "get_output_measurement", "(", ")", ",", "\",\"", "+", "tags", "if", "tags", "else", "...
Converts the given metrics as a single line of InfluxDB line protocol
[ "Converts", "the", "given", "metrics", "as", "a", "single", "line", "of", "InfluxDB", "line", "protocol" ]
a5a326bd99902768be2bf10da7dde2dfa165c013
https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/protocol.py#L66-L77
train
52,007
paksu/pytelegraf
telegraf/utils.py
format_string
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 not be surrounded in quotes. """ if isinstance(key, basestring): key = key.replace(",", "\,") key = key.replace(" ", "\ ") key = key.replace("=", "\=") return key
python
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 not be surrounded in quotes. """ if isinstance(key, basestring): key = key.replace(",", "\,") key = key.replace(" ", "\ ") key = key.replace("=", "\=") return key
[ "def", "format_string", "(", "key", ")", ":", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "key", "=", "key", ".", "replace", "(", "\",\"", ",", "\"\\,\"", ")", "key", "=", "key", ".", "replace", "(", "\" \"", ",", "\"\\ \"", ")", "...
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 not be surrounded in quotes.
[ "Formats", "either", "measurement", "names", "tag", "names", "or", "tag", "values", "." ]
a5a326bd99902768be2bf10da7dde2dfa165c013
https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/utils.py#L8-L22
train
52,008
tomduck/pandoc-eqnos
pandoc_eqnos.py
_process_equation
def _process_equation(value, fmt): """Processes the equation. Returns a dict containing eq properties.""" # 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': False, 'attrs': attrs} # Bail out if the label does not conform if not LABEL_PATTERN.match(attrs[0]): eq['is_unnumbered'] = True eq['is_unreferenceable'] = True return eq # Process unreferenceable equations if attrs[0] == 'eq:': # Make up a unique description attrs[0] = attrs[0] + str(uuid.uuid4()) eq['is_unreferenceable'] = True unreferenceable.append(attrs[0]) # For html, hard-code in the section numbers as tags 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 # Save to the global references tracker eq['is_tagged'] = 'tag' in kvs if eq['is_tagged']: # Remove any surrounding quotes 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 # Adjust equation depending on the output format if fmt in ['latex', 'beamer']: if not eq['is_unreferenceable']: # Code in the tags 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 # Insert html in process_equations() instead else: # Hard-code in the number/tag if isinstance(references[attrs[0]], int): # Numbered reference value[-1] += r'\qquad (%d)' % references[attrs[0]] else: # Tagged reference assert isinstance(references[attrs[0]], STRTYPES) text = references[attrs[0]].replace(' ', r'\ ') if text.startswith('$') and text.endswith('$'): # Math tag = text[1:-1] else: # Text tag = r'\text{%s}' % text value[-1] += r'\qquad (%s)' % tag return eq
python
def _process_equation(value, fmt): """Processes the equation. Returns a dict containing eq properties.""" # 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': False, 'attrs': attrs} # Bail out if the label does not conform if not LABEL_PATTERN.match(attrs[0]): eq['is_unnumbered'] = True eq['is_unreferenceable'] = True return eq # Process unreferenceable equations if attrs[0] == 'eq:': # Make up a unique description attrs[0] = attrs[0] + str(uuid.uuid4()) eq['is_unreferenceable'] = True unreferenceable.append(attrs[0]) # For html, hard-code in the section numbers as tags 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 # Save to the global references tracker eq['is_tagged'] = 'tag' in kvs if eq['is_tagged']: # Remove any surrounding quotes 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 # Adjust equation depending on the output format if fmt in ['latex', 'beamer']: if not eq['is_unreferenceable']: # Code in the tags 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 # Insert html in process_equations() instead else: # Hard-code in the number/tag if isinstance(references[attrs[0]], int): # Numbered reference value[-1] += r'\qquad (%d)' % references[attrs[0]] else: # Tagged reference assert isinstance(references[attrs[0]], STRTYPES) text = references[attrs[0]].replace(' ', r'\ ') if text.startswith('$') and text.endswith('$'): # Math tag = text[1:-1] else: # Text tag = r'\text{%s}' % text value[-1] += r'\qquad (%s)' % tag return eq
[ "def", "_process_equation", "(", "value", ",", "fmt", ")", ":", "# pylint: disable=global-statement", "global", "Nreferences", "# Global references counter", "global", "cursec", "# Current section", "# Parse the equation", "attrs", "=", "value", "[", "0", "]", "# Initiali...
Processes the equation. Returns a dict containing eq properties.
[ "Processes", "the", "equation", ".", "Returns", "a", "dict", "containing", "eq", "properties", "." ]
a0e2b5684d2024ea96049ed2cff3acf4ab47c541
https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L84-L154
train
52,009
tomduck/pandoc-eqnos
pandoc_eqnos.py
process_equations
def process_equations(key, value, fmt, meta): """Processes the attributed equations.""" 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 function # Context-dependent output if eq['is_unnumbered']: # Unnumbered is also unreferenceable 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): # Present equation and its number in a span 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': # As per http://officeopenxml.com/WPhyperlink.php 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
python
def process_equations(key, value, fmt, meta): """Processes the attributed equations.""" 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 function # Context-dependent output if eq['is_unnumbered']: # Unnumbered is also unreferenceable 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): # Present equation and its number in a span 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': # As per http://officeopenxml.com/WPhyperlink.php 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
[ "def", "process_equations", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "if", "key", "==", "'Math'", "and", "len", "(", "value", ")", "==", "3", ":", "# Process the equation", "eq", "=", "_process_equation", "(", "value", ",", "fmt", "...
Processes the attributed equations.
[ "Processes", "the", "attributed", "equations", "." ]
a0e2b5684d2024ea96049ed2cff3acf4ab47c541
https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L158-L208
train
52,010
tomduck/pandoc-eqnos
pandoc_eqnos.py
process
def process(meta): """Saves metadata fields in global variables and returns a few computed fields.""" # 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 cleveref in all 3 of fignos/eqnos/tablenos # 'cleveref' is deprecated 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']: # 'eqnos-capitalise' is an alternative spelling # 'xnos-capitalise' enables capitalise in all 3 of fignos/eqnos/tablenos # 'xnos-capitalize' is an alternative spelling 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'))
python
def process(meta): """Saves metadata fields in global variables and returns a few computed fields.""" # 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 cleveref in all 3 of fignos/eqnos/tablenos # 'cleveref' is deprecated 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']: # 'eqnos-capitalise' is an alternative spelling # 'xnos-capitalise' enables capitalise in all 3 of fignos/eqnos/tablenos # 'xnos-capitalize' is an alternative spelling 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'))
[ "def", "process", "(", "meta", ")", ":", "# 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", ...
Saves metadata fields in global variables and returns a few computed fields.
[ "Saves", "metadata", "fields", "in", "global", "variables", "and", "returns", "a", "few", "computed", "fields", "." ]
a0e2b5684d2024ea96049ed2cff3acf4ab47c541
https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L213-L263
train
52,011
nedbat/django_coverage_plugin
django_coverage_plugin/plugin.py
check_debug
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 """ 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 # django.template.backends.django gets loaded lazily, so return false # until they've been loaded 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
python
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 """ 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 # django.template.backends.django gets loaded lazily, so return false # until they've been loaded 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
[ "def", "check_debug", "(", ")", ":", "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 clea...
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
[ "Check", "that", "Django", "s", "template", "debugging", "is", "enabled", "." ]
0072737c0ea5a1ca6b9f046af4947de191f13804
https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L50-L89
train
52,012
nedbat/django_coverage_plugin
django_coverage_plugin/plugin.py
read_template_source
def read_template_source(filename): """Read the source of a Django template, returning the Unicode text.""" # 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
python
def read_template_source(filename): """Read the source of a Django template, returning the Unicode text.""" # 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", ")", ":", "# 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...
Read the source of a Django template, returning the Unicode text.
[ "Read", "the", "source", "of", "a", "Django", "template", "returning", "the", "Unicode", "text", "." ]
0072737c0ea5a1ca6b9f046af4947de191f13804
https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L127-L139
train
52,013
nedbat/django_coverage_plugin
django_coverage_plugin/plugin.py
get_line_number
def get_line_number(line_map, offset): """Find a line number, given a line map and a character offset.""" for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1
python
def get_line_number(line_map, offset): """Find a line number, given a line map and a character offset.""" 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", ")", ":", "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.
[ "Find", "a", "line", "number", "given", "a", "line", "map", "and", "a", "character", "offset", "." ]
0072737c0ea5a1ca6b9f046af4947de191f13804
https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L389-L394
train
52,014
nedbat/django_coverage_plugin
django_coverage_plugin/plugin.py
dump_frame
def dump_frame(frame, label=""): """Dump interesting information about this frame.""" 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("\\--")
python
def dump_frame(frame, label=""): """Dump interesting information about this frame.""" 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("\\--")
[ "def", "dump_frame", "(", "frame", ",", "label", "=", "\"\"", ")", ":", "locals", "=", "dict", "(", "frame", ".", "f_locals", ")", "self", "=", "locals", ".", "get", "(", "'self'", ",", "None", ")", "context", "=", "locals", ".", "get", "(", "'cont...
Dump interesting information about this frame.
[ "Dump", "interesting", "information", "about", "this", "frame", "." ]
0072737c0ea5a1ca6b9f046af4947de191f13804
https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L397-L418
train
52,015
nedbat/django_coverage_plugin
django_coverage_plugin/plugin.py
DjangoTemplatePlugin.get_line_map
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. """ 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_map[filename] = make_line_map(template_source) return self.source_map[filename]
python
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. """ 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_map[filename] = make_line_map(template_source) return self.source_map[filename]
[ "def", "get_line_map", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "source_map", ":", "template_source", "=", "read_template_source", "(", "filename", ")", "if", "0", ":", "# change to see the template text", "for", "i", ...
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.
[ "The", "line", "map", "for", "filename", "." ]
0072737c0ea5a1ca6b9f046af4947de191f13804
https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L256-L274
train
52,016
dylanaraps/bum
bum/display.py
init
def init(size=250): """Initialize mpv.""" 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
python
def init(size=250): """Initialize mpv.""" 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", ")", ":", "player", "=", "mpv", ".", "MPV", "(", "start_event_thread", "=", "False", ")", "player", "[", "\"force-window\"", "]", "=", "\"immediate\"", "player", "[", "\"keep-open\"", "]", "=", "\"yes\"", "player", ...
Initialize mpv.
[ "Initialize", "mpv", "." ]
004d795a67398e79f2c098d7775e9cd97231646b
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/display.py#L7-L16
train
52,017
dylanaraps/bum
bum/util.py
bytes_to_file
def bytes_to_file(input_data, output_file): """Save bytes to a file.""" pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True) with open(output_file, "wb") as file: file.write(input_data)
python
def bytes_to_file(input_data, output_file): """Save bytes to a file.""" 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", ")", ":", "pathlib", ".", "Path", "(", "output_file", ".", "parent", ")", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "output_file", ","...
Save bytes to a file.
[ "Save", "bytes", "to", "a", "file", "." ]
004d795a67398e79f2c098d7775e9cd97231646b
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/util.py#L7-L12
train
52,018
dylanaraps/bum
bum/song.py
init
def init(port=6600, server="localhost"): """Initialize mpd.""" client = mpd.MPDClient() try: client.connect(server, port) return client except ConnectionRefusedError: print("error: Connection refused to mpd/mopidy.") os._exit(1)
python
def init(port=6600, server="localhost"): """Initialize mpd.""" 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\"", ")", ":", "client", "=", "mpd", ".", "MPDClient", "(", ")", "try", ":", "client", ".", "connect", "(", "server", ",", "port", ")", "return", "client", "except", "ConnectionRe...
Initialize mpd.
[ "Initialize", "mpd", "." ]
004d795a67398e79f2c098d7775e9cd97231646b
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/song.py#L12-L22
train
52,019
dylanaraps/bum
bum/song.py
get_art
def get_art(cache_dir, size, client): """Get the album art.""" 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']}.")
python
def get_art(cache_dir, size, client): """Get the album art.""" 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']}.")
[ "def", "get_art", "(", "cache_dir", ",", "size", ",", "client", ")", ":", "song", "=", "client", ".", "currentsong", "(", ")", "if", "len", "(", "song", ")", "<", "2", ":", "print", "(", "\"album: Nothing currently playing.\"", ")", "return", "file_name", ...
Get the album art.
[ "Get", "the", "album", "art", "." ]
004d795a67398e79f2c098d7775e9cd97231646b
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/song.py#L25-L50
train
52,020
dylanaraps/bum
bum/brainz.py
get_cover
def get_cover(song, size=250): """Download the cover art.""" 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']}")
python
def get_cover(song, size=250): """Download the cover art.""" 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']}")
[ "def", "get_cover", "(", "song", ",", "size", "=", "250", ")", ":", "try", ":", "data", "=", "mus", ".", "search_releases", "(", "artist", "=", "song", "[", "\"artist\"", "]", ",", "release", "=", "song", "[", "\"album\"", "]", ",", "limit", "=", "...
Download the cover art.
[ "Download", "the", "cover", "art", "." ]
004d795a67398e79f2c098d7775e9cd97231646b
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/brainz.py#L16-L32
train
52,021
proycon/clam
clam/common/converters.py
AbstractConverter.convertforinput
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!""" 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__ + "!") return False
python
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!""" 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__ + "!") return False
[ "def", "convertforinput", "(", "self", ",", "filepath", ",", "metadata", ")", ":", "assert", "isinstance", "(", "metadata", ",", "CLAMMetaData", ")", "#metadata of the destination file (file to be generated here)", "if", "not", "metadata", ".", "__class__", "in", "sel...
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!
[ "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",...
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L37-L42
train
52,022
proycon/clam
clam/common/converters.py
AbstractConverter.convertforoutput
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.""" 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.__class__.__name__ + "!") return []
python
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.""" 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.__class__.__name__ + "!") return []
[ "def", "convertforoutput", "(", "self", ",", "outputfile", ")", ":", "assert", "isinstance", "(", "outputfile", ",", "CLAMOutputFile", ")", "#metadata of the destination file (file to be generated here)", "if", "not", "outputfile", ".", "metadata", ".", "__class__", "in...
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance.
[ "Convert", "from", "one", "of", "the", "source", "formats", "into", "target", "format", ".", "Relevant", "if", "converters", "are", "used", "in", "OutputTemplates", ".", "Sourcefile", "is", "a", "CLAMOutputFile", "instance", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L44-L49
train
52,023
proycon/clam
clam/common/converters.py
CharEncodingConverter.convertforinput
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.""" 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
python
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.""" 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
[ "def", "convertforinput", "(", "self", ",", "filepath", ",", "metadata", "=", "None", ")", ":", "super", "(", "CharEncodingConverter", ",", "self", ")", ".", "convertforinput", "(", "filepath", ",", "metadata", ")", "shutil", ".", "copy", "(", "filepath", ...
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.
[ "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",...
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L71-L90
train
52,024
proycon/clam
clam/common/converters.py
CharEncodingConverter.convertforoutput
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.""" super(CharEncodingConverter,self).convertforoutput(outputfile) return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , 'text/plain; charset=' + self.charset)
python
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.""" 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", ")", ":", "super", "(", "CharEncodingConverter", ",", "self", ")", ".", "convertforoutput", "(", "outputfile", ")", "return", "withheaders", "(", "flask", ".", "make_response", "(", "(", "line", ".", ...
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance.
[ "Convert", "from", "one", "of", "the", "source", "formats", "into", "target", "format", ".", "Relevant", "if", "converters", "are", "used", "in", "OutputTemplates", ".", "Outputfile", "is", "a", "CLAMOutputFile", "instance", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L93-L97
train
52,025
proycon/clam
clam/common/data.py
getclamdata
def getclamdata(filename, custom_formats=None): global CUSTOM_FORMATS #pylint: disable=global-statement """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. """ 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)
python
def getclamdata(filename, custom_formats=None): global CUSTOM_FORMATS #pylint: disable=global-statement """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. """ 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", ")", ":", "global", "CUSTOM_FORMATS", "#pylint: disable=global-statement", "f", "=", "io", ".", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "xml", "=", ...
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.
[ "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", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L379-L391
train
52,026
proycon/clam
clam/common/data.py
sanitizeparameters
def sanitizeparameters(parameters): """Construct a dictionary of parameters, for internal use only""" 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
python
def sanitizeparameters(parameters): """Construct a dictionary of parameters, for internal use only""" 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
[ "def", "sanitizeparameters", "(", "parameters", ")", ":", "if", "not", "isinstance", "(", "parameters", ",", "dict", ")", ":", "d", "=", "{", "}", "for", "x", "in", "parameters", ":", "if", "isinstance", "(", "x", ",", "tuple", ")", "and", "len", "("...
Construct a dictionary of parameters, for internal use only
[ "Construct", "a", "dictionary", "of", "parameters", "for", "internal", "use", "only" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L773-L785
train
52,027
proycon/clam
clam/common/data.py
CLAMFile.loadmetadata
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.""" 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 #parse metadata try: self.metadata = CLAMMetaData.fromxml(xml, self) #returns CLAMMetaData object (or child thereof) except ElementTree.XMLSyntaxError: raise ValueError("Metadata is not XML! Contents: " + xml)
python
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.""" 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 #parse metadata try: self.metadata = CLAMMetaData.fromxml(xml, self) #returns CLAMMetaData object (or child thereof) except ElementTree.XMLSyntaxError: raise ValueError("Metadata is not XML! Contents: " + xml)
[ "def", "loadmetadata", "(", "self", ")", ":", "if", "not", "self", ".", "remote", ":", "metafile", "=", "self", ".", "projectpath", "+", "self", ".", "basedir", "+", "'/'", "+", "self", ".", "metafilename", "(", ")", "if", "os", ".", "path", ".", "...
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.
[ "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...
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L237-L264
train
52,028
proycon/clam
clam/common/data.py
CLAMFile.delete
def delete(self): """Delete this file""" 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.projectpath + self.basedir + '/' + self.metafilename() if os.path.exists(metafile): os.unlink(metafile) #also remove any .*.INPUTTEMPLATE.* links that pointed to this file: simply remove all dead links 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
python
def delete(self): """Delete this file""" 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.projectpath + self.basedir + '/' + self.metafilename() if os.path.exists(metafile): os.unlink(metafile) #also remove any .*.INPUTTEMPLATE.* links that pointed to this file: simply remove all dead links 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
[ "def", "delete", "(", "self", ")", ":", "if", "not", "self", ".", "remote", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "projectpath", "+", "self", ".", "basedir", "+", "'/'", "+", "self", ".", "filename", ")", ":", "ret...
Delete this file
[ "Delete", "this", "file" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L300-L325
train
52,029
proycon/clam
clam/common/data.py
CLAMFile.read
def read(self): """Loads all lines in memory""" 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)
python
def read(self): """Loads all lines in memory""" 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)
[ "def", "read", "(", "self", ")", ":", "lines", "=", "self", ".", "readlines", "(", ")", "if", "self", ".", "metadata", "and", "'encoding'", "in", "self", ".", "metadata", ":", "encoding", "=", "self", ".", "metadata", "[", "'encoding'", "]", "else", ...
Loads all lines in memory
[ "Loads", "all", "lines", "in", "memory" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L332-L342
train
52,030
proycon/clam
clam/common/data.py
CLAMFile.copy
def copy(self, target, timeout=500): """Copy or download this file to a new local file""" 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): #pylint: disable=undefined-variable f.write(line.encode('utf-8')) elif sys.version >= '3' and isinstance(line,str): f.write(line.encode('utf-8')) else: f.write(line)
python
def copy(self, target, timeout=500): """Copy or download this file to a new local file""" 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): #pylint: disable=undefined-variable f.write(line.encode('utf-8')) elif sys.version >= '3' and isinstance(line,str): f.write(line.encode('utf-8')) else: f.write(line)
[ "def", "copy", "(", "self", ",", "target", ",", "timeout", "=", "500", ")", ":", "if", "self", ".", "metadata", "and", "'encoding'", "in", "self", ".", "metadata", ":", "with", "io", ".", "open", "(", "target", ",", "'w'", ",", "encoding", "=", "se...
Copy or download this file to a new local file
[ "Copy", "or", "download", "this", "file", "to", "a", "new", "local", "file" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L345-L360
train
52,031
proycon/clam
clam/common/data.py
CLAMData.outputtemplate
def outputtemplate(self, template_id): """Get an output template by 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")
python
def outputtemplate(self, template_id): """Get an output template by 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")
[ "def", "outputtemplate", "(", "self", ",", "template_id", ")", ":", "for", "profile", "in", "self", ".", "profiles", ":", "for", "outputtemplate", "in", "profile", ".", "outputtemplates", "(", ")", ":", "if", "outputtemplate", ".", "id", "==", "template_id",...
Get an output template by ID
[ "Get", "an", "output", "template", "by", "ID" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L656-L662
train
52,032
proycon/clam
clam/common/data.py
CLAMData.commandlineargs
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.""" 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(commandlineargs)
python
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.""" 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(commandlineargs)
[ "def", "commandlineargs", "(", "self", ")", ":", "commandlineargs", "=", "[", "]", "for", "parametergroup", ",", "parameters", "in", "self", ".", "parameters", ":", "#pylint: disable=unused-variable", "for", "parameter", "in", "parameters", ":", "p", "=", "param...
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.
[ "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", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L665-L673
train
52,033
proycon/clam
clam/common/data.py
CLAMData.parametererror
def parametererror(self): """Return the first parameter error, or False if there is none""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.error: return parameter.error return False
python
def parametererror(self): """Return the first parameter error, or False if there is none""" 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", ")", ":", "for", "parametergroup", ",", "parameters", "in", "self", ".", "parameters", ":", "#pylint: disable=unused-variable", "for", "parameter", "in", "parameters", ":", "if", "parameter", ".", "error", ":", "return", "pa...
Return the first parameter error, or False if there is none
[ "Return", "the", "first", "parameter", "error", "or", "False", "if", "there", "is", "none" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L714-L720
train
52,034
proycon/clam
clam/common/data.py
CLAMData.inputtemplate
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""" 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))
python
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""" 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", ")", ":", "for", "profile", "in", "self", ".", "profiles", ":", "for", "inputtemplate", "in", "profile", ".", "input", ":", "if", "inputtemplate", ".", "id", "==", "template_id", ":", "return", "inpu...
Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance
[ "Return", "the", "inputtemplate", "with", "the", "specified", "ID", ".", "This", "is", "used", "to", "resolve", "a", "inputtemplate", "ID", "to", "an", "InputTemplate", "object", "instance" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L742-L748
train
52,035
proycon/clam
clam/common/data.py
CLAMData.inputfiles
def inputfiles(self, inputtemplate=None): """Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate.""" if isinstance(inputtemplate, InputTemplate): #ID suffices: inputtemplate = inputtemplate.id for inputfile in self.input: if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate: yield inputfile
python
def inputfiles(self, inputtemplate=None): """Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate.""" 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", ")", ":", "if", "isinstance", "(", "inputtemplate", ",", "InputTemplate", ")", ":", "#ID suffices:", "inputtemplate", "=", "inputtemplate", ".", "id", "for", "inputfile", "in", "self", ".", ...
Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate.
[ "Generator", "yielding", "all", "inputfiles", "for", "the", "specified", "inputtemplate", "if", "inputtemplate", "=", "None", "inputfiles", "are", "returned", "regardless", "of", "inputtemplate", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L764-L771
train
52,036
proycon/clam
clam/common/data.py
Profile.outputtemplates
def outputtemplates(self): """Returns all outputtemplates, resolving ParameterConditions to all possibilities""" outputtemplates = [] for o in self.output: if isinstance(o, ParameterCondition): outputtemplates += o.allpossibilities() else: assert isinstance(o, OutputTemplate) outputtemplates.append(o) return outputtemplates
python
def outputtemplates(self): """Returns all outputtemplates, resolving ParameterConditions to all possibilities""" 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", ")", ":", "outputtemplates", "=", "[", "]", "for", "o", "in", "self", ".", "output", ":", "if", "isinstance", "(", "o", ",", "ParameterCondition", ")", ":", "outputtemplates", "+=", "o", ".", "allpossibilities", "(", ...
Returns all outputtemplates, resolving ParameterConditions to all possibilities
[ "Returns", "all", "outputtemplates", "resolving", "ParameterConditions", "to", "all", "possibilities" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L898-L907
train
52,037
proycon/clam
clam/common/data.py
Profile.generate
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. """ #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 #gather all input files that match inputfiles = self.matchingfiles(projectpath) #list of (seqnr, filename,inputtemplate) tuples inputfiles_full = [] #We need the full CLAMInputFiles for generating provenance data for seqnr, filename, inputtemplate in inputfiles: #pylint: disable=unused-variable inputfiles_full.append(CLAMInputFile(projectpath, filename)) for outputtemplate in self.output: if isinstance(outputtemplate, ParameterCondition): outputtemplate = outputtemplate.evaluate(parameters) #generate output files if outputtemplate: if isinstance(outputtemplate, OutputTemplate): #generate provenance data 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
python
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. """ #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 #gather all input files that match inputfiles = self.matchingfiles(projectpath) #list of (seqnr, filename,inputtemplate) tuples inputfiles_full = [] #We need the full CLAMInputFiles for generating provenance data for seqnr, filename, inputtemplate in inputfiles: #pylint: disable=unused-variable inputfiles_full.append(CLAMInputFile(projectpath, filename)) for outputtemplate in self.output: if isinstance(outputtemplate, ParameterCondition): outputtemplate = outputtemplate.evaluate(parameters) #generate output files if outputtemplate: if isinstance(outputtemplate, OutputTemplate): #generate provenance data 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
[ "def", "generate", "(", "self", ",", "projectpath", ",", "parameters", ",", "serviceid", ",", "servicename", ",", "serviceurl", ")", ":", "#Make dictionary of parameters", "parameters", "=", "sanitizeparameters", "(", "parameters", ")", "program", "=", "Program", ...
Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance.
[ "Generate", "output", "metadata", "on", "the", "basis", "of", "input", "files", "and", "parameters", ".", "Projectpath", "must", "be", "absolute", ".", "Returns", "a", "Program", "instance", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L910-L956
train
52,038
proycon/clam
clam/common/data.py
Profile.xml
def xml(self, indent = ""): """Produce XML output for the profile""" 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" #works for ParameterCondition as well! xml += indent + " </output>\n" xml += indent + "</profile>\n" return xml
python
def xml(self, indent = ""): """Produce XML output for the profile""" 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" #works for ParameterCondition as well! xml += indent + " </output>\n" xml += indent + "</profile>\n" return xml
[ "def", "xml", "(", "self", ",", "indent", "=", "\"\"", ")", ":", "xml", "=", "\"\\n\"", "+", "indent", "+", "\"<profile>\\n\"", "xml", "+=", "indent", "+", "\" <input>\\n\"", "for", "inputtemplate", "in", "self", ".", "input", ":", "xml", "+=", "inputtem...
Produce XML output for the profile
[ "Produce", "XML", "output", "for", "the", "profile" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L959-L971
train
52,039
proycon/clam
clam/common/data.py
Profile.fromxml
def fromxml(node): """Return a profile instance from the given XML description. Node can be a string or an etree._Element.""" 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: 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)
python
def fromxml(node): """Return a profile instance from the given XML description. Node can be a string or an etree._Element.""" 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: 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)
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "args", "=", "[", "]", "if", "node", ".", ...
Return a profile instance from the given XML description. Node can be a string or an etree._Element.
[ "Return", "a", "profile", "instance", "from", "the", "given", "XML", "description", ".", "Node", "can", "be", "a", "string", "or", "an", "etree", ".", "_Element", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L985-L1004
train
52,040
proycon/clam
clam/common/data.py
Program.add
def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None): """Add a new path to the program""" 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, {})
python
def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None): """Add a new path to the program""" 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, {})
[ "def", "add", "(", "self", ",", "outputfilename", ",", "outputtemplate", ",", "inputfilename", "=", "None", ",", "inputtemplate", "=", "None", ")", ":", "if", "isinstance", "(", "outputtemplate", ",", "OutputTemplate", ")", ":", "outputtemplate", "=", "outputt...
Add a new path to the program
[ "Add", "a", "new", "path", "to", "the", "program" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1023-L1037
train
52,041
proycon/clam
clam/common/data.py
CLAMProvenanceData.xml
def xml(self, indent = ""): """Serialise provenance data to XML. This is included in CLAM Metadata files""" 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
python
def xml(self, indent = ""): """Serialise provenance data to XML. This is included in CLAM Metadata files""" 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
[ "def", "xml", "(", "self", ",", "indent", "=", "\"\"", ")", ":", "xml", "=", "indent", "+", "\"<provenance type=\\\"clam\\\" id=\\\"\"", "+", "self", ".", "serviceid", "+", "\"\\\" name=\\\"\"", "+", "self", ".", "servicename", "+", "\"\\\" url=\\\"\"", "+", "...
Serialise provenance data to XML. This is included in CLAM Metadata files
[ "Serialise", "provenance", "data", "to", "XML", ".", "This", "is", "included", "in", "CLAM", "Metadata", "files" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1123-L1140
train
52,042
proycon/clam
clam/common/data.py
CLAMProvenanceData.fromxml
def fromxml(node): """Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element.""" 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'] 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
python
def fromxml(node): """Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element.""" 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'] 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
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "if", "node", ".", "tag", "==", "'provenance...
Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element.
[ "Return", "a", "CLAMProvenanceData", "instance", "from", "the", "given", "XML", "description", ".", "Node", "can", "be", "a", "string", "or", "an", "lxml", ".", "etree", ".", "_Element", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1143-L1174
train
52,043
proycon/clam
clam/common/data.py
CLAMMetaData.xml
def xml(self, indent = ""): """Render an XML representation of the metadata""" #(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=\""+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
python
def xml(self, indent = ""): """Render an XML representation of the metadata""" #(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=\""+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
[ "def", "xml", "(", "self", ",", "indent", "=", "\"\"", ")", ":", "#(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", ...
Render an XML representation of the metadata
[ "Render", "an", "XML", "representation", "of", "the", "metadata" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1283-L1305
train
52,044
proycon/clam
clam/common/data.py
CLAMMetaData.save
def save(self, filename): """Save metadata to XML file""" with io.open(filename,'w',encoding='utf-8') as f: f.write(self.xml())
python
def save(self, filename): """Save metadata to XML file""" with io.open(filename,'w',encoding='utf-8') as f: f.write(self.xml())
[ "def", "save", "(", "self", ",", "filename", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "xml", "(", ")", ")" ]
Save metadata to XML file
[ "Save", "metadata", "to", "XML", "file" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1307-L1310
train
52,045
proycon/clam
clam/common/data.py
InputTemplate.json
def json(self): """Produce a JSON representation for the web interface""" 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 #d['parameters'] = {} #The actual parameters are included as XML, and transformed by clam.js using XSLT (parameter.xsl) to generate the forms 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)
python
def json(self): """Produce a JSON representation for the web interface""" 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 #d['parameters'] = {} #The actual parameters are included as XML, and transformed by clam.js using XSLT (parameter.xsl) to generate the forms 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)
[ "def", "json", "(", "self", ")", ":", "d", "=", "{", "'id'", ":", "self", ".", "id", ",", "'format'", ":", "self", ".", "formatclass", ".", "__name__", ",", "'label'", ":", "self", ".", "label", ",", "'mimetype'", ":", "self", ".", "formatclass", "...
Produce a JSON representation for the web interface
[ "Produce", "a", "JSON", "representation", "for", "the", "web", "interface" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1524-L1545
train
52,046
proycon/clam
clam/common/data.py
InputTemplate.validate
def validate(self, postdata, user = None): """Validate posted data against the inputtemplate""" clam.common.util.printdebug("Validating inputtemplate " + self.id + "...") errors, parameters, _ = processparameters(postdata, self.parameters, user) return errors, parameters
python
def validate(self, postdata, user = None): """Validate posted data against the inputtemplate""" clam.common.util.printdebug("Validating inputtemplate " + self.id + "...") errors, parameters, _ = processparameters(postdata, self.parameters, user) return errors, parameters
[ "def", "validate", "(", "self", ",", "postdata", ",", "user", "=", "None", ")", ":", "clam", ".", "common", ".", "util", ".", "printdebug", "(", "\"Validating inputtemplate \"", "+", "self", ".", "id", "+", "\"...\"", ")", "errors", ",", "parameters", ",...
Validate posted data against the inputtemplate
[ "Validate", "posted", "data", "against", "the", "inputtemplate" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1578-L1582
train
52,047
proycon/clam
clam/common/data.py
AbstractMetaField.xml
def xml(self, operator='set', indent = ""): """Serialize the metadata field to XML""" xml = indent + "<meta id=\"" + self.key + "\"" if operator != 'set': xml += " operator=\"" + operator + "\"" if not self.value: xml += " />" else: xml += ">" + self.value + "</meta>" return xml
python
def xml(self, operator='set', indent = ""): """Serialize the metadata field to XML""" 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", "=", "\"\"", ")", ":", "xml", "=", "indent", "+", "\"<meta id=\\\"\"", "+", "self", ".", "key", "+", "\"\\\"\"", "if", "operator", "!=", "'set'", ":", "xml", "+=", "\" operator=\\...
Serialize the metadata field to XML
[ "Serialize", "the", "metadata", "field", "to", "XML" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1625-L1634
train
52,048
proycon/clam
clam/common/data.py
OutputTemplate.fromxml
def fromxml(node): """Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element.""" 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'] 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'] #find formatclass formatcls = None for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py 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 #MAYBE TODO: Reading converters from XML is not implemented (and not necessary at this stage) elif subnode.tag == 'viewer': pass #MAYBE TODO: Reading viewers from XML is not implemented (and not necessary at this stage) else: args.append(AbstractMetaField.fromxml(subnode)) return OutputTemplate(template_id,formatcls,label, *args, **kwargs)
python
def fromxml(node): """Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element.""" 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'] 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'] #find formatclass formatcls = None for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py 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 #MAYBE TODO: Reading converters from XML is not implemented (and not necessary at this stage) elif subnode.tag == 'viewer': pass #MAYBE TODO: Reading viewers from XML is not implemented (and not necessary at this stage) else: args.append(AbstractMetaField.fromxml(subnode)) return OutputTemplate(template_id,formatcls,label, *args, **kwargs)
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "assert", "node", ".", "tag", ".", "lower", ...
Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element.
[ "Static", "method", "return", "an", "OutputTemplate", "instance", "from", "the", "given", "XML", "description", ".", "Node", "can", "be", "a", "string", "or", "an", "etree", ".", "_Element", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1825-L1867
train
52,049
proycon/clam
clam/common/data.py
OutputTemplate.getparent
def getparent(self, profile): """Resolve a parent ID""" assert self.parent for inputtemplate in profile.input: if inputtemplate == self.parent: return inputtemplate raise Exception("Parent InputTemplate '"+self.parent+"' not found!")
python
def getparent(self, profile): """Resolve a parent ID""" 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", ")", ":", "assert", "self", ".", "parent", "for", "inputtemplate", "in", "profile", ".", "input", ":", "if", "inputtemplate", "==", "self", ".", "parent", ":", "return", "inputtemplate", "raise", "Exception", ...
Resolve a parent ID
[ "Resolve", "a", "parent", "ID" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1881-L1887
train
52,050
proycon/clam
clam/common/data.py
ParameterCondition.fromxml
def fromxml(node): """Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element.""" 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': #interpret conditions: 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': #interpret statements: for subnode in node: #MAYBE TODO LATER: Support for multiple statement in then=, else= ? if subnode.tag.lower() == 'parametercondition': kwargs[node.tag] = ParameterCondition.fromxml(subnode) elif subnode.tag == 'meta': #assume metafield? 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)
python
def fromxml(node): """Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element.""" 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': #interpret conditions: 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': #interpret statements: for subnode in node: #MAYBE TODO LATER: Support for multiple statement in then=, else= ? if subnode.tag.lower() == 'parametercondition': kwargs[node.tag] = ParameterCondition.fromxml(subnode) elif subnode.tag == 'meta': #assume metafield? 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)
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "assert", "node", ".", "tag", ".", "lower", ...
Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element.
[ "Static", "method", "returning", "a", "ParameterCondition", "instance", "from", "the", "given", "XML", "description", ".", "Node", "can", "be", "a", "string", "or", "an", "etree", ".", "_Element", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2110-L2140
train
52,051
proycon/clam
clam/common/data.py
Action.fromxml
def fromxml(node): """Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element.""" 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 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)
python
def fromxml(node): """Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element.""" 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 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)
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "assert", "node", ".", "tag", ".", "lower", ...
Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element.
[ "Static", "method", "returning", "an", "Action", "instance", "from", "the", "given", "XML", "description", ".", "Node", "can", "be", "a", "string", "or", "an", "etree", ".", "_Element", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2294-L2324
train
52,052
proycon/clam
clam/wrappers/textstats.py
crude_tokenizer
def crude_tokenizer(line): """This is a very crude tokenizer from pynlpl""" 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
python
def crude_tokenizer(line): """This is a very crude tokenizer from pynlpl""" 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", ")", ":", "tokens", "=", "[", "]", "buffer", "=", "''", "for", "c", "in", "line", ".", "strip", "(", ")", ":", "if", "c", "==", "' '", "or", "c", "in", "string", ".", "punctuation", ":", "if", "buffer", ":",...
This is a very crude tokenizer from pynlpl
[ "This", "is", "a", "very", "crude", "tokenizer", "from", "pynlpl" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/wrappers/textstats.py#L43-L55
train
52,053
proycon/clam
clam/common/client.py
CLAMClient.initauth
def initauth(self): """Initialise authentication, for internal use""" 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: #indicates failure 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
python
def initauth(self): """Initialise authentication, for internal use""" 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: #indicates failure 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
[ "def", "initauth", "(", "self", ")", ":", "headers", "=", "{", "'User-agent'", ":", "'CLAMClientAPI-'", "+", "clam", ".", "common", ".", "data", ".", "VERSION", "}", "if", "self", ".", "oauth", ":", "if", "not", "self", ".", "oauth_access_token", ":", ...
Initialise authentication, for internal use
[ "Initialise", "authentication", "for", "internal", "use" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L91-L112
train
52,054
proycon/clam
clam/common/client.py
CLAMClient.request
def request(self, url='', method = 'GET', data = None, parse=True, encoding=None): """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""" 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: #pylint: disable=too-many-nested-blocks content = r.text if parse: data = self._parse(content) if data: if data.errors: error = data.parametererror() #print("DEBUG: parametererror=" + str(error),file=sys.stderr) #for parametergroup, parameters in data.parameters: #pylint: disable=unused-variable # for parameter in parameters: # print("DEBUG: ", parameter.id, parameter.error,file=sys.stderr) if error: raise clam.common.data.ParameterError(error) #print(content,file=sys.stderr) 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
python
def request(self, url='', method = 'GET', data = None, parse=True, encoding=None): """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""" 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: #pylint: disable=too-many-nested-blocks content = r.text if parse: data = self._parse(content) if data: if data.errors: error = data.parametererror() #print("DEBUG: parametererror=" + str(error),file=sys.stderr) #for parametergroup, parameters in data.parameters: #pylint: disable=unused-variable # for parameter in parameters: # print("DEBUG: ", parameter.id, parameter.error,file=sys.stderr) if error: raise clam.common.data.ParameterError(error) #print(content,file=sys.stderr) 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
[ "def", "request", "(", "self", ",", "url", "=", "''", ",", "method", "=", "'GET'", ",", "data", "=", "None", ",", "parse", "=", "True", ",", "encoding", "=", "None", ")", ":", "requestparams", "=", "self", ".", "initrequest", "(", "data", ")", "if"...
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
[ "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", ...
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L132-L188
train
52,055
proycon/clam
clam/common/client.py
CLAMClient._parse
def _parse(self, content): """Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors.""" 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
python
def _parse(self, content): """Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors.""" 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
[ "def", "_parse", "(", "self", ",", "content", ")", ":", "if", "content", ".", "find", "(", "'<clam'", ")", "!=", "-", "1", ":", "data", "=", "clam", ".", "common", ".", "data", ".", "CLAMData", "(", "content", ",", "self", ",", "loadmetadata", "=",...
Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors.
[ "Parses", "CLAM", "XML", "data", "and", "returns", "a", "CLAMData", "object", ".", "For", "internal", "use", ".", "Raises", "ParameterError", "exception", "on", "parameter", "errors", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L191-L201
train
52,056
proycon/clam
clam/common/client.py
CLAMClient.get
def get(self, project): """Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code""" 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
python
def get(self, project): """Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code""" 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
[ "def", "get", "(", "self", ",", "project", ")", ":", "try", ":", "data", "=", "self", ".", "request", "(", "project", "+", "'/'", ")", "except", ":", "raise", "if", "not", "isinstance", "(", "data", ",", "clam", ".", "common", ".", "data", ".", "...
Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code
[ "Query", "the", "project", "status", ".", "Returns", "a", "CLAMData", "instance", "or", "raises", "an", "exception", "according", "to", "the", "returned", "HTTP", "Status", "code" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L207-L216
train
52,057
proycon/clam
clam/common/client.py
CLAMClient.getinputfilename
def getinputfilename(self, inputtemplate, filename): """Determine the final filename for an input file given an inputtemplate and a given filename. Example:: filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file") """ 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': #pass archives as-is return filename if filename[-len(inputtemplate.extension) - 1:].lower() != '.' + inputtemplate.extension.lower(): filename += '.' + inputtemplate.extension return filename
python
def getinputfilename(self, inputtemplate, filename): """Determine the final filename for an input file given an inputtemplate and a given filename. Example:: filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file") """ 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': #pass archives as-is return filename if filename[-len(inputtemplate.extension) - 1:].lower() != '.' + inputtemplate.extension.lower(): filename += '.' + inputtemplate.extension return filename
[ "def", "getinputfilename", "(", "self", ",", "inputtemplate", ",", "filename", ")", ":", "if", "inputtemplate", ".", "filename", ":", "filename", "=", "inputtemplate", ".", "filename", "elif", "inputtemplate", ".", "extension", ":", "if", "filename", ".", "low...
Determine the final filename for an input file given an inputtemplate and a given filename. Example:: filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file")
[ "Determine", "the", "final", "filename", "for", "an", "input", "file", "given", "an", "inputtemplate", "and", "a", "given", "filename", "." ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L318-L336
train
52,058
proycon/clam
clam/common/client.py
CLAMClient._parseupload
def _parseupload(self, node): """Parse CLAM Upload XML Responses. For internal use""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access 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: #pylint: disable=too-many-nested-blocks 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" #default 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
python
def _parseupload(self, node): """Parse CLAM Upload XML Responses. For internal use""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access 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: #pylint: disable=too-many-nested-blocks 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" #default 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
[ "def", "_parseupload", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "try", ":", "node", "=", "clam", ".", "common", ".", "data", ".", "parsex...
Parse CLAM Upload XML Responses. For internal use
[ "Parse", "CLAM", "Upload", "XML", "Responses", ".", "For", "internal", "use" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L338-L360
train
52,059
proycon/clam
clam/common/client.py
CLAMClient.download
def download(self, project, filename, targetfilename, loadmetadata=None): """Download an output file""" if loadmetadata is None: loadmetadata = self.loadmetadata f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self) f.copy(targetfilename)
python
def download(self, project, filename, targetfilename, loadmetadata=None): """Download an output file""" if loadmetadata is None: loadmetadata = self.loadmetadata f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self) f.copy(targetfilename)
[ "def", "download", "(", "self", ",", "project", ",", "filename", ",", "targetfilename", ",", "loadmetadata", "=", "None", ")", ":", "if", "loadmetadata", "is", "None", ":", "loadmetadata", "=", "self", ".", "loadmetadata", "f", "=", "clam", ".", "common", ...
Download an output file
[ "Download", "an", "output", "file" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L534-L538
train
52,060
proycon/clam
clam/common/parameters.py
AbstractParameter.validate
def validate(self,value): """Validate the parameter""" 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 #reset error return True
python
def validate(self,value): """Validate the parameter""" 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 #reset error return True
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "self", ".", "validator", "is", "not", "None", ":", "try", ":", "valid", "=", "self", ".", "validator", "(", "value", ")", "except", "Exception", "as", "e", ":", "import", "pdb", "pdb", ...
Validate the parameter
[ "Validate", "the", "parameter" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L96-L116
train
52,061
proycon/clam
clam/common/parameters.py
BooleanParameter.set
def set(self, value = True): """Set the boolean parameter""" 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"))) #pylint: disable=undefined-variable return super(BooleanParameter,self).set(value)
python
def set(self, value = True): """Set the boolean parameter""" 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"))) #pylint: disable=undefined-variable return super(BooleanParameter,self).set(value)
[ "def", "set", "(", "self", ",", "value", "=", "True", ")", ":", "value", "=", "value", "in", "(", "True", ",", "1", ")", "or", "(", "(", "isinstance", "(", "value", ",", "str", ")", "or", "(", "sys", ".", "version", "<", "'3'", "and", "isinstan...
Set the boolean parameter
[ "Set", "the", "boolean", "parameter" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L280-L283
train
52,062
proycon/clam
clam/common/parameters.py
ChoiceParameter.compilearg
def compilearg(self): """This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value""" if isinstance(self.value,list): value = self.delimiter.join(self.value) else: value = self.value if value.find(" ") >= 0: value = '"' + value + '"' #wrap all in quotes #for some odd, reason this produced an error, as if we're not an instance of choiceparameter #return super(ChoiceParameter,self).compilearg(value) #workaround: 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)
python
def compilearg(self): """This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value""" if isinstance(self.value,list): value = self.delimiter.join(self.value) else: value = self.value if value.find(" ") >= 0: value = '"' + value + '"' #wrap all in quotes #for some odd, reason this produced an error, as if we're not an instance of choiceparameter #return super(ChoiceParameter,self).compilearg(value) #workaround: 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)
[ "def", "compilearg", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "value", ",", "list", ")", ":", "value", "=", "self", ".", "delimiter", ".", "join", "(", "self", ".", "value", ")", "else", ":", "value", "=", "self", ".", "value", ...
This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value
[ "This", "method", "compiles", "the", "parameter", "into", "syntax", "that", "can", "be", "used", "on", "the", "shell", "such", "as", "-", "paramflag", "=", "value" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L438-L457
train
52,063
proycon/clam
clam/clamservice.py
index
def index(credentials = None): """Get list of projects or shortcut to other functionality""" #handle shortcut 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() #pylint: disable=bad-continuation 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})
python
def index(credentials = None): """Get list of projects or shortcut to other functionality""" #handle shortcut 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() #pylint: disable=bad-continuation 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})
[ "def", "index", "(", "credentials", "=", "None", ")", ":", "#handle shortcut", "shortcutresponse", "=", "entryshortcut", "(", "credentials", ")", "if", "shortcutresponse", "is", "not", "None", ":", "return", "shortcutresponse", "projects", "=", "[", "]", "user",...
Get list of projects or shortcut to other functionality
[ "Get", "list", "of", "projects", "or", "shortcut", "to", "other", "functionality" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L364-L418
train
52,064
proycon/clam
clam/clamservice.py
run_wsgi
def run_wsgi(settings_module): """Run CLAM in WSGI mode""" global settingsmodule, DEBUG #pylint: disable=global-statement 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() #host, port test_dirs() if DEBUG: from werkzeug.debug import DebuggedApplication return DebuggedApplication(CLAMService('wsgi').service.wsgi_app, True) else: return CLAMService('wsgi').service.wsgi_app
python
def run_wsgi(settings_module): """Run CLAM in WSGI mode""" global settingsmodule, DEBUG #pylint: disable=global-statement 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() #host, port test_dirs() if DEBUG: from werkzeug.debug import DebuggedApplication return DebuggedApplication(CLAMService('wsgi').service.wsgi_app, True) else: return CLAMService('wsgi').service.wsgi_app
[ "def", "run_wsgi", "(", "settings_module", ")", ":", "global", "settingsmodule", ",", "DEBUG", "#pylint: disable=global-statement", "printdebug", "(", "\"Initialising WSGI service\"", ")", "globals", "(", ")", "[", "'settings'", "]", "=", "settings_module", "settingsmod...
Run CLAM in WSGI mode
[ "Run", "CLAM", "in", "WSGI", "mode" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L2895-L2927
train
52,065
proycon/clam
clam/clamservice.py
Admin.index
def index(credentials=None): """Get list of projects""" 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})
python
def index(credentials=None): """Get list of projects""" 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})
[ "def", "index", "(", "credentials", "=", "None", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "if", "not", "settings", ".", "ADMINS", "or", "user", "not", "in", "settings", ".", "ADMINS", ":", "return", "fl...
Get list of projects
[ "Get", "list", "of", "projects" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L473-L501
train
52,066
proycon/clam
clam/clamservice.py
Project.exists
def exists(project, credentials): """Check if the project exists""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable printdebug("Checking if project " + project + " exists for " + user) return os.path.isdir(Project.path(project, user))
python
def exists(project, credentials): """Check if the project exists""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable printdebug("Checking if project " + project + " exists for " + user) return os.path.isdir(Project.path(project, user))
[ "def", "exists", "(", "project", ",", "credentials", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "#pylint: disable=unused-variable", "printdebug", "(", "\"Checking if project \"", "+", "project", "+", "\" exists for \""...
Check if the project exists
[ "Check", "if", "the", "project", "exists" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L748-L752
train
52,067
proycon/clam
clam/clamservice.py
Project.new
def new(project, credentials=None): """Create an empty project""" 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'})
python
def new(project, credentials=None): """Create an empty project""" 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'})
[ "def", "new", "(", "project", ",", "credentials", "=", "None", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "response", "=", "Project", ".", "create", "(", "project", ",", "user", ")", "if", "response", "is...
Create an empty project
[ "Create", "an", "empty", "project" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1021-L1032
train
52,068
proycon/clam
clam/clamservice.py
Project.deleteoutputfile
def deleteoutputfile(project, filename, credentials=None): """Delete an output file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable if filename: filename = filename.replace("..","") #Simple security if not filename or len(filename) == 0: #Deleting all output files and resetting Project.reset(project, user) msg = "Deleted" return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) #200 elif os.path.isdir(Project.path(project, user) + filename): #Deleting specified directory 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}) #200 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})
python
def deleteoutputfile(project, filename, credentials=None): """Delete an output file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable if filename: filename = filename.replace("..","") #Simple security if not filename or len(filename) == 0: #Deleting all output files and resetting Project.reset(project, user) msg = "Deleted" return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) #200 elif os.path.isdir(Project.path(project, user) + filename): #Deleting specified directory 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}) #200 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})
[ "def", "deleteoutputfile", "(", "project", ",", "filename", ",", "credentials", "=", "None", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "#pylint: disable=unused-variable", "if", "filename", ":", "filename", "=", ...
Delete an output file
[ "Delete", "an", "output", "file" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1280-L1307
train
52,069
proycon/clam
clam/clamservice.py
Project.reset
def reset(project, user): """Reset system, delete all output files and prepare for a new run""" 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")
python
def reset(project, user): """Reset system, delete all output files and prepare for a new run""" 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")
[ "def", "reset", "(", "project", ",", "user", ")", ":", "d", "=", "Project", ".", "path", "(", "project", ",", "user", ")", "+", "\"output\"", "if", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "shutil", ".", "rmtree", "(", "d", ")", "os...
Reset system, delete all output files and prepare for a new run
[ "Reset", "system", "delete", "all", "output", "files", "and", "prepare", "for", "a", "new", "run" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1311-L1322
train
52,070
proycon/clam
clam/clamservice.py
Project.deleteinputfile
def deleteinputfile(project, filename, credentials=None): """Delete an input file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable filename = filename.replace("..","") #Simple security if len(filename) == 0: #Deleting all input files shutil.rmtree(Project.path(project, user) + 'input') os.makedirs(Project.path(project, user) + 'input') #re-add new input directory return "Deleted" #200 elif os.path.isdir(Project.path(project, user) + filename): #Deleting specified directory shutil.rmtree(Project.path(project, user) + filename) return "Deleted" #200 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})
python
def deleteinputfile(project, filename, credentials=None): """Delete an input file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable filename = filename.replace("..","") #Simple security if len(filename) == 0: #Deleting all input files shutil.rmtree(Project.path(project, user) + 'input') os.makedirs(Project.path(project, user) + 'input') #re-add new input directory return "Deleted" #200 elif os.path.isdir(Project.path(project, user) + filename): #Deleting specified directory shutil.rmtree(Project.path(project, user) + filename) return "Deleted" #200 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})
[ "def", "deleteinputfile", "(", "project", ",", "filename", ",", "credentials", "=", "None", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "#pylint: disable=unused-variable", "filename", "=", "filename", ".", "replace"...
Delete an input file
[ "Delete", "an", "input", "file" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1447-L1473
train
52,071
proycon/clam
clam/clamservice.py
CLAMService.corpusindex
def corpusindex(): """Get list of pre-installed corpora""" corpora = [] for f in glob.glob(settings.ROOT + "corpora/*"): if os.path.isdir(f): corpora.append(os.path.basename(f)) return corpora
python
def corpusindex(): """Get list of pre-installed corpora""" corpora = [] for f in glob.glob(settings.ROOT + "corpora/*"): if os.path.isdir(f): corpora.append(os.path.basename(f)) return corpora
[ "def", "corpusindex", "(", ")", ":", "corpora", "=", "[", "]", "for", "f", "in", "glob", ".", "glob", "(", "settings", ".", "ROOT", "+", "\"corpora/*\"", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "f", ")", ":", "corpora", ".", "append...
Get list of pre-installed corpora
[ "Get", "list", "of", "pre", "-", "installed", "corpora" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L2552-L2558
train
52,072
proycon/clam
clam/common/auth.py
NonceMemory.validate
def validate(self, nonce): """Does the nonce exist and is it valid for the request?""" if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr) try: opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable 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
python
def validate(self, nonce): """Does the nonce exist and is it valid for the request?""" if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr) try: opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable 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
[ "def", "validate", "(", "self", ",", "nonce", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"Checking nonce \"", "+", "str", "(", "nonce", ")", ",", "file", "=", "sys", ".", "stderr", ")", "try", ":", "opaque", ",", "ip", ",", "expiret...
Does the nonce exist and is it valid for the request?
[ "Does", "the", "nonce", "exist", "and", "is", "it", "valid", "for", "the", "request?" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/auth.py#L463-L480
train
52,073
proycon/clam
clam/common/auth.py
NonceMemory.cleanup
def cleanup(self): """Delete expired nonces""" t = time.time() for noncefile in glob(self.path + '/*.nonce'): if os.path.getmtime(noncefile) + self.expiration > t: os.unlink(noncefile)
python
def cleanup(self): """Delete expired nonces""" t = time.time() for noncefile in glob(self.path + '/*.nonce'): if os.path.getmtime(noncefile) + self.expiration > t: os.unlink(noncefile)
[ "def", "cleanup", "(", "self", ")", ":", "t", "=", "time", ".", "time", "(", ")", "for", "noncefile", "in", "glob", "(", "self", ".", "path", "+", "'/*.nonce'", ")", ":", "if", "os", ".", "path", ".", "getmtime", "(", "noncefile", ")", "+", "self...
Delete expired nonces
[ "Delete", "expired", "nonces" ]
09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/auth.py#L503-L508
train
52,074
guillermo-carrasco/bcbio-nextgen-monitor
bcbio_monitor/analysis/__init__.py
RunData.json
def json(self): """Retrun JSON representation for this run""" return { "id": self.ID, "steps": self.steps, "graph_source": self.source, "errored": self.errored }
python
def json(self): """Retrun JSON representation for this run""" return { "id": self.ID, "steps": self.steps, "graph_source": self.source, "errored": self.errored }
[ "def", "json", "(", "self", ")", ":", "return", "{", "\"id\"", ":", "self", ".", "ID", ",", "\"steps\"", ":", "self", ".", "steps", ",", "\"graph_source\"", ":", "self", ".", "source", ",", "\"errored\"", ":", "self", ".", "errored", "}" ]
Retrun JSON representation for this run
[ "Retrun", "JSON", "representation", "for", "this", "run" ]
6d059154d774140e1fd03a0e3625f607cef06f5a
https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L31-L38
train
52,075
guillermo-carrasco/bcbio-nextgen-monitor
bcbio_monitor/analysis/__init__.py
AnalysisData.new_run
def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
python
def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
[ "def", "new_run", "(", "self", ")", ":", "self", ".", "current_run", "+=", "1", "self", ".", "runs", ".", "append", "(", "RunData", "(", "self", ".", "current_run", "+", "1", ")", ")" ]
Creates a new RunData object and increments pointers
[ "Creates", "a", "new", "RunData", "object", "and", "increments", "pointers" ]
6d059154d774140e1fd03a0e3625f607cef06f5a
https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L69-L72
train
52,076
guillermo-carrasco/bcbio-nextgen-monitor
bcbio_monitor/analysis/__init__.py
AnalysisData.update_frontend
def update_frontend(self, info): """Updates frontend with info from the log :param info: dict - Information from a line in the log. i.e regular line, new step. """ 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)
python
def update_frontend(self, info): """Updates frontend with info from the log :param info: dict - Information from a line in the log. i.e regular line, new step. """ 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)
[ "def", "update_frontend", "(", "self", ",", "info", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'text/event-stream'", "}", "if", "info", ".", "get", "(", "'when'", ")", ":", "info", "[", "'when'", "]", "=", "info", "[", "'when'", "]", ".", ...
Updates frontend with info from the log :param info: dict - Information from a line in the log. i.e regular line, new step.
[ "Updates", "frontend", "with", "info", "from", "the", "log" ]
6d059154d774140e1fd03a0e3625f607cef06f5a
https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L155-L163
train
52,077
guillermo-carrasco/bcbio-nextgen-monitor
bcbio_monitor/analysis/__init__.py
AnalysisData.get_summary
def get_summary(self): """Returns some summary data for a finished analysis""" 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
python
def get_summary(self): """Returns some summary data for a finished analysis""" 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
[ "def", "get_summary", "(", "self", ")", ":", "if", "not", "self", ".", "analysis_finished", ":", "return", "[", "]", "summary", "=", "{", "'times_summary'", ":", "[", "]", "}", "for", "i", "in", "range", "(", "len", "(", "self", ".", "runs", "[", "...
Returns some summary data for a finished analysis
[ "Returns", "some", "summary", "data", "for", "a", "finished", "analysis" ]
6d059154d774140e1fd03a0e3625f607cef06f5a
https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L176-L187
train
52,078
harcokuppens/thonny-ev3dev
thonnycontrib/ev3dev/__init__.py
_handle_rundebug_from_shell
def _handle_rundebug_from_shell(cmd_line): """ Handles all commands that take a filename and 0 or more extra arguments. Passes the command to backend. (Debugger plugin may also use this method) """ 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))
python
def _handle_rundebug_from_shell(cmd_line): """ Handles all commands that take a filename and 0 or more extra arguments. Passes the command to backend. (Debugger plugin may also use this method) """ 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))
[ "def", "_handle_rundebug_from_shell", "(", "cmd_line", ")", ":", "command", ",", "args", "=", "parse_shell_command", "(", "cmd_line", ")", "if", "len", "(", "args", ")", ">=", "1", ":", "get_workbench", "(", ")", ".", "get_editor_notebook", "(", ")", ".", ...
Handles all commands that take a filename and 0 or more extra arguments. Passes the command to backend. (Debugger plugin may also use this method)
[ "Handles", "all", "commands", "that", "take", "a", "filename", "and", "0", "or", "more", "extra", "arguments", ".", "Passes", "the", "command", "to", "backend", "." ]
e3437d7716068976faf2146c6bb0332ed56a1760
https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L326-L364
train
52,079
harcokuppens/thonny-ev3dev
thonnycontrib/ev3dev/__init__.py
download_log
def download_log(currentfile=None): """downloads log of given .py file from EV3.""" if currentfile == None: return # add ".err.log" if file doesn't end with it! 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)
python
def download_log(currentfile=None): """downloads log of given .py file from EV3.""" if currentfile == None: return # add ".err.log" if file doesn't end with it! 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)
[ "def", "download_log", "(", "currentfile", "=", "None", ")", ":", "if", "currentfile", "==", "None", ":", "return", "# add \".err.log\" if file doesn't end with it!", "if", "not", "currentfile", ".", "endswith", "(", "\".err.log\"", ")", ":", "currentfile", "=", "...
downloads log of given .py file from EV3.
[ "downloads", "log", "of", "given", ".", "py", "file", "from", "EV3", "." ]
e3437d7716068976faf2146c6bb0332ed56a1760
https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L473-L495
train
52,080
harcokuppens/thonny-ev3dev
thonnycontrib/ev3dev/__init__.py
download_log_of_current_script
def download_log_of_current_script(): """download log of current python script from EV3""" try: #Return None, if script is not saved and user closed file saving window, otherwise return file name. 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)
python
def download_log_of_current_script(): """download log of current python script from EV3""" try: #Return None, if script is not saved and user closed file saving window, otherwise return file name. 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)
[ "def", "download_log_of_current_script", "(", ")", ":", "try", ":", "#Return None, if script is not saved and user closed file saving window, otherwise return file name.", "src_file", "=", "get_workbench", "(", ")", ".", "get_current_editor", "(", ")", ".", "get_filename", "(",...
download log of current python script from EV3
[ "download", "log", "of", "current", "python", "script", "from", "EV3" ]
e3437d7716068976faf2146c6bb0332ed56a1760
https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L528-L539
train
52,081
harcokuppens/thonny-ev3dev
thonnycontrib/ev3dev/__init__.py
cleanup_files_on_ev3
def cleanup_files_on_ev3(): """cleanup files in homedir 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()
python
def cleanup_files_on_ev3(): """cleanup files in homedir 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()
[ "def", "cleanup_files_on_ev3", "(", ")", ":", "list", "=", "get_base_ev3dev_cmd", "(", ")", "+", "[", "'cleanup'", "]", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", "[", "\"PYTHONUSERBASE\"", "]", "=", "THONNY_USER_BASE", "proc", "=", ...
cleanup files in homedir on EV3.
[ "cleanup", "files", "in", "homedir", "on", "EV3", "." ]
e3437d7716068976faf2146c6bb0332ed56a1760
https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L541-L551
train
52,082
jasonkeene/python-ubersmith
ubersmith/__init__.py
init
def init(base_url, username=None, password=None, verify=True): """Initialize ubersmith API module with HTTP request handler.""" handler = RequestHandler(base_url, username, password, verify) set_default_request_handler(handler) return handler
python
def init(base_url, username=None, password=None, verify=True): """Initialize ubersmith API module with HTTP request handler.""" handler = RequestHandler(base_url, username, password, verify) set_default_request_handler(handler) return handler
[ "def", "init", "(", "base_url", ",", "username", "=", "None", ",", "password", "=", "None", ",", "verify", "=", "True", ")", ":", "handler", "=", "RequestHandler", "(", "base_url", ",", "username", ",", "password", ",", "verify", ")", "set_default_request_...
Initialize ubersmith API module with HTTP request handler.
[ "Initialize", "ubersmith", "API", "module", "with", "HTTP", "request", "handler", "." ]
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/__init__.py#L34-L38
train
52,083
i3visio/deepify
deepify/utils/configuration.py
getConfigPath
def getConfigPath(configFileName = None): """ Auxiliar function to get the configuration path depending on the system. """ if configFileName != None: # Returning the path of the configuration file 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: # Returning the path of the configuration folder if sys.platform == 'win32': return os.path.expanduser(os.path.join('~\\', 'Deepify')) else: return os.path.expanduser(os.path.join('~/', '.config', 'Deepify'))
python
def getConfigPath(configFileName = None): """ Auxiliar function to get the configuration path depending on the system. """ if configFileName != None: # Returning the path of the configuration file 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: # Returning the path of the configuration folder if sys.platform == 'win32': return os.path.expanduser(os.path.join('~\\', 'Deepify')) else: return os.path.expanduser(os.path.join('~/', '.config', 'Deepify'))
[ "def", "getConfigPath", "(", "configFileName", "=", "None", ")", ":", "if", "configFileName", "!=", "None", ":", "# Returning the path of the configuration file", "if", "sys", ".", "platform", "==", "'win32'", ":", "return", "os", ".", "path", ".", "expanduser", ...
Auxiliar function to get the configuration path depending on the system.
[ "Auxiliar", "function", "to", "get", "the", "configuration", "path", "depending", "on", "the", "system", "." ]
2af04e0bea3eaabe96b0565e10f7eeb29b042a2b
https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/configuration.py#L59-L74
train
52,084
shmir/PyTrafficGenerator
trafficgenerator/tgn_utils.py
new_log_file
def new_log_file(logger, suffix, file_type='tcl'): """ Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param suffix: string to add to the existing log file name to create the new log file name. :param file_type: logger file type (tcl. txt. etc.) :return: the newly created logger """ 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
python
def new_log_file(logger, suffix, file_type='tcl'): """ Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param suffix: string to add to the existing log file name to create the new log file name. :param file_type: logger file type (tcl. txt. etc.) :return: the newly created logger """ 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
[ "def", "new_log_file", "(", "logger", ",", "suffix", ",", "file_type", "=", "'tcl'", ")", ":", "file_handler", "=", "None", "for", "handler", "in", "logger", ".", "handlers", ":", "if", "isinstance", "(", "handler", ",", "logging", ".", "FileHandler", ")",...
Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param suffix: string to add to the existing log file name to create the new log file name. :param file_type: logger file type (tcl. txt. etc.) :return: the newly created logger
[ "Create", "new", "logger", "and", "log", "file", "from", "existing", "logger", "." ]
382e5d549c83404af2a6571fe19c9e71df8bac14
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_utils.py#L81-L104
train
52,085
jasonkeene/python-ubersmith
ubersmith/api.py
RequestHandler.process_request
def process_request(self, method, data=None): """Process request over HTTP to ubersmith instance. method: Ubersmith API method string data: dict of method arguments """ # make sure requested method is valid self._validate_request_method(method) # attempt the request multiple times attempts = 3 for i in range(attempts): response = self._send_request(method, data) # handle case where ubersmith is 'updating token' # see: https://github.com/jasonkeene/python-ubersmith/issues/1 if self._is_token_response(response): if i < attempts - 1: # wait 2 secs before retrying request time.sleep(2) continue else: raise UpdatingTokenResponse break resp = BaseResponse(response) # test for error in json 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
python
def process_request(self, method, data=None): """Process request over HTTP to ubersmith instance. method: Ubersmith API method string data: dict of method arguments """ # make sure requested method is valid self._validate_request_method(method) # attempt the request multiple times attempts = 3 for i in range(attempts): response = self._send_request(method, data) # handle case where ubersmith is 'updating token' # see: https://github.com/jasonkeene/python-ubersmith/issues/1 if self._is_token_response(response): if i < attempts - 1: # wait 2 secs before retrying request time.sleep(2) continue else: raise UpdatingTokenResponse break resp = BaseResponse(response) # test for error in json 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
[ "def", "process_request", "(", "self", ",", "method", ",", "data", "=", "None", ")", ":", "# make sure requested method is valid", "self", ".", "_validate_request_method", "(", "method", ")", "# attempt the request multiple times", "attempts", "=", "3", "for", "i", ...
Process request over HTTP to ubersmith instance. method: Ubersmith API method string data: dict of method arguments
[ "Process", "request", "over", "HTTP", "to", "ubersmith", "instance", "." ]
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/api.py#L253-L292
train
52,086
jasonkeene/python-ubersmith
ubersmith/api.py
RequestHandler._encode_data
def _encode_data(data): """URL encode 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
python
def _encode_data(data): """URL encode 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
[ "def", "_encode_data", "(", "data", ")", ":", "data", "=", "data", "if", "data", "is", "not", "None", "else", "{", "}", "data", "=", "to_nested_php_args", "(", "data", ")", "files", "=", "dict", "(", "[", "(", "key", ",", "value", ")", "for", "key"...
URL encode data.
[ "URL", "encode", "data", "." ]
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/api.py#L313-L322
train
52,087
shmir/PyTrafficGenerator
trafficgenerator/tgn_object.py
TgnObject.get_objects_or_children_by_type
def get_objects_or_children_by_type(self, *types): """ Get objects if children already been read or get children. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. """ objects = self.get_objects_by_type(*types) return objects if objects else self.get_children(*types)
python
def get_objects_or_children_by_type(self, *types): """ Get objects if children already been read or get children. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. """ objects = self.get_objects_by_type(*types) return objects if objects else self.get_children(*types)
[ "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. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types.
[ "Get", "objects", "if", "children", "already", "been", "read", "or", "get", "children", "." ]
382e5d549c83404af2a6571fe19c9e71df8bac14
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L177-L187
train
52,088
shmir/PyTrafficGenerator
trafficgenerator/tgn_object.py
TgnObject.get_object_or_child_by_type
def get_object_or_child_by_type(self, *types): """ Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. """ objects = self.get_objects_or_children_by_type(*types) return objects[0] if any(objects) else None
python
def get_object_or_child_by_type(self, *types): """ Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. """ objects = self.get_objects_or_children_by_type(*types) return objects[0] if any(objects) else None
[ "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. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types.
[ "Get", "object", "if", "child", "already", "been", "read", "or", "get", "child", "." ]
382e5d549c83404af2a6571fe19c9e71df8bac14
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L189-L199
train
52,089
shmir/PyTrafficGenerator
trafficgenerator/tgn_object.py
TgnObject.del_object_from_parent
def del_object_from_parent(self): """ Delete object from parent object. """ if self.parent: self.parent.objects.pop(self.ref)
python
def del_object_from_parent(self): """ Delete object from parent object. """ if self.parent: self.parent.objects.pop(self.ref)
[ "def", "del_object_from_parent", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "self", ".", "parent", ".", "objects", ".", "pop", "(", "self", ".", "ref", ")" ]
Delete object from parent object.
[ "Delete", "object", "from", "parent", "object", "." ]
382e5d549c83404af2a6571fe19c9e71df8bac14
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L249-L252
train
52,090
Nic30/pyDigitalWaveTools
pyDigitalWaveTools/vcd/writer.py
VcdVarIdScope._idToStr
def _idToStr(self, x): """ Convert VCD id in int to string """ 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)
python
def _idToStr(self, x): """ Convert VCD id in int to string """ 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)
[ "def", "_idToStr", "(", "self", ",", "x", ")", ":", "if", "x", "<", "0", ":", "sign", "=", "-", "1", "elif", "x", "==", "0", ":", "return", "self", ".", "_idChars", "[", "0", "]", "else", ":", "sign", "=", "1", "x", "*=", "sign", "digits", ...
Convert VCD id in int to string
[ "Convert", "VCD", "id", "in", "int", "to", "string" ]
95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc
https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/writer.py#L31-L50
train
52,091
Nic30/pyDigitalWaveTools
pyDigitalWaveTools/vcd/writer.py
VcdVarWritingScope.addVar
def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int, valueFormatter: Callable[["Value"], str]): """ Add variable to scope :ivar sig: user specified object to keep track of VcdVarInfo in change() :ivar sigType: vcd type name :ivar valueFormatter: value which converts new value in change() to vcd string """ 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))
python
def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int, valueFormatter: Callable[["Value"], str]): """ Add variable to scope :ivar sig: user specified object to keep track of VcdVarInfo in change() :ivar sigType: vcd type name :ivar valueFormatter: value which converts new value in change() to vcd string """ 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))
[ "def", "addVar", "(", "self", ",", "sig", ":", "object", ",", "name", ":", "str", ",", "sigType", ":", "VCD_SIG_TYPE", ",", "width", ":", "int", ",", "valueFormatter", ":", "Callable", "[", "[", "\"Value\"", "]", ",", "str", "]", ")", ":", "vInf", ...
Add variable to scope :ivar sig: user specified object to keep track of VcdVarInfo in change() :ivar sigType: vcd type name :ivar valueFormatter: value which converts new value in change() to vcd string
[ "Add", "variable", "to", "scope" ]
95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc
https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/writer.py#L78-L91
train
52,092
Nic30/pyDigitalWaveTools
pyDigitalWaveTools/vcd/writer.py
VcdVarWritingScope.varScope
def varScope(self, name): """ Create sub variable scope with defined name """ ch = VcdVarWritingScope(name, self._writer, parent=self) assert name not in self.children, name self.children[name] = ch return ch
python
def varScope(self, name): """ Create sub variable scope with defined name """ ch = VcdVarWritingScope(name, self._writer, parent=self) assert name not in self.children, name self.children[name] = ch return ch
[ "def", "varScope", "(", "self", ",", "name", ")", ":", "ch", "=", "VcdVarWritingScope", "(", "name", ",", "self", ".", "_writer", ",", "parent", "=", "self", ")", "assert", "name", "not", "in", "self", ".", "children", ",", "name", "self", ".", "chil...
Create sub variable scope with defined name
[ "Create", "sub", "variable", "scope", "with", "defined", "name" ]
95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc
https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/writer.py#L93-L100
train
52,093
jasonkeene/python-ubersmith
ubersmith/utils.py
append_qs
def append_qs(url, query_string): """Append query_string values to an existing URL and return it as a string. query_string can be: * an encoded string: 'test3=val1&test3=val2' * a dict of strings: {'test3': 'val'} * a dict of lists of strings: {'test3': ['val1', 'val2']} * a list of tuples: [('test3', 'val1'), ('test3', 'val2')] """ 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, ))
python
def append_qs(url, query_string): """Append query_string values to an existing URL and return it as a string. query_string can be: * an encoded string: 'test3=val1&test3=val2' * a dict of strings: {'test3': 'val'} * a dict of lists of strings: {'test3': ['val1', 'val2']} * a list of tuples: [('test3', 'val1'), ('test3', 'val2')] """ 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, ))
[ "def", "append_qs", "(", "url", ",", "query_string", ")", ":", "parsed_url", "=", "urlsplit", "(", "url", ")", "parsed_qs", "=", "parse_qsl", "(", "parsed_url", ".", "query", ",", "True", ")", "if", "isstr", "(", "query_string", ")", ":", "parsed_qs", "+...
Append query_string values to an existing URL and return it as a string. query_string can be: * an encoded string: 'test3=val1&test3=val2' * a dict of strings: {'test3': 'val'} * a dict of lists of strings: {'test3': ['val1', 'val2']} * a list of tuples: [('test3', 'val1'), ('test3', 'val2')]
[ "Append", "query_string", "values", "to", "an", "existing", "URL", "and", "return", "it", "as", "a", "string", "." ]
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L33-L66
train
52,094
jasonkeene/python-ubersmith
ubersmith/utils.py
urlencode_unicode
def urlencode_unicode(data, doseq=0): """urllib.urlencode can't handle unicode, this is a hack to fix it.""" 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 to convert to str try: safe_val = str(value) except UnicodeEncodeError: # try to encode as utf-8 # if an exception is raised here then idk what to do 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)
python
def urlencode_unicode(data, doseq=0): """urllib.urlencode can't handle unicode, this is a hack to fix it.""" 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 to convert to str try: safe_val = str(value) except UnicodeEncodeError: # try to encode as utf-8 # if an exception is raised here then idk what to do 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)
[ "def", "urlencode_unicode", "(", "data", ",", "doseq", "=", "0", ")", ":", "data_iter", "=", "None", "if", "isdict", "(", "data", ")", ":", "data_iter", "=", "list", "(", "data", ".", "items", "(", ")", ")", "elif", "islist", "(", "data", ")", ":",...
urllib.urlencode can't handle unicode, this is a hack to fix it.
[ "urllib", ".", "urlencode", "can", "t", "handle", "unicode", "this", "is", "a", "hack", "to", "fix", "it", "." ]
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L69-L93
train
52,095
jasonkeene/python-ubersmith
ubersmith/utils.py
to_nested_php_args
def to_nested_php_args(data, prefix_key=None): """ 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. """ 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
python
def to_nested_php_args(data, prefix_key=None): """ 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. """ 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
[ "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", "=", "dat...
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.
[ "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...
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L101-L138
train
52,096
jasonkeene/python-ubersmith
ubersmith/utils.py
get_filename
def get_filename(disposition): """Parse Content-Disposition header to pull out the filename bit. See: http://tools.ietf.org/html/rfc2616#section-19.5.1 """ 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('"')
python
def get_filename(disposition): """Parse Content-Disposition header to pull out the filename bit. See: http://tools.ietf.org/html/rfc2616#section-19.5.1 """ 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('"')
[ "def", "get_filename", "(", "disposition", ")", ":", "if", "disposition", ":", "params", "=", "[", "param", ".", "strip", "(", ")", "for", "param", "in", "disposition", ".", "split", "(", "';'", ")", "[", "1", ":", "]", "]", "for", "param", "in", "...
Parse Content-Disposition header to pull out the filename bit. See: http://tools.ietf.org/html/rfc2616#section-19.5.1
[ "Parse", "Content", "-", "Disposition", "header", "to", "pull", "out", "the", "filename", "bit", "." ]
0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a
https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L161-L173
train
52,097
shmir/PyTrafficGenerator
trafficgenerator/tgn_tcl.py
tcl_list_2_py_list
def tcl_list_2_py_list(tcl_list, within_tcl_str=False): """ Convert Tcl list to Python list using Tcl interpreter. :param tcl_list: string representing the Tcl string. :param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string. :return: Python list equivalent to the Tcl ist. :rtye: list """ 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 []
python
def tcl_list_2_py_list(tcl_list, within_tcl_str=False): """ Convert Tcl list to Python list using Tcl interpreter. :param tcl_list: string representing the Tcl string. :param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string. :return: Python list equivalent to the Tcl ist. :rtye: list """ 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 []
[ "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", "+", "'...
Convert Tcl list to Python list using Tcl interpreter. :param tcl_list: string representing the Tcl string. :param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string. :return: Python list equivalent to the Tcl ist. :rtye: list
[ "Convert", "Tcl", "list", "to", "Python", "list", "using", "Tcl", "interpreter", "." ]
382e5d549c83404af2a6571fe19c9e71df8bac14
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L68-L79
train
52,098
shmir/PyTrafficGenerator
trafficgenerator/tgn_tcl.py
py_list_to_tcl_list
def py_list_to_tcl_list(py_list): """ Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python list. :type py_list: list :return: string representing the Tcl string equivalent to the Python 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'))
python
def py_list_to_tcl_list(py_list): """ Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python list. :type py_list: list :return: string representing the Tcl string equivalent to the Python 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'))
[ "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", "...
Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python list. :type py_list: list :return: string representing the Tcl string equivalent to the Python list.
[ "Convert", "Python", "list", "to", "Tcl", "list", "using", "Tcl", "interpreter", "." ]
382e5d549c83404af2a6571fe19c9e71df8bac14
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L82-L91
train
52,099